class ReporterTest(unittest.TestCase): def setUp(self): os.chdir(join(dirname(dirname(__file__)), 'example')) sh.rm('-f', '.coverage') sh.rm('-f', 'extra.py') self.cover = Coveralls(repo_token='xxx') def test_reporter(self): sh.coverage('run', 'runtests.py') results = self.cover.get_coverage() assert len(results) == 2 assert_coverage({ 'source': '# coding: utf-8\n\n\ndef hello():\n print(\'world\')\n\n\nclass Foo(object):\n """ Bar """\n\n\ndef baz():\n print(\'this is not tested\')', 'name': 'project.py', 'coverage': [None, None, None, 1, 1, None, None, 1, None, None, None, 1, 0]}, results[0]) assert_coverage({ 'source': "# coding: utf-8\nfrom project import hello\n\nif __name__ == '__main__':\n hello()", 'name': 'runtests.py', 'coverage': [None, 1, None, 1, 1]}, results[1]) def test_missing_file(self): sh.echo('print("Python rocks!")', _out="extra.py") sh.coverage('run', 'extra.py') sh.rm('-f', 'extra.py') assert self.cover.get_coverage() == [] def test_not_python(self): sh.echo('print("Python rocks!")', _out="extra.py") sh.coverage('run', 'extra.py') sh.echo("<h1>This isn't python!</h1>", _out="extra.py") assert self.cover.get_coverage() == []
def main(argv=None): options = docopt(__doc__, argv=argv) if options['debug']: options['--verbose'] = True level = logging.DEBUG if options['--verbose'] else logging.INFO log.addHandler(logging.StreamHandler()) log.setLevel(level) try: coverallz = Coveralls(config_file=options['--rcfile']) if not options['debug']: log.info("Submitting coverage to coveralls.io...") result = coverallz.wear() log.info("Coverage submitted!") log.info(result['message']) log.info(result['url']) log.debug(result) else: log.info("Testing coveralls-python...") coverallz.wear(dry_run=True) except KeyboardInterrupt: # pragma: no cover log.info('Aborted') except CoverallsException as e: log.error(e) except KeyError as e: # pragma: no cover log.error(e) except Exception: # pragma: no cover raise
def main(argv=None): options = docopt(__doc__, argv=argv) if options["debug"]: options["--verbose"] = True level = logging.DEBUG if options["--verbose"] else logging.INFO log.addHandler(logging.StreamHandler()) log.setLevel(level) try: coverallz = Coveralls() if not options["debug"]: log.info("Submitting coverage to coveralls.io...") result = coverallz.wear() log.info("Coverage submitted!") log.info(result["message"]) log.info(result["url"]) log.debug(result) else: log.info("Testing coveralls-python...") coverallz.wear(dry_run=True) except KeyboardInterrupt: # pragma: no cover log.info("Aborted") except CoverallsException as e: log.error(e) except Exception: # pragma: no cover raise
def test_merge(self, mock_requests): api = Coveralls(repo_token='xxx') coverage_file = tempfile.NamedTemporaryFile() coverage_file.write(b'{"source_files": [{"name": "foobar", "coverage": []}]}') coverage_file.seek(0) api.merge(coverage_file.name) result = api.create_report() assert json.loads(result)['source_files'] == [{'name': 'foobar', 'coverage': []}]
def test_merge_empty_data(self, mock_requests): api = Coveralls(repo_token='xxx') coverage_file = tempfile.NamedTemporaryFile() coverage_file.write(b'{}') coverage_file.seek(0) api.merge(coverage_file.name) result = api.create_report() assert json.loads(result)['source_files'] == []
def test_reporter(self): os.chdir(join(dirname(dirname(__file__)), 'example')) sh.coverage('run', 'runtests.py') cover = Coveralls(repo_token='xxx') expect(cover.get_coverage()).should.be.equal([{ 'source': '# coding: utf-8\n\n\ndef hello():\n print(\'world\')\n\n\nclass Foo(object):\n """ Bar """\n\n\ndef baz():\n print(\'this is not tested\')', 'name': 'project.py', 'coverage': [None, None, None, 1, 1, None, None, 1, None, None, None, 1, 0]}, { 'source': "# coding: utf-8\nfrom project import hello\n\nif __name__ == '__main__':\n hello()", 'name': 'runtests.py', 'coverage': [None, 1, None, 1, 1]}])
def test_merge_invalid_data(self, mock_logger, mock_requests): api = Coveralls(repo_token='xxx') coverage_file = tempfile.NamedTemporaryFile() coverage_file.write(b'{"random": "stuff"}') coverage_file.seek(0) api.merge(coverage_file.name) result = api.create_report() assert json.loads(result)['source_files'] == [] mock_logger.assert_called_once_with('No data to be merged; does the ' 'json file contain "source_files" data?')
class ReporterTest(unittest.TestCase): def setUp(self): os.chdir(join(dirname(dirname(__file__)), 'example')) sh.rm('-f', '.coverage') sh.rm('-f', 'extra.py') self.cover = Coveralls(repo_token='xxx') def test_reporter(self): sh.coverage('run', 'runtests.py') results = self.cover.get_coverage() assert len(results) == 2 assert_coverage({ 'source': '# coding: utf-8\n\n\ndef hello():\n print(\'world\')\n\n\nclass Foo(object):\n """ Bar """\n\n\ndef baz():\n print(\'this is not tested\')\n\ndef branch(cond1, cond2):\n if cond1:\n print(\'condition tested both ways\')\n if cond2:\n print(\'condition not tested both ways\')', 'name': 'project.py', 'coverage': [None, None, None, 1, 1, None, None, 1, None, None, None, 1, 0, None, 1, 1, 1, 1, 1]}, results[0]) assert_coverage({ 'source': "# coding: utf-8\nfrom project import hello, branch\n\nif __name__ == '__main__':\n hello()\n branch(False, True)\n branch(True, True)", 'name': 'runtests.py', 'coverage': [None, 1, None, 1, 1, 1, 1]}, results[1]) def test_reporter_with_branches(self): sh.coverage('run', '--branch', 'runtests.py') results = self.cover.get_coverage() assert len(results) == 2 # Branches are expressed as four values each in a flat list assert not len(results[0]['branches']) % 4 assert not len(results[1]['branches']) % 4 assert_coverage({ 'source': '# coding: utf-8\n\n\ndef hello():\n print(\'world\')\n\n\nclass Foo(object):\n """ Bar """\n\n\ndef baz():\n print(\'this is not tested\')\n\ndef branch(cond1, cond2):\n if cond1:\n print(\'condition tested both ways\')\n if cond2:\n print(\'condition not tested both ways\')', 'name': 'project.py', 'branches': [16, 0, 17, 1, 16, 0, 18, 1, 18, 0, 19, 1, 18, 0, 15, 0], 'coverage': [None, None, None, 1, 1, None, None, 1, None, None, None, 1, 0, None, 1, 1, 1, 1, 1]}, results[0]) assert_coverage({ 'source': "# coding: utf-8\nfrom project import hello, branch\n\nif __name__ == '__main__':\n hello()\n branch(False, True)\n branch(True, True)", 'name': 'runtests.py', 'branches': [4, 0, 5, 1, 4, 0, 2, 0], 'coverage': [None, 1, None, 1, 1, 1, 1]}, results[1]) def test_missing_file(self): sh.echo('print("Python rocks!")', _out="extra.py") sh.coverage('run', 'extra.py') sh.rm('-f', 'extra.py') assert self.cover.get_coverage() == [] def test_not_python(self): sh.echo('print("Python rocks!")', _out="extra.py") sh.coverage('run', 'extra.py') sh.echo("<h1>This isn't python!</h1>", _out="extra.py") assert self.cover.get_coverage() == []
def test_misconfigured(self): with pytest.raises(Exception) as excinfo: Coveralls() assert str(excinfo.value) == ( 'Not on Travis or CircleCI. You have to provide either repo_token ' 'in .coveralls.mock or set the COVERALLS_REPO_TOKEN env var.')
def test_misconfigured(self): with pytest.raises(Exception) as excinfo: Coveralls() assert str( excinfo.value ) == 'You have to provide either repo_token in .coveralls.mock, or launch via Travis'
def test_reporter(self): sh.coverage('run', 'runtests.py') results = Coveralls(repo_token='xxx').get_coverage() assert len(results) == 2 assert_coverage(results[0], { 'source': ('# coding: utf-8\n\n\n' 'def hello():\n' ' print(\'world\')\n\n\n' 'class Foo(object):\n' ' """ Bar """\n\n\n' 'def baz():\n' ' print(\'this is not tested\')\n\n' 'def branch(cond1, cond2):\n' ' if cond1:\n' ' print(\'condition tested both ways\')\n' ' if cond2:\n' ' print(\'condition not tested both ways\')'), 'name': 'project.py', 'coverage': [None, None, None, 1, 1, None, None, 1, None, None, None, 1, 0, None, 1, 1, 1, 1, 1]}) assert_coverage(results[1], { 'source': ('# coding: utf-8\n' 'from project import hello, branch\n\n' "if __name__ == '__main__':\n" ' hello()\n' ' branch(False, True)\n' ' branch(True, True)'), 'name': 'runtests.py', 'coverage': [None, 1, None, 1, 1, 1, 1]})
def test_reporter_with_base_dir_arg(self): subprocess.call(['coverage', 'run', '--omit=**/.tox/*', 'example/runtests.py'], cwd=BASE_DIR) # without base_dir arg, file name is prefixed with 'example/' os.chdir(BASE_DIR) results = Coveralls(repo_token='xxx', base_dir='example').get_coverage() assert len(results) == 2 assert_coverage(results[0], { 'source': ('def hello():\n' ' print(\'world\')\n\n\n' 'class Foo:\n' ' """ Bar """\n\n\n' 'def baz():\n' ' print(\'this is not tested\')\n\n' 'def branch(cond1, cond2):\n' ' if cond1:\n' ' print(\'condition tested both ways\')\n' ' if cond2:\n' ' print(\'condition not tested both ways\')\n'), 'name': 'project.py', 'coverage': [1, 1, None, None, 1, None, None, None, 1, 0, None, 1, 1, 1, 1, 1]}) assert_coverage(results[1], { 'source': ('from project import branch\n' 'from project import hello\n\n' "if __name__ == '__main__':\n" ' hello()\n' ' branch(False, True)\n' ' branch(True, True)\n'), 'name': 'runtests.py', 'coverage': [1, 1, None, 1, 1, 1, 1]})
def test_output_to_file(tmpdir): """Check we can write coveralls report into the file.""" test_log = tmpdir.join('test.log') Coveralls(repo_token='xxx').save_report(test_log.strpath) report = test_log.read() assert json.loads(report)['repo_token'] == 'xxx'
def test_not_python(self): with open('extra.py', 'w') as f: f.write('print("Python rocks!")\n') subprocess.call(['coverage', 'run', '--omit=**/.tox/*', 'extra.py'], cwd=EXAMPLE_DIR) with open('extra.py', 'w') as f: f.write("<h1>This isn't python!</h1>\n") assert Coveralls(repo_token='xxx').get_coverage() == []
def test_malformed_encoding_declaration(capfd): os.chdir(join(dirname(dirname(__file__)), 'nonunicode')) sh.coverage('run', 'malformed.py') logging.getLogger('coveralls').addHandler(logging.StreamHandler()) result_object = Coveralls(repo_token='xxx').get_coverage() assert result_object == [] out, err = capfd.readouterr() assert 'Source file malformed.py can not be properly decoded' in err
def test_no_coverage(self, report_files, mock_requests): report_files.side_effect = coverage.CoverageException( 'No data to report') self.setup_mock(mock_requests) result = Coveralls(repo_token='xxx').wear() assert result == { 'message': 'Failure to gather coverage: No data to report' }
def test_non_unicode(): os.chdir(NONUNICODE_DIR) sh.coverage('run', 'nonunicode.py') actual_json = json.dumps(Coveralls(repo_token='xxx').get_coverage()) expected_json_part = ('"source": "# coding: iso-8859-15\\n\\n' 'def hello():\\n' ' print(\'I like P\\u00f3lya distribution.\')') assert expected_json_part in actual_json
def test_coveralls_unavailable(self, mock_requests): mock_requests.post.return_value.json.side_effect = ValueError mock_requests.post.return_value.status_code = 500 mock_requests.post.return_value.text = '<html>Http 1./1 500</html>' result = Coveralls(repo_token='xxx').wear() assert result == { 'message': 'Failure to submit data. Response [500]: <html>Http 1./1 500</html>' }
def test_coveralls_unavailable(self, mock_requests): mock_requests.post.return_value.json.side_effect = ValueError mock_requests.post.return_value.status_code = 500 mock_requests.post.return_value.text = '<html>Http 1./1 500</html>' result = Coveralls(repo_token='xxx').wear(dry_run=False) expect(result).should.be.equal({ 'error': 'Failure to submit data. Response [500]: <html>Http 1./1 500</html>' })
def test_malformed_encoding_declaration(capfd): os.chdir(NONUNICODE_DIR) sh.coverage('run', 'malformed.py') logging.getLogger('coveralls').addHandler(logging.StreamHandler()) assert Coveralls(repo_token='xxx').get_coverage() == [] _, err = capfd.readouterr() assert 'Source file malformed.py can not be properly decoded' in err
def test_reporter(self): os.chdir(join(dirname(dirname(__file__)), 'example')) sh.coverage('run', 'runtests.py') cover = Coveralls(repo_token='xxx') expect(cover.get_coverage()).should.be.equal([{ 'source': '# coding: utf-8\n\n\ndef hello():\n print(\'world\')\n\n\nclass Foo(object):\n """ Bar """\n\n\ndef baz():\n print(\'this is not tested\')', 'name': 'project.py', 'coverage': [None, None, None, 1, 1, None, None, 1, None, None, None, 1, 0] }, { 'source': "# coding: utf-8\nfrom project import hello\n\nif __name__ == '__main__':\n hello()", 'name': 'runtests.py', 'coverage': [None, 1, None, 1, 1] }])
def test_no_coverage(self, report_files, mock_requests): mock_requests.post.return_value.json.return_value = EXPECTED report_files.side_effect = coverage.CoverageException( 'No data to report') result = Coveralls(repo_token='xxx').wear() assert result == { 'message': 'Failure to gather coverage: No data to report' }
def test_malformed_encoding_declaration_py3_or_coverage4(capfd): os.chdir(join(dirname(dirname(__file__)), 'nonunicode')) sh.coverage('run', 'malformed.py') logging.getLogger('coveralls').addHandler(logging.StreamHandler()) result_object = Coveralls(repo_token='xxx').get_coverage() assert len(result_object) == 1 assert_coverage({'coverage': [None, None, 1, 0], 'name': 'malformed.py', 'source': '# -*- cоding: utf-8 -*-\n\ndef hello():\n return 1\n'}, result_object[0])
def test_missing_file(self): with open('extra.py', 'w') as f: f.write('print("Python rocks!")\n') subprocess.call(['coverage', 'run', '--omit=**/.tox/*', 'extra.py'], cwd=EXAMPLE_DIR) try: os.remove('extra.py') except Exception: pass assert Coveralls(repo_token='xxx').get_coverage() == []
def test_git(self): cover = Coveralls(repo_token='xxx') git_info = cover.git_info() commit_id = git_info['git']['head'].pop('id') assert re.match(r'^[a-f0-9]{40}$', commit_id) assert git_info == {'git': { 'head': { 'committer_email': '*****@*****.**', 'author_email': '*****@*****.**', 'author_name': 'Daniël', 'message': 'first commit', 'committer_name': 'Daniël', }, 'remotes': [{ 'url': 'https://github.com/username/Hello-World.git', 'name': 'origin' }], 'branch': 'master' }}
def test_git(self): cover = Coveralls(repo_token='xxx') git_info = cover.git_info() commit_id = git_info['git']['head'].pop('id') self.assertTrue(re.match(r'^[a-f0-9]{40}$', commit_id)) # expect(commit_id).should.match(r'^[a-f0-9]{40}$', re.I | re.U) sure 1.1.7 is broken for py2.6 expect(git_info).should.be.equal({'git': { 'head': { 'committer_email': '*****@*****.**', 'author_email': '*****@*****.**', 'author_name': 'Guido', 'message': 'first commit', 'committer_name': 'Guido', }, 'remotes': [{ 'url': u'https://github.com/username/Hello-World.git', 'name': u'origin' }], 'branch': u'master'}})
def test_git(self): cover = Coveralls(repo_token='xxx') git_info = cover.git_info() commit_id = git_info['git']['head'].pop('id') assert re.match(r'^[a-f0-9]{40}$', commit_id) assert git_info == { 'git': { 'head': { 'committer_email': GIT_EMAIL, 'author_email': GIT_EMAIL, 'author_name': GIT_NAME, 'message': GIT_COMMIT_MSG, 'committer_name': GIT_NAME, }, 'remotes': [{ 'url': GIT_URL, 'name': GIT_REMOTE }], 'branch': 'master' } }
def test_malformed_encoding_declaration_py3_or_coverage4(): os.chdir(NONUNICODE_DIR) sh.coverage('run', 'malformed.py') result = Coveralls(repo_token='xxx').get_coverage() assert len(result) == 1 assert result[0]['coverage'] == [None, None, 1, 0] assert result[0]['name'] == 'malformed.py' assert result[0]['source'].strip() == ('# -*- cоding: utf-8 -*-\n\n' 'def hello():\n' ' return 1') assert 'branches' not in result[0]
def coverage_report(self): """ Outputs Coverage report to screen and coverage.xml. """ include = ['%s*' % package for package in self.packages] omit = ['*testing*'] log.info("\n\nCoverage Report:") try: self.coverage.stop() self.coverage.report(include=include, omit=omit) except CoverageException as e: log.info("Coverage Exception: %s" % e) if os.environ.get('TRAVIS'): log.info("Submitting coverage to coveralls.io...") try: result = Coveralls() result.wear() except CoverallsException as e: log.error("Coveralls Exception: %s" % e)
def test_git(self): cover = Coveralls(repo_token='xxx') git_info = cover.git_info() commit_id = git_info['git']['head'].pop('id') self.assertTrue(re.match(r'^[a-f0-9]{40}$', commit_id)) # expect(commit_id).should.match(r'^[a-f0-9]{40}$', re.I | re.U) sure 1.1.7 is broken for py2.6 expect(git_info).should.be.equal({ 'git': { 'head': { 'committer_email': '*****@*****.**', 'author_email': '*****@*****.**', 'author_name': 'Guido', 'message': 'first commit', 'committer_name': 'Guido', }, 'remotes': [{ 'url': u'https://github.com/username/Hello-World.git', 'name': u'origin' }], 'branch': u'master' } })
def test_reporter_with_branches(self): subprocess.call( ['coverage', 'run', '--branch', '--omit=**/.tox/*', 'runtests.py'], cwd=EXAMPLE_DIR) results = Coveralls(repo_token='xxx').get_coverage() assert len(results) == 2 # Branches are expressed as four values each in a flat list assert not len(results[0]['branches']) % 4 assert not len(results[1]['branches']) % 4 assert_coverage( results[0], { 'source': ('def hello():\n' ' print(\'world\')\n\n\n' 'class Foo:\n' ' """ Bar """\n\n\n' 'def baz():\n' ' print(\'this is not tested\')\n\n' 'def branch(cond1, cond2):\n' ' if cond1:\n' ' print(\'condition tested both ways\')\n' ' if cond2:\n' ' print(\'condition not tested both ways\')\n'), 'name': 'project.py', 'branches': [13, 0, 14, 1, 13, 0, 15, 1, 15, 0, 16, 1, 15, 0, 12, 0], 'coverage': [ 1, 1, None, None, 1, None, None, None, 1, 0, None, 1, 1, 1, 1, 1 ] }) assert_coverage( results[1], { 'source': ('from project import branch\n' 'from project import hello\n\n' "if __name__ == '__main__':\n" ' hello()\n' ' branch(False, True)\n' ' branch(True, True)\n'), 'name': 'runtests.py', 'branches': [4, 0, 5, 1, 4, 0, 1, 0], 'coverage': [1, 1, None, 1, 1, 1, 1] })
def test_local_with_config_without_yaml_module(self, mock_logger): """test local with config in yaml, but without yaml-installed""" if sys.version_info < (3,0): builtin_import_func = '__builtin__.__import__' else: builtin_import_func = 'builtins.__import__' yaml_import_mock = self.generate_import_mock('yaml', 'No module named yaml') try: # patching of `import` function of the Coveralls module (it shoud throw ImportException): with patch(builtin_import_func, side_effect=yaml_import_mock): Coveralls() except: pass mock_logger.assert_called_once_with('Seems, like some modules are not installed: %s', mock.ANY)
def main(argv=None): options = docopt(__doc__, argv=argv) if options['debug']: options['--verbose'] = True level = logging.DEBUG if options['--verbose'] else logging.INFO log.addHandler(logging.StreamHandler()) log.setLevel(level) try: token_required = not options['debug'] and not options['--output'] coverallz = Coveralls(token_required, config_file=options['--rcfile']) if options['--merge']: coverallz.merge(options['--merge']) if options['debug']: log.info("Testing coveralls-python...") coverallz.wear(dry_run=True) elif options['--output']: log.info('Write coverage report to file...') coverallz.save_report(options['--output']) else: log.info("Submitting coverage to coveralls.io...") result = coverallz.wear() log.info("Coverage submitted!") log.info(result['message']) log.info(result['url']) log.debug(result) except KeyboardInterrupt: # pragma: no cover log.info('Aborted') except CoverallsException as e: log.error(e) sys.exit(1) except KeyError as e: # pragma: no cover log.error(e) sys.exit(2) except Exception: # pragma: no cover raise
def test_reporter_with_branches(self): sh.coverage('run', '--branch', 'runtests.py') results = Coveralls(repo_token='xxx').get_coverage() assert len(results) == 2 # Branches are expressed as four values each in a flat list assert not len(results[0]['branches']) % 4 assert not len(results[1]['branches']) % 4 assert_coverage(results[0], { 'source': ('# coding: utf-8\n\n\n' 'def hello():\n' ' print(\'world\')\n\n\n' 'class Foo(object):\n' ' """ Bar """\n\n\n' 'def baz():\n' ' print(\'this is not tested\')\n\n' 'def branch(cond1, cond2):\n' ' if cond1:\n' ' print(\'condition tested both ways\')\n' ' if cond2:\n' ' print(\'condition not tested both ways\')'), 'name': 'project.py', 'branches': [16, 0, 17, 1, 16, 0, 18, 1, 18, 0, 19, 1, 18, 0, 15, 0], 'coverage': [None, None, None, 1, 1, None, None, 1, None, None, None, 1, 0, None, 1, 1, 1, 1, 1]}) assert_coverage(results[1], { 'source': ('# coding: utf-8\n' 'from project import hello, branch\n\n' "if __name__ == '__main__':\n" ' hello()\n' ' branch(False, True)\n' ' branch(True, True)'), 'name': 'runtests.py', 'branches': [4, 0, 5, 1, 4, 0, 2, 0], 'coverage': [None, 1, None, 1, 1, 1, 1]})
def setUp(self): os.chdir(join(dirname(dirname(__file__)), 'example')) sh.rm('-f', '.coverage') sh.rm('-f', 'extra.py') self.cover = Coveralls(repo_token='xxx')