コード例 #1
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()
コード例 #2
0
ファイル: test_logging.py プロジェクト: wakatime/wakatime
    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()
コード例 #3
0
ファイル: test_logging.py プロジェクト: wakatime/wakatime
    def test_default_log_file_used(self, logs):
        logging.disable(logging.NOTSET)

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

        now = u(int(time.time()))
        entity = 'tests/samples/codefiles/python.py'
        config = 'tests/samples/configs/has_regex_errors.cfg'
        args = ['--file', entity, '--config', config, '--time', now]

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

        self.assertEquals(logging.WARNING, logging.getLogger('WakaTime').level)
        logfile = os.path.realpath(os.path.expanduser('~/.wakatime.log'))
        self.assertEquals(logfile, logging.getLogger('WakaTime').handlers[0].baseFilename)
        output = [u(' ').join(x) for x in logs.actual()]
        expected = u('WakaTime WARNING Regex error (unbalanced parenthesis) for include pattern: \\(invalid regex)')
        if self.isPy35OrNewer:
            expected = u('WakaTime WARNING Regex error (unbalanced parenthesis at position 15) for include pattern: \\(invalid regex)')
        self.assertEquals(output[0], expected)
        expected = u('WakaTime WARNING Regex error (unbalanced parenthesis) for exclude pattern: \\(invalid regex)')
        if self.isPy35OrNewer:
            expected = u('WakaTime WARNING Regex error (unbalanced parenthesis at position 15) for exclude pattern: \\(invalid regex)')
        self.assertEquals(output[1], expected)
コード例 #4
0
ファイル: test_logging.py プロジェクト: wakatime/wakatime
    def test_verbose_flag_enables_verbose_logging(self, logs):
        logging.disable(logging.NOTSET)

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

        now = u(int(time.time()))
        entity = 'tests/samples/codefiles/python.py'
        config = 'tests/samples/configs/has_regex_errors.cfg'
        args = ['--file', entity, '--config', config, '--time', now, '--verbose']

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

        self.assertEquals(logging.DEBUG, logging.getLogger('WakaTime').level)
        logfile = os.path.realpath(os.path.expanduser('~/.wakatime.log'))
        self.assertEquals(logfile, logging.getLogger('WakaTime').handlers[0].baseFilename)
        output = [u(' ').join(x) for x in logs.actual()]

        expected = u('WakaTime WARNING Regex error (unbalanced parenthesis) for include pattern: \\(invalid regex)')
        if self.isPy35OrNewer:
            expected = u('WakaTime WARNING Regex error (unbalanced parenthesis at position 15) for include pattern: \\(invalid regex)')
        self.assertEquals(output[0], expected)
        expected = u('WakaTime WARNING Regex error (unbalanced parenthesis) for exclude pattern: \\(invalid regex)')
        if self.isPy35OrNewer:
            expected = u('WakaTime WARNING Regex error (unbalanced parenthesis at position 15) for exclude pattern: \\(invalid regex)')
        self.assertEquals(output[1], expected)
        self.assertEquals(output[2], u('WakaTime DEBUG Sending heartbeats to api at https://api.wakatime.com/api/v1/users/current/heartbeats.bulk'))
        self.assertIn('Python', output[3])
        self.assertIn('response_code', output[4])
コード例 #5
0
ファイル: test_main.py プロジェクト: isopropylcyanide/prog
    def test_nonascii_hostname(self):
        response = Response()
        response.status_code = 201
        self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response

        hostname = 'test汉语' if is_py3 else 'test\xe6\xb1\x89\xe8\xaf\xad'
        with utils.mock.patch('socket.gethostname') as mock_gethostname:
            mock_gethostname.return_value = hostname
            self.assertEquals(type(hostname).__name__, 'str')

            entity = 'tests/samples/codefiles/emptyfile.txt'
            config = 'tests/samples/configs/has_everything.cfg'
            args = ['--file', entity, '--config', config]
            retval = execute(args)
            self.assertEquals(retval, SUCCESS)
            expected_stdout = open('tests/samples/output/main_test_good_config_file').read()
            traceback_file = os.path.realpath('wakatime/main.py')
            lineno = int(re.search(r' line (\d+),', sys.stdout.getvalue()).group(1))
            self.assertEquals(sys.stdout.getvalue(), expected_stdout.format(file=traceback_file, lineno=lineno))
            self.assertEquals(sys.stderr.getvalue(), '')

            self.patched['wakatime.session_cache.SessionCache.get'].assert_called_once_with()
            self.patched['wakatime.session_cache.SessionCache.delete'].assert_not_called()
            self.patched['wakatime.session_cache.SessionCache.save'].assert_called_once_with(ANY)

            self.patched['wakatime.offlinequeue.Queue.push'].assert_not_called()
            self.patched['wakatime.offlinequeue.Queue.pop'].assert_called_once_with()

            headers = self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].call_args[0][0].headers
            self.assertEquals(headers.get('X-Machine-Name'), hostname.encode('utf-8') if is_py3 else hostname)
コード例 #6
0
ファイル: test_main.py プロジェクト: awesome-archive/wakatime
    def test_good_config_file(self):
        response = Response()
        response.status_code = 201
        self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response

        with utils.TemporaryDirectory() as tempdir:
            entity = 'tests/samples/codefiles/emptyfile.txt'
            shutil.copy(entity, os.path.join(tempdir, 'emptyfile.txt'))
            entity = os.path.realpath(os.path.join(tempdir, 'emptyfile.txt'))

            config = 'tests/samples/configs/has_everything.cfg'
            args = ['--file', entity, '--config', config]
            retval = execute(args)
            self.assertEquals(retval, SUCCESS)
            expected_stdout = open('tests/samples/output/main_test_good_config_file').read()
            traceback_file = os.path.realpath('wakatime/main.py')
            lineno = int(re.search(r' line (\d+),', sys.stdout.getvalue()).group(1))
            self.assertEquals(sys.stdout.getvalue(), expected_stdout.format(file=traceback_file, lineno=lineno))
            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()
コード例 #7
0
ファイル: test_proxy.py プロジェクト: wakatime/wakatime
    def test_ntlm_proxy_used_after_trying_normal_proxy(self):
        response = Response()
        response.status_code = 400
        self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response

        with utils.TemporaryDirectory() as tempdir:
            entity = 'tests/samples/codefiles/emptyfile.txt'
            shutil.copy(entity, os.path.join(tempdir, 'emptyfile.txt'))
            entity = os.path.realpath(os.path.join(tempdir, 'emptyfile.txt'))
            proxy = 'domain\\user:pass'
            config = 'tests/samples/configs/good_config.cfg'
            args = ['--file', entity, '--config', config, '--proxy', proxy]

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

            self.patched['wakatime.session_cache.SessionCache.get'].assert_has_calls([call(), call()])
            self.patched['wakatime.session_cache.SessionCache.delete'].assert_called_once_with()
            self.patched['wakatime.session_cache.SessionCache.save'].assert_not_called()

            self.patched['wakatime.offlinequeue.Queue.push'].assert_not_called()
            self.patched['wakatime.offlinequeue.Queue.pop'].assert_not_called()

            expected_calls = [
                call(ANY, cert=None, proxies={'https': proxy}, stream=False, timeout=60, verify=True),
                call(ANY, cert=None, proxies={}, stream=False, timeout=60, verify=True),
            ]
            self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].assert_has_calls(expected_calls)
コード例 #8
0
ファイル: test_main.py プロジェクト: awesome-archive/wakatime
    def test_nonascii_hostname(self):
        response = Response()
        response.status_code = 201
        self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response

        with utils.TemporaryDirectory() as tempdir:
            entity = 'tests/samples/codefiles/emptyfile.txt'
            shutil.copy(entity, os.path.join(tempdir, 'emptyfile.txt'))
            entity = os.path.realpath(os.path.join(tempdir, 'emptyfile.txt'))

            hostname = 'test汉语' if is_py3 else 'test\xe6\xb1\x89\xe8\xaf\xad'
            with utils.mock.patch('socket.gethostname') as mock_gethostname:
                mock_gethostname.return_value = hostname
                self.assertEquals(type(hostname).__name__, 'str')

                config = 'tests/samples/configs/good_config.cfg'
                args = ['--file', entity, '--config', config]
                retval = execute(args)
                self.assertEquals(retval, SUCCESS)
                self.assertEquals(sys.stdout.getvalue(), '')
                self.assertEquals(sys.stderr.getvalue(), '')

                self.patched['wakatime.session_cache.SessionCache.get'].assert_called_once_with()
                self.patched['wakatime.session_cache.SessionCache.delete'].assert_not_called()
                self.patched['wakatime.session_cache.SessionCache.save'].assert_called_once_with(ANY)

                self.patched['wakatime.offlinequeue.Queue.push'].assert_not_called()
                self.patched['wakatime.offlinequeue.Queue.pop'].assert_called_once_with()

                headers = self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].call_args[0][0].headers
                self.assertEquals(headers.get('X-Machine-Name'), hostname.encode('utf-8') if is_py3 else hostname)
コード例 #9
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()
コード例 #10
0
ファイル: test_project.py プロジェクト: wakatime/wakatime
    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'])
コード例 #11
0
ファイル: test_main.py プロジェクト: awesome-archive/wakatime
    def test_hostname_set_from_config_file(self):
        response = Response()
        response.status_code = 201
        self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response

        with utils.TemporaryDirectory() as tempdir:
            entity = 'tests/samples/codefiles/emptyfile.txt'
            shutil.copy(entity, os.path.join(tempdir, 'emptyfile.txt'))
            entity = os.path.realpath(os.path.join(tempdir, 'emptyfile.txt'))

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

            self.patched['wakatime.session_cache.SessionCache.get'].assert_called_once_with()
            self.patched['wakatime.session_cache.SessionCache.delete'].assert_not_called()
            self.patched['wakatime.session_cache.SessionCache.save'].assert_called_once_with(ANY)

            self.patched['wakatime.offlinequeue.Queue.push'].assert_not_called()
            self.patched['wakatime.offlinequeue.Queue.pop'].assert_called_once_with()

            headers = self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].call_args[0][0].headers
            self.assertEquals(headers.get('X-Machine-Name'), hostname.encode('utf-8') if is_py3 else hostname)
コード例 #12
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()
コード例 #13
0
ファイル: test_main.py プロジェクト: wakatime/wakatime
    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()))
            key = str(uuid.uuid4())
            heartbeat = {
                'language': 'Text only',
                'entity': 'HIDDEN.txt',
                'project': None,
                'time': float(now),
                'type': 'file',
                'is_write': False,
                'user_agent': ANY,
            }

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

            retval = execute(args)
            self.assertEquals(retval, API_ERROR)
            self.assertNothingPrinted()
            self.assertHeartbeatSent(heartbeat)
            self.assertHeartbeatNotSavedOffline()
            self.assertOfflineHeartbeatsNotSynced()
            self.assertSessionCacheDeleted()
コード例 #14
0
ファイル: test_main.py プロジェクト: awesome-archive/wakatime
    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)
コード例 #15
0
ファイル: test_configs.py プロジェクト: wakatime/wakatime
    def test_exclude_file_because_project_unknown(self, logs):
        logging.disable(logging.NOTSET)

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

        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/exclude_unknown_project.cfg'

            args = ['--file', entity, '--config', config, '--verbose', '--log-file', '~/.wakatime.log']
            retval = execute(args)
            self.assertEquals(retval, SUCCESS)
            self.assertNothingPrinted()
            actual = self.getLogOutput(logs)
            expected = 'WakaTime DEBUG Skipping because project unknown.'
            self.assertEquals(actual, expected)

            self.assertHeartbeatNotSent()

            self.assertHeartbeatNotSavedOffline()
            self.assertOfflineHeartbeatsSynced()
            self.assertSessionCacheUntouched()
コード例 #16
0
ファイル: test_main.py プロジェクト: awesome-archive/wakatime
    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()
コード例 #17
0
ファイル: test_main.py プロジェクト: awesome-archive/wakatime
    def test_proxy_argument(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, '--proxy', 'localhost:1234']
            retval = execute(args)
            self.assertEquals(retval, SUCCESS)
            self.assertEquals(sys.stdout.getvalue(), '')
            self.assertEquals(sys.stderr.getvalue(), '')

            self.patched['wakatime.session_cache.SessionCache.get'].assert_called_once_with()
            self.patched['wakatime.session_cache.SessionCache.delete'].assert_not_called()
            self.patched['wakatime.session_cache.SessionCache.save'].assert_called_once_with(ANY)

            self.patched['wakatime.offlinequeue.Queue.push'].assert_not_called()
            self.patched['wakatime.offlinequeue.Queue.pop'].assert_called_once_with()

            self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].assert_called_once_with(ANY, cert=None, proxies={'https': 'localhost:1234'}, stream=False, timeout=60, verify=True)
コード例 #18
0
ファイル: test_project.py プロジェクト: wakatime/wakatime
    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)
コード例 #19
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()
コード例 #20
0
ファイル: test_wakatime_base.py プロジェクト: queenp/wakatime
    def test_set_project_from_command_line(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/twolinefile.txt'
        config = 'tests/samples/sample.cfg'

        args = ['--file', entity, '--project', 'xyz', '--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': 'Text only',
            'lines': 2,
            'entity': os.path.abspath(entity),
            'project': 'xyz',
            'branch': os.environ.get('TRAVIS_COMMIT', ANY),
            'time': float(now),
            'type': 'file',
        }
        stats = '{"cursorpos": null, "dependencies": [], "lines": 2, "lineno": null, "language": "Text only"}'

        self.patched['wakatime.offlinequeue.Queue.push'].assert_called_once_with(heartbeat, stats, None)
        self.patched['wakatime.offlinequeue.Queue.pop'].assert_not_called()
コード例 #21
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)
コード例 #22
0
ファイル: test_project.py プロジェクト: wakatime/wakatime
    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'])
コード例 #23
0
ファイル: test_main.py プロジェクト: awesome-archive/wakatime
    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
ファイル: test_main.py プロジェクト: itimetrack/itimetrack
    def test_extra_heartbeats_argument(self):
        response = Response()
        response.status_code = 201
        self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response

        entity = 'tests/samples/codefiles/emptyfile.txt'
        config = 'tests/samples/configs/good_config.cfg'
        args = ['--file', entity, '--config', config, '--extra-heartbeats']

        with utils.mock.patch('wakatime.main.sys.stdin') as mock_stdin:
            now = int(time.time())
            heartbeats = json.dumps([{
                'timestamp': now,
                'entity': entity,
                'entity_type': 'file',
                'is_write': True,
            }])
            mock_stdin.read.return_value = heartbeats

            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_has_calls([call(), call()])
            self.patched['wakatime.session_cache.SessionCache.delete'].assert_not_called()
            self.patched['wakatime.session_cache.SessionCache.save'].assert_has_calls([call(ANY), call(ANY)])

            self.patched['wakatime.offlinequeue.Queue.push'].assert_not_called()
            self.patched['wakatime.offlinequeue.Queue.pop'].assert_has_calls([call(), call()])
コード例 #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/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()
コード例 #26
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()
コード例 #27
0
    def test_nonascii_heartbeat_saved(self, logs):
        logging.disable(logging.NOTSET)

        with NamedTemporaryFile() as fh:
            with mock.patch('wakatime.offlinequeue.Queue._get_db_file') as mock_db_file:
                mock_db_file.return_value = fh.name

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

                with TemporaryDirectory() as tempdir:
                    filename = list(filter(lambda x: x.endswith('.txt'), os.listdir(u('tests/samples/codefiles/unicode'))))[0]
                    entity = os.path.join('tests/samples/codefiles/unicode', filename)
                    shutil.copy(entity, os.path.join(tempdir, filename))
                    entity = os.path.realpath(os.path.join(tempdir, filename))
                    now = u(int(time.time()))
                    config = 'tests/samples/configs/good_config.cfg'
                    key = str(uuid.uuid4())
                    language = 'lang汉语' if self.isPy35OrNewer else 'lang\xe6\xb1\x89\xe8\xaf\xad'
                    project = 'proj汉语' if self.isPy35OrNewer else 'proj\xe6\xb1\x89\xe8\xaf\xad'
                    branch = 'branch汉语' if self.isPy35OrNewer else 'branch\xe6\xb1\x89\xe8\xaf\xad'
                    heartbeat = {
                        'language': u(language),
                        'lines': 0,
                        'entity': os.path.realpath(entity),
                        'project': u(project),
                        'branch': u(branch),
                        'time': float(now),
                        'type': 'file',
                        'is_write': False,
                        'user_agent': ANY,
                        'dependencies': [],
                    }

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

                    with mock.patch('wakatime.stats.standardize_language') as mock_language:
                        mock_language.return_value = language

                        with mock.patch('wakatime.heartbeat.get_project_info') as mock_project:
                            mock_project.return_value = (project, branch)

                            execute(args)

                    self.assertNothingPrinted()
                    self.assertNothingLogged(logs)

                    self.assertHeartbeatSent(heartbeat)

                    queue = Queue(None, None)
                    saved_heartbeat = queue.pop()
                    self.assertPathsEqual(os.path.realpath(entity), saved_heartbeat['entity'])
                    self.assertEquals(u(language), saved_heartbeat['language'])
                    self.assertEquals(u(project), saved_heartbeat['project'])
                    self.assertEquals(u(branch), saved_heartbeat['branch'])
コード例 #28
0
    def test_classnotfound_error_when_parsing_dependencies(self):
        response = Response()
        response.status_code = 0
        self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response

        with utils.TemporaryDirectory() as tempdir:
            entity = 'tests/samples/codefiles/python.py'
            shutil.copy(entity, os.path.join(tempdir, 'python.py'))
            entity = os.path.realpath(os.path.join(tempdir, 'python.py'))

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

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

            with utils.mock.patch('wakatime.stats.guess_lexer_using_filename') as mock_guess:
                mock_guess.return_value = (None, None)

                with utils.mock.patch('wakatime.stats.get_filetype_from_buffer') as mock_filetype:
                    mock_filetype.return_value = 'foo'
                    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': None,
                'lines': 36,
                'dependencies': [],
                'entity': os.path.realpath(entity),
                'project': u(os.path.basename(os.path.realpath('.'))),
                'time': float(now),
                'type': 'file',
            }
            stats = {
                u('cursorpos'): None,
                u('language'): None,
                u('lineno'): None,
                u('lines'): 36,
                u('dependencies'): [],
            }

            self.patched['wakatime.offlinequeue.Queue.push'].assert_called_once_with(ANY, ANY, None)
            for key, val in self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][0].items():
                self.assertEquals(heartbeat[key], val)
            self.assertEquals(stats, json.loads(self.patched['wakatime.offlinequeue.Queue.push'].call_args[0][1]))
            self.patched['wakatime.offlinequeue.Queue.pop'].assert_not_called()
コード例 #29
0
ファイル: test_main.py プロジェクト: awesome-archive/wakatime
    def test_extra_heartbeats_argument(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/twolinefile.txt'
            shutil.copy(entity, os.path.join(tempdir, 'twolinefile.txt'))
            entity = os.path.realpath(os.path.join(tempdir, 'twolinefile.txt'))

            project1 = os.path.basename(os.path.abspath('.'))
            project2 = 'xyz'
            entity1 = os.path.abspath('tests/samples/codefiles/emptyfile.txt')
            entity2 = os.path.abspath('tests/samples/codefiles/twolinefile.txt')
            config = 'tests/samples/configs/good_config.cfg'
            args = ['--file', entity1, '--config', config, '--extra-heartbeats']

            with utils.mock.patch('wakatime.main.sys.stdin') as mock_stdin:
                now = int(time.time())
                heartbeats = json.dumps([{
                    'timestamp': now,
                    'entity': entity2,
                    'entity_type': 'file',
                    'project': project2,
                    'is_write': True,
                }])
                mock_stdin.readline.return_value = heartbeats

                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_has_calls([call(), call()])
                self.patched['wakatime.session_cache.SessionCache.delete'].assert_not_called()
                self.patched['wakatime.session_cache.SessionCache.save'].assert_has_calls([call(ANY), call(ANY)])

                self.patched['wakatime.offlinequeue.Queue.push'].assert_not_called()
                self.patched['wakatime.offlinequeue.Queue.pop'].assert_called_once_with()

                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'), entity1)
                self.assertEquals(data.get('project'), project1)

                body = calls[1][0][0].body
                data = json.loads(body)
                self.assertEquals(data.get('entity'), entity2)
                self.assertEquals(data.get('project'), project2)
コード例 #30
0
    def test_cpp_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/seeplusplus.cpp'
        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()

        {'project': 'wakatime-cli', 'language': 'C', 'time': 1443295423.0, 'type': 'file', 'lines': 7, 'entity': '/Users/alanhamlett/git/wakatime-cli/tests/samples/codefiles/see.c'}
        {'language': 'C', 'lines': 7, 'entity': '/Users/alanhamlett/git/wakatime-cli/tests/samples/codefiles/see.c', 'project': u'wakatime-cli', 'time': 1443295423.0, 'type': 'file'}

        heartbeat = {
            'language': u('C++'),
            'lines': 8,
            '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('C++'),
            u('lineno'): None,
            u('lines'): 8,
        }
        expected_dependencies = [
            'openssl',
        ]

        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()
コード例 #31
0
    def test_nonascii_filename_saved_when_offline(self, logs):
        logging.disable(logging.NOTSET)

        response = Response()
        response.status_code = 500
        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()))
            config = 'tests/samples/configs/good_config.cfg'
            key = str(uuid.uuid4())
            heartbeat = {
                'language': 'Text only',
                'lines': 0,
                'entity': os.path.realpath(entity),
                'project': None,
                'time': float(now),
                'type': 'file',
                'is_write': False,
                'user_agent': ANY,
                'dependencies': [],
            }

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

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

            self.assertHeartbeatSent(heartbeat)

            self.assertHeartbeatSavedOffline()
            self.assertOfflineHeartbeatsNotSynced()
            self.assertSessionCacheDeleted()
コード例 #32
0
    def test_project_map_with_replacement_group_index_error(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_map42/emptyfile.txt'
        config = 'tests/samples/configs/project_map_malformed.cfg'

        args = ['--file', entity, '--config', config, '--time', now]
        retval = execute(args)

        self.assertEquals(retval, API_ERROR)
        self.assertNothingPrinted()
        actual = self.getLogOutput(logs)
        expected = u(
            'WakaTime WARNING Regex error (tuple index out of range) for projectmap pattern: proj-map{3}'
        )
        self.assertEquals(expected, actual)
コード例 #33
0
ファイル: test_logging.py プロジェクト: Aareon/wakatime
    def test_exception_traceback_logged_in_debug_mode(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/good_config.cfg'
        args = ['--file', entity, '--config', config, '--time', now, '--verbose']

        with utils.mock.patch('wakatime.stats.open') as mock_open:
            mock_open.side_effect = Exception('FooBar')

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

            log_output = u("\n").join([u(' ').join(x) for x in logs.actual()])
            self.assertIn(u('WakaTime DEBUG Traceback (most recent call last):'), log_output)
            self.assertIn(u('Exception: FooBar'), log_output)
コード例 #34
0
    def test_api_key_setting_without_underscore_accepted(self):
        """Api key in wakatime.cfg should also work without an underscore:
            apikey = XXX
        """

        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/sample_alternate_apikey.cfg'
            args = [
                '--file', entity, '--config', config, '--logfile',
                '~/.wakatime.log'
            ]
            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()
コード例 #35
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'])
コード例 #36
0
ファイル: test_offlinequeue.py プロジェクト: trikyas/wakatime
    def test_heartbeat_saved_from_error_response(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/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'])
コード例 #37
0
    def test_config_file_from_env(self, logs):
        logging.disable(logging.NOTSET)

        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/has_everything.cfg'
            shutil.copy(config, os.path.join(tempdir, '.wakatime.cfg'))
            config = os.path.realpath(os.path.join(tempdir, '.wakatime.cfg'))

            with utils.mock.patch(
                    'wakatime.configs.os.environ.get') as mock_env:
                mock_env.return_value = tempdir

                args = ['--file', entity, '--logfile', '~/.wakatime.log']
                retval = execute(args)
                self.assertEquals(retval, SUCCESS)
                expected_stdout = open(
                    'tests/samples/output/configs_test_good_config_file').read(
                    )
                traceback_file = os.path.realpath('wakatime/arguments.py')
                lineno = int(
                    re.search(r' line (\d+),', sys.stdout.getvalue()).group(1))
                self.assertEquals(
                    sys.stdout.getvalue(),
                    expected_stdout.format(file=traceback_file, lineno=lineno))
                self.assertEquals(sys.stderr.getvalue(), '')

                self.assertHeartbeatSent(proxies=ANY, verify=ANY)

                self.assertHeartbeatNotSavedOffline()
                self.assertOfflineHeartbeatsSynced()
                self.assertSessionCacheSaved()
コード例 #38
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)
コード例 #39
0
    def test_exception_traceback_not_logged_normally(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/good_config.cfg'
        args = ['--file', entity, '--config', config, '--time', now]

        with utils.mock.patch('wakatime.stats.open') as mock_open:
            mock_open.side_effect = Exception('FooBar')

            retval = execute(args)
            self.assertEquals(retval, 102)
            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(u(''), log_output)
コード例 #40
0
ファイル: test_main.py プロジェクト: syns2191/wakatime
    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()
コード例 #41
0
ファイル: test_main.py プロジェクト: shadowbq/dot.atom
    def test_missing_entity_file(self):
        response = Response()
        response.status_code = 201
        self.patched[
            'wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response

        entity = 'tests/samples/codefiles/missingfile.txt'
        config = 'tests/samples/configs/good_config.cfg'
        args = ['--file', entity, '--config', config]
        retval = execute(args)
        self.assertEquals(retval, 0)
        self.assertEquals(sys.stdout.getvalue(), '')
        self.assertEquals(sys.stderr.getvalue(), '')

        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()
コード例 #42
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)
コード例 #43
0
    def test_empty_project_can_be_saved(self):
        with NamedTemporaryFile() as fh:
            with mock.patch('wakatime.offlinequeue.Queue._get_db_file'
                            ) as mock_db_file:
                mock_db_file.return_value = fh.name

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

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

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

                queue = Queue(None, None)
                saved_heartbeat = queue.pop()
                self.assertNothingPrinted()
                self.assertPathsEqual(os.path.realpath(entity),
                                      saved_heartbeat['entity'])
コード例 #44
0
ファイル: test_logging.py プロジェクト: syns2191/wakatime
    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()
コード例 #45
0
ファイル: test_main.py プロジェクト: shadowbq/dot.atom
    def test_proxy_argument(self):
        response = Response()
        response.status_code = 201
        self.patched[
            'wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response

        entity = 'tests/samples/codefiles/emptyfile.txt'
        config = 'tests/samples/configs/good_config.cfg'
        args = [
            '--file', entity, '--config', config, '--proxy', 'localhost:1234'
        ]
        retval = execute(args)
        self.assertEquals(retval, 0)
        self.assertEquals(sys.stdout.getvalue(), '')
        self.assertEquals(sys.stderr.getvalue(), '')

        self.patched[
            'wakatime.session_cache.SessionCache.get'].assert_called_once_with(
            )
        self.patched[
            'wakatime.session_cache.SessionCache.delete'].assert_not_called()
        self.patched[
            'wakatime.session_cache.SessionCache.save'].assert_called_once_with(
                ANY)

        self.patched['wakatime.offlinequeue.Queue.push'].assert_not_called()
        self.patched[
            'wakatime.offlinequeue.Queue.pop'].assert_called_once_with()

        self.patched[
            'wakatime.packages.requests.adapters.HTTPAdapter.send'].assert_called_once_with(
                ANY,
                cert=None,
                proxies={'https': 'localhost:1234'},
                stream=False,
                timeout=30,
                verify=True)
コード例 #46
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()
コード例 #47
0
    def test_hostname_set_from_config_file(self):
        response = Response()
        response.status_code = 201
        self.patched[
            'wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response

        with utils.TemporaryDirectory() as tempdir:
            entity = 'tests/samples/codefiles/emptyfile.txt'
            shutil.copy(entity, os.path.join(tempdir, 'emptyfile.txt'))
            entity = os.path.realpath(os.path.join(tempdir, 'emptyfile.txt'))

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

            self.patched[
                'wakatime.session_cache.SessionCache.get'].assert_called_once_with(
                )
            self.patched[
                'wakatime.session_cache.SessionCache.delete'].assert_not_called(
                )
            self.patched[
                'wakatime.session_cache.SessionCache.save'].assert_called_once_with(
                    ANY)

            self.patched['wakatime.offlinequeue.Queue.push'].assert_not_called(
            )
            self.patched[
                'wakatime.offlinequeue.Queue.pop'].assert_called_once_with()

            headers = self.patched[
                'wakatime.packages.requests.adapters.HTTPAdapter.send'].call_args[
                    0][0].headers
            self.assertEquals(headers.get('X-Machine-Name'),
                              hostname.encode('utf-8') if is_py3 else hostname)
コード例 #48
0
    def test_invalid_api_key(self, logs):
        logging.disable(logging.NOTSET)

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

        config = 'tests/samples/configs/missing_api_key.cfg'
        args = ['--config', config, '--key', 'invalid-api-key']

        with self.assertRaises(SystemExit) as e:
            execute(args)

        self.assertEquals(int(str(e.exception)), AUTH_ERROR)
        self.assertEquals(sys.stdout.getvalue(), '')
        expected = 'error: Invalid api key. Find your api key from wakatime.com/settings.'
        self.assertIn(expected, sys.stderr.getvalue())

        log_output = u("\n").join([u(' ').join(x) for x in logs.actual()])
        expected = ''
        self.assertEquals(log_output, expected)

        self.patched[
            'wakatime.session_cache.SessionCache.get'].assert_not_called()
        self.patched[
            'wakatime.session_cache.SessionCache.delete'].assert_not_called()
        self.patched[
            'wakatime.session_cache.SessionCache.save'].assert_not_called()

        self.patched['wakatime.offlinequeue.Queue.push'].assert_not_called()
        self.patched['wakatime.offlinequeue.Queue.pop'].assert_not_called()

        self.patched[
            'wakatime.packages.requests.adapters.HTTPAdapter.send'].assert_not_called(
            )
コード例 #49
0
ファイル: test_arguments.py プロジェクト: Aareon/wakatime
    def test_missing_entity_file(self, logs):
        logging.disable(logging.NOTSET)

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

        entity = 'tests/samples/codefiles/missingfile.txt'

        config = 'tests/samples/configs/good_config.cfg'
        args = ['--file', entity, '--config', config, '--verbose']
        retval = execute(args)
        self.assertEquals(retval, SUCCESS)
        self.assertNothingPrinted()
        actual = self.getLogOutput(logs)
        expected = 'WakaTime DEBUG File does not exist; ignoring this heartbeat.'
        self.assertIn(expected, actual)

        self.assertHeartbeatNotSent()

        self.assertHeartbeatNotSavedOffline()
        self.assertOfflineHeartbeatsSynced()
        self.assertSessionCacheUntouched()
コード例 #50
0
ファイル: test_languages.py プロジェクト: trikyas/wakatime
    def test_language_detected_for_header_file(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/see.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)

        entity = 'tests/samples/codefiles/seeplusplus.h'
        args[1] = entity

        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)
コード例 #51
0
    def test_offline_heartbeat_sent_after_success_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)

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

                queue = Queue(None, None)
                saved_heartbeat = queue.pop()
                self.assertEquals(None, saved_heartbeat)
コード例 #52
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()
コード例 #53
0
ファイル: test_main.py プロジェクト: shadowbq/dot.atom
    def test_config_file_not_passed_in_command_line_args(self):
        response = Response()
        response.status_code = 201
        self.patched[
            'wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response

        with utils.mock.patch('wakatime.main.open') as mock_open:
            mock_open.side_effect = IOError('')

            config = os.path.join(os.path.expanduser('~'), '.wakatime.cfg')
            entity = 'tests/samples/codefiles/emptyfile.txt'
            args = ['--file', entity]

            with self.assertRaises(SystemExit):
                execute(args)
            expected_stdout = u(
                "Error: Could not read from config file {0}\n").format(
                    u(config))
            expected_stderr = open(
                'tests/samples/output/test_missing_config_file').read()
            self.assertEquals(sys.stdout.getvalue(), expected_stdout)
            self.assertEquals(sys.stderr.getvalue(), expected_stderr)
            self.patched[
                'wakatime.session_cache.SessionCache.get'].assert_not_called()
コード例 #54
0
    def test_invalid_timeout_passed_via_command_line(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/twolinefile.txt'
            shutil.copy(entity, os.path.join(tempdir, 'twolinefile.txt'))
            entity = os.path.realpath(os.path.join(tempdir, 'twolinefile.txt'))
            config = 'tests/samples/configs/good_config.cfg'
            key = str(uuid.uuid4())
            args = ['--file', entity, '--key', key, '--config', config, '--timeout', 'abc']

            with self.assertRaises(SystemExit) as e:
                execute(args)

            self.assertEquals(int(str(e.exception)), 2)
            self.assertEquals(sys.stdout.getvalue(), '')
            expected_stderr = open('tests/samples/output/main_test_timeout_passed_via_command_line').read()
            self.assertEquals(sys.stderr.getvalue(), expected_stderr)

            self.patched['wakatime.offlinequeue.Queue.push'].assert_not_called()
            self.patched['wakatime.offlinequeue.Queue.pop'].assert_not_called()
            self.patched['wakatime.session_cache.SessionCache.get'].assert_not_called()
コード例 #55
0
    def test_config_file_not_passed_in_command_line_args(self):
        response = Response()
        response.status_code = 201
        self.patched[
            'wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response

        with utils.TemporaryDirectory() as tempdir:
            entity = 'tests/samples/codefiles/emptyfile.txt'
            shutil.copy(entity, os.path.join(tempdir, 'emptyfile.txt'))
            entity = os.path.realpath(os.path.join(tempdir, 'emptyfile.txt'))

            with utils.mock.patch(
                    'wakatime.configs.os.environ.get') as mock_env:
                mock_env.return_value = None

                with utils.mock.patch('wakatime.configs.open') as mock_open:
                    mock_open.side_effect = IOError('')

                    config = os.path.join(os.path.expanduser('~'),
                                          '.wakatime.cfg')
                    args = ['--file', entity]

                    with self.assertRaises(SystemExit) as e:
                        execute(args)

                    self.assertEquals(int(str(e.exception)),
                                      CONFIG_FILE_PARSE_ERROR)
                    expected_stdout = u('')
                    expected_stderr = u(
                        "Error: Could not read from config file {0}\n").format(
                            u(config))
                    self.assertEquals(sys.stdout.getvalue(), expected_stdout)
                    self.assertEquals(sys.stderr.getvalue(), expected_stderr)
                    self.patched[
                        'wakatime.session_cache.SessionCache.get'].assert_not_called(
                        )
コード例 #56
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()
コード例 #57
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'])
コード例 #58
0
    def test_500_error_when_sending_offline_heartbeats(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

                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 = CustomResponse()
                response.second_response_code = 500
                response.limit = 2
                response.response_text = '{"responses": [[null,201], [null,201], [null,201]]}'
                self.patched['wakatime.packages.requests.adapters.HTTPAdapter.send'].return_value = response

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

                # offline queue should still have saved heartbeats
                queue = Queue(None, None)
                saved_heartbeats = queue.pop_many()
                self.assertNothingPrinted()
                self.assertEquals(len(saved_heartbeats), 2)
コード例 #59
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'])
コード例 #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)