diff --git a/tests/samples/output/configs_test_config_file_not_passed_in_command_line_args b/tests/samples/output/configs_test_config_file_not_passed_in_command_line_args new file mode 100644 index 0000000..412c3f6 --- /dev/null +++ b/tests/samples/output/configs_test_config_file_not_passed_in_command_line_args @@ -0,0 +1,9 @@ +usage: wakatime [-h] [--entity FILE] [--key KEY] [--write] [--plugin PLUGIN] + [--time time] [--lineno LINENO] [--cursorpos CURSORPOS] + [--entity-type ENTITY_TYPE] [--proxy PROXY] + [--project PROJECT] [--alternate-project ALTERNATE_PROJECT] + [--language LANGUAGE] [--hostname HOSTNAME] [--disableoffline] + [--hidefilenames] [--exclude EXCLUDE] [--include INCLUDE] + [--extra-heartbeats] [--logfile LOGFILE] [--apiurl API_URL] + [--timeout TIMEOUT] [--config CONFIG] [--verbose] [--version] +wakatime: error: Missing api key. Find your api key from wakatime.com/settings. diff --git a/tests/samples/output/configs_test_missing_config_file b/tests/samples/output/configs_test_missing_config_file new file mode 100644 index 0000000..412c3f6 --- /dev/null +++ b/tests/samples/output/configs_test_missing_config_file @@ -0,0 +1,9 @@ +usage: wakatime [-h] [--entity FILE] [--key KEY] [--write] [--plugin PLUGIN] + [--time time] [--lineno LINENO] [--cursorpos CURSORPOS] + [--entity-type ENTITY_TYPE] [--proxy PROXY] + [--project PROJECT] [--alternate-project ALTERNATE_PROJECT] + [--language LANGUAGE] [--hostname HOSTNAME] [--disableoffline] + [--hidefilenames] [--exclude EXCLUDE] [--include INCLUDE] + [--extra-heartbeats] [--logfile LOGFILE] [--apiurl API_URL] + [--timeout TIMEOUT] [--config CONFIG] [--verbose] [--version] +wakatime: error: Missing api key. Find your api key from wakatime.com/settings. diff --git a/tests/test_arguments.py b/tests/test_arguments.py index 4a9bccb..9a762e2 100644 --- a/tests/test_arguments.py +++ b/tests/test_arguments.py @@ -241,6 +241,89 @@ class MainTestCase(utils.TestCase): self.patched['wakatime.offlinequeue.Queue.push'].assert_not_called() self.patched['wakatime.offlinequeue.Queue.pop'].assert_not_called() + @log_capture() + def test_invalid_api_key(self, logs): + logging.disable(logging.NOTSET) + + response = Response() + response.status_code = 201 + self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response + + key = 'an-invalid-key' + args = ['--key', key] + + with self.assertRaises(SystemExit) as e: + execute(args) + + self.assertEquals(int(str(e.exception)), AUTH_ERROR) + self.assertEquals(sys.stdout.getvalue(), '') + expected = 'error: Invalid api key. Find your api key from wakatime.com/settings.' + self.assertIn(expected, sys.stderr.getvalue()) + + log_output = u("\n").join([u(' ').join(x) for x in logs.actual()]) + expected = '' + self.assertEquals(log_output, expected) + + self.patched['wakatime.session_cache.SessionCache.get'].assert_not_called() + self.patched['wakatime.session_cache.SessionCache.delete'].assert_not_called() + self.patched['wakatime.session_cache.SessionCache.save'].assert_not_called() + + self.patched['wakatime.offlinequeue.Queue.push'].assert_not_called() + self.patched['wakatime.offlinequeue.Queue.pop'].assert_not_called() + + @log_capture() + def test_api_key_passed_via_command_line(self, logs): + logging.disable(logging.NOTSET) + + response = Response() + response.status_code = 0 + self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response + + with utils.TemporaryDirectory() as tempdir: + filename = list(filter(lambda x: x.endswith('.txt'), os.listdir('tests/samples/codefiles/unicode')))[0] + entity = os.path.join('tests/samples/codefiles/unicode', filename) + shutil.copy(entity, os.path.join(tempdir, filename)) + entity = os.path.realpath(os.path.join(tempdir, filename)) + now = u(int(time.time())) + key = str(uuid.uuid4()) + + args = ['--file', entity, '--key', key, '--time', now] + + retval = execute(args) + self.assertEquals(sys.stdout.getvalue(), '') + self.assertEquals(sys.stderr.getvalue(), '') + + log_output = u("\n").join([u(' ').join(x) for x in logs.actual()]) + self.assertEquals(log_output, '') + + self.assertEquals(retval, API_ERROR) + + self.patched['wakatime.session_cache.SessionCache.get'].assert_called_once_with() + self.patched['wakatime.session_cache.SessionCache.delete'].assert_called_once_with() + self.patched['wakatime.session_cache.SessionCache.save'].assert_not_called() + + heartbeat = { + 'language': 'Text only', + 'lines': 0, + 'entity': os.path.realpath(entity), + 'project': os.path.basename(os.path.abspath('.')), + 'time': float(now), + 'type': 'file', + } + stats = { + u('cursorpos'): None, + u('dependencies'): [], + u('language'): u('Text only'), + u('lineno'): None, + u('lines'): 0, + } + + self.patched['wakatime.offlinequeue.Queue.push'].assert_called_once_with(ANY, ANY, None) + for key, val in self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0].items(): + self.assertEquals(heartbeat[key], val) + self.assertEquals(stats, json.loads(self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][1])) + self.patched['wakatime.offlinequeue.Queue.pop'].assert_not_called() + def test_proxy_argument(self): response = Response() response.status_code = 201 diff --git a/tests/test_configs.py b/tests/test_configs.py index 5f0ecbb..b25cc10 100644 --- a/tests/test_configs.py +++ b/tests/test_configs.py @@ -15,6 +15,7 @@ from testfixtures import log_capture from wakatime.compat import u, is_py3 from wakatime.constants import ( API_ERROR, + AUTH_ERROR, CONFIG_FILE_PARSE_ERROR, SUCCESS, ) @@ -52,6 +53,7 @@ class MainTestCase(utils.TestCase): entity = 'tests/samples/codefiles/emptyfile.txt' shutil.copy(entity, os.path.join(tempdir, 'emptyfile.txt')) entity = os.path.realpath(os.path.join(tempdir, 'emptyfile.txt')) + args = ['--file', entity] with utils.mock.patch('wakatime.configs.os.environ.get') as mock_env: mock_env.return_value = None @@ -59,18 +61,15 @@ class MainTestCase(utils.TestCase): with utils.mock.patch('wakatime.configs.open') as mock_open: mock_open.side_effect = IOError('') - config = os.path.join(os.path.expanduser('~'), '.wakatime.cfg') - args = ['--file', entity] - with self.assertRaises(SystemExit) as e: execute(args) - self.assertEquals(int(str(e.exception)), CONFIG_FILE_PARSE_ERROR) - expected_stdout = u('') - expected_stderr = u("Error: Could not read from config file {0}\n").format(u(config)) - self.assertEquals(sys.stdout.getvalue(), expected_stdout) - self.assertEquals(sys.stderr.getvalue(), expected_stderr) - self.patched['wakatime.session_cache.SessionCache.get'].assert_not_called() + self.assertEquals(int(str(e.exception)), AUTH_ERROR) + expected_stdout = u('') + expected_stderr = open('tests/samples/output/configs_test_config_file_not_passed_in_command_line_args').read() + self.assertEquals(sys.stdout.getvalue(), expected_stdout) + self.assertEquals(sys.stderr.getvalue(), expected_stderr) + self.patched['wakatime.session_cache.SessionCache.get'].assert_not_called() def test_config_file_from_env(self): response = Response() @@ -116,13 +115,14 @@ class MainTestCase(utils.TestCase): with self.assertRaises(SystemExit) as e: execute(args) - self.assertEquals(int(str(e.exception)), CONFIG_FILE_PARSE_ERROR) - expected_stdout = u('') - expected_stderr = u("Error: Could not read from config file foo\n") - self.assertEquals(sys.stdout.getvalue(), expected_stdout) - self.assertEquals(sys.stderr.getvalue(), expected_stderr) + self.assertEquals(int(str(e.exception)), AUTH_ERROR) - self.patched['wakatime.session_cache.SessionCache.get'].assert_not_called() + expected_stdout = u('') + expected_stderr = open('tests/samples/output/configs_test_missing_config_file').read() + self.assertEquals(sys.stdout.getvalue(), expected_stdout) + self.assertEquals(sys.stderr.getvalue(), expected_stderr) + + self.patched['wakatime.session_cache.SessionCache.get'].assert_not_called() def test_good_config_file(self): response = Response() @@ -179,7 +179,10 @@ class MainTestCase(utils.TestCase): self.patched['wakatime.offlinequeue.Queue.push'].assert_not_called() self.patched['wakatime.offlinequeue.Queue.pop'].assert_called_once_with() - def test_bad_config_file(self): + @log_capture() + def test_bad_config_file(self, logs): + logging.disable(logging.NOTSET) + with utils.TemporaryDirectory() as tempdir: entity = 'tests/samples/codefiles/emptyfile.txt' shutil.copy(entity, os.path.join(tempdir, 'emptyfile.txt')) @@ -187,10 +190,20 @@ class MainTestCase(utils.TestCase): config = 'tests/samples/configs/bad_config.cfg' args = ['--file', entity, '--config', config] - retval = execute(args) - self.assertEquals(retval, CONFIG_FILE_PARSE_ERROR) + + with self.assertRaises(SystemExit) as e: + execute(args) + + self.assertEquals(int(str(e.exception)), CONFIG_FILE_PARSE_ERROR) self.assertIn('ParsingError', sys.stdout.getvalue()) - self.assertEquals(sys.stderr.getvalue(), '') + expected_stderr = '' + self.assertEquals(sys.stderr.getvalue(), expected_stderr) + + log_output = u("\n").join([u(' ').join(x) for x in logs.actual()]) + expected = '' + self.assertEquals(log_output, expected) + + self.patched['wakatime.offlinequeue.Queue.push'].assert_not_called() self.patched['wakatime.session_cache.SessionCache.get'].assert_not_called() self.patched['wakatime.session_cache.SessionCache.delete'].assert_not_called() diff --git a/tests/test_main.py b/tests/test_main.py index 9e420cd..6920237 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -492,7 +492,7 @@ class MainTestCase(utils.TestCase): self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with utils.TemporaryDirectory() as tempdir: - filename = os.listdir('tests/samples/codefiles/unicode')[0] + filename = list(filter(lambda x: x.endswith('.txt'), os.listdir('tests/samples/codefiles/unicode')))[0] entity = os.path.join('tests/samples/codefiles/unicode', filename) shutil.copy(entity, os.path.join(tempdir, filename)) entity = os.path.realpath(os.path.join(tempdir, filename)) @@ -507,8 +507,8 @@ class MainTestCase(utils.TestCase): self.assertEquals(sys.stdout.getvalue(), '') self.assertEquals(sys.stderr.getvalue(), '') - output = [u(' ').join(x) for x in logs.actual()] - self.assertEquals(len(output), 0) + log_output = u("\n").join([u(' ').join(x) for x in logs.actual()]) + self.assertEquals(log_output, '') self.patched['wakatime.session_cache.SessionCache.get'].assert_called_once_with() self.patched['wakatime.session_cache.SessionCache.delete'].assert_called_once_with() diff --git a/wakatime/arguments.py b/wakatime/arguments.py index b6ed963..0fbe7f0 100644 --- a/wakatime/arguments.py +++ b/wakatime/arguments.py @@ -128,8 +128,6 @@ def parseArguments(): # parse ~/.wakatime.cfg file configs = parseConfigFile(args.config) - if configs is None: - return args, configs # update args from configs if not args.hostname: diff --git a/wakatime/configs.py b/wakatime/configs.py index fb399b6..9ff9ec0 100644 --- a/wakatime/configs.py +++ b/wakatime/configs.py @@ -13,10 +13,9 @@ from __future__ import print_function import os -import sys import traceback -from .compat import u, open +from .compat import open from .constants import CONFIG_FILE_PARSE_ERROR @@ -48,8 +47,7 @@ def parseConfigFile(configFile=None): configs.read_file(fh) except configparser.Error: print(traceback.format_exc()) - return None + raise SystemExit(CONFIG_FILE_PARSE_ERROR) except IOError: - sys.stderr.write(u("Error: Could not read from config file {0}\n").format(u(configFile))) - raise SystemExit(CONFIG_FILE_PARSE_ERROR) + pass return configs diff --git a/wakatime/main.py b/wakatime/main.py index c040b79..136ff6e 100644 --- a/wakatime/main.py +++ b/wakatime/main.py @@ -29,7 +29,6 @@ from .compat import u, is_py3 from .constants import ( API_ERROR, AUTH_ERROR, - CONFIG_FILE_PARSE_ERROR, SUCCESS, UNKNOWN_ERROR, MALFORMED_HEARTBEAT_ERROR, @@ -293,8 +292,6 @@ def execute(argv=None): sys.argv = ['wakatime'] + argv args, configs = parseArguments() - if configs is None: - return CONFIG_FILE_PARSE_ERROR setup_logging(args, __version__)