diff options
author | Danny Allen <me@dannya.com> | 2014-08-11 16:13:06 +0100 |
---|---|---|
committer | Danny Allen <me@dannya.com> | 2014-08-11 16:13:06 +0100 |
commit | e38016c499921dd7bf5919a699a76305a1936129 (patch) | |
tree | 07a4125732561f2489dfb6b75a339cfef46d80d4 /tests | |
parent | c81183f614ca982cd2ed93ac8e6e76610d162202 (diff) | |
parent | ee5ea987f8978d91c1ef189fe4f334511ddf6215 (diff) | |
download | python-coveragepy-git-e38016c499921dd7bf5919a699a76305a1936129.tar.gz |
Merged ned/coveragepy into default
Diffstat (limited to 'tests')
-rw-r--r-- | tests/backtest.py | 50 | ||||
-rw-r--r-- | tests/backunittest.py | 29 | ||||
-rw-r--r-- | tests/coveragetest.py | 70 | ||||
-rw-r--r-- | tests/farm/annotate/annotate_dir.py | 4 | ||||
-rw-r--r-- | tests/farm/annotate/run.py | 4 | ||||
-rw-r--r-- | tests/farm/annotate/run_multi.py | 4 | ||||
-rw-r--r-- | tests/farm/run/run_chdir.py | 2 | ||||
-rw-r--r-- | tests/farm/run/run_timid.py | 8 | ||||
-rw-r--r-- | tests/farm/run/run_xxx.py | 4 | ||||
-rw-r--r-- | tests/modules/pkg1/p1a.py | 2 | ||||
-rw-r--r-- | tests/test_api.py | 8 | ||||
-rw-r--r-- | tests/test_backward.py | 2 | ||||
-rw-r--r-- | tests/test_cmdline.py | 2 | ||||
-rw-r--r-- | tests/test_codeunit.py | 28 | ||||
-rw-r--r-- | tests/test_config.py | 144 | ||||
-rw-r--r-- | tests/test_coroutine.py | 61 | ||||
-rw-r--r-- | tests/test_coverage.py | 14 | ||||
-rw-r--r-- | tests/test_data.py | 14 | ||||
-rw-r--r-- | tests/test_execfile.py | 9 | ||||
-rw-r--r-- | tests/test_farm.py | 20 | ||||
-rw-r--r-- | tests/test_files.py | 14 | ||||
-rw-r--r-- | tests/test_html.py | 42 | ||||
-rw-r--r-- | tests/test_parser.py | 4 | ||||
-rw-r--r-- | tests/test_phystokens.py | 5 | ||||
-rw-r--r-- | tests/test_process.py | 91 | ||||
-rw-r--r-- | tests/test_summary.py | 148 | ||||
-rw-r--r-- | tests/test_templite.py | 6 | ||||
-rw-r--r-- | tests/test_testing.py | 10 |
28 files changed, 533 insertions, 266 deletions
diff --git a/tests/backtest.py b/tests/backtest.py index 89a25536..439493d1 100644 --- a/tests/backtest.py +++ b/tests/backtest.py @@ -4,41 +4,31 @@ # (Redefining built-in blah) # The whole point of this file is to redefine built-ins, so shut up about it. -import os +import subprocess -# Py2 and Py3 don't agree on how to run commands in a subprocess. -try: - import subprocess -except ImportError: - def run_command(cmd, status=0): - """Run a command in a subprocess. - - Returns the exit status code and the combined stdout and stderr. - """ - _, stdouterr = os.popen4(cmd) - return status, stdouterr.read() +# This isn't really a backward compatibility thing, should be moved into a +# helpers file or something. +def run_command(cmd): + """Run a command in a subprocess. -else: - def run_command(cmd, status=0): - """Run a command in a subprocess. + Returns the exit status code and the combined stdout and stderr. - Returns the exit status code and the combined stdout and stderr. + """ + proc = subprocess.Popen(cmd, shell=True, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT + ) + output, _ = proc.communicate() + status = proc.returncode # pylint: disable=E1101 - """ - proc = subprocess.Popen(cmd, shell=True, - stdin=subprocess.PIPE, stdout=subprocess.PIPE, - stderr=subprocess.STDOUT - ) - output, _ = proc.communicate() - status = proc.returncode # pylint: disable=E1101 + # Get the output, and canonicalize it to strings with newlines. + if not isinstance(output, str): + output = output.decode('utf-8') + output = output.replace('\r', '') - # Get the output, and canonicalize it to strings with newlines. - if not isinstance(output, str): - output = output.decode('utf-8') - output = output.replace('\r', '') + return status, output - return status, output # No more execfile in Py3 try: @@ -46,4 +36,6 @@ try: except NameError: def execfile(filename, globs): """A Python 3 implementation of execfile.""" - exec(compile(open(filename).read(), filename, 'exec'), globs) + with open(filename) as fobj: + code = fobj.read() + exec(compile(code, filename, 'exec'), globs) diff --git a/tests/backunittest.py b/tests/backunittest.py index ca741d37..6498397f 100644 --- a/tests/backunittest.py +++ b/tests/backunittest.py @@ -8,9 +8,9 @@ except ImportError: import unittest -def _need(method): - """Do we need to define our own `method` method?""" - return not hasattr(unittest.TestCase, method) +def unittest_has(method): + """Does `unitttest.TestCase` have `method` defined?""" + return hasattr(unittest.TestCase, method) class TestCase(unittest.TestCase): @@ -20,7 +20,22 @@ class TestCase(unittest.TestCase): `unittest` doesn't have them. """ - if _need('assertSameElements'): - def assertSameElements(self, s1, s2): - """Assert that the two arguments are equal as sets.""" - self.assertEqual(set(s1), set(s2)) + # pylint: disable=missing-docstring + + if not unittest_has('assertCountEqual'): + if unittest_has('assertSameElements'): + def assertCountEqual(self, *args, **kwargs): + # pylint: disable=no-member + return self.assertSameElements(*args, **kwargs) + else: + def assertCountEqual(self, s1, s2): + """Assert these have the same elements, regardless of order.""" + self.assertEqual(set(s1), set(s2)) + + if not unittest_has('assertRaisesRegex'): + def assertRaisesRegex(self, *args, **kwargs): + return self.assertRaisesRegexp(*args, **kwargs) + + if not unittest_has('assertRegex'): + def assertRegex(self, *args, **kwargs): + return self.assertRegexpMatches(*args, **kwargs) diff --git a/tests/coveragetest.py b/tests/coveragetest.py index a309f17d..1eedad39 100644 --- a/tests/coveragetest.py +++ b/tests/coveragetest.py @@ -1,10 +1,11 @@ """Base test case class for coverage testing.""" -import glob, imp, os, random, shlex, shutil, sys, tempfile, textwrap +import glob, os, random, re, shlex, shutil, sys, tempfile, textwrap import atexit, collections import coverage -from coverage.backward import StringIO, to_bytes +from coverage.backward import StringIO, to_bytes, import_local_file +from coverage.backward import importlib # pylint: disable=unused-import from coverage.control import _TEST_NAME_FILE from tests.backtest import run_command from tests.backunittest import TestCase @@ -221,18 +222,7 @@ class CoverageTest(TestCase): as `modname`, and returns the module object. """ - modfile = modname + '.py' - - for suff in imp.get_suffixes(): - if suff[0] == '.py': - break - - with open(modfile, 'r') as f: - # pylint: disable=W0631 - # (Using possibly undefined loop variable 'suff') - mod = imp.load_module(modname, f, modfile, suff) - - return mod + return import_local_file(modname) def start_import_stop(self, cov, modname): """Start coverage, import a file, then stop coverage. @@ -365,19 +355,21 @@ class CoverageTest(TestCase): if statements == line_list: break else: - self.fail("None of the lines choices matched %r" % - statements + self.fail( + "None of the lines choices matched %r" % statements ) + missing_formatted = analysis.missing_formatted() if type(missing) == type(""): - self.assertEqual(analysis.missing_formatted(), missing) + self.assertEqual(missing_formatted, missing) else: for missing_list in missing: - if analysis.missing_formatted() == missing_list: + if missing_formatted == missing_list: break else: - self.fail("None of the missing choices matched %r" % - analysis.missing_formatted() + self.fail( + "None of the missing choices matched %r" % + missing_formatted ) if arcs is not None: @@ -412,17 +404,17 @@ class CoverageTest(TestCase): """Assert that `flist1` and `flist2` are the same set of file names.""" flist1_nice = [self.nice_file(f) for f in flist1] flist2_nice = [self.nice_file(f) for f in flist2] - self.assertSameElements(flist1_nice, flist2_nice) + self.assertCountEqual(flist1_nice, flist2_nice) def assert_exists(self, fname): """Assert that `fname` is a file that exists.""" msg = "File %r should exist" % fname - self.assert_(os.path.exists(fname), msg) + self.assertTrue(os.path.exists(fname), msg) def assert_doesnt_exist(self, fname): """Assert that `fname` is a file that doesn't exist.""" msg = "File %r shouldn't exist" % fname - self.assert_(not os.path.exists(fname), msg) + self.assertTrue(not os.path.exists(fname), msg) def assert_starts_with(self, s, prefix, msg=None): """Assert that `s` starts with `prefix`.""" @@ -466,7 +458,7 @@ class CoverageTest(TestCase): _, output = self.run_command_status(cmd) return output - def run_command_status(self, cmd, status=0): + def run_command_status(self, cmd): """Run the command-line `cmd` in a subprocess, and print its output. Use this when you need to test the process behavior of coverage. @@ -475,9 +467,6 @@ class CoverageTest(TestCase): Returns a pair: the process' exit status and stdout text. - The `status` argument is returned as the status on older Pythons where - we can't get the actual exit status of the process. - """ # Add our test modules directory to PYTHONPATH. I'm sure there's too # much path munging here, but... @@ -490,10 +479,35 @@ class CoverageTest(TestCase): pypath += testmods + os.pathsep + zipfile self.set_environ('PYTHONPATH', pypath) - status, output = run_command(cmd, status=status) + status, output = run_command(cmd) print(output) return status, output + def report_from_command(self, cmd): + """Return the report from the `cmd`, with some convenience added.""" + report = self.run_command(cmd).replace('\\', '/') + self.assertNotIn("error", report.lower()) + return report + + def report_lines(self, report): + """Return the lines of the report, as a list.""" + lines = report.split('\n') + self.assertEqual(lines[-1], "") + return lines[:-1] + + def line_count(self, report): + """How many lines are in `report`?""" + return len(self.report_lines(report)) + + def squeezed_lines(self, report): + """Return a list of the lines in report, with the spaces squeezed.""" + lines = self.report_lines(report) + return [re.sub(r"\s+", " ", l.strip()) for l in lines] + + def last_line_squeezed(self, report): + """Return the last line of `report` with the spaces squeezed down.""" + return self.squeezed_lines(report)[-1] + # We run some tests in temporary directories, because they may need to make # files for the tests. But this is expensive, so we can change per-class # whether a temp dir is used or not. It's easy to forget to set that diff --git a/tests/farm/annotate/annotate_dir.py b/tests/farm/annotate/annotate_dir.py index 3e37f9ed..86c18cab 100644 --- a/tests/farm/annotate/annotate_dir.py +++ b/tests/farm/annotate/annotate_dir.py @@ -1,7 +1,7 @@ copy("src", "run") run(""" - coverage -e -x multi.py - coverage -a -d out_anno_dir + coverage run multi.py + coverage annotate -d out_anno_dir """, rundir="run") compare("run/out_anno_dir", "gold_anno_dir", "*,cover", left_extra=True) clean("run") diff --git a/tests/farm/annotate/run.py b/tests/farm/annotate/run.py index c645f21c..236f401f 100644 --- a/tests/farm/annotate/run.py +++ b/tests/farm/annotate/run.py @@ -1,7 +1,7 @@ copy("src", "out") run(""" - coverage -e -x white.py - coverage -a white.py + coverage run white.py + coverage annotate white.py """, rundir="out") compare("out", "gold", "*,cover") clean("out") diff --git a/tests/farm/annotate/run_multi.py b/tests/farm/annotate/run_multi.py index 4e8252ed..ef1e8238 100644 --- a/tests/farm/annotate/run_multi.py +++ b/tests/farm/annotate/run_multi.py @@ -1,7 +1,7 @@ copy("src", "out_multi") run(""" - coverage -e -x multi.py - coverage -a + coverage run multi.py + coverage annotate """, rundir="out_multi") compare("out_multi", "gold_multi", "*,cover") clean("out_multi") diff --git a/tests/farm/run/run_chdir.py b/tests/farm/run/run_chdir.py index f459f500..367cd0ad 100644 --- a/tests/farm/run/run_chdir.py +++ b/tests/farm/run/run_chdir.py @@ -1,7 +1,7 @@ copy("src", "out") run(""" coverage run chdir.py - coverage -r + coverage report """, rundir="out", outfile="stdout.txt") contains("out/stdout.txt", "Line One", diff --git a/tests/farm/run/run_timid.py b/tests/farm/run/run_timid.py index ce78fff1..d4e69a46 100644 --- a/tests/farm/run/run_timid.py +++ b/tests/farm/run/run_timid.py @@ -17,8 +17,8 @@ if os.environ.get('COVERAGE_COVERAGE', ''): copy("src", "out") run(""" python showtrace.py none - coverage -e -x showtrace.py regular - coverage -e -x --timid showtrace.py timid + coverage run showtrace.py regular + coverage run --timid showtrace.py timid """, rundir="out", outfile="showtraceout.txt") # When running without coverage, no trace function @@ -42,8 +42,8 @@ old_opts = os.environ.get('COVERAGE_OPTIONS') os.environ['COVERAGE_OPTIONS'] = '--timid' run(""" - coverage -e -x showtrace.py regular - coverage -e -x --timid showtrace.py timid + coverage run showtrace.py regular + coverage run --timid showtrace.py timid """, rundir="out", outfile="showtraceout.txt") contains("out/showtraceout.txt", diff --git a/tests/farm/run/run_xxx.py b/tests/farm/run/run_xxx.py index 19e94a42..6fedc934 100644 --- a/tests/farm/run/run_xxx.py +++ b/tests/farm/run/run_xxx.py @@ -1,7 +1,7 @@ copy("src", "out") run(""" - coverage -e -x xxx - coverage -r + coverage run xxx + coverage report """, rundir="out", outfile="stdout.txt") contains("out/stdout.txt", "xxx: 3 4 0 7", diff --git a/tests/modules/pkg1/p1a.py b/tests/modules/pkg1/p1a.py index be5fcdd3..337add49 100644 --- a/tests/modules/pkg1/p1a.py +++ b/tests/modules/pkg1/p1a.py @@ -1,5 +1,5 @@ import os, sys # Invoke functions in os and sys so we can see if we measure code there. -x = sys.getcheckinterval() +x = sys.getfilesystemencoding() y = os.getcwd() diff --git a/tests/test_api.py b/tests/test_api.py index 097947d2..31bfc57f 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -100,7 +100,7 @@ class ApiTest(CoverageTest): """Assert that the files here are `files`, ignoring the usual junk.""" here = os.listdir(".") here = self.clean_files(here, ["*.pyc", "__pycache__"]) - self.assertSameElements(here, files) + self.assertCountEqual(here, files) def test_unexecuted_file(self): cov = coverage.coverage() @@ -221,7 +221,7 @@ class ApiTest(CoverageTest): self.assertEqual(cov.get_exclude_list(), ["foo"]) cov.exclude("bar") self.assertEqual(cov.get_exclude_list(), ["foo", "bar"]) - self.assertEqual(cov._exclude_regex('exclude'), "(foo)|(bar)") + self.assertEqual(cov._exclude_regex('exclude'), "(?:foo)|(?:bar)") cov.clear_exclude() self.assertEqual(cov.get_exclude_list(), []) @@ -233,7 +233,9 @@ class ApiTest(CoverageTest): self.assertEqual(cov.get_exclude_list(which='partial'), ["foo"]) cov.exclude("bar", which='partial') self.assertEqual(cov.get_exclude_list(which='partial'), ["foo", "bar"]) - self.assertEqual(cov._exclude_regex(which='partial'), "(foo)|(bar)") + self.assertEqual( + cov._exclude_regex(which='partial'), "(?:foo)|(?:bar)" + ) cov.clear_exclude(which='partial') self.assertEqual(cov.get_exclude_list(which='partial'), []) diff --git a/tests/test_backward.py b/tests/test_backward.py index e98017ae..2c688edd 100644 --- a/tests/test_backward.py +++ b/tests/test_backward.py @@ -12,7 +12,7 @@ class BackwardTest(TestCase): def test_iitems(self): d = {'a': 1, 'b': 2, 'c': 3} items = [('a', 1), ('b', 2), ('c', 3)] - self.assertSameElements(list(iitems(d)), items) + self.assertCountEqual(list(iitems(d)), items) def test_binary_bytes(self): byte_values = [0, 255, 17, 23, 42, 57] diff --git a/tests/test_cmdline.py b/tests/test_cmdline.py index 99bae516..038e9214 100644 --- a/tests/test_cmdline.py +++ b/tests/test_cmdline.py @@ -754,7 +754,7 @@ class CmdMainTest(CoverageTest): self.assertEqual(err[-2], 'Exception: oh noes!') def test_internalraise(self): - with self.assertRaisesRegexp(ValueError, "coverage is broken"): + with self.assertRaisesRegex(ValueError, "coverage is broken"): coverage.cmdline.main(['internalraise']) def test_exit(self): diff --git a/tests/test_codeunit.py b/tests/test_codeunit.py index e4912e11..fe82ea1c 100644 --- a/tests/test_codeunit.py +++ b/tests/test_codeunit.py @@ -31,9 +31,9 @@ class CodeUnitTest(CoverageTest): self.assertEqual(acu[0].flat_rootname(), "aa_afile") self.assertEqual(bcu[0].flat_rootname(), "aa_bb_bfile") self.assertEqual(ccu[0].flat_rootname(), "aa_bb_cc_cfile") - self.assertEqual(acu[0].source_file().read(), "# afile.py\n") - self.assertEqual(bcu[0].source_file().read(), "# bfile.py\n") - self.assertEqual(ccu[0].source_file().read(), "# cfile.py\n") + self.assertEqual(acu[0].source(), "# afile.py\n") + self.assertEqual(bcu[0].source(), "# bfile.py\n") + self.assertEqual(ccu[0].source(), "# cfile.py\n") def test_odd_filenames(self): acu = code_unit_factory("aa/afile.odd.py", FileLocator()) @@ -45,9 +45,9 @@ class CodeUnitTest(CoverageTest): self.assertEqual(acu[0].flat_rootname(), "aa_afile_odd") self.assertEqual(bcu[0].flat_rootname(), "aa_bb_bfile_odd") self.assertEqual(b2cu[0].flat_rootname(), "aa_bb_odd_bfile") - self.assertEqual(acu[0].source_file().read(), "# afile.odd.py\n") - self.assertEqual(bcu[0].source_file().read(), "# bfile.odd.py\n") - self.assertEqual(b2cu[0].source_file().read(), "# bfile.py\n") + self.assertEqual(acu[0].source(), "# afile.odd.py\n") + self.assertEqual(bcu[0].source(), "# bfile.odd.py\n") + self.assertEqual(b2cu[0].source(), "# bfile.py\n") def test_modules(self): import aa, aa.bb, aa.bb.cc @@ -58,9 +58,9 @@ class CodeUnitTest(CoverageTest): self.assertEqual(cu[0].flat_rootname(), "aa") self.assertEqual(cu[1].flat_rootname(), "aa_bb") self.assertEqual(cu[2].flat_rootname(), "aa_bb_cc") - self.assertEqual(cu[0].source_file().read(), "# aa\n") - self.assertEqual(cu[1].source_file().read(), "# bb\n") - self.assertEqual(cu[2].source_file().read(), "") # yes, empty + self.assertEqual(cu[0].source(), "# aa\n") + self.assertEqual(cu[1].source(), "# bb\n") + self.assertEqual(cu[2].source(), "") # yes, empty def test_module_files(self): import aa.afile, aa.bb.bfile, aa.bb.cc.cfile @@ -72,9 +72,9 @@ class CodeUnitTest(CoverageTest): self.assertEqual(cu[0].flat_rootname(), "aa_afile") self.assertEqual(cu[1].flat_rootname(), "aa_bb_bfile") self.assertEqual(cu[2].flat_rootname(), "aa_bb_cc_cfile") - self.assertEqual(cu[0].source_file().read(), "# afile.py\n") - self.assertEqual(cu[1].source_file().read(), "# bfile.py\n") - self.assertEqual(cu[2].source_file().read(), "# cfile.py\n") + self.assertEqual(cu[0].source(), "# afile.py\n") + self.assertEqual(cu[1].source(), "# bfile.py\n") + self.assertEqual(cu[2].source(), "# cfile.py\n") def test_comparison(self): acu = code_unit_factory("aa/afile.py", FileLocator())[0] @@ -97,7 +97,7 @@ class CodeUnitTest(CoverageTest): self.assert_doesnt_exist(egg1.__file__) cu = code_unit_factory([egg1, egg1.egg1], FileLocator()) - self.assertEqual(cu[0].source_file().read(), "") - self.assertEqual(cu[1].source_file().read().split("\n")[0], + self.assertEqual(cu[0].source(), "") + self.assertEqual(cu[1].source().split("\n")[0], "# My egg file!" ) diff --git a/tests/test_config.py b/tests/test_config.py index 7fa31208..7409f4aa 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -125,58 +125,71 @@ class ConfigTest(CoverageTest): class ConfigFileTest(CoverageTest): """Tests of the config file settings in particular.""" - def test_config_file_settings(self): - # This sample file tries to use lots of variation of syntax... - self.make_file(".coveragerc", """\ - # This is a settings file for coverage.py - [run] - timid = yes - data_file = something_or_other.dat - branch = 1 - cover_pylib = TRUE - parallel = on - include = a/ , b/ - - [report] - ; these settings affect reporting. - exclude_lines = - if 0: - - pragma:?\\s+no cover - another_tab - - ignore_errors = TRUE - omit = - one, another, some_more, - yet_more - precision = 3 - - partial_branches = - pragma:?\\s+no branch - partial_branches_always = - if 0: - while True: - - show_missing= TruE - - [html] - - directory = c:\\tricky\\dir.somewhere - extra_css=something/extra.css - title = Title & nums # nums! - [xml] - output=mycov.xml - - [paths] - source = - . - /home/ned/src/ - - other = other, /home/ned/other, c:\\Ned\\etc - - """) - cov = coverage.coverage() - + # This sample file tries to use lots of variation of syntax... + # The {section} placeholder lets us nest these settings in another file. + LOTSA_SETTINGS = """\ + # This is a settings file for coverage.py + [{section}run] + timid = yes + data_file = something_or_other.dat + branch = 1 + cover_pylib = TRUE + parallel = on + include = a/ , b/ + + [{section}report] + ; these settings affect reporting. + exclude_lines = + if 0: + + pragma:?\\s+no cover + another_tab + + ignore_errors = TRUE + omit = + one, another, some_more, + yet_more + precision = 3 + + partial_branches = + pragma:?\\s+no branch + partial_branches_always = + if 0: + while True: + + show_missing= TruE + + [{section}html] + + directory = c:\\tricky\\dir.somewhere + extra_css=something/extra.css + title = Title & nums # nums! + [{section}xml] + output=mycov.xml + + [{section}paths] + source = + . + /home/ned/src/ + + other = other, /home/ned/other, c:\\Ned\\etc + + """ + + # Just some sample setup.cfg text from the docs. + SETUP_CFG = """\ + [bdist_rpm] + release = 1 + packager = Jane Packager <janep@pysoft.com> + doc_files = CHANGES.txt + README.txt + USAGE.txt + doc/ + examples/ + """ + + def assert_config_settings_are_correct(self, cov): + """Check that `cov` has all the settings from LOTSA_SETTINGS.""" self.assertTrue(cov.config.timid) self.assertEqual(cov.config.data_file, "something_or_other.dat") self.assertTrue(cov.config.branch) @@ -211,8 +224,33 @@ class ConfigFileTest(CoverageTest): 'other': ['other', '/home/ned/other', 'c:\\Ned\\etc'] }) + def test_config_file_settings(self): + self.make_file(".coveragerc", self.LOTSA_SETTINGS.format(section="")) + cov = coverage.coverage() + self.assert_config_settings_are_correct(cov) + + def test_config_file_settings_in_setupcfg(self): + nested = self.LOTSA_SETTINGS.format(section="coverage:") + self.make_file("setup.cfg", nested + "\n" + self.SETUP_CFG) + cov = coverage.coverage() + self.assert_config_settings_are_correct(cov) + + def test_setupcfg_only_if_not_coveragerc(self): + self.make_file(".coveragerc", """\ + [run] + include = foo + """) + self.make_file("setup.cfg", """\ + [run] + omit = bar + branch = true + """) + cov = coverage.coverage() + self.assertEqual(cov.config.include, ["foo"]) + self.assertEqual(cov.config.omit, None) + self.assertEqual(cov.config.branch, False) + def test_one(self): - # This sample file tries to use lots of variation of syntax... self.make_file(".coveragerc", """\ [html] title = tabblo & «ταБЬℓσ» # numbers diff --git a/tests/test_coroutine.py b/tests/test_coroutine.py index 28539801..fe6c8326 100644 --- a/tests/test_coroutine.py +++ b/tests/test_coroutine.py @@ -1,5 +1,7 @@ """Tests for coroutining.""" +import os.path, sys + from nose.plugins.skip import SkipTest import coverage @@ -20,15 +22,19 @@ except ImportError: def line_count(s): - """How many non-blank lines are in `s`?""" - return sum(1 for l in s.splitlines() if l.strip()) + """How many non-blank non-comment lines are in `s`?""" + def code_line(l): + """Is this a code line? Not blank, and not a full-line comment.""" + return l.strip() and not l.strip().startswith('#') + return sum(1 for l in s.splitlines() if code_line(l)) class CoroutineTest(CoverageTest): """Tests of the coroutine support in coverage.py.""" - # The code common to all the concurrency models. Don't use any comments, - # we're counting non-blank lines to see they are all covered. + LIMIT = 1000 + + # The code common to all the concurrency models. COMMON = """ class Producer(threading.Thread): def __init__(self, q): @@ -36,7 +42,7 @@ class CoroutineTest(CoverageTest): self.q = q def run(self): - for i in range(1000): + for i in range({LIMIT}): self.q.put(i) self.q.put(None) @@ -54,28 +60,32 @@ class CoroutineTest(CoverageTest): break sum += i - q = Queue.Queue() + q = queue.Queue() c = Consumer(q) - c.start() p = Producer(q) + c.start() p.start() + p.join() c.join() - """ + """.format(LIMIT=LIMIT) # Import the things to use threads. - THREAD = """\ + if sys.version_info < (3, 0): + THREAD = """\ + import threading + import Queue as queue + """ + COMMON + else: + THREAD = """\ import threading - try: - import Queue - except ImportError: # Python 3 :) - import queue as Queue + import queue """ + COMMON # Import the things to use eventlet. EVENTLET = """\ import eventlet.green.threading as threading - import eventlet.queue as Queue + import eventlet.queue as queue """ + COMMON # Import the things to use gevent. @@ -83,7 +93,7 @@ class CoroutineTest(CoverageTest): from gevent import monkey monkey.patch_thread() import threading - import gevent.queue as Queue + import gevent.queue as queue """ + COMMON def try_some_code(self, code, args): @@ -91,16 +101,21 @@ class CoroutineTest(CoverageTest): self.make_file("try_it.py", code) - raise SkipTest("Need to put this on a back burner for a while...") - - out = self.run_command("coverage run %s try_it.py" % args) - expected_out = "%d\n" % (sum(range(1000))) + out = self.run_command("coverage run --timid %s try_it.py" % args) + expected_out = "%d\n" % (sum(range(self.LIMIT))) self.assertEqual(out, expected_out) # Read the coverage file and see that try_it.py has all its lines # executed. data = coverage.CoverageData() data.read_file(".coverage") + + # If the test fails, it's helpful to see this info: + fname = os.path.abspath("try_it.py") + linenos = data.executed_lines(fname).keys() + print("{0}: {1}".format(len(linenos), linenos)) + print_simple_annotation(code, linenos) + lines = line_count(code) self.assertEqual(data.summary()['try_it.py'], lines) @@ -114,7 +129,15 @@ class CoroutineTest(CoverageTest): self.try_some_code(self.EVENTLET, "--coroutine=eventlet") def test_gevent(self): + raise SkipTest("Still not sure why gevent isn't working...") + if gevent is None: raise SkipTest("No gevent available") self.try_some_code(self.GEVENT, "--coroutine=gevent") + + +def print_simple_annotation(code, linenos): + """Print the lines in `code` with X for each line number in `linenos`.""" + for lineno, line in enumerate(code.splitlines(), start=1): + print(" {0:s} {1}".format("X" if lineno in linenos else " ", line)) diff --git a/tests/test_coverage.py b/tests/test_coverage.py index 33f644fa..565fa4e1 100644 --- a/tests/test_coverage.py +++ b/tests/test_coverage.py @@ -46,7 +46,7 @@ class TestCoverageTest(CoverageTest): def test_failed_coverage(self): # If the lines are wrong, the message shows right and wrong. - with self.assertRaisesRegexp(AssertionError, r"\[1, 2] != \[1]"): + with self.assertRaisesRegex(AssertionError, r"\[1, 2] != \[1]"): self.check_coverage("""\ a = 1 b = 2 @@ -55,7 +55,7 @@ class TestCoverageTest(CoverageTest): ) # If the list of lines possibilities is wrong, the msg shows right. msg = r"None of the lines choices matched \[1, 2]" - with self.assertRaisesRegexp(AssertionError, msg): + with self.assertRaisesRegex(AssertionError, msg): self.check_coverage("""\ a = 1 b = 2 @@ -63,7 +63,7 @@ class TestCoverageTest(CoverageTest): ([1], [2]) ) # If the missing lines are wrong, the message shows right and wrong. - with self.assertRaisesRegexp(AssertionError, r"'3' != '37'"): + with self.assertRaisesRegex(AssertionError, r"'3' != '37'"): self.check_coverage("""\ a = 1 if a == 2: @@ -74,7 +74,7 @@ class TestCoverageTest(CoverageTest): ) # If the missing lines possibilities are wrong, the msg shows right. msg = r"None of the missing choices matched '3'" - with self.assertRaisesRegexp(AssertionError, msg): + with self.assertRaisesRegex(AssertionError, msg): self.check_coverage("""\ a = 1 if a == 2: @@ -1671,7 +1671,7 @@ class ReportingTest(CoverageTest): def test_no_data_to_report_on_annotate(self): # Reporting with no data produces a nice message and no output dir. - with self.assertRaisesRegexp(CoverageException, "No data to report."): + with self.assertRaisesRegex(CoverageException, "No data to report."): self.command_line("annotate -d ann") self.assert_doesnt_exist("ann") @@ -1681,12 +1681,12 @@ class ReportingTest(CoverageTest): def test_no_data_to_report_on_html(self): # Reporting with no data produces a nice message and no output dir. - with self.assertRaisesRegexp(CoverageException, "No data to report."): + with self.assertRaisesRegex(CoverageException, "No data to report."): self.command_line("html -d htmlcov") self.assert_doesnt_exist("htmlcov") def test_no_data_to_report_on_xml(self): # Reporting with no data produces a nice message. - with self.assertRaisesRegexp(CoverageException, "No data to report."): + with self.assertRaisesRegex(CoverageException, "No data to report."): self.command_line("xml") self.assert_doesnt_exist("coverage.xml") diff --git a/tests/test_data.py b/tests/test_data.py index 31578f26..b048fd18 100644 --- a/tests/test_data.py +++ b/tests/test_data.py @@ -33,7 +33,7 @@ class DataTest(CoverageTest): def assert_measured_files(self, covdata, measured): """Check that `covdata`'s measured files are `measured`.""" - self.assertSameElements(covdata.measured_files(), measured) + self.assertCountEqual(covdata.measured_files(), measured) def test_reading_empty(self): covdata = CoverageData() @@ -96,9 +96,9 @@ class DataTest(CoverageTest): data = pickle.load(fdata) lines = data['lines'] - self.assertSameElements(lines.keys(), MEASURED_FILES_1) - self.assertSameElements(lines['a.py'], A_PY_LINES_1) - self.assertSameElements(lines['b.py'], B_PY_LINES_1) + self.assertCountEqual(lines.keys(), MEASURED_FILES_1) + self.assertCountEqual(lines['a.py'], A_PY_LINES_1) + self.assertCountEqual(lines['b.py'], B_PY_LINES_1) # If not measuring branches, there's no arcs entry. self.assertEqual(data.get('arcs', 'not there'), 'not there') @@ -111,10 +111,10 @@ class DataTest(CoverageTest): with open(".coverage", 'rb') as fdata: data = pickle.load(fdata) - self.assertSameElements(data['lines'].keys(), []) + self.assertCountEqual(data['lines'].keys(), []) arcs = data['arcs'] - self.assertSameElements(arcs['x.py'], X_PY_ARCS_3) - self.assertSameElements(arcs['y.py'], Y_PY_ARCS_3) + self.assertCountEqual(arcs['x.py'], X_PY_ARCS_3) + self.assertCountEqual(arcs['y.py'], Y_PY_ARCS_3) def test_combining_with_aliases(self): covdata1 = CoverageData() diff --git a/tests/test_execfile.py b/tests/test_execfile.py index 7cd8ac4e..2427847e 100644 --- a/tests/test_execfile.py +++ b/tests/test_execfile.py @@ -118,11 +118,11 @@ class RunPycFileTest(CoverageTest): fpyc.write(binary_bytes([0x2a, 0xeb, 0x0d, 0x0a])) fpyc.close() - with self.assertRaisesRegexp(NoCode, "Bad magic number in .pyc file"): + with self.assertRaisesRegex(NoCode, "Bad magic number in .pyc file"): run_python_file(pycfile, [pycfile]) def test_no_such_pyc_file(self): - with self.assertRaisesRegexp(NoCode, "No file to run: 'xyzzy.pyc'"): + with self.assertRaisesRegex(NoCode, "No file to run: 'xyzzy.pyc'"): run_python_file("xyzzy.pyc", []) @@ -138,22 +138,27 @@ class RunModuleTest(CoverageTest): def test_runmod1(self): run_python_module("runmod1", ["runmod1", "hello"]) + self.assertEqual(self.stderr(), "") self.assertEqual(self.stdout(), "runmod1: passed hello\n") def test_runmod2(self): run_python_module("pkg1.runmod2", ["runmod2", "hello"]) + self.assertEqual(self.stderr(), "") self.assertEqual(self.stdout(), "runmod2: passed hello\n") def test_runmod3(self): run_python_module("pkg1.sub.runmod3", ["runmod3", "hello"]) + self.assertEqual(self.stderr(), "") self.assertEqual(self.stdout(), "runmod3: passed hello\n") def test_pkg1_main(self): run_python_module("pkg1", ["pkg1", "hello"]) + self.assertEqual(self.stderr(), "") self.assertEqual(self.stdout(), "pkg1.__main__: passed hello\n") def test_pkg1_sub_main(self): run_python_module("pkg1.sub", ["pkg1.sub", "hello"]) + self.assertEqual(self.stderr(), "") self.assertEqual(self.stdout(), "pkg1.sub.__main__: passed hello\n") def test_no_such_module(self): diff --git a/tests/test_farm.py b/tests/test_farm.py index 261ce4d0..b2ea3697 100644 --- a/tests/test_farm.py +++ b/tests/test_farm.py @@ -15,6 +15,10 @@ def test_farm(clean_only=False): yield (case,) +# "rU" was deprecated in 3.4 +READ_MODE = "rU" if sys.version_info < (3, 4) else "r" + + class FarmTestCase(object): """A test case from the farm tree. @@ -22,8 +26,8 @@ class FarmTestCase(object): copy("src", "out") run(''' - coverage -x white.py - coverage -a white.py + coverage run white.py + coverage annotate white.py ''', rundir="out") compare("out", "gold", "*,cover") clean("out") @@ -258,9 +262,9 @@ class FarmTestCase(object): # ourselves. text_diff = [] for f in diff_files: - with open(os.path.join(dir1, f), "rU") as fobj: + with open(os.path.join(dir1, f), READ_MODE) as fobj: left = fobj.read() - with open(os.path.join(dir2, f), "rU") as fobj: + with open(os.path.join(dir2, f), READ_MODE) as fobj: right = fobj.read() if scrubs: left = self._scrub(left, scrubs) @@ -280,7 +284,7 @@ class FarmTestCase(object): def _scrub(self, strdata, scrubs): """Scrub uninteresting data from the payload in `strdata`. - `scrubs is a list of (find, replace) pairs of regexes that are used on + `scrubs` is a list of (find, replace) pairs of regexes that are used on `strdata`. A string is returned. """ @@ -295,7 +299,8 @@ class FarmTestCase(object): missing in `filename`. """ - text = open(filename, "r").read() + with open(filename, "r") as fobj: + text = fobj.read() for s in strlist: assert s in text, "Missing content in %s: %r" % (filename, s) @@ -306,7 +311,8 @@ class FarmTestCase(object): `filename`. """ - text = open(filename, "r").read() + with open(filename, "r") as fobj: + text = fobj.read() for s in strlist: assert s not in text, "Forbidden content in %s: %r" % (filename, s) diff --git a/tests/test_files.py b/tests/test_files.py index f93feba7..070430ff 100644 --- a/tests/test_files.py +++ b/tests/test_files.py @@ -93,6 +93,12 @@ class MatcherTest(CoverageTest): for filepath, matches in matches_to_try: self.assertMatches(fnm, filepath, matches) + def test_fnmatch_matcher_overload(self): + fnm = FnmatchMatcher(["*x%03d*.txt" % i for i in range(500)]) + self.assertMatches(fnm, "x007foo.txt", True) + self.assertMatches(fnm, "x123foo.txt", True) + self.assertMatches(fnm, "x798bar.txt", False) + class PathAliasesTest(CoverageTest): """Tests for coverage/files.py:PathAliases""" @@ -131,11 +137,11 @@ class PathAliasesTest(CoverageTest): def test_cant_have_wildcard_at_end(self): aliases = PathAliases() msg = "Pattern must not end with wildcards." - with self.assertRaisesRegexp(CoverageException, msg): + with self.assertRaisesRegex(CoverageException, msg): aliases.add("/ned/home/*", "fooey") - with self.assertRaisesRegexp(CoverageException, msg): + with self.assertRaisesRegex(CoverageException, msg): aliases.add("/ned/home/*/", "fooey") - with self.assertRaisesRegexp(CoverageException, msg): + with self.assertRaisesRegex(CoverageException, msg): aliases.add("/ned/home/*/*/", "fooey") def test_no_accidental_munging(self): @@ -177,7 +183,7 @@ class RelativePathAliasesTest(CoverageTest): aliases.add(d, '/the/source') the_file = os.path.join(d, 'a.py') the_file = os.path.expanduser(the_file) - the_file = os.path.abspath(the_file) + the_file = os.path.abspath(os.path.realpath(the_file)) assert '~' not in the_file # to be sure the test is pure. self.assertEqual(aliases.map(the_file), '/the/source/a.py') diff --git a/tests/test_html.py b/tests/test_html.py index 41859382..8e43e7cf 100644 --- a/tests/test_html.py +++ b/tests/test_html.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- """Tests that HTML generation is awesome.""" -import os.path, re +import os.path, re, sys import coverage import coverage.html from coverage.misc import CoverageException, NotPython, NoSource @@ -42,6 +42,13 @@ class HtmlTestHelpers(CoverageTest): os.remove("htmlcov/helper1.html") os.remove("htmlcov/helper2.html") + def get_html_report_content(self, module): + """Return the content of the HTML report for `module`.""" + filename = module.replace(".py", ".html").replace("/", "_") + filename = os.path.join("htmlcov", filename) + with open(filename) as f: + return f.read() + class HtmlDeltaTest(HtmlTestHelpers, CoverageTest): """Tests of the HTML delta speed-ups.""" @@ -208,7 +215,7 @@ class HtmlTitleTest(HtmlTestHelpers, CoverageTest): ) -class HtmlWithUnparsableFilesTest(CoverageTest): +class HtmlWithUnparsableFilesTest(HtmlTestHelpers, CoverageTest): """Test the behavior when measuring unparsable files.""" def test_dotpy_not_python(self): @@ -217,7 +224,7 @@ class HtmlWithUnparsableFilesTest(CoverageTest): self.start_import_stop(cov, "innocuous") self.make_file("innocuous.py", "<h1>This isn't python!</h1>") msg = "Couldn't parse '.*innocuous.py' as Python source: .* at line 1" - with self.assertRaisesRegexp(NotPython, msg): + with self.assertRaisesRegex(NotPython, msg): cov.html_report() def test_dotpy_not_python_ignored(self): @@ -267,6 +274,31 @@ class HtmlWithUnparsableFilesTest(CoverageTest): cov.html_report() self.assert_exists("htmlcov/index.html") + def test_decode_error(self): + # imp.load_module won't load a file with an undecodable character + # in a comment, though Python will run them. So we'll change the + # file after running. + self.make_file("main.py", "import sub.not_ascii") + self.make_file("sub/__init__.py") + self.make_file("sub/not_ascii.py", """\ + a = 1 # Isn't this great?! + """) + cov = coverage.coverage() + self.start_import_stop(cov, "main") + + # Create the undecodable version of the file. + self.make_file("sub/not_ascii.py", """\ + a = 1 # Isn't this great?\xcb! + """) + cov.html_report() + + html_report = self.get_html_report_content("sub/not_ascii.py") + if sys.version_info < (3, 0): + expected = "# Isn't this great?�!" + else: + expected = "# Isn't this great?Ë!" + self.assertIn(expected, html_report) + class HtmlTest(CoverageTest): """Moar HTML tests.""" @@ -283,7 +315,7 @@ class HtmlTest(CoverageTest): missing_file = os.path.join(self.temp_dir, "sub", "another.py") missing_file = os.path.realpath(missing_file) msg = "(?i)No source for code: '%s'" % re.escape(missing_file) - with self.assertRaisesRegexp(NoSource, msg): + with self.assertRaisesRegex(NoSource, msg): cov.html_report() class HtmlStaticFileTest(CoverageTest): @@ -340,5 +372,5 @@ class HtmlStaticFileTest(CoverageTest): cov = coverage.coverage() self.start_import_stop(cov, "main") msg = "Couldn't find static file '.*'" - with self.assertRaisesRegexp(CoverageException, msg): + with self.assertRaisesRegex(CoverageException, msg): cov.html_report() diff --git a/tests/test_parser.py b/tests/test_parser.py index 5b90f342..a392ea03 100644 --- a/tests/test_parser.py +++ b/tests/test_parser.py @@ -13,7 +13,7 @@ class PythonParserTest(CoverageTest): def parse_source(self, text): """Parse `text` as source, and return the `PythonParser` used.""" text = textwrap.dedent(text) - parser = PythonParser(None, text=text, exclude="nocover") + parser = PythonParser(text=text, exclude="nocover") parser.parse_source() return parser @@ -98,7 +98,7 @@ class ParserFileTest(CoverageTest): def parse_file(self, filename): """Parse `text` as source, and return the `PythonParser` used.""" - parser = PythonParser(None, filename=filename, exclude="nocover") + parser = PythonParser(filename=filename, exclude="nocover") parser.parse_source() return parser diff --git a/tests/test_phystokens.py b/tests/test_phystokens.py index e15400b6..4755c167 100644 --- a/tests/test_phystokens.py +++ b/tests/test_phystokens.py @@ -97,6 +97,11 @@ if sys.version_info < (3, 0): source = "# This Python file uses this encoding: utf-8\n" self.assertEqual(source_encoding(source), 'utf-8') + def test_detect_source_encoding_not_in_comment(self): + # Should not detect anything here + source = 'def parse(src, encoding=None):\n pass' + self.assertEqual(source_encoding(source), 'ascii') + def test_detect_source_encoding_on_second_line(self): # A coding declaration should be found despite a first blank line. source = "\n# coding=cp850\n\n" diff --git a/tests/test_process.py b/tests/test_process.py index fa4759a8..d8314982 100644 --- a/tests/test_process.py +++ b/tests/test_process.py @@ -26,7 +26,7 @@ class ProcessTest(CoverageTest): """) self.assert_doesnt_exist(".coverage") - self.run_command("coverage -x mycode.py") + self.run_command("coverage run mycode.py") self.assert_exists(".coverage") def test_environment(self): @@ -39,7 +39,7 @@ class ProcessTest(CoverageTest): """) self.assert_doesnt_exist(".coverage") - out = self.run_command("coverage -x mycode.py") + out = self.run_command("coverage run mycode.py") self.assert_exists(".coverage") self.assertEqual(out, 'done\n') @@ -55,11 +55,11 @@ class ProcessTest(CoverageTest): print('done') """) - out = self.run_command("coverage -x -p b_or_c.py b") + out = self.run_command("coverage run -p b_or_c.py b") self.assertEqual(out, 'done\n') self.assert_doesnt_exist(".coverage") - out = self.run_command("coverage -x -p b_or_c.py c") + out = self.run_command("coverage run -p b_or_c.py c") self.assertEqual(out, 'done\n') self.assert_doesnt_exist(".coverage") @@ -67,7 +67,7 @@ class ProcessTest(CoverageTest): self.assertEqual(self.number_of_data_files(), 2) # Combine the parallel coverage data files into .coverage . - self.run_command("coverage -c") + self.run_command("coverage combine") self.assert_exists(".coverage") # After combining, there should be only the .coverage file. @@ -91,23 +91,23 @@ class ProcessTest(CoverageTest): print('done') """) - out = self.run_command("coverage -x -p b_or_c.py b") + out = self.run_command("coverage run -p b_or_c.py b") self.assertEqual(out, 'done\n') self.assert_doesnt_exist(".coverage") self.assertEqual(self.number_of_data_files(), 1) # Combine the (one) parallel coverage data file into .coverage . - self.run_command("coverage -c") + self.run_command("coverage combine") self.assert_exists(".coverage") self.assertEqual(self.number_of_data_files(), 1) - out = self.run_command("coverage -x -p b_or_c.py c") + out = self.run_command("coverage run --append -p b_or_c.py c") self.assertEqual(out, 'done\n') self.assert_exists(".coverage") self.assertEqual(self.number_of_data_files(), 2) # Combine the parallel coverage data files into .coverage . - self.run_command("coverage -c") + self.run_command("coverage combine") self.assert_exists(".coverage") # After combining, there should be only the .coverage file. @@ -229,7 +229,7 @@ class ProcessTest(CoverageTest): self.run_command("coverage run fleeting.py") os.remove("fleeting.py") out = self.run_command("coverage html -d htmlcov") - self.assertRegexpMatches(out, "No source for code: '.*fleeting.py'") + self.assertRegex(out, "No source for code: '.*fleeting.py'") self.assertNotIn("Traceback", out) # It happens that the code paths are different for *.py and other @@ -240,14 +240,14 @@ class ProcessTest(CoverageTest): self.run_command("coverage run fleeting") os.remove("fleeting") - status, out = self.run_command_status("coverage html -d htmlcov", 1) - self.assertRegexpMatches(out, "No source for code: '.*fleeting'") + status, out = self.run_command_status("coverage html -d htmlcov") + self.assertRegex(out, "No source for code: '.*fleeting'") self.assertNotIn("Traceback", out) self.assertEqual(status, 1) def test_running_missing_file(self): - status, out = self.run_command_status("coverage run xyzzy.py", 1) - self.assertRegexpMatches(out, "No file to run: .*xyzzy.py") + status, out = self.run_command_status("coverage run xyzzy.py") + self.assertRegex(out, "No file to run: .*xyzzy.py") self.assertNotIn("raceback", out) self.assertNotIn("rror", out) self.assertEqual(status, 1) @@ -265,7 +265,7 @@ class ProcessTest(CoverageTest): # The important thing is for "coverage run" and "python" to report the # same traceback. - status, out = self.run_command_status("coverage run throw.py", 1) + status, out = self.run_command_status("coverage run throw.py") out2 = self.run_command("python throw.py") if '__pypy__' in sys.builtin_module_names: # Pypy has an extra frame in the traceback for some reason @@ -294,8 +294,8 @@ class ProcessTest(CoverageTest): # The important thing is for "coverage run" and "python" to have the # same output. No traceback. - status, out = self.run_command_status("coverage run exit.py", 17) - status2, out2 = self.run_command_status("python exit.py", 17) + status, out = self.run_command_status("coverage run exit.py") + status2, out2 = self.run_command_status("python exit.py") self.assertMultiLineEqual(out, out2) self.assertMultiLineEqual(out, "about to exit..\n") self.assertEqual(status, status2) @@ -310,8 +310,8 @@ class ProcessTest(CoverageTest): f1() """) - status, out = self.run_command_status("coverage run exit_none.py", 0) - status2, out2 = self.run_command_status("python exit_none.py", 0) + status, out = self.run_command_status("coverage run exit_none.py") + status2, out2 = self.run_command_status("python exit_none.py") self.assertMultiLineEqual(out, out2) self.assertMultiLineEqual(out, "about to exit quietly..\n") self.assertEqual(status, status2) @@ -378,7 +378,7 @@ class ProcessTest(CoverageTest): self.assertEqual(self.number_of_data_files(), 2) # Combine the parallel coverage data files into .coverage . - self.run_command("coverage -c") + self.run_command("coverage combine") self.assert_exists(".coverage") # After combining, there should be only the .coverage file. @@ -502,6 +502,18 @@ class ProcessTest(CoverageTest): # about 5. self.assertGreater(data.summary()['os.py'], 50) + def test_deprecation_warnings(self): + # Test that coverage doesn't trigger deprecation warnings. + # https://bitbucket.org/ned/coveragepy/issue/305/pendingdeprecationwarning-the-imp-module + self.make_file("allok.py", """\ + import warnings + warnings.simplefilter('default') + import coverage + print("No warnings!") + """) + out = self.run_command("python allok.py") + self.assertEqual(out, "No warnings!\n") + class AliasedCommandTest(CoverageTest): """Tests of the version-specific command aliases.""" @@ -556,32 +568,47 @@ class FailUnderTest(CoverageTest): def setUp(self): super(FailUnderTest, self).setUp() - self.make_file("fifty.py", """\ - # I have 50% coverage! + self.make_file("forty_two_plus.py", """\ + # I have 42.857% (3/7) coverage! a = 1 - if a > 2: - b = 3 - c = 4 + b = 2 + if a > 3: + b = 4 + c = 5 + d = 6 + e = 7 """) - st, _ = self.run_command_status("coverage run fifty.py", 0) + st, _ = self.run_command_status("coverage run forty_two_plus.py") + self.assertEqual(st, 0) + st, out = self.run_command_status("coverage report") self.assertEqual(st, 0) + self.assertEqual( + self.last_line_squeezed(out), + "forty_two_plus 7 4 43%" + ) def test_report(self): - st, _ = self.run_command_status("coverage report --fail-under=50", 0) + st, _ = self.run_command_status("coverage report --fail-under=42") + self.assertEqual(st, 0) + st, _ = self.run_command_status("coverage report --fail-under=43") self.assertEqual(st, 0) - st, _ = self.run_command_status("coverage report --fail-under=51", 2) + st, _ = self.run_command_status("coverage report --fail-under=44") self.assertEqual(st, 2) def test_html_report(self): - st, _ = self.run_command_status("coverage html --fail-under=50", 0) + st, _ = self.run_command_status("coverage html --fail-under=42") self.assertEqual(st, 0) - st, _ = self.run_command_status("coverage html --fail-under=51", 2) + st, _ = self.run_command_status("coverage html --fail-under=43") + self.assertEqual(st, 0) + st, _ = self.run_command_status("coverage html --fail-under=44") self.assertEqual(st, 2) def test_xml_report(self): - st, _ = self.run_command_status("coverage xml --fail-under=50", 0) + st, _ = self.run_command_status("coverage xml --fail-under=42") + self.assertEqual(st, 0) + st, _ = self.run_command_status("coverage xml --fail-under=43") self.assertEqual(st, 0) - st, _ = self.run_command_status("coverage xml --fail-under=51", 2) + st, _ = self.run_command_status("coverage xml --fail-under=44") self.assertEqual(st, 2) diff --git a/tests/test_summary.py b/tests/test_summary.py index 29167bf8..7bd1c496 100644 --- a/tests/test_summary.py +++ b/tests/test_summary.py @@ -21,26 +21,10 @@ class SummaryTest(CoverageTest): # Parent class saves and restores sys.path, we can just modify it. sys.path.append(self.nice_file(os.path.dirname(__file__), 'modules')) - def report_from_command(self, cmd): - """Return the report from the `cmd`, with some convenience added.""" - report = self.run_command(cmd).replace('\\', '/') - self.assertNotIn("error", report.lower()) - return report - - def line_count(self, report): - """How many lines are in `report`?""" - self.assertEqual(report.split('\n')[-1], "") - return len(report.split('\n')) - 1 - - def last_line_squeezed(self, report): - """Return the last line of `report` with the spaces squeezed down.""" - last_line = report.split('\n')[-2] - return re.sub(r"\s+", " ", last_line) - def test_report(self): - out = self.run_command("coverage -x mycode.py") + out = self.run_command("coverage run mycode.py") self.assertEqual(out, 'done\n') - report = self.report_from_command("coverage -r") + report = self.report_from_command("coverage report") # Name Stmts Miss Cover # --------------------------------------------------------------------- @@ -58,8 +42,24 @@ class SummaryTest(CoverageTest): def test_report_just_one(self): # Try reporting just one module - self.run_command("coverage -x mycode.py") - report = self.report_from_command("coverage -r mycode.py") + self.run_command("coverage run mycode.py") + report = self.report_from_command("coverage report mycode.py") + + # Name Stmts Miss Cover + # ---------------------------- + # mycode 4 0 100% + + self.assertEqual(self.line_count(report), 3) + self.assertNotIn("/coverage/", report) + self.assertNotIn("/tests/modules/covmod1 ", report) + self.assertNotIn("/tests/zipmods.zip/covmodzip1 ", report) + self.assertIn("mycode ", report) + self.assertEqual(self.last_line_squeezed(report), "mycode 4 0 100%") + + def test_report_wildcard(self): + # Try reporting using wildcards to get the modules. + self.run_command("coverage run mycode.py") + report = self.report_from_command("coverage report my*.py") # Name Stmts Miss Cover # ---------------------------- @@ -75,8 +75,10 @@ class SummaryTest(CoverageTest): def test_report_omitting(self): # Try reporting while omitting some modules prefix = os.path.split(__file__)[0] - self.run_command("coverage -x mycode.py") - report = self.report_from_command("coverage -r -o '%s/*'" % prefix) + self.run_command("coverage run mycode.py") + report = self.report_from_command( + "coverage report --omit '%s/*'" % prefix + ) # Name Stmts Miss Cover # ---------------------------- @@ -126,13 +128,109 @@ class SummaryTest(CoverageTest): self.assertEqual(self.last_line_squeezed(report), "mybranch 5 0 2 1 86%") + def test_report_show_missing(self): + self.make_file("mymissing.py", """\ + def missing(x, y): + if x: + print("x") + return x + if y: + print("y") + try: + print("z") + 1/0 + print("Never!") + except ZeroDivisionError: + pass + return x + missing(0, 1) + """) + out = self.run_command("coverage run mymissing.py") + self.assertEqual(out, 'y\nz\n') + report = self.report_from_command("coverage report --show-missing") + + # Name Stmts Miss Cover Missing + # ----------------------------------------- + # mymissing 14 3 79% 3-4, 10 + + self.assertEqual(self.line_count(report), 3) + self.assertIn("mymissing ", report) + self.assertEqual(self.last_line_squeezed(report), + "mymissing 14 3 79% 3-4, 10") + + def test_report_show_missing_branches(self): + self.make_file("mybranch.py", """\ + def branch(x, y): + if x: + print("x") + if y: + print("y") + return x + branch(1, 1) + """) + out = self.run_command("coverage run --branch mybranch.py") + self.assertEqual(out, 'x\ny\n') + report = self.report_from_command("coverage report --show-missing") + + # Name Stmts Miss Branch BrMiss Cover Missing + # ------------------------------------------------------- + # mybranch 7 0 4 2 82% 2->4, 4->6 + + self.assertEqual(self.line_count(report), 3) + self.assertIn("mybranch ", report) + self.assertEqual(self.last_line_squeezed(report), + "mybranch 7 0 4 2 82% 2->4, 4->6") + + def test_report_show_missing_branches_and_lines(self): + self.make_file("main.py", """\ + import mybranch + """) + self.make_file("mybranch.py", """\ + def branch(x, y, z): + if x: + print("x") + if y: + print("y") + if z: + if x and y: + print("z") + return x + branch(1, 1, 0) + """) + out = self.run_command("coverage run --branch main.py") + self.assertEqual(out, 'x\ny\n') + report = self.report_from_command("coverage report --show-missing") + + # pylint: disable=C0301 + # Name Stmts Miss Branch BrMiss Cover Missing + # ------------------------------------------------------- + # main 1 0 0 0 100% + # mybranch 10 2 8 5 61% 7-8, 2->4, 4->6 + # ------------------------------------------------------- + # TOTAL 11 2 8 5 63% + + self.assertEqual(self.line_count(report), 6) + squeezed = self.squeezed_lines(report) + self.assertEqual( + squeezed[2], + "main 1 0 0 0 100%" + ) + self.assertEqual( + squeezed[3], + "mybranch 10 2 8 5 61% 7-8, 2->4, 4->6" + ) + self.assertEqual( + squeezed[5], + "TOTAL 11 2 8 5 63%" + ) + def test_dotpy_not_python(self): # We run a .py file, and when reporting, we can't parse it as Python. # We should get an error message in the report. self.run_command("coverage run mycode.py") self.make_file("mycode.py", "This isn't python at all!") - report = self.report_from_command("coverage -r mycode.py") + report = self.report_from_command("coverage report mycode.py") # pylint: disable=C0301 # Name Stmts Miss Cover @@ -155,7 +253,7 @@ class SummaryTest(CoverageTest): # but we've said to ignore errors, so there's no error reported. self.run_command("coverage run mycode.py") self.make_file("mycode.py", "This isn't python at all!") - report = self.report_from_command("coverage -r -i mycode.py") + report = self.report_from_command("coverage report -i mycode.py") # Name Stmts Miss Cover # ---------------------------- @@ -171,7 +269,7 @@ class SummaryTest(CoverageTest): self.run_command("coverage run mycode.html") # Before reporting, change it to be an HTML file. self.make_file("mycode.html", "<h1>This isn't python at all!</h1>") - report = self.report_from_command("coverage -r mycode.html") + report = self.report_from_command("coverage report mycode.html") # Name Stmts Miss Cover # ---------------------------- diff --git a/tests/test_templite.py b/tests/test_templite.py index 4b1f6e45..a4667a62 100644 --- a/tests/test_templite.py +++ b/tests/test_templite.py @@ -35,8 +35,12 @@ class TempliteTest(CoverageTest): self.assertEqual(actual, result) def assertSynErr(self, msg): + """Assert that a `TempliteSyntaxError` will happen. + + A context manager, and the message should be `msg`. + """ pat = "^" + re.escape(msg) + "$" - return self.assertRaisesRegexp(TempliteSyntaxError, pat) + return self.assertRaisesRegex(TempliteSyntaxError, pat) def test_passthrough(self): # Strings without variables are passed through unchanged. diff --git a/tests/test_testing.py b/tests/test_testing.py index a89a59a9..049a1982 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -12,13 +12,13 @@ class TestingTest(TestCase): run_in_temp_dir = False - def test_assert_same_elements(self): - self.assertSameElements(set(), set()) - self.assertSameElements(set([1,2,3]), set([3,1,2])) + def test_assert_count_equal(self): + self.assertCountEqual(set(), set()) + self.assertCountEqual(set([1,2,3]), set([3,1,2])) with self.assertRaises(AssertionError): - self.assertSameElements(set([1,2,3]), set()) + self.assertCountEqual(set([1,2,3]), set()) with self.assertRaises(AssertionError): - self.assertSameElements(set([1,2,3]), set([4,5,6])) + self.assertCountEqual(set([1,2,3]), set([4,5,6])) class CoverageTestTest(CoverageTest): |