diff --git a/.vscode/settings.json b/.vscode/settings.json index e48632d..3c0a58b 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -2,5 +2,6 @@ "python.pythonPath": "bin/python3", "python.envFile": "${workspaceFolder}/.env", "python.linting.pylintEnabled": true, - "python.linting.enabled": true + "python.linting.enabled": true, + "python.autoComplete.addBrackets": true } \ No newline at end of file diff --git a/scrape.py b/scrape.py index 574b20e..a41dad7 100644 --- a/scrape.py +++ b/scrape.py @@ -73,7 +73,7 @@ def main(config, log): if does_file_exist(config['message_sent_file']): log.info( f'Already had positive result, remove {config["message_sent_file"]} to allow script to run again') - return + raise StopIteration('Already run once') json = get_json_from_url(config['api_url']) @@ -81,6 +81,7 @@ def main(config, log): if id['edp'] == config['item_id']: if id['stockStatus'] == 'OutOfStock': log.info("Item is out of stock") + return False else: log.info("Item is in stock") send_sms( @@ -88,6 +89,7 @@ def main(config, log): # Prevents it being run again create_file(config['message_sent_file']) + return True if __name__ == '__main__': diff --git a/test_scrape.py b/test_scrape.py new file mode 100644 index 0000000..af183b9 --- /dev/null +++ b/test_scrape.py @@ -0,0 +1,37 @@ +from unittest.mock import Mock, patch +import pytest +import scrape +import logging + + +@pytest.fixture(scope="module") +def log(): + log = scrape.get_logger(logging.DEBUG) + yield log + + +@patch('scrape.does_file_exist') +def test_already_run(mock_does_file_exist, log): + mock_does_file_exist.return_value = True + assert scrape.does_file_exist(scrape.config['message_sent_file']) + with pytest.raises(StopIteration): + scrape.main(scrape.config, log) + + +@pytest.mark.parametrize("json, expected", + [({"Y1357": [{"edp": "40263442", "stockStatus": "OutOfStock"}]}, False), + ({"Y1357": [{"edp": "40263442", "stockStatus": "LowStock"}]}, True)]) +@patch('scrape.does_file_exist') +@patch('scrape.requests.get') +@patch('scrape.create_file') +@patch('scrape.send_sms') +def test_full_process(mock_send_sms, mock_create_file, mock_request_get, mock_does_file_exist, json, expected, log): + mock_does_file_exist.return_value = False + mock_response = Mock(**{'json.return_value': json}) + mock_request_get.return_value = mock_response + + assert scrape.main(scrape.config, log) == expected + if expected: + mock_send_sms.assert_called_once_with(scrape.config['msg_to'], + 'The coat is in stock at ' + scrape.config['website_url']) + mock_create_file.assert_called_once()