Пример #1
0
    def test_does_not_hide_unmatching_filenames(self):
        self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = CustomResponse()

        with 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/hide_file_names_not_python.cfg'
            key = u(uuid.uuid4())
            dependencies = ['sqlalchemy', 'jinja', 'simplejson', 'flask', 'app', 'django', 'pygments', 'unittest', 'mock']
            project = 'abcxyz'

            args = ['--file', entity, '--key', key, '--config', config, '--time', now, '--log-file', '~/.wakatime.log', '--alternate-project', project]

            retval = execute(args)
            self.assertEquals(retval, SUCCESS)
            self.assertNothingPrinted()

            heartbeat = {
                'language': 'Python',
                'lines': 37,
                'entity': entity,
                'project': project,
                'time': float(now),
                'is_write': False,
                'type': 'file',
                'dependencies': dependencies,
                'user_agent': ANY,
            }
            self.assertHeartbeatSent(heartbeat)

            self.assertHeartbeatNotSavedOffline()
            self.assertOfflineHeartbeatsSynced()
            self.assertSessionCacheSaved()
Пример #2
0
    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/sample.cfg'
        args = ['--file', entity, '--config', config, '--time', now, '--verbose']

        retval = execute(args)
        self.assertEquals(retval, 102)
        self.assertEquals(sys.stdout.getvalue(), '')
        self.assertEquals(sys.stderr.getvalue(), '')

        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()]
        self.assertEquals(output[0], u('WakaTime WARNING Regex error (unbalanced parenthesis) for include pattern: \\(invalid regex)'))
        self.assertEquals(output[1], u('WakaTime WARNING Regex error (unbalanced parenthesis) for exclude pattern: \\(invalid regex)'))
        self.assertEquals(output[2], u('WakaTime DEBUG Sending heartbeat to api at https://wakatime.com/api/v1/heartbeats'))
        self.assertIn('Python', output[3])
        self.assertIn('response_code', output[4])
Пример #3
0
    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()
Пример #4
0
    def test_legacy_hidefilenames_config_supported(self):
        self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = CustomResponse()

        with 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/paranoid_legacy.cfg'
            key = u(uuid.uuid4())
            project = 'abcxyz'

            args = ['--file', entity, '--key', key, '--config', config, '--time', now, '--log-file', '~/.wakatime.log', '--alternate-project', project]

            retval = execute(args)
            self.assertEquals(retval, SUCCESS)
            self.assertNothingPrinted()

            heartbeat = {
                'language': 'Python',
                'lines': None,
                'entity': 'HIDDEN.py',
                'project': project,
                'time': float(now),
                'is_write': False,
                'type': 'file',
                'dependencies': None,
                'user_agent': ANY,
            }
            self.assertHeartbeatSent(heartbeat)

            self.assertHeartbeatNotSavedOffline()
            self.assertOfflineHeartbeatsSynced()
            self.assertSessionCacheSaved()
Пример #5
0
    def test_timezone_with_invalid_encoding(self):
        self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = CustomResponse()

        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'))

            class TZ(object):
                @property
                def zone(self):
                    return bytes('\xab', 'utf-16') if is_py3 else '\xab'
            timezone = TZ()

            with self.assertRaises(UnicodeDecodeError):
                timezone.zone.decode('utf8')

            with utils.mock.patch('wakatime.packages.tzlocal.get_localzone') as mock_getlocalzone:
                mock_getlocalzone.return_value = timezone

                timeout = 15
                config = 'tests/samples/configs/has_everything.cfg'
                args = ['--file', entity, '--config', config, '--timeout', u(timeout)]
                retval = execute(args)
                self.assertEquals(retval, SUCCESS)
                self.assertNothingPrinted()

                headers = {
                    'TimeZone': u(bytes('\xab', 'utf-16') if is_py3 else '\xab').encode('utf-8'),
                }
                self.assertHeartbeatSent(headers=headers, proxies=ANY, timeout=timeout)
                self.assertHeartbeatNotSavedOffline()
                self.assertOfflineHeartbeatsSynced()
                self.assertSessionCacheSaved()
Пример #6
0
    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()
Пример #7
0
    def test_requests_exception_without_offline_logging(self, logs):
        logging.disable(logging.NOTSET)

        self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].side_effect = RequestException('requests exception')

        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, '--disable-offline',
                    '--config', 'tests/samples/configs/good_config.cfg', '--time', now]

            retval = execute(args)
            self.assertEquals(retval, API_ERROR)
            self.assertNothingPrinted()

            log_output = u("\n").join([u(' ').join(x) for x in logs.actual()])
            expected = "WakaTime ERROR {'RequestException': u'requests exception'}"
            if is_py3:
                expected = "WakaTime ERROR {'RequestException': 'requests exception'}"
            self.assertEquals(expected, log_output)

            self.assertHeartbeatSent()
            self.assertHeartbeatNotSavedOffline()
            self.assertOfflineHeartbeatsNotSynced()
            self.assertSessionCacheDeleted()
Пример #8
0
    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()
Пример #9
0
    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()
Пример #10
0
    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()
Пример #11
0
    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()
Пример #12
0
    def test_python_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/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]

            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': 36,
                '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('Python'),
                u('lineno'): None,
                u('lines'): 36,
            }
            expected_dependencies = [
                'app',
                'django',
                'flask',
                'jinja',
                'mock',
                'pygments',
                'simplejson',
                'sqlalchemy',
                'unittest',
            ]

            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_python_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/python.py'
        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('Python'),
            'lines': 36,
            '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('Python'),
            u('lineno'): None,
            u('lines'): 36,
        }
        expected_dependencies = [
            'app',
            'django',
            'flask',
            'jinja',
            'mock',
            'os',
            'pygments',
            'simplejson',
            'sqlalchemy',
            'sys',
            'unittest',
        ]

        def normalize(items):
            return sorted([u(x) for x in items])

        self.patched['wakatime.offlinequeue.Queue.push'].assert_called_once_with(heartbeat, ANY, None)
        dependencies = self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]['dependencies']
        self.assertEquals(normalize(dependencies), normalize(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()
Пример #14
0
    def test_cpp_language_detected_for_header_with_c_and_cpp_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_cpp/empty.h'
        args = ['--file', entity, '--config', config, '--time', now]

        retval = execute(args)
        self.assertEquals(retval, 102)

        language = u('C++')
        self.assertEqual(self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0].get('language'), language)
Пример #15
0
    def test_alternate_language_not_used_when_guessed(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, '--alternate-language', 'java']

        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)
Пример #16
0
    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)
Пример #17
0
    def test_cpp_language_detected_for_header_with_c_and_cpp_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_cpp/empty.h"
        args = ["--file", entity, "--config", config, "--time", now]

        retval = execute(args)
        self.assertEquals(retval, 102)

        language = u("C++")
        self.assertEqual(self.patched["wakatime.offlinequeue.Queue.push"].call_args[0][0]["language"], language)
Пример #18
0
    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)
Пример #19
0
    def test_400_response(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/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()))

            args = ['--file', entity, '--key', '123',
                    '--config', 'tests/samples/configs/paranoid.cfg', '--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.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()
Пример #20
0
    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)
Пример #21
0
    def test_can_log_invalid_utf8(self, logs):
        logging.disable(logging.NOTSET)

        data = bytes('\xab', 'utf-16') if is_py3 else '\xab'

        with self.assertRaises(UnicodeDecodeError):
            data.decode('utf8')

        logger = logging.getLogger('WakaTime')
        logger.error(data)

        found = False
        for msg in list(logs.actual())[0]:
            if u(msg) == u(data):
                found = True
        self.assertTrue(found)
Пример #22
0
    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()
Пример #23
0
    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)
Пример #24
0
    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'])
Пример #25
0
    def test_python_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/codefile.py'
        config = 'tests/samples/sample.cfg'

        args = ['--file', entity, '--config', config, '--time', now]

        retval = main(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': 'Python',
            'lines': 26,
            'entity': os.path.abspath(entity),
            'project': os.path.basename(os.path.abspath('.')),
            'dependencies': ['wakatime', 'os', 'mock', 'simplejson', 'django'],
            'branch': os.environ.get('TRAVIS_COMMIT', ANY),
            'time': float(now),
            'type': 'file',
        }
        stats = '{"cursorpos": null, "dependencies": ["wakatime", "os", "mock", "simplejson", "django"], "lines": 26, "lineno": null, "language": "Python"}'

        self.patched['wakatime.offlinequeue.Queue.push'].assert_called_once_with(heartbeat, stats, None)
        self.patched['wakatime.offlinequeue.Queue.pop'].assert_not_called()
Пример #26
0
    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'])
Пример #27
0
    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()
Пример #28
0
    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)
Пример #29
0
    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)
Пример #30
0
    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()
Пример #31
0
    def test_alternate_project_argument_does_not_override_project_argument(
            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', '--alternate-project',
            'alt-project', '--file', entity, '--config', config, '--time', now
        ]

        execute(args)

        self.assertEquals(
            'forced-project',
            self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0]
            ['project'])
Пример #32
0
    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()
Пример #33
0
    def test_heartbeat_saved_from_error_response(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/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'])
Пример #34
0
    def test_push_handles_exception_on_execute(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_c = mock.MagicMock()
                mock_c.execute.side_effect = sqlite3.Error('')

                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()
Пример #35
0
    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)
Пример #36
0
    def test_timezone_header(self):
        self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = CustomResponse()

        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.assertNothingPrinted()

            timezone = tzlocal.get_localzone()
            headers = {
                'TimeZone': u(timezone.zone).encode('utf-8') if is_py3 else timezone.zone,
            }
            self.assertHeartbeatSent(headers=headers)
            self.assertHeartbeatNotSavedOffline()
            self.assertOfflineHeartbeatsSynced()
            self.assertSessionCacheSaved()
Пример #37
0
    def test_nonascii_timezone(self):
        response = Response()
        response.status_code = 201
        self.patched[
            'wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response

        package_path = 'wakatime.packages.tzlocal3.get_localzone' if is_py3 else 'wakatime.packages.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

            entity = 'tests/samples/codefiles/emptyfile.txt'
            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)
Пример #38
0
    def test_large_file_skips_lines_count(self):
        response = Response()
        response.status_code = 0
        self.patched[
            'wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response

        entity = 'tests/samples/codefiles/twolinefile.txt'
        config = 'tests/samples/configs/good_config.cfg'
        now = u(int(time.time()))
        heartbeat = {
            'language': 'Text only',
            'lines': None,
            'entity': os.path.realpath(entity),
            'project': os.path.basename(os.path.abspath('.')),
            'cursorpos': None,
            'lineno': None,
            'branch': ANY,
            'time': float(now),
            'type': 'file',
            'is_write': False,
            'user_agent': ANY,
            'dependencies': [],
        }

        args = ['--entity', entity, '--config', config, '--time', now]

        with utils.mock.patch('os.path.getsize') as mock_getsize:
            mock_getsize.return_value = MAX_FILE_SIZE_SUPPORTED + 1

            retval = execute(args)
            self.assertEquals(retval, API_ERROR)
            self.assertNothingPrinted()

        self.assertHeartbeatSent(heartbeat)

        self.assertHeartbeatSavedOffline()
        self.assertOfflineHeartbeatsNotSynced()
        self.assertSessionCacheDeleted()
Пример #39
0
    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()
Пример #40
0
    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)
Пример #41
0
    def test_write_argument(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()))
            key = str(uuid.uuid4())
            heartbeat = {
                'language': 'Text only',
                'lines': 0,
                'entity': entity,
                'project': None,
                'time': float(now),
                'type': 'file',
                'is_write': True,
                'dependencies': [],
                'user_agent': ANY,
            }

            args = ['--file', entity, '--key', key, '--write', '--verbose',
                    '--config', 'tests/samples/configs/good_config.cfg', '--time', now]

            retval = execute(args)
            self.assertEquals(retval, SUCCESS)
            self.assertNothingPrinted()
            actual = self.getLogOutput(logs)
            self.assertIn('WakaTime DEBUG Sending heartbeats to api', actual)

            self.assertHeartbeatSent(heartbeat)

            self.assertHeartbeatNotSavedOffline()
            self.assertOfflineHeartbeatsSynced()
            self.assertSessionCacheSaved()
Пример #42
0
    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()
Пример #43
0
    def test_400_response(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/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()))

            args = [
                '--file', entity, '--key', '123', '--config',
                'tests/samples/configs/paranoid.cfg', '--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.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()
Пример #44
0
    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'])
Пример #45
0
    def test_empty_project_can_be_saved(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/emptyfile.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(sys.stdout.getvalue(), '')
                self.assertEquals(sys.stderr.getvalue(), '')
                self.assertEquals(os.path.realpath(entity),
                                  saved_heartbeat['entity'])
Пример #46
0
    def test_entity_type_app(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, '--entity-type', '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()
Пример #47
0
    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.assertEquals(sys.stdout.getvalue(), '')
        self.assertEquals(sys.stderr.getvalue(), '')

        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.isPy35:
            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.isPy35:
            expected = u(
                'WakaTime WARNING Regex error (unbalanced parenthesis at position 15) for exclude pattern: \\(invalid regex)'
            )
        self.assertEquals(output[1], expected)
Пример #48
0
 def getLogOutput(self, logs):
     return u("\n").join([u(' ').join(x) for x in logs.actual()])
Пример #49
0
    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(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()))
            key = str(uuid.uuid4())

            args = [
                '--file', entity, '--key', key, '--time', now, '--config',
                'fake-foobar'
            ]

            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()
Пример #50
0
    def assertHeartbeatSent(self,
                            heartbeat=None,
                            extra_heartbeats=[],
                            headers=None,
                            cert=None,
                            proxies={},
                            stream=False,
                            timeout=60,
                            verify=True):
        self.patched[
            'wakatime.packages.requests.adapters.HTTPAdapter.send'].assert_called_once_with(
                ANY,
                cert=cert,
                proxies=proxies,
                stream=stream,
                timeout=timeout,
                verify=verify,
            )

        body = json.loads(
            self.
            patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].
            call_args[0][0].body)
        self.assertIsInstance(body, list)

        if headers:
            actual_headers = self.patched[
                'wakatime.packages.requests.adapters.HTTPAdapter.send'].call_args[
                    0][0].headers
            for key, val in headers.items():
                self.assertEquals(
                    actual_headers.get(key), val,
                    u('Expected api request to have header {0}={1}, instead {0}={2}'
                      ).format(u(key), u(actual_headers.get(key)), u(val)))

        if heartbeat:
            keys = list(body[0].keys()) + list(heartbeat.keys())
            for key in keys:
                if isinstance(heartbeat.get(key), list):
                    self.assertListsEqual(
                        heartbeat.get(key), body[0].get(key),
                        u('Expected heartbeat to be sent with {0}={1}, instead {0}={2}'
                          ).format(u(key), u(heartbeat.get(key)),
                                   u(body[0].get(key))))
                else:
                    self.assertEquals(
                        heartbeat.get(key), body[0].get(key),
                        u('Expected heartbeat to be sent with {1} {0}={2}, instead {3} {0}={4}'
                          ).format(u(key),
                                   type(heartbeat.get(key)).__name__,
                                   u(heartbeat.get(key)),
                                   type(body[0].get(key)).__name__,
                                   u(body[0].get(key))))

        if extra_heartbeats:
            for i in range(len(extra_heartbeats)):
                keys = list(body[i + 1].keys()) + list(
                    extra_heartbeats[i].keys())
                for key in keys:
                    if isinstance(extra_heartbeats[i].get(key), list):
                        self.assertListsEqual(
                            extra_heartbeats[i].get(key), body[i + 1].get(key),
                            u('Expected extra heartbeat {3} to be sent with {0}={1}, instead {0}={2}'
                              ).format(u(key), u(extra_heartbeats[i].get(key)),
                                       u(body[i + 1].get(key)), i))
                    else:
                        self.assertEquals(
                            extra_heartbeats[i].get(key), body[i + 1].get(key),
                            u('Expected extra heartbeat {5} to be sent with {1} {0}={2}, instead {3} {0}={4}'
                              ).format(
                                  u(key),
                                  type(extra_heartbeats[i].get(key)).__name__,
                                  u(extra_heartbeats[i].get(key)),
                                  type(body[i + 1].get(key)).__name__,
                                  u(body[i + 1].get(key)), i))
Пример #51
0
    def test_500_error_when_sending_offline_heartbeats(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

                config = 'tests/samples/configs/good_config.cfg'

                now1 = u(int(time.time()))
                entity1 = 'tests/samples/codefiles/emptyfile.txt'
                project1 = 'proj1'

                args = [
                    '--file', entity1, '--config', config, '--time', now1,
                    '--project', project1
                ]
                execute(args)

                now2 = u(int(time.time()))
                entity2 = 'tests/samples/codefiles/twolinefile.txt'
                project2 = 'proj2'

                args = [
                    '--file', entity2, '--config', config, '--time', now2,
                    '--project', project2
                ]
                execute(args)

                # send heartbeats from offline queue after 201 response
                now3 = u(int(time.time()))
                entity3 = 'tests/samples/codefiles/python.py'
                project3 = 'proj3'
                args = [
                    '--file', entity3, '--config', config, '--time', now3,
                    '--project', project3
                ]

                class CustomResponse(Response):
                    count = 0

                    @property
                    def status_code(self):
                        if self.count > 2:
                            return 500
                        self.count += 1
                        return 201

                    @status_code.setter
                    def status_code(self, value):
                        pass

                response = CustomResponse()
                self.patched[
                    'wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response

                retval = execute(args)
                self.assertEquals(retval, SUCCESS)

                # offline queue should be empty
                queue = Queue()
                saved_heartbeat = queue.pop()
                self.assertEquals(sys.stdout.getvalue(), '')
                self.assertEquals(sys.stderr.getvalue(), '')
                self.assertEquals(os.path.realpath(entity2),
                                  saved_heartbeat['entity'])
Пример #52
0
 def __exit__(self, exc_type, exc_value, traceback):
     try:
         shutil.rmtree(u(self.name))
     except:
         pass
Пример #53
0
    def test_heartbeats_sent_not_saved_from_bulk_response(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

                entities = [
                    'emptyfile.txt',
                    'twolinefile.txt',
                    'python.py',
                    'go.go',
                ]

                with TemporaryDirectory() as tempdir:
                    for entity in entities:
                        shutil.copy(os.path.join('tests/samples/codefiles', entity), os.path.join(tempdir, entity))

                    now = u(int(time.time()))
                    key = str(uuid.uuid4())
                    args = ['--file', os.path.join(tempdir, entities[0]), '--key', key, '--config', 'tests/samples/configs/good_config.cfg', '--time', now, '--extra-heartbeats']

                    response = CustomResponse()
                    response.response_code = 202
                    response.response_text = '{"responses": [[null,201], [null,500], [null,201], [null, 500]]}'
                    self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response

                    with mock.patch('wakatime.main.sys.stdin') as mock_stdin:
                        heartbeats = json.dumps([{
                            'timestamp': now,
                            'entity': os.path.join(tempdir, entity),
                            'entity_type': 'file',
                            'is_write': False,
                        } for entity in entities[1:]])
                        mock_stdin.readline.return_value = heartbeats

                        with mock.patch('wakatime.offlinequeue.Queue.pop') as mock_pop:
                            mock_pop.return_value = None

                            retval = execute(args)

                        self.assertEquals(retval, SUCCESS)
                        self.assertNothingPrinted()

                        heartbeat = {
                            'entity': os.path.realpath(os.path.join(tempdir, entities[0])),
                            'language': ANY,
                            'lines': ANY,
                            'project': ANY,
                            'time': ANY,
                            'type': 'file',
                            'is_write': ANY,
                            'user_agent': ANY,
                            'dependencies': ANY,
                        }
                        extra_heartbeats = [{
                            'entity': os.path.realpath(os.path.join(tempdir, entity)),
                            'language': ANY,
                            'lines': ANY,
                            'project': ANY,
                            'branch': ANY,
                            'time': ANY,
                            'is_write': ANY,
                            'type': 'file',
                            'dependencies': ANY,
                            'user_agent': ANY,
                        } for entity in entities[1:]]
                        self.assertHeartbeatSent(heartbeat, extra_heartbeats=extra_heartbeats)

                        self.assertSessionCacheSaved()

                        queue = Queue(None, None)
                        self.assertEquals(queue._get_db_file(), fh.name)
                        saved_heartbeats = queue.pop_many()
                        self.assertNothingPrinted()
                        self.assertNothingLogged(logs)

                        # make sure only heartbeats with error code responses were saved
                        self.assertEquals(len(saved_heartbeats), 2)
                        self.assertEquals(saved_heartbeats[0].entity, os.path.realpath(os.path.join(tempdir, entities[1])))
                        self.assertEquals(saved_heartbeats[1].entity, os.path.realpath(os.path.join(tempdir, entities[3])))
Пример #54
0
    def test_write_argument(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/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()))
            key = str(uuid.uuid4())

            args = [
                '--file', entity, '--key', key, '--write', '--verbose',
                '--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(), '')

            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(
                )

            heartbeat = {
                'language': 'Text only',
                'lines': 0,
                'entity': entity,
                'project': os.path.basename(os.path.abspath('.')),
                'time': float(now),
                'type': 'file',
                'is_write': True,
            }
            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()
Пример #55
0
    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()

            self.patched[
                'wakatime.packages.requests.adapters.HTTPAdapter.send'].assert_called_once_with(
                    ANY,
                    cert=None,
                    proxies={},
                    stream=False,
                    timeout=60,
                    verify=True,
                )
Пример #56
0
    def test_requests_exception(self, logs):
        logging.disable(logging.NOTSET)

        self.patched[
            'wakatime.packages.requests.adapters.HTTPAdapter.send'].side_effect = RequestException(
                'requests exception')

        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, '--verbose', '--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 = 'Parsing dependencies not supported for special.TextParser'
            self.assertIn(expected, log_output)
            expected = 'WakaTime DEBUG Sending heartbeat to api at https://api.wakatime.com/api/v1/heartbeats'
            self.assertIn(expected, log_output)
            expected = "RequestException': u'requests exception'"
            if is_py3:
                expected = "RequestException': 'requests exception'"
            self.assertIn(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(
                )

            heartbeat = {
                'language': 'Text only',
                'lines': 2,
                'entity': 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'): 2,
            }

            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()

            self.patched[
                'wakatime.packages.requests.adapters.HTTPAdapter.send'].assert_called_once_with(
                    ANY,
                    cert=None,
                    proxies={},
                    stream=False,
                    timeout=60,
                    verify=True,
                )
Пример #57
0
    def test_large_file_skips_lines_count(self):
        response = Response()
        response.status_code = 0
        self.patched[
            'wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response

        entity = 'tests/samples/codefiles/twolinefile.txt'
        config = 'tests/samples/configs/good_config.cfg'
        now = u(int(time.time()))

        args = ['--entity', entity, '--config', config, '--time', now]

        with utils.mock.patch('os.path.getsize') as mock_getsize:
            mock_getsize.return_value = MAX_FILE_SIZE_SUPPORTED + 1

            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 = {
            'language': 'Text only',
            'lines': None,
            'entity': os.path.realpath(entity),
            'project': os.path.basename(os.path.abspath('.')),
            'cursorpos': None,
            'lineno': None,
            'branch': 'master',
            'time': float(now),
            'type': 'file',
        }
        stats = {
            u('cursorpos'): None,
            u('dependencies'): [],
            u('language'): u('Text only'),
            u('lineno'): None,
            u('lines'): None,
        }

        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()

        self.patched[
            'wakatime.packages.requests.adapters.HTTPAdapter.send'].assert_called_once_with(
                ANY,
                cert=None,
                proxies={},
                stream=False,
                timeout=60,
                verify=True,
            )
Пример #58
0
    def test_lineno_and_cursorpos(self):
        response = Response()
        response.status_code = 0
        self.patched[
            'wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response

        entity = 'tests/samples/codefiles/twolinefile.txt'
        config = 'tests/samples/configs/good_config.cfg'
        now = u(int(time.time()))

        args = [
            '--entity', entity, '--config', config, '--time', now, '--lineno',
            '3', '--cursorpos', '4', '--verbose'
        ]
        retval = execute(args)

        self.assertEquals(sys.stdout.getvalue(), '')
        self.assertEquals(sys.stderr.getvalue(), '')

        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': 2,
            'entity': os.path.realpath(entity),
            'project': os.path.basename(os.path.abspath('.')),
            'cursorpos': '4',
            'lineno': '3',
            'branch': 'master',
            'time': float(now),
            'type': 'file',
        }
        stats = {
            u('cursorpos'): '4',
            u('dependencies'): [],
            u('language'): u('Text only'),
            u('lineno'): '3',
            u('lines'): 2,
        }

        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()
Пример #59
0
 def normalize_list(self, items):
     return sorted([u(x) for x in items])
Пример #60
0
    def test_all_offline_heartbeats_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

                config = 'tests/samples/configs/good_config.cfg'

                now1 = u(int(time.time()))
                entity1 = 'tests/samples/codefiles/emptyfile.txt'
                project1 = 'proj1'

                args = [
                    '--file', entity1, '--config', config, '--time', now1,
                    '--project', project1
                ]
                execute(args)

                now2 = u(int(time.time()))
                entity2 = 'tests/samples/codefiles/twolinefile.txt'
                project2 = 'proj2'

                args = [
                    '--file', entity2, '--config', config, '--time', now2,
                    '--project', project2
                ]
                execute(args)

                # send heartbeats from offline queue after 201 response
                now3 = u(int(time.time()))
                entity3 = 'tests/samples/codefiles/python.py'
                project3 = 'proj3'
                args = [
                    '--file', entity3, '--config', config, '--time', now3,
                    '--project', project3
                ]
                response.status_code = 201
                execute(args)

                # offline queue should be empty
                queue = Queue()
                saved_heartbeat = queue.pop()
                self.assertEquals(None, saved_heartbeat)

                calls = self.patched[
                    'wakatime.packages.requests.adapters.HTTPAdapter.send'].call_args_list

                body = calls[0][0][0].body
                data = json.loads(body)
                self.assertEquals(data.get('entity'), os.path.abspath(entity1))
                self.assertEquals(data.get('project'), project1)
                self.assertEquals(u(int(data.get('time'))), now1)

                body = calls[1][0][0].body
                data = json.loads(body)
                self.assertEquals(data.get('entity'), os.path.abspath(entity2))
                self.assertEquals(data.get('project'), project2)
                self.assertEquals(u(int(data.get('time'))), now2)

                body = calls[2][0][0].body
                data = json.loads(body)
                self.assertEquals(data.get('entity'), os.path.abspath(entity3))
                self.assertEquals(data.get('project'), project3)
                self.assertEquals(u(int(data.get('time'))), now3)

                body = calls[3][0][0].body
                data = json.loads(body)
                self.assertEquals(data.get('entity'), os.path.abspath(entity1))
                self.assertEquals(data.get('project'), project1)
                self.assertEquals(u(int(data.get('time'))), now1)

                body = calls[4][0][0].body
                data = json.loads(body)
                self.assertEquals(data.get('entity'), os.path.abspath(entity2))
                self.assertEquals(data.get('project'), project2)
                self.assertEquals(u(int(data.get('time'))), now2)