def test_push_handles_connection_exception(self): with tempfile.NamedTemporaryFile() as fh: with utils.mock.patch('wakatime.offlinequeue.Queue.get_db_file') as mock_db_file: mock_db_file.return_value = fh.name response = Response() response.status_code = 500 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/codefiles/twolinefile.txt' config = 'tests/samples/configs/sample.cfg' with utils.mock.patch('wakatime.offlinequeue.Queue.connect') as mock_connect: mock_connect.side_effect = sqlite3.Error('') args = ['--file', entity, '--config', config, '--time', now] execute(args) response.status_code = 201 execute(args) queue = Queue() saved_heartbeat = queue.pop() self.assertEquals(None, saved_heartbeat)
def test_get_project_not_used_when_project_names_hidden(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) now = u(int(time.time())) entity = os.path.join(tempdir, 'git', 'emptyfile.txt') config = 'tests/samples/configs/good_config.cfg' args = ['--hide-project-names', '--file', entity, '--config', config, '--time', now] execute(args) self.assertHeartbeatSavedOffline() self.assertNotEquals('git', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) self.assertEquals(None, self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['branch']) proj = open(os.path.join(tempdir, 'git', '.wakatime-project')).read() self.assertEquals(proj, self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) execute(args) self.assertEquals(proj, self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project'])
def test_alternate_project_argument_used_when_project_not_detected(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response tempdir = tempfile.mkdtemp() entity = 'tests/samples/projects/git/emptyfile.txt' shutil.copy(entity, os.path.join(tempdir, 'emptyfile.txt')) now = u(int(time.time())) entity = os.path.join(tempdir, 'emptyfile.txt') config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--time', now] execute(args) args = ['--file', entity, '--config', config, '--time', now, '--alternate-project', 'alt-project'] execute(args) calls = self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].call_args_list body = calls[0][0][0].body data = json.loads(body)[0] self.assertEquals(None, data.get('project')) body = calls[1][0][0].body data = json.loads(body)[0] self.assertEquals('alt-project', data['project'])
def test_push_handles_exception_on_close(self, logs): logging.disable(logging.NOTSET) with NamedTemporaryFile() as fh: with mock.patch('wakatime.offlinequeue.Queue._get_db_file') as mock_db_file: mock_db_file.return_value = fh.name response = Response() response.status_code = 500 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/codefiles/twolinefile.txt' config = 'tests/samples/configs/good_config.cfg' mock_conn = mock.MagicMock() mock_conn.close.side_effect = sqlite3.Error('') mock_c = mock.MagicMock() mock_c.fetchone.return_value = None with mock.patch('wakatime.offlinequeue.Queue.connect') as mock_connect: mock_connect.return_value = (mock_conn, mock_c) args = ['--file', entity, '--config', config, '--time', now] execute(args) response.status_code = 201 execute(args) queue = Queue(None, None) saved_heartbeat = queue.pop() self.assertEquals(None, saved_heartbeat) self.assertNothingPrinted()
def test_heartbeat_saved_from_result_index_error(self, logs): logging.disable(logging.NOTSET) with NamedTemporaryFile() as fh: with mock.patch('wakatime.offlinequeue.Queue._get_db_file') as mock_db_file: mock_db_file.return_value = fh.name response = CustomResponse() response.response_text = '{"responses": [[{"id":1}]]}' self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/codefiles/twolinefile.txt' config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--time', now] execute(args) queue = Queue(None, None) saved_heartbeat = queue.pop() self.assertPathsEqual(os.path.realpath(entity), saved_heartbeat['entity']) self.assertNothingPrinted() expected = 'IndexError' actual = self.getLogOutput(logs) self.assertIn(expected, actual)
def test_config_file_not_passed_in_command_line_args(self): self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = CustomResponse() with TemporaryDirectory() as tempdir: 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, '--log-file', '~/.wakatime.log'] with mock.patch('wakatime.configs.os.environ.get') as mock_env: mock_env.return_value = None with mock.patch('wakatime.configs.open') as mock_open: mock_open.side_effect = IOError('') with self.assertRaises(SystemExit) as e: execute(args) self.assertEquals(int(str(e.exception)), AUTH_ERROR) expected_stdout = u('') expected_stderr = open('tests/samples/output/common_usage_header').read() 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_log_file_location_can_be_set_from_env_variable(self, logs): logging.disable(logging.NOTSET) response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) with utils.TemporaryDirectory() as tempdir: entity = 'tests/samples/codefiles/python.py' shutil.copy(entity, os.path.join(tempdir, 'python.py')) entity = os.path.realpath(os.path.join(tempdir, 'python.py')) config = 'tests/samples/configs/good_config.cfg' shutil.copy(config, os.path.join(tempdir, '.wakatime.cfg')) config = os.path.realpath(os.path.join(tempdir, '.wakatime.cfg')) expected_logfile = os.path.realpath(os.path.join(tempdir, '.wakatime.log')) with utils.mock.patch('wakatime.main.os.environ.get') as mock_env: mock_env.return_value = tempdir args = ['--file', entity, '--config', config, '--time', now] execute(args) retval = execute(args) self.assertEquals(retval, 102) self.assertNothingPrinted() self.assertEquals(logging.WARNING, logging.getLogger('WakaTime').level) logfile = os.path.realpath(logging.getLogger('WakaTime').handlers[0].baseFilename) self.assertEquals(logfile, expected_logfile) logs.check()
def test_bad_config_file(self, logs): logging.disable(logging.NOTSET) with TemporaryDirectory() as tempdir: 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')) config = 'tests/samples/configs/bad_config.cfg' args = ['--file', entity, '--config', config, '--log-file', '~/.wakatime.log'] with self.assertRaises(SystemExit) as e: execute(args) self.assertEquals(int(str(e.exception)), CONFIG_FILE_PARSE_ERROR) self.assertIn('ParsingError', sys.stdout.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() self.patched['wakatime.session_cache.SessionCache.save'].assert_not_called()
def test_unhandled_exception(self, logs): logging.disable(logging.NOTSET) with utils.mock.patch('wakatime.main.send_heartbeats') as mock_send: ex_msg = 'testing unhandled exception' mock_send.side_effect = RuntimeError(ex_msg) entity = 'tests/samples/codefiles/twolinefile.txt' config = 'tests/samples/configs/good_config.cfg' key = str(uuid.uuid4()) args = ['--entity', entity, '--key', key, '--config', config] execute(args) self.assertIn(ex_msg, sys.stdout.getvalue()) self.assertEquals(sys.stderr.getvalue(), '') log_output = u("\n").join([u(' ').join(x) for x in logs.actual()]) self.assertIn(ex_msg, log_output) self.assertHeartbeatNotSent() self.assertHeartbeatNotSavedOffline() self.assertOfflineHeartbeatsNotSynced() self.assertSessionCacheUntouched()
def test_heartbeat_saved_when_requests_raises_exception(self, logs): logging.disable(logging.NOTSET) with tempfile.NamedTemporaryFile() as fh: with utils.mock.patch('wakatime.offlinequeue.Queue.get_db_file') as mock_db_file: mock_db_file.return_value = fh.name exception_msg = u("Oops, requests raised an exception. You're move.") self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].side_effect = AttributeError(exception_msg) now = u(int(time.time())) entity = 'tests/samples/codefiles/twolinefile.txt' config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--time', now] execute(args) queue = Queue() saved_heartbeat = queue.pop() self.assertEquals(os.path.realpath(entity), saved_heartbeat['entity']) self.assertEquals(sys.stdout.getvalue(), '') self.assertEquals(sys.stderr.getvalue(), '') output = [u(' ').join(x) for x in logs.actual()] self.assertIn(exception_msg, output[0]) self.patched['wakatime.session_cache.SessionCache.get'].assert_called_once_with() self.patched['wakatime.session_cache.SessionCache.delete'].assert_has_calls([call(), call()]) self.patched['wakatime.session_cache.SessionCache.save'].assert_not_called()
def test_ioerror_when_reading_mercurial_branch(self, logs): logging.disable(logging.NOTSET) response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with mock.patch('wakatime.projects.git.Git.process') as mock_git: mock_git.return_value = False now = u(int(time.time())) entity = 'tests/samples/projects/hg/emptyfile.txt' config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--time', now] with mock.patch('wakatime.projects.mercurial.open') as mock_open: mock_open.side_effect = IOError('') execute(args) self.assertEquals('hg', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project']) self.assertEquals('default', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['branch']) self.assertNothingPrinted() actual = self.getLogOutput(logs) expected = 'OSError' if self.isPy33OrNewer else 'IOError' self.assertIn(expected, actual)
def test_invalid_proxy(self, logs): logging.disable(logging.NOTSET) response = CustomResponse() self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with utils.TemporaryDirectory() as tempdir: 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')) proxy = 'invaliddd:proxyarg' config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--proxy', proxy] with self.assertRaises(SystemExit) as e: execute(args) self.assertEquals(int(str(e.exception)), 2) self.assertEquals(sys.stdout.getvalue(), '') expected = 'error: Invalid proxy. Must be in format https://user:pass@host:port or socks5://user:pass@host:port or domain\\user:pass.' 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() self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].assert_not_called()
def test_nonascii_heartbeat_saved(self, logs): logging.disable(logging.NOTSET) with NamedTemporaryFile() as fh: with mock.patch('wakatime.offlinequeue.Queue._get_db_file') as mock_db_file: mock_db_file.return_value = fh.name response = Response() response.status_code = 500 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with TemporaryDirectory() as tempdir: filename = list(filter(lambda x: x.endswith('.txt'), os.listdir(u('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())) config = 'tests/samples/configs/good_config.cfg' key = str(uuid.uuid4()) language = 'lang汉语' if self.isPy35OrNewer else 'lang\xe6\xb1\x89\xe8\xaf\xad' project = 'proj汉语' if self.isPy35OrNewer else 'proj\xe6\xb1\x89\xe8\xaf\xad' branch = 'branch汉语' if self.isPy35OrNewer else 'branch\xe6\xb1\x89\xe8\xaf\xad' heartbeat = { 'language': u(language), 'lines': 0, 'entity': os.path.realpath(entity), 'project': u(project), 'branch': u(branch), 'time': float(now), 'type': 'file', 'is_write': False, 'user_agent': ANY, 'dependencies': [], } args = ['--file', entity, '--key', key, '--config', config, '--time', now] with mock.patch('wakatime.stats.standardize_language') as mock_language: mock_language.return_value = language with mock.patch('wakatime.heartbeat.get_project_info') as mock_project: mock_project.return_value = (project, branch) execute(args) self.assertNothingPrinted() self.assertNothingLogged(logs) self.assertHeartbeatSent(heartbeat) queue = Queue(None, None) saved_heartbeat = queue.pop() self.assertPathsEqual(os.path.realpath(entity), saved_heartbeat['entity']) self.assertEquals(u(language), saved_heartbeat['language']) self.assertEquals(u(project), saved_heartbeat['project']) self.assertEquals(u(branch), saved_heartbeat['branch'])
def test_help_contents(self): args = ['--help'] with self.assertRaises(SystemExit): execute(args) expected_stdout = open('tests/samples/output/test_help_contents').read() self.assertEquals(sys.stdout.getvalue(), expected_stdout) self.assertEquals(sys.stderr.getvalue(), '') self.patched['wakatime.offlinequeue.Queue.push'].assert_not_called() self.patched['wakatime.offlinequeue.Queue.pop'].assert_not_called()
def test_missing_config_file(self): config = 'foo' entity = 'tests/samples/codefiles/emptyfile.txt' args = ['--file', entity, '--config', config] with self.assertRaises(SystemExit): execute(args) expected_stdout = u("Error: Could not read from config file foo\n") expected_stderr = open('tests/samples/output/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_project_map_group_usage(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/projects/project_map42/emptyfile.txt' config = 'tests/samples/configs/project_map.cfg' args = ['--file', entity, '--config', config, '--time', now] execute(args) self.assertEquals('proj-map42', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project'])
def test_project_argument_overrides_detected_project(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/projects/git/emptyfile.txt' config = 'tests/samples/configs/good_config.cfg' args = ['--project', 'forced-project', '--file', entity, '--config', config, '--time', now] execute(args) self.assertEquals('forced-project', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['project'])
def test_heartbeat_discarded_from_400_response(self): response = Response() response.status_code = 400 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/codefiles/twolinefile.txt' config = 'tests/samples/configs/sample.cfg' args = ['--file', entity, '--config', config, '--time', now] execute(args) queue = Queue() saved_heartbeat = queue.pop() self.assertEquals(None, saved_heartbeat)
def test_go_dependencies_detected(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with utils.TemporaryDirectory() as tempdir: entity = 'tests/samples/codefiles/go.go' shutil.copy(entity, os.path.join(tempdir, 'go.go')) entity = os.path.realpath(os.path.join(tempdir, 'go.go')) now = u(int(time.time())) config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--time', now] retval = execute(args) self.assertEquals(retval, 102) self.assertEquals(sys.stdout.getvalue(), '') self.assertEquals(sys.stderr.getvalue(), '') 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': u('Go'), 'lines': 24, 'entity': os.path.realpath(entity), 'project': u(os.path.basename(os.path.realpath('.'))), 'dependencies': ANY, 'time': float(now), 'type': 'file', } stats = { u('cursorpos'): None, u('dependencies'): ANY, u('language'): u('Go'), u('lineno'): None, u('lines'): 24, } expected_dependencies = [ '"compress/gzip"', '"direct"', '"foobar"', '"github.com/golang/example/stringutil"', '"image/gif"', '"log"', '"math"', '"oldname"', '"os"', '"supress"', ] 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) dependencies = self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['dependencies'] self.assertListsEqual(dependencies, expected_dependencies) 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_php_dependencies_detected(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with utils.TemporaryDirectory() as tempdir: entity = 'tests/samples/codefiles/php.php' shutil.copy(entity, os.path.join(tempdir, 'php.php')) entity = os.path.realpath(os.path.join(tempdir, 'php.php')) now = u(int(time.time())) config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--time', now] retval = execute(args) self.assertEquals(retval, 102) self.assertEquals(sys.stdout.getvalue(), '') self.assertEquals(sys.stderr.getvalue(), '') 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': u('PHP'), 'lines': ANY, 'entity': os.path.realpath(entity), 'dependencies': ANY, 'project': u(os.path.basename(os.path.realpath('.'))), 'time': float(now), 'type': 'file', } stats = { u('cursorpos'): None, u('dependencies'): ANY, u('language'): u('PHP'), u('lineno'): None, u('lines'): ANY, } expected_dependencies = [ 'Interop', 'FooBarOne', 'FooBarTwo', 'FooBarThree', 'FooBarFour', 'FooBarSeven', 'FooBarEight', 'ArrayObject', "'ServiceLocator.php'", "'ServiceLocatorTwo.php'", ] 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])) dependencies = self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['dependencies'] self.assertListsEqual(dependencies, expected_dependencies) self.patched['wakatime.offlinequeue.Queue.pop'].assert_not_called()
def test_timezone_header(self): response = Response() response.status_code = 201 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with utils.TemporaryDirectory() as tempdir: 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')) config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config] retval = execute(args) self.assertEquals(retval, SUCCESS) self.assertEquals(sys.stdout.getvalue(), '') self.assertEquals(sys.stderr.getvalue(), '') self.patched['wakatime.session_cache.SessionCache.get'].assert_called_once_with() self.patched['wakatime.session_cache.SessionCache.delete'].assert_not_called() self.patched['wakatime.session_cache.SessionCache.save'].assert_called_once_with(ANY) self.patched['wakatime.offlinequeue.Queue.push'].assert_not_called() self.patched['wakatime.offlinequeue.Queue.pop'].assert_called_once_with() timezone = tzlocal.get_localzone() headers = self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].call_args[0][0].headers self.assertEquals(headers.get('TimeZone'), u(timezone.zone).encode('utf-8') if is_py3 else timezone.zone)
def test_nonascii_timezone(self): response = Response() response.status_code = 201 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with utils.TemporaryDirectory() as tempdir: 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')) package_path = 'wakatime.packages.py3.tzlocal.get_localzone' if is_py3 else 'wakatime.packages.py2.tzlocal.get_localzone' timezone = tzlocal.get_localzone() timezone.zone = 'tz汉语' if is_py3 else 'tz\xe6\xb1\x89\xe8\xaf\xad' with utils.mock.patch(package_path) as mock_getlocalzone: mock_getlocalzone.return_value = timezone config = 'tests/samples/configs/has_everything.cfg' args = ['--file', entity, '--config', config, '--timeout', '15'] retval = execute(args) self.assertEquals(retval, SUCCESS) self.patched['wakatime.session_cache.SessionCache.get'].assert_called_once_with() self.patched['wakatime.session_cache.SessionCache.delete'].assert_not_called() self.patched['wakatime.session_cache.SessionCache.save'].assert_called_once_with(ANY) self.patched['wakatime.offlinequeue.Queue.push'].assert_not_called() self.patched['wakatime.offlinequeue.Queue.pop'].assert_called_once_with() headers = self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].call_args[0][0].headers self.assertEquals(headers.get('TimeZone'), u(timezone.zone).encode('utf-8') if is_py3 else timezone.zone)
def test_hostname_set_from_config_file(self): response = Response() response.status_code = 201 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with utils.TemporaryDirectory() as tempdir: 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')) hostname = 'fromcfgfile' config = 'tests/samples/configs/has_everything.cfg' args = ['--file', entity, '--config', config, '--timeout', '15'] retval = execute(args) self.assertEquals(retval, SUCCESS) self.patched['wakatime.session_cache.SessionCache.get'].assert_called_once_with() self.patched['wakatime.session_cache.SessionCache.delete'].assert_not_called() self.patched['wakatime.session_cache.SessionCache.save'].assert_called_once_with(ANY) self.patched['wakatime.offlinequeue.Queue.push'].assert_not_called() self.patched['wakatime.offlinequeue.Queue.pop'].assert_called_once_with() headers = self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].call_args[0][0].headers self.assertEquals(headers.get('X-Machine-Name'), hostname.encode('utf-8') if is_py3 else hostname)
def test_ntlm_proxy_used_after_trying_normal_proxy(self): response = Response() response.status_code = 400 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with utils.TemporaryDirectory() as tempdir: 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')) proxy = 'domain\\user:pass' config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--proxy', proxy] retval = execute(args) self.assertEquals(retval, API_ERROR) self.assertEquals(sys.stdout.getvalue(), '') self.assertEquals(sys.stderr.getvalue(), '') self.patched['wakatime.session_cache.SessionCache.get'].assert_has_calls([call(), call()]) self.patched['wakatime.session_cache.SessionCache.delete'].assert_called_once_with() 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() expected_calls = [ call(ANY, cert=None, proxies={'https': proxy}, stream=False, timeout=60, verify=True), call(ANY, cert=None, proxies={}, stream=False, timeout=60, verify=True), ] self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].assert_has_calls(expected_calls)
def shared(self, expected_project='', expected_branch=ANY, entity='', config='good_config.cfg', extra_args=[]): self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = CustomResponse() config = os.path.join('tests/samples/configs', config) if not os.path.exists(entity): entity = os.path.realpath(os.path.join('tests/samples', entity)) now = u(int(time.time())) args = ['--file', entity, '--config', config, '--time', now] + extra_args retval = execute(args) self.assertEquals(retval, SUCCESS) self.assertNothingPrinted() heartbeat = { 'language': ANY, 'lines': ANY, 'entity': os.path.realpath(entity), 'project': expected_project, 'branch': expected_branch, 'dependencies': ANY, 'time': float(now), 'type': 'file', 'is_write': False, 'user_agent': ANY, } self.assertHeartbeatSent(heartbeat) self.assertHeartbeatNotSavedOffline() self.assertOfflineHeartbeatsSynced() self.assertSessionCacheSaved()
def test_nonascii_hostname(self): response = Response() response.status_code = 201 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with utils.TemporaryDirectory() as tempdir: 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')) hostname = 'test汉语' if is_py3 else 'test\xe6\xb1\x89\xe8\xaf\xad' with utils.mock.patch('socket.gethostname') as mock_gethostname: mock_gethostname.return_value = hostname self.assertEquals(type(hostname).__name__, 'str') config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config] retval = execute(args) self.assertEquals(retval, SUCCESS) self.assertEquals(sys.stdout.getvalue(), '') self.assertEquals(sys.stderr.getvalue(), '') self.patched['wakatime.session_cache.SessionCache.get'].assert_called_once_with() self.patched['wakatime.session_cache.SessionCache.delete'].assert_not_called() self.patched['wakatime.session_cache.SessionCache.save'].assert_called_once_with(ANY) self.patched['wakatime.offlinequeue.Queue.push'].assert_not_called() self.patched['wakatime.offlinequeue.Queue.pop'].assert_called_once_with() headers = self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].call_args[0][0].headers self.assertEquals(headers.get('X-Machine-Name'), hostname.encode('utf-8') if is_py3 else hostname)
def test_guess_lexer_using_filename_analyse_text_exception(self, logs): logging.disable(logging.NOTSET) self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = CustomResponse() with NamedTemporaryFile() as fh: with mock.patch('wakatime.offlinequeue.Queue._get_db_file') as mock_db_file: mock_db_file.return_value = fh.name mock_analyse = mock.MagicMock() mock_analyse.analyse_text.side_effect = Exception('foobar') with mock.patch('wakatime.stats.custom_pygments_guess_lexer_for_filename') as mock_lexer: mock_lexer.return_value = mock_analyse entity = os.path.realpath('tests/samples/codefiles/python.py') args = ['--file', entity, '--key', str(uuid.uuid4()), '--config', 'tests/samples/configs/good_config.cfg', '--time', u(int(time.time()))] retval = execute(args) self.assertEquals(retval, SUCCESS) self.assertNothingPrinted() self.assertNothingLogged(logs) heartbeat = { 'entity': entity, 'language': ANY, 'lines': ANY, 'project': ANY, 'branch': ANY, 'time': ANY, 'type': 'file', 'is_write': ANY, 'user_agent': ANY, 'dependencies': ANY, } self.assertHeartbeatSent(heartbeat)
def test_verbose_flag_enables_verbose_logging(self, logs): logging.disable(logging.NOTSET) response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/codefiles/python.py' config = 'tests/samples/configs/has_regex_errors.cfg' args = ['--file', entity, '--config', config, '--time', now, '--verbose'] retval = execute(args) self.assertEquals(retval, 102) self.assertNothingPrinted() self.assertEquals(logging.DEBUG, logging.getLogger('WakaTime').level) logfile = os.path.realpath(os.path.expanduser('~/.wakatime.log')) self.assertEquals(logfile, logging.getLogger('WakaTime').handlers[0].baseFilename) output = [u(' ').join(x) for x in logs.actual()] expected = u('WakaTime WARNING Regex error (unbalanced parenthesis) for include pattern: \\(invalid regex)') if self.isPy35OrNewer: expected = u('WakaTime WARNING Regex error (unbalanced parenthesis at position 15) for include pattern: \\(invalid regex)') self.assertEquals(output[0], expected) expected = u('WakaTime WARNING Regex error (unbalanced parenthesis) for exclude pattern: \\(invalid regex)') if self.isPy35OrNewer: expected = u('WakaTime WARNING Regex error (unbalanced parenthesis at position 15) for exclude pattern: \\(invalid regex)') self.assertEquals(output[1], expected) self.assertEquals(output[2], u('WakaTime DEBUG Sending heartbeats to api at https://api.wakatime.com/api/v1/users/current/heartbeats.bulk')) self.assertIn('Python', output[3]) self.assertIn('response_code', output[4])
def test_socks_proxy(self): response = CustomResponse() self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with utils.TemporaryDirectory() as tempdir: 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')) proxy = 'socks5://user:pass@localhost:12345' config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--proxy', proxy] retval = execute(args) self.assertEquals(retval, SUCCESS) self.assertEquals(sys.stdout.getvalue(), '') self.assertEquals(sys.stderr.getvalue(), '') self.patched['wakatime.session_cache.SessionCache.get'].assert_called_once_with() self.patched['wakatime.session_cache.SessionCache.delete'].assert_not_called() self.patched['wakatime.session_cache.SessionCache.save'].assert_called_once_with(ANY) self.patched['wakatime.offlinequeue.Queue.push'].assert_not_called() self.patched['wakatime.offlinequeue.Queue.pop'].assert_called_once_with() self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].assert_called_once_with(ANY, cert=None, proxies={'https': proxy}, stream=False, timeout=60, verify=True)
def test_default_log_file_used(self, logs): logging.disable(logging.NOTSET) response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/codefiles/python.py' config = 'tests/samples/configs/has_regex_errors.cfg' args = ['--file', entity, '--config', config, '--time', now] retval = execute(args) self.assertEquals(retval, 102) self.assertNothingPrinted() self.assertEquals(logging.WARNING, logging.getLogger('WakaTime').level) logfile = os.path.realpath(os.path.expanduser('~/.wakatime.log')) self.assertEquals(logfile, logging.getLogger('WakaTime').handlers[0].baseFilename) output = [u(' ').join(x) for x in logs.actual()] expected = u('WakaTime WARNING Regex error (unbalanced parenthesis) for include pattern: \\(invalid regex)') if self.isPy35OrNewer: expected = u('WakaTime WARNING Regex error (unbalanced parenthesis at position 15) for include pattern: \\(invalid regex)') self.assertEquals(output[0], expected) expected = u('WakaTime WARNING Regex error (unbalanced parenthesis) for exclude pattern: \\(invalid regex)') if self.isPy35OrNewer: expected = u('WakaTime WARNING Regex error (unbalanced parenthesis at position 15) for exclude pattern: \\(invalid regex)') self.assertEquals(output[1], expected)
def test_500_response_without_offline_logging(self, logs): logging.disable(logging.NOTSET) response = Response() response.status_code = 500 response._content = 'fake content' if is_py3: response._content = 'fake content'.encode('utf8') self.patched[ 'wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with utils.TemporaryDirectory() as tempdir: entity = 'tests/samples/codefiles/twolinefile.txt' shutil.copy(entity, os.path.join(tempdir, 'twolinefile.txt')) entity = os.path.realpath(os.path.join(tempdir, 'twolinefile.txt')) now = u(int(time.time())) key = str(uuid.uuid4()) args = [ '--file', entity, '--key', key, '--disableoffline', '--config', 'tests/samples/configs/good_config.cfg', '--time', now ] retval = execute(args) self.assertEquals(retval, API_ERROR) self.assertEquals(sys.stdout.getvalue(), '') self.assertEquals(sys.stderr.getvalue(), '') log_output = u("\n").join([u(' ').join(x) for x in logs.actual()]) expected = "WakaTime ERROR {'response_code': 500, 'response_content': u'fake content'}" if log_output[-2] == '0': expected = "WakaTime ERROR {'response_content': u'fake content', 'response_code': 500}" if is_py3: expected = "WakaTime ERROR {'response_code': 500, 'response_content': 'fake content'}" if log_output[-2] == '0': expected = "WakaTime ERROR {'response_content': 'fake content', 'response_code': 500}" self.assertEquals(expected, log_output) self.patched[ 'wakatime.session_cache.SessionCache.delete'].assert_called_once_with( ) self.patched[ 'wakatime.session_cache.SessionCache.get'].assert_called_once_with( ) 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()
def test_nonascii_filename(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 = 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())) config = 'tests/samples/configs/good_config.cfg' key = str(uuid.uuid4()) args = ['--file', entity, '--key', key, '--config', config, '--time', now] retval = execute(args) self.assertEquals(retval, API_ERROR) self.assertEquals(sys.stdout.getvalue(), '') self.assertEquals(sys.stderr.getvalue(), '') output = [u(' ').join(x) for x in logs.actual()] self.assertEquals(len(output), 0) 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_app_heartbeat(self): response = Response() response.status_code = 0 self.patched[ 'wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response entity = 'Firefox' config = 'tests/samples/configs/good_config.cfg' now = u(int(time.time())) args = [ '--entity', entity, '--entitytype', 'app', '--config', config, '--time', now ] retval = execute(args) self.assertEquals(retval, API_ERROR) self.assertEquals(sys.stdout.getvalue(), '') self.assertEquals(sys.stderr.getvalue(), '') 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 = { 'entity': u(entity), 'time': float(now), 'type': 'app', } stats = { u('cursorpos'): None, u('dependencies'): [], u('language'): None, u('lineno'): None, u('lines'): None, } self.patched[ 'wakatime.offlinequeue.Queue.push'].assert_called_once_with( heartbeat, ANY, None) 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_io_error_when_parsing_dependencies(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with utils.TemporaryDirectory() as tempdir: entity = 'tests/samples/codefiles/python.py' shutil.copy(entity, os.path.join(tempdir, 'python.py')) entity = os.path.realpath(os.path.join(tempdir, 'python.py')) now = u(int(time.time())) config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--time', now] with utils.mock.patch('wakatime.dependencies.open') as mock_open: mock_open.side_effect = IOError('') retval = execute(args) self.assertEquals(retval, 102) self.assertEquals(sys.stdout.getvalue(), '') self.assertEquals(sys.stderr.getvalue(), '') 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': u('Python'), 'lines': 37, 'entity': os.path.realpath(entity), 'project': u(os.path.basename(os.path.realpath('.'))), 'time': float(now), 'type': 'file', } stats = { u('cursorpos'): None, u('dependencies'): [], u('language'): u('Python'), u('lineno'): None, u('lines'): 37, } expected_dependencies = [] 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) dependencies = self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0].get('dependencies', []) self.assertListsEqual(dependencies, expected_dependencies) 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_html_django_dependencies_detected(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with utils.TemporaryDirectory() as tempdir: entity = 'tests/samples/codefiles/html-django.html' shutil.copy(entity, os.path.join(tempdir, 'html-django.html')) entity = os.path.realpath(os.path.join(tempdir, 'html-django.html')) now = u(int(time.time())) config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--time', now] retval = execute(args) self.assertEquals(retval, 102) self.assertEquals(sys.stdout.getvalue(), '') self.assertEquals(sys.stderr.getvalue(), '') 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': u('HTML+Django/Jinja'), 'lines': ANY, 'dependencies': ANY, 'entity': os.path.realpath(entity), 'project': u(os.path.basename(os.path.realpath('.'))), 'time': float(now), 'type': 'file', } stats = { u('cursorpos'): None, u('dependencies'): ANY, u('language'): u('HTML+Django/Jinja'), u('lineno'): None, u('lines'): ANY, } expected_dependencies = [ '"libs/json2.js"', ] 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])) dependencies = self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['dependencies'] self.assertListsEqual(dependencies, expected_dependencies) self.patched['wakatime.offlinequeue.Queue.pop'].assert_not_called()
def test_does_not_hide_filenames_from_invalid_regex(self, logs): logging.disable(logging.NOTSET) self.patched[ 'wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = CustomResponse( ) with TemporaryDirectory() as tempdir: 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')) now = u(int(time.time())) config = 'tests/samples/configs/invalid_hide_file_names.cfg' key = str(uuid.uuid4()) args = [ '--file', entity, '--key', key, '--config', config, '--time', now, '--log-file', '~/.wakatime.log' ] retval = execute(args) self.assertEquals(retval, SUCCESS) self.assertNothingPrinted() actual = self.getLogOutput(logs) expected = u( 'WakaTime WARNING Regex error (unbalanced parenthesis) for include pattern: invalid(regex' ) if self.isPy35OrNewer: expected = 'WakaTime WARNING Regex error (missing ), unterminated subpattern at position 7) for include pattern: invalid(regex' self.assertEquals(expected, actual) heartbeat = { 'language': 'Text only', 'lines': 0, 'entity': os.path.realpath(entity), 'project': None, 'cursorpos': None, 'lineno': None, 'time': float(now), 'is_write': False, 'type': 'file', 'dependencies': [], 'user_agent': ANY, } self.assertHeartbeatSent(heartbeat) self.assertHeartbeatNotSavedOffline() self.assertOfflineHeartbeatsSynced() self.assertSessionCacheSaved()
def test_empty_project_can_be_saved(self): with NamedTemporaryFile() as fh: with mock.patch('wakatime.offlinequeue.Queue._get_db_file' ) as mock_db_file: mock_db_file.return_value = fh.name response = Response() response.status_code = 500 self.patched[ 'wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/codefiles/emptyfile.txt' config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--time', now] execute(args) queue = Queue(None, None) saved_heartbeat = queue.pop() self.assertNothingPrinted() self.assertPathsEqual(os.path.realpath(entity), saved_heartbeat['entity'])
def test_log_file_location_can_be_changed(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.NamedTemporaryFile() as fh: now = u(int(time.time())) entity = 'tests/samples/codefiles/python.py' config = 'tests/samples/configs/good_config.cfg' logfile = os.path.realpath(fh.name) args = ['--file', entity, '--config', config, '--time', now, '--log-file', logfile] execute(args) retval = execute(args) self.assertEquals(retval, 102) self.assertNothingPrinted() self.assertEquals(logging.WARNING, logging.getLogger('WakaTime').level) self.assertEquals(logfile, logging.getLogger('WakaTime').handlers[0].baseFilename) logs.check()
def test_bower_dependencies_detected(self): response = Response() response.status_code = 0 self.patched[ 'wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/codefiles/bower.json' config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--time', now] retval = execute(args) self.assertEquals(sys.stdout.getvalue(), '') self.assertEquals(sys.stderr.getvalue(), '') self.assertEquals(retval, 102) heartbeat = { 'language': u('JSON'), 'lines': 11, 'entity': os.path.realpath(entity), 'project': u(os.path.basename(os.path.realpath('.'))), 'dependencies': ANY, 'branch': os.environ.get('TRAVIS_COMMIT', ANY), 'time': float(now), 'type': 'file', } stats = { u('cursorpos'): None, u('dependencies'): ANY, u('language'): u('JSON'), u('lineno'): None, u('lines'): 11, } expected_dependencies = ['animate.css', 'moment', 'moment-timezone'] self.patched[ 'wakatime.offlinequeue.Queue.push'].assert_called_once_with( heartbeat, ANY, None) for dep in expected_dependencies: self.assertIn( dep, self.patched['wakatime.offlinequeue.Queue.push'].call_args[0] [0]['dependencies']) 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_project_map_allows_colon_in_key(self, logs): logging.disable(logging.NOTSET) response = Response() response.status_code = 0 self.patched[ 'wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/projects/project_map/emptyfile.txt' config = 'tests/samples/configs/project_map_with_colon_in_key.cfg' args = ['--file', entity, '--config', config, '--time', now] execute(args) self.assertEquals( 'proj-map-match', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0] ['project']) self.assertNothingPrinted() self.assertNothingLogged(logs)
def test_ntlm_proxy_used_after_trying_normal_proxy(self): response = Response() response.status_code = 400 self.patched[ 'wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with utils.TemporaryDirectory() as tempdir: 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')) proxy = 'domain\\user:pass' config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--proxy', proxy] retval = execute(args) self.assertEquals(retval, API_ERROR) self.assertEquals(sys.stdout.getvalue(), '') self.assertEquals(sys.stderr.getvalue(), '') self.patched[ 'wakatime.session_cache.SessionCache.get'].assert_has_calls( [call(), call()]) self.patched[ 'wakatime.session_cache.SessionCache.delete'].assert_called_once_with( ) 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() expected_calls = [ call(ANY, cert=None, proxies={'https': proxy}, stream=False, timeout=60, verify=True), call(ANY, cert=None, proxies={}, stream=False, timeout=60, verify=True), ] self.patched[ 'wakatime.packages.requests.adapters.HTTPAdapter.send'].assert_has_calls( expected_calls)
def test_alternate_project_argument_does_not_override_detected_project( self): response = Response() response.status_code = 0 self.patched[ 'wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/projects/git/emptyfile.txt' config = 'tests/samples/configs/good_config.cfg' project = os.path.basename(os.path.abspath('.')) args = [ '--alternate-project', 'alt-project', '--file', entity, '--config', config, '--time', now ] execute(args) self.assertEquals( project, self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0] ['project'])
def test_log_file_location_can_be_set_from_env_variable(self, logs): logging.disable(logging.NOTSET) response = Response() response.status_code = 0 self.patched[ 'wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) with utils.TemporaryDirectory() as tempdir: entity = 'tests/samples/codefiles/python.py' shutil.copy(entity, os.path.join(tempdir, 'python.py')) entity = os.path.realpath(os.path.join(tempdir, 'python.py')) config = 'tests/samples/configs/good_config.cfg' shutil.copy(config, os.path.join(tempdir, '.wakatime.cfg')) config = os.path.realpath(os.path.join(tempdir, '.wakatime.cfg')) expected_logfile = os.path.realpath( os.path.join(tempdir, '.wakatime.log')) with utils.mock.patch('wakatime.main.os.environ.get') as mock_env: mock_env.return_value = tempdir args = ['--file', entity, '--config', config, '--time', now] execute(args) retval = execute(args) self.assertEquals(retval, 102) self.assertNothingPrinted() self.assertEquals(logging.WARNING, logging.getLogger('WakaTime').level) logfile = os.path.realpath( logging.getLogger('WakaTime').handlers[0].baseFilename) self.assertEquals(logfile, expected_logfile) logs.check()
def test_csharp_dependencies_detected(self): response = Response() response.status_code = 0 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/codefiles/seesharp.cs' config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--time', now] retval = execute(args) self.assertEquals(retval, 102) self.assertEquals(sys.stdout.getvalue(), '') self.assertEquals(sys.stderr.getvalue(), '') 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': u('C#'), 'lines': 18, 'entity': os.path.realpath(entity), 'dependencies': ANY, 'project': u(os.path.basename(os.path.realpath('.'))), 'branch': os.environ.get('TRAVIS_COMMIT', ANY), 'time': float(now), 'type': 'file', } stats = { u('cursorpos'): None, u('dependencies'): ANY, u('language'): u('C#'), u('lineno'): None, u('lines'): 18, } expected_dependencies = [ 'Proper', 'Fart', 'Math', 'WakaTime', ] self.patched['wakatime.offlinequeue.Queue.push'].assert_called_once_with(heartbeat, ANY, None) self.assertEquals(stats, json.loads(self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][1])) dependencies = self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['dependencies'] self.assertListsEqual(dependencies, expected_dependencies) self.patched['wakatime.offlinequeue.Queue.pop'].assert_not_called()
def test_500_response_without_offline_logging(self, logs): logging.disable(logging.NOTSET) response = Response() response.status_code = 500 response._content = 'fake content' if is_py3: response._content = 'fake content'.encode('utf8') self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with utils.TemporaryDirectory() as tempdir: entity = 'tests/samples/codefiles/twolinefile.txt' shutil.copy(entity, os.path.join(tempdir, 'twolinefile.txt')) entity = os.path.realpath(os.path.join(tempdir, 'twolinefile.txt')) now = u(int(time.time())) key = str(uuid.uuid4()) heartbeat = { 'language': 'Text only', 'lines': 2, 'entity': entity, 'project': None, 'time': float(now), 'type': 'file', 'is_write': False, 'user_agent': ANY, 'dependencies': [], } args = ['--file', entity, '--key', key, '--disable-offline', '--config', 'tests/samples/configs/good_config.cfg', '--time', now] retval = execute(args) self.assertEquals(retval, API_ERROR) self.assertNothingPrinted() actual = self.getLogOutput(logs) expected = "WakaTime ERROR {'response_code': 500, 'response_content': u'fake content'}" if actual[-2] == '0': expected = "WakaTime ERROR {'response_content': u'fake content', 'response_code': 500}" if is_py3: expected = "WakaTime ERROR {'response_code': 500, 'response_content': 'fake content'}" if actual[-2] == '0': expected = "WakaTime ERROR {'response_content': 'fake content', 'response_code': 500}" self.assertEquals(expected, actual) self.assertHeartbeatSent(heartbeat) self.assertHeartbeatNotSavedOffline() self.assertOfflineHeartbeatsNotSynced() self.assertSessionCacheDeleted()
def test_invalid_api_key(self, logs): logging.disable(logging.NOTSET) self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = CustomResponse() config = 'tests/samples/configs/missing_api_key.cfg' args = ['--config', config, '--key', 'invalid-api-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.assertHeartbeatNotSent() self.assertHeartbeatNotSavedOffline() self.assertOfflineHeartbeatsNotSynced() self.assertSessionCacheUntouched()
def test_git_project_detected(self): response = Response() response.status_code = 0 self.patched[ 'wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response tempdir = tempfile.mkdtemp() shutil.copytree('tests/samples/projects/git', os.path.join(tempdir, 'git')) shutil.move(os.path.join(tempdir, 'git', 'dot_git'), os.path.join(tempdir, 'git', '.git')) now = u(int(time.time())) entity = os.path.join(tempdir, 'git', 'emptyfile.txt') config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--time', now] execute(args) self.assertEquals( 'git', self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0] ['project'])
def test_offline_heartbeat_sent_after_success_response(self): with utils.NamedTemporaryFile() as fh: with utils.mock.patch( 'wakatime.offlinequeue.Queue.get_db_file') as mock_db_file: mock_db_file.return_value = fh.name response = Response() response.status_code = 500 self.patched[ 'wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) entity = 'tests/samples/codefiles/twolinefile.txt' config = 'tests/samples/configs/good_config.cfg' args = ['--file', entity, '--config', config, '--time', now] execute(args) response.status_code = 201 execute(args) queue = Queue() saved_heartbeat = queue.pop() self.assertEquals(None, saved_heartbeat)
def test_guess_language_from_vim_modeline(self): response = Response() response.status_code = 500 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) config = 'tests/samples/configs/good_config.cfg' entity = 'tests/samples/codefiles/python_without_extension' args = ['--file', entity, '--config', config, '--time', now] retval = execute(args) self.assertEquals(retval, 102) language = u('Python') self.assertEqual(self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0].get('language'), language)
def test_matlab_detected_over_objectivec_when_mat_file_in_folder(self): response = Response() response.status_code = 500 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) config = 'tests/samples/configs/good_config.cfg' entity = 'tests/samples/codefiles/matlab/with_mat_files/empty.m' args = ['--file', entity, '--config', config, '--time', now] retval = execute(args) self.assertEquals(retval, 102) language = u('Matlab') self.assertEqual(self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0].get('language'), language)
def test_bad_config_file(self): entity = 'tests/samples/codefiles/emptyfile.txt' config = 'tests/samples/configs/bad_config.cfg' args = ['--file', entity, '--config', config] retval = execute(args) self.assertEquals(retval, 103) self.assertIn('ParsingError', sys.stdout.getvalue()) self.assertEquals(sys.stderr.getvalue(), '') 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() self.patched[ 'wakatime.session_cache.SessionCache.save'].assert_not_called()
def test_config_file_not_passed_in_command_line_args(self): response = Response() response.status_code = 201 self.patched[ 'wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with utils.mock.patch('wakatime.main.open') as mock_open: mock_open.side_effect = IOError('') config = os.path.join(os.path.expanduser('~'), '.wakatime.cfg') entity = 'tests/samples/codefiles/emptyfile.txt' args = ['--file', entity] with self.assertRaises(SystemExit): execute(args) expected_stdout = u( "Error: Could not read from config file {0}\n").format( u(config)) expected_stderr = open( 'tests/samples/output/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_bad_config_file(self, logs): logging.disable(logging.NOTSET) with TemporaryDirectory() as tempdir: 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')) config = 'tests/samples/configs/bad_config.cfg' args = [ '--file', entity, '--config', config, '--log-file', '~/.wakatime.log' ] with self.assertRaises(SystemExit) as e: execute(args) self.assertEquals(int(str(e.exception)), CONFIG_FILE_PARSE_ERROR) self.assertIn('ParsingError', sys.stdout.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( ) self.patched[ 'wakatime.session_cache.SessionCache.save'].assert_not_called( )
def test_config_file_not_passed_in_command_line_args(self): response = Response() response.status_code = 201 self.patched[ 'wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response with utils.TemporaryDirectory() as tempdir: 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')) with utils.mock.patch( 'wakatime.configs.os.environ.get') as mock_env: mock_env.return_value = None 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( )
def test_fsharp_detected_over_forth(self): response = Response() response.status_code = 500 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) config = 'tests/samples/configs/good_config.cfg' entity = 'tests/samples/codefiles/fsharp.fs' args = ['--file', entity, '--config', config, '--time', now] retval = execute(args) self.assertEquals(retval, 102) language = u('F#') self.assertEqual(self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0].get('language'), language)
def test_invalid_timeout_passed_via_command_line(self, logs): logging.disable(logging.NOTSET) self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = CustomResponse() with TemporaryDirectory() as tempdir: entity = 'tests/samples/codefiles/twolinefile.txt' shutil.copy(entity, os.path.join(tempdir, 'twolinefile.txt')) entity = os.path.realpath(os.path.join(tempdir, 'twolinefile.txt')) config = 'tests/samples/configs/good_config.cfg' key = str(uuid.uuid4()) args = ['--file', entity, '--key', key, '--config', config, '--timeout', 'abc'] with self.assertRaises(SystemExit) as e: execute(args) self.assertNothingLogged(logs) self.assertEquals(int(str(e.exception)), 2) self.assertEquals(sys.stdout.getvalue(), '') expected_stderr = open('tests/samples/output/main_test_timeout_passed_via_command_line').read() self.assertEquals(sys.stderr.getvalue(), expected_stderr) self.patched['wakatime.offlinequeue.Queue.push'].assert_not_called() self.patched['wakatime.offlinequeue.Queue.pop'].assert_not_called() self.patched['wakatime.session_cache.SessionCache.get'].assert_not_called()
def test_c_not_detected_for_non_header_with_c_files_in_folder(self): response = Response() response.status_code = 500 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) config = 'tests/samples/configs/good_config.cfg' entity = 'tests/samples/codefiles/c_and_python/see.py' args = ['--file', entity, '--config', config, '--time', now] retval = execute(args) self.assertEquals(retval, 102) language = u('Python') self.assertEqual(self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0].get('language'), language)
def test_unhandled_exception(self, logs): logging.disable(logging.NOTSET) with utils.mock.patch('wakatime.main.process_heartbeat') as mock_process_heartbeat: ex_msg = 'testing unhandled exception' mock_process_heartbeat.side_effect = RuntimeError(ex_msg) entity = 'tests/samples/codefiles/twolinefile.txt' config = 'tests/samples/configs/good_config.cfg' key = str(uuid.uuid4()) args = ['--entity', entity, '--key', key, '--config', config] execute(args) self.assertIn(ex_msg, sys.stdout.getvalue()) self.assertEquals(sys.stderr.getvalue(), '') log_output = u("\n").join([u(' ').join(x) for x in logs.actual()]) self.assertIn(ex_msg, log_output) self.patched['wakatime.offlinequeue.Queue.push'].assert_not_called() self.patched['wakatime.offlinequeue.Queue.pop'].assert_not_called() self.patched['wakatime.session_cache.SessionCache.get'].assert_not_called()
def test_alternate_language_takes_priority_over_detected_language(self): response = Response() response.status_code = 500 self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response now = u(int(time.time())) config = 'tests/samples/configs/good_config.cfg' entity = 'tests/samples/codefiles/python.py' args = ['--file', entity, '--config', config, '--time', now, '--language', 'JAVA'] retval = execute(args) self.assertEquals(retval, 102) language = u('Java') self.assertEqual(self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0].get('language'), language)
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 config = 'tests/samples/configs/missing_api_key.cfg' args = ['--config', config, '--key', 'invalid-api-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() self.patched[ 'wakatime.packages.requests.adapters.HTTPAdapter.send'].assert_not_called( )