diff options
author | Ned Batchelder <ned@nedbatchelder.com> | 2013-12-13 22:45:10 -0500 |
---|---|---|
committer | Ned Batchelder <ned@nedbatchelder.com> | 2013-12-13 22:45:10 -0500 |
commit | 2df9b1c35cbb5c92204fc5923368a3d619a34f6d (patch) | |
tree | d1ede8ffef812ba4e345b08f698f001ebe69cb56 /tests | |
parent | 84221611890880b749dbb650e8d07ac8918dba46 (diff) | |
parent | 7c66441eab3af17539c478a2cb4e19cd93ba0cf4 (diff) | |
download | python-coveragepy-git-2df9b1c35cbb5c92204fc5923368a3d619a34f6d.tar.gz |
Merged 4.0 to default
Diffstat (limited to 'tests')
-rw-r--r-- | tests/backunittest.py | 19 | ||||
-rw-r--r-- | tests/coveragetest.py | 36 | ||||
-rw-r--r-- | tests/farm/html/run_partial.py | 7 | ||||
-rw-r--r-- | tests/osinfo.py | 7 | ||||
-rw-r--r-- | tests/test_arcs.py | 117 | ||||
-rw-r--r-- | tests/test_collector.py | 3 | ||||
-rw-r--r-- | tests/test_config.py | 24 | ||||
-rw-r--r-- | tests/test_coverage.py | 332 | ||||
-rw-r--r-- | tests/test_data.py | 10 | ||||
-rw-r--r-- | tests/test_execfile.py | 5 | ||||
-rw-r--r-- | tests/test_farm.py | 4 | ||||
-rw-r--r-- | tests/test_files.py | 1 | ||||
-rw-r--r-- | tests/test_html.py | 31 | ||||
-rw-r--r-- | tests/test_oddball.py | 73 | ||||
-rw-r--r-- | tests/test_phystokens.py | 11 | ||||
-rw-r--r-- | tests/test_process.py | 44 | ||||
-rw-r--r-- | tests/test_summary.py | 2 | ||||
-rw-r--r-- | tests/test_testing.py | 9 |
18 files changed, 334 insertions, 401 deletions
diff --git a/tests/backunittest.py b/tests/backunittest.py index 30da78eb..0964ab1d 100644 --- a/tests/backunittest.py +++ b/tests/backunittest.py @@ -1,8 +1,6 @@ """Implementations of unittest features from the future.""" -import difflib, re, sys, unittest - -from coverage.backward import set # pylint: disable=W0622 +import difflib, re, unittest def _need(method): @@ -17,18 +15,6 @@ class TestCase(unittest.TestCase): the builtin `unittest` doesn't have them. """ - if _need('assertTrue'): - def assertTrue(self, exp, msg=None): - """Assert that `exp` is true.""" - if not exp: - self.fail(msg) - - if _need('assertFalse'): - def assertFalse(self, exp, msg=None): - """Assert that `exp` is false.""" - if exp: - self.fail(msg) - if _need('assertIn'): def assertIn(self, member, container, msg=None): """Assert that `member` is in `container`.""" @@ -57,8 +43,7 @@ class TestCase(unittest.TestCase): """ try: callobj(*args, **kw) - except excClass: - _, exc, _ = sys.exc_info() + except excClass as exc: excMsg = str(exc) if re.search(regexp, excMsg): # Message provided, and we got the right one: it passes. diff --git a/tests/coveragetest.py b/tests/coveragetest.py index f6680cc9..d047a472 100644 --- a/tests/coveragetest.py +++ b/tests/coveragetest.py @@ -1,11 +1,10 @@ """Base test case class for coverage testing.""" import glob, imp, os, random, shlex, shutil, sys, tempfile, textwrap -import atexit +import atexit, collections import coverage -from coverage.backward import sorted, StringIO # pylint: disable=W0622 -from coverage.backward import to_bytes +from coverage.backward import StringIO, to_bytes from coverage.control import _TEST_NAME_FILE from tests.backtest import run_command from tests.backunittest import TestCase @@ -191,11 +190,8 @@ class CoverageTest(TestCase): os.makedirs(dirs) # Create the file. - f = open(filename, 'wb') - try: + with open(filename, 'wb') as f: f.write(to_bytes(text)) - finally: - f.close() return filename @@ -224,17 +220,16 @@ class CoverageTest(TestCase): """ modfile = modname + '.py' - f = open(modfile, 'r') for suff in imp.get_suffixes(): if suff[0] == '.py': break - try: + + with open(modfile, 'r') as f: # pylint: disable=W0631 # (Using possibly undefined loop variable 'suff') mod = imp.load_module(modname, f, modfile, suff) - finally: - f.close() + return mod def start_import_stop(self, cov, modname): @@ -267,10 +262,10 @@ class CoverageTest(TestCase): # Map chars to numbers for arcz_to_arcs _arcz_map = {'.': -1} - _arcz_map.update(dict([(c, ord(c)-ord('0')) for c in '123456789'])) + _arcz_map.update(dict((c, ord(c)-ord('0')) for c in '123456789')) _arcz_map.update(dict( - [(c, 10+ord(c)-ord('A')) for c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'] - )) + (c, 10+ord(c)-ord('A')) for c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + )) def arcz_to_arcs(self, arcz): """Convert a compact textual representation of arcs to a list of pairs. @@ -306,8 +301,8 @@ class CoverageTest(TestCase): def assertEqualArcs(self, a1, a2, msg=None): """Assert that the arc lists `a1` and `a2` are equal.""" # Make them into multi-line strings so we can see what's going wrong. - s1 = "\n".join([repr(a) for a in a1]) + "\n" - s2 = "\n".join([repr(a) for a in a2]) + "\n" + s1 = "\n".join(repr(a) for a in a1) + "\n" + s2 = "\n".join(repr(a) for a in a2) + "\n" self.assertMultiLineEqual(s1, s2, msg) def check_coverage(self, text, lines=None, missing="", report="", @@ -508,8 +503,9 @@ class CoverageTest(TestCase): self.test_method_made_any_files = False # Map from class to info about how it ran. - class_behaviors = {} + class_behaviors = collections.defaultdict(ClassBehavior) + @classmethod def report_on_class_behavior(cls): """Called at process exit to report on class behavior.""" for test_class, behavior in cls.class_behaviors.items(): @@ -534,14 +530,10 @@ class CoverageTest(TestCase): where, ) ) - report_on_class_behavior = classmethod(report_on_class_behavior) def class_behavior(self): """Get the ClassBehavior instance for this test.""" - cls = self.__class__ - if cls not in self.class_behaviors: - self.class_behaviors[cls] = self.ClassBehavior() - return self.class_behaviors[cls] + return self.class_behaviors[self.__class__] # When the process ends, find out about bad classes. diff --git a/tests/farm/html/run_partial.py b/tests/farm/html/run_partial.py index 41e6ba96..eab14411 100644 --- a/tests/farm/html/run_partial.py +++ b/tests/farm/html/run_partial.py @@ -24,9 +24,8 @@ contains("html_partial/partial.html", contains("html_partial/index.html", "<a href='partial.html'>partial</a>", ) -if sys.version_info >= (2, 4): - contains("html_partial/index.html", - "<span class='pc_cov'>100%</span>" - ) +contains("html_partial/index.html", + "<span class='pc_cov'>100%</span>" + ) clean("html_partial") diff --git a/tests/osinfo.py b/tests/osinfo.py index 25c3a7c6..a123123c 100644 --- a/tests/osinfo.py +++ b/tests/osinfo.py @@ -2,7 +2,7 @@ import sys -if sys.version_info >= (2, 5) and sys.platform == 'win32': +if sys.platform == 'win32': # Windows implementation def process_ram(): """How much RAM is this process using? (Windows)""" @@ -44,11 +44,8 @@ elif sys.platform == 'linux2': """Read the /proc/PID/status file to find memory use.""" try: # get pseudo file /proc/<pid>/status - t = open('/proc/%d/status' % os.getpid()) - try: + with open('/proc/%d/status' % os.getpid()) as t: v = t.read() - finally: - t.close() except IOError: return 0 # non-Linux? # get VmKey line e.g. 'VmRSS: 9999 kB\n ...' diff --git a/tests/test_arcs.py b/tests/test_arcs.py index 6268e289..80923f8d 100644 --- a/tests/test_arcs.py +++ b/tests/test_arcs.py @@ -88,12 +88,6 @@ class SimpleArcTest(CoverageTest): arcz=".1 14 45 5. .2 2. 23 3.", arcz_missing="23 3.") def test_multiline(self): - # The firstlineno of the a assignment below differs among Python - # versions. - if sys.version_info >= (2, 5): - arcz = ".1 15 5-2" - else: - arcz = ".1 15 5-1" self.check_coverage("""\ a = ( 2 + @@ -102,7 +96,7 @@ class SimpleArcTest(CoverageTest): b = \\ 6 """, - arcz=arcz, arcz_missing="") + arcz=".1 15 5-2", arcz_missing="") def test_if_return(self): self.check_coverage("""\ @@ -151,33 +145,32 @@ class SimpleArcTest(CoverageTest): ) -if sys.version_info >= (2, 6): - class WithTest(CoverageTest): - """Arc-measuring tests involving context managers.""" +class WithTest(CoverageTest): + """Arc-measuring tests involving context managers.""" - def test_with(self): - self.check_coverage("""\ - def example(): - with open("test", "w") as f: # exit - f.write("") - return 1 + def test_with(self): + self.check_coverage("""\ + def example(): + with open("test", "w") as f: # exit + f.write("") + return 1 - example() - """, - arcz=".1 .2 23 34 4. 16 6." - ) + example() + """, + arcz=".1 .2 23 34 4. 16 6." + ) - def test_bug_146(self): - # https://bitbucket.org/ned/coveragepy/issue/146 - self.check_coverage("""\ - for i in range(2): - with open("test", "w") as f: - print(3) - print(4) - print(5) - """, - arcz=".1 12 23 34 41 15 5." - ) + def test_bug_146(self): + # https://bitbucket.org/ned/coveragepy/issue/146 + self.check_coverage("""\ + for i in range(2): + with open("test", "w") as f: + print(3) + print(4) + print(5) + """, + arcz=".1 12 23 34 41 15 5." + ) class LoopArcTest(CoverageTest): @@ -509,9 +502,9 @@ class ExceptionArcTest(CoverageTest): arcz=".1 12 23 35 56 61 17 7.", arcz_missing="", arcz_unpredicted="") - # Run this test only on 2.6 and 2.7 for now. I hope to fix it on Py3 + # Run this test only on Py2 for now. I hope to fix it on Py3 # eventually... - if (2, 6) <= sys.version_info < (3,): + if sys.version_info < (3, 0): # "except Exception as e" is crucial here. def test_bug_212(self): self.check_coverage("""\ @@ -533,36 +526,34 @@ class ExceptionArcTest(CoverageTest): arcz=".1 .2 1A 23 34 56 67 68 8. AB BC C. DE E.", arcz_missing="C.", arcz_unpredicted="45 7. CD") - if sys.version_info >= (2, 5): - # Try-except-finally was new in 2.5 - def test_except_finally(self): - self.check_coverage("""\ - a, b, c = 1, 1, 1 - try: - a = 3 - except: - b = 5 - finally: - c = 7 - assert a == 3 and b == 1 and c == 7 - """, - arcz=".1 12 23 45 37 57 78 8.", arcz_missing="45 57") - self.check_coverage("""\ - a, b, c = 1, 1, 1 - def oops(x): - if x % 2: raise Exception("odd") - try: - a = 5 - oops(1) - a = 7 - except: - b = 9 - finally: - c = 11 - assert a == 5 and b == 9 and c == 11 - """, - arcz=".1 12 .3 3-2 24 45 56 67 7B 89 9B BC C.", - arcz_missing="67 7B", arcz_unpredicted="68") + def test_except_finally(self): + self.check_coverage("""\ + a, b, c = 1, 1, 1 + try: + a = 3 + except: + b = 5 + finally: + c = 7 + assert a == 3 and b == 1 and c == 7 + """, + arcz=".1 12 23 45 37 57 78 8.", arcz_missing="45 57") + self.check_coverage("""\ + a, b, c = 1, 1, 1 + def oops(x): + if x % 2: raise Exception("odd") + try: + a = 5 + oops(1) + a = 7 + except: + b = 9 + finally: + c = 11 + assert a == 5 and b == 9 and c == 11 + """, + arcz=".1 12 .3 3-2 24 45 56 67 7B 89 9B BC C.", + arcz_missing="67 7B", arcz_unpredicted="68") class MiscArcTest(CoverageTest): diff --git a/tests/test_collector.py b/tests/test_collector.py index 2714398a..7bd4bebb 100644 --- a/tests/test_collector.py +++ b/tests/test_collector.py @@ -4,7 +4,6 @@ import re import coverage from coverage.backward import StringIO -from coverage.backward import set # pylint: disable=W0622 from tests.coveragetest import CoverageTest @@ -49,7 +48,7 @@ class CollectorTest(CoverageTest): # duplicates. trace_lines = [ l for l in debug_out.getvalue().splitlines() - if l.startswith("Tracing ") or l.startswith("Not tracing ") + if l.startswith(("Tracing ", "Not tracing ")) ] filenames = [re.search(r"'[^']+'", l).group() for l in trace_lines] self.assertEqual(len(filenames), len(set(filenames))) diff --git a/tests/test_config.py b/tests/test_config.py index 6d370255..0862d6b2 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1,7 +1,6 @@ # -*- coding: utf-8 -*- """Test the config file handling for coverage.py""" -import sys import coverage from coverage.misc import CoverageException @@ -211,15 +210,14 @@ class ConfigFileTest(CoverageTest): 'other': ['other', '/home/ned/other', 'c:\\Ned\\etc'] }) - if sys.version_info[:2] != (3,1): - def test_one(self): - # This sample file tries to use lots of variation of syntax... - self.make_file(".coveragerc", """\ - [html] - title = tabblo & «ταБЬℓσ» # numbers - """) - cov = coverage.coverage() - - self.assertEqual(cov.config.html_title, - "tabblo & «ταБЬℓσ» # numbers" - ) + def test_one(self): + # This sample file tries to use lots of variation of syntax... + self.make_file(".coveragerc", """\ + [html] + title = tabblo & «ταБЬℓσ» # numbers + """) + cov = coverage.coverage() + + self.assertEqual(cov.config.html_title, + "tabblo & «ταБЬℓσ» # numbers" + ) diff --git a/tests/test_coverage.py b/tests/test_coverage.py index 6de4d0ea..078c66ca 100644 --- a/tests/test_coverage.py +++ b/tests/test_coverage.py @@ -839,15 +839,13 @@ class CompoundStatementTest(CoverageTest): """, [1,2,4,5,7,9,10], "4, 7") - if sys.version_info >= (2, 4): - # In 2.4 and up, constant if's were compiled away. - def test_constant_if(self): - self.check_coverage("""\ - if 1: - a = 2 - assert a == 2 - """, - [2,3], "") + def test_constant_if(self): + self.check_coverage("""\ + if 1: + a = 2 + assert a == 2 + """, + [2,3], "") def test_while(self): self.check_coverage("""\ @@ -1510,187 +1508,185 @@ class ExcludeTest(CoverageTest): [8,9], "", excludes=['#pragma: NO COVER']) -if sys.version_info >= (2, 4): - class Py24Test(CoverageTest): - """Tests of new syntax in Python 2.4.""" +class Py24Test(CoverageTest): + """Tests of new syntax in Python 2.4.""" - def test_function_decorators(self): - self.check_coverage("""\ - def require_int(func): - def wrapper(arg): - assert isinstance(arg, int) - return func(arg) + def test_function_decorators(self): + self.check_coverage("""\ + def require_int(func): + def wrapper(arg): + assert isinstance(arg, int) + return func(arg) + return wrapper + + @require_int + def p1(arg): + return arg*2 + + assert p1(10) == 20 + """, + [1,2,3,4,6,8,10,12], "") + + def test_function_decorators_with_args(self): + self.check_coverage("""\ + def boost_by(extra): + def decorator(func): + def wrapper(arg): + return extra*func(arg) return wrapper + return decorator - @require_int - def p1(arg): - return arg*2 + @boost_by(10) + def boosted(arg): + return arg*2 - assert p1(10) == 20 - """, - [1,2,3,4,6,8,10,12], "") + assert boosted(10) == 200 + """, + [1,2,3,4,5,6,8,10,12], "") - def test_function_decorators_with_args(self): - self.check_coverage("""\ - def boost_by(extra): - def decorator(func): - def wrapper(arg): - return extra*func(arg) - return wrapper - return decorator - - @boost_by(10) - def boosted(arg): - return arg*2 - - assert boosted(10) == 200 - """, - [1,2,3,4,5,6,8,10,12], "") + def test_double_function_decorators(self): + self.check_coverage("""\ + def require_int(func): + def wrapper(arg): + assert isinstance(arg, int) + return func(arg) + return wrapper - def test_double_function_decorators(self): - self.check_coverage("""\ - def require_int(func): + def boost_by(extra): + def decorator(func): def wrapper(arg): - assert isinstance(arg, int) - return func(arg) + return extra*func(arg) return wrapper + return decorator - def boost_by(extra): - def decorator(func): - def wrapper(arg): - return extra*func(arg) - return wrapper - return decorator + @require_int + @boost_by(10) + def boosted1(arg): + return arg*2 - @require_int - @boost_by(10) - def boosted1(arg): - return arg*2 + assert boosted1(10) == 200 - assert boosted1(10) == 200 + @boost_by(10) + @require_int + def boosted2(arg): + return arg*2 - @boost_by(10) - @require_int - def boosted2(arg): - return arg*2 + assert boosted2(10) == 200 + """, + ([1,2,3,4,5,7,8,9,10,11,12,14,15,17,19,21,22,24,26], + [1,2,3,4,5,7,8,9,10,11,12,14, 17,19,21, 24,26]), "") - assert boosted2(10) == 200 - """, - ([1,2,3,4,5,7,8,9,10,11,12,14,15,17,19,21,22,24,26], - [1,2,3,4,5,7,8,9,10,11,12,14, 17,19,21, 24,26]), "") +class Py25Test(CoverageTest): + """Tests of new syntax in Python 2.5.""" -if sys.version_info >= (2, 5): - class Py25Test(CoverageTest): - """Tests of new syntax in Python 2.5.""" + def test_with_statement(self): + self.check_coverage("""\ + from __future__ import with_statement - def test_with_statement(self): - self.check_coverage("""\ - from __future__ import with_statement + class Managed: + def __enter__(self): + desc = "enter" - class Managed: - def __enter__(self): - desc = "enter" + def __exit__(self, type, value, tb): + desc = "exit" - def __exit__(self, type, value, tb): - desc = "exit" + m = Managed() + with m: + desc = "block1a" + desc = "block1b" - m = Managed() + try: with m: - desc = "block1a" - desc = "block1b" - - try: - with m: - desc = "block2" - raise Exception("Boo!") - except: - desc = "caught" - """, - [1,3,4,5,7,8,10,11,12,13,15,16,17,18,19,20], "") + desc = "block2" + raise Exception("Boo!") + except: + desc = "caught" + """, + [1,3,4,5,7,8,10,11,12,13,15,16,17,18,19,20], "") - def test_try_except_finally(self): - self.check_coverage("""\ - a = 0; b = 0 - try: - a = 1 - except: - a = 99 - finally: - b = 2 - assert a == 1 and b == 2 - """, - [1,2,3,4,5,7,8], "4-5") - self.check_coverage("""\ - a = 0; b = 0 - try: - a = 1 - raise Exception("foo") - except: - a = 99 - finally: - b = 2 - assert a == 99 and b == 2 - """, - [1,2,3,4,5,6,8,9], "") - self.check_coverage("""\ - a = 0; b = 0 - try: - a = 1 - raise Exception("foo") - except ImportError: - a = 99 - except: - a = 123 - finally: - b = 2 - assert a == 123 and b == 2 - """, - [1,2,3,4,5,6,7,8,10,11], "6") - self.check_coverage("""\ - a = 0; b = 0 - try: - a = 1 - raise IOError("foo") - except ImportError: - a = 99 - except IOError: - a = 17 - except: - a = 123 - finally: - b = 2 - assert a == 17 and b == 2 - """, - [1,2,3,4,5,6,7,8,9,10,12,13], "6, 9-10") - self.check_coverage("""\ - a = 0; b = 0 - try: - a = 1 - except: - a = 99 - else: - a = 123 - finally: - b = 2 - assert a == 123 and b == 2 - """, - [1,2,3,4,5,7,9,10], "4-5") - self.check_coverage("""\ - a = 0; b = 0 - try: - a = 1 - raise Exception("foo") - except: - a = 99 - else: - a = 123 - finally: - b = 2 - assert a == 99 and b == 2 - """, - [1,2,3,4,5,6,8,10,11], "8") + def test_try_except_finally(self): + self.check_coverage("""\ + a = 0; b = 0 + try: + a = 1 + except: + a = 99 + finally: + b = 2 + assert a == 1 and b == 2 + """, + [1,2,3,4,5,7,8], "4-5") + self.check_coverage("""\ + a = 0; b = 0 + try: + a = 1 + raise Exception("foo") + except: + a = 99 + finally: + b = 2 + assert a == 99 and b == 2 + """, + [1,2,3,4,5,6,8,9], "") + self.check_coverage("""\ + a = 0; b = 0 + try: + a = 1 + raise Exception("foo") + except ImportError: + a = 99 + except: + a = 123 + finally: + b = 2 + assert a == 123 and b == 2 + """, + [1,2,3,4,5,6,7,8,10,11], "6") + self.check_coverage("""\ + a = 0; b = 0 + try: + a = 1 + raise IOError("foo") + except ImportError: + a = 99 + except IOError: + a = 17 + except: + a = 123 + finally: + b = 2 + assert a == 17 and b == 2 + """, + [1,2,3,4,5,6,7,8,9,10,12,13], "6, 9-10") + self.check_coverage("""\ + a = 0; b = 0 + try: + a = 1 + except: + a = 99 + else: + a = 123 + finally: + b = 2 + assert a == 123 and b == 2 + """, + [1,2,3,4,5,7,9,10], "4-5") + self.check_coverage("""\ + a = 0; b = 0 + try: + a = 1 + raise Exception("foo") + except: + a = 99 + else: + a = 123 + finally: + b = 2 + assert a == 99 and b == 2 + """, + [1,2,3,4,5,6,8,10,11], "8") class ModuleTest(CoverageTest): diff --git a/tests/test_data.py b/tests/test_data.py index 9c29289d..31578f26 100644 --- a/tests/test_data.py +++ b/tests/test_data.py @@ -92,11 +92,8 @@ class DataTest(CoverageTest): covdata.add_line_data(DATA_1) covdata.write() - fdata = open(".coverage", 'rb') - try: + with open(".coverage", 'rb') as fdata: data = pickle.load(fdata) - finally: - fdata.close() lines = data['lines'] self.assertSameElements(lines.keys(), MEASURED_FILES_1) @@ -111,11 +108,8 @@ class DataTest(CoverageTest): covdata.add_arc_data(ARC_DATA_3) covdata.write() - fdata = open(".coverage", 'rb') - try: + with open(".coverage", 'rb') as fdata: data = pickle.load(fdata) - finally: - fdata.close() self.assertSameElements(data['lines'].keys(), []) arcs = data['arcs'] diff --git a/tests/test_execfile.py b/tests/test_execfile.py index 24c521bd..ca13d7c8 100644 --- a/tests/test_execfile.py +++ b/tests/test_execfile.py @@ -54,11 +54,8 @@ class RunFileTest(CoverageTest): # Make sure we can read any sort of line ending. pylines = """# try newlines|print('Hello, world!')|""".split('|') for nl in ('\n', '\r\n', '\r'): - fpy = open('nl.py', 'wb') - try: + with open('nl.py', 'wb') as fpy: fpy.write(nl.join(pylines).encode('utf-8')) - finally: - fpy.close() run_python_file('nl.py', ['nl.py']) self.assertEqual(self.stdout(), "Hello, world!\n"*3) diff --git a/tests/test_farm.py b/tests/test_farm.py index fee28063..c86983e5 100644 --- a/tests/test_farm.py +++ b/tests/test_farm.py @@ -78,10 +78,10 @@ class FarmTestCase(object): copy run runfunc compare contains doesnt_contain clean skip """.split() if self.clean_only: - glo = dict([(fn, self.noop) for fn in fns]) + glo = dict((fn, self.noop) for fn in fns) glo['clean'] = self.clean else: - glo = dict([(fn, getattr(self, fn)) for fn in fns]) + glo = dict((fn, getattr(self, fn)) for fn in fns) if self.dont_clean: # pragma: not covered glo['clean'] = self.noop diff --git a/tests/test_files.py b/tests/test_files.py index b24e8b8b..230cd092 100644 --- a/tests/test_files.py +++ b/tests/test_files.py @@ -4,7 +4,6 @@ import os, os.path from coverage.files import FileLocator, TreeMatcher, FnmatchMatcher from coverage.files import PathAliases, find_python_files, abs_file -from coverage.backward import set # pylint: disable=W0622 from coverage.misc import CoverageException from tests.coveragetest import CoverageTest diff --git a/tests/test_html.py b/tests/test_html.py index 06132fb4..f22fdc21 100644 --- a/tests/test_html.py +++ b/tests/test_html.py @@ -177,22 +177,21 @@ class HtmlTitleTest(HtmlTestHelpers, CoverageTest): self.assertIn("<title>Metrics & stuff!</title>", index) self.assertIn("<h1>Metrics & stuff!:", index) - if sys.version_info[:2] != (3,1): - def test_non_ascii_title_set_in_config_file(self): - self.create_initial_files() - self.make_file(".coveragerc", - "[html]\ntitle = «ταБЬℓσ» numbers" - ) - self.run_coverage() - index = open("htmlcov/index.html").read() - self.assertIn( - "<title>«ταБЬℓσ»" - " numbers", index - ) - self.assertIn( - "<h1>«ταБЬℓσ»" - " numbers", index - ) + def test_non_ascii_title_set_in_config_file(self): + self.create_initial_files() + self.make_file(".coveragerc", + "[html]\ntitle = «ταБЬℓσ» numbers" + ) + self.run_coverage() + index = open("htmlcov/index.html").read() + self.assertIn( + "<title>«ταБЬℓσ»" + " numbers", index + ) + self.assertIn( + "<h1>«ταБЬℓσ»" + " numbers", index + ) def test_title_set_in_args(self): self.create_initial_files() diff --git a/tests/test_oddball.py b/tests/test_oddball.py index 4b18a4ee..eba507be 100644 --- a/tests/test_oddball.py +++ b/tests/test_oddball.py @@ -329,43 +329,42 @@ class ExceptionTest(CoverageTest): self.assertEqual(clean_lines, lines_expected) -if sys.version_info >= (2, 5): - class DoctestTest(CoverageTest): - """Tests invoked with doctest should measure properly.""" - - def setUp(self): - super(DoctestTest, self).setUp() - - # Oh, the irony! This test case exists because Python 2.4's - # doctest module doesn't play well with coverage. But nose fixes - # the problem by monkeypatching doctest. I want to undo the - # monkeypatch to be sure I'm getting the doctest module that users - # of coverage will get. Deleting the imported module here is - # enough: when the test imports doctest again, it will get a fresh - # copy without the monkeypatch. - del sys.modules['doctest'] - - def test_doctest(self): - self.check_coverage('''\ - def return_arg_or_void(arg): - """If <arg> is None, return "Void"; otherwise return <arg> - - >>> return_arg_or_void(None) - 'Void' - >>> return_arg_or_void("arg") - 'arg' - >>> return_arg_or_void("None") - 'None' - """ - if arg is None: - return "Void" - else: - return arg - - import doctest, sys - doctest.testmod(sys.modules[__name__]) # we're not __main__ :( - ''', - [1,11,12,14,16,17], "") +class DoctestTest(CoverageTest): + """Tests invoked with doctest should measure properly.""" + + def setUp(self): + super(DoctestTest, self).setUp() + + # Oh, the irony! This test case exists because Python 2.4's + # doctest module doesn't play well with coverage. But nose fixes + # the problem by monkeypatching doctest. I want to undo the + # monkeypatch to be sure I'm getting the doctest module that users + # of coverage will get. Deleting the imported module here is + # enough: when the test imports doctest again, it will get a fresh + # copy without the monkeypatch. + del sys.modules['doctest'] + + def test_doctest(self): + self.check_coverage('''\ + def return_arg_or_void(arg): + """If <arg> is None, return "Void"; otherwise return <arg> + + >>> return_arg_or_void(None) + 'Void' + >>> return_arg_or_void("arg") + 'arg' + >>> return_arg_or_void("None") + 'None' + """ + if arg is None: + return "Void" + else: + return arg + + import doctest, sys + doctest.testmod(sys.modules[__name__]) # we're not __main__ :( + ''', + [1,11,12,14,16,17], "") if hasattr(sys, 'gettrace'): diff --git a/tests/test_phystokens.py b/tests/test_phystokens.py index c1e51f1c..9ff053c4 100644 --- a/tests/test_phystokens.py +++ b/tests/test_phystokens.py @@ -29,7 +29,7 @@ class PhysTokensTest(CoverageTest): """Tokenize `source`, then put it back together, should be the same.""" tokenized = "" for line in source_token_lines(source): - text = "".join([t for _,t in line]) + text = "".join(t for _, t in line) tokenized += text + "\n" # source_token_lines doesn't preserve trailing spaces, so trim all that # before comparing. @@ -86,11 +86,6 @@ if sys.version_info < (3, 0): run_in_temp_dir = False - if sys.version_info >= (2,4): - default_encoding = 'ascii' - else: - default_encoding = 'iso-8859-1' - def test_detect_source_encoding(self): # Various forms from http://www.python.org/dev/peps/pep-0263/ source = "# coding=cp850\n\n" @@ -110,11 +105,11 @@ if sys.version_info < (3, 0): def test_dont_detect_source_encoding_on_third_line(self): # A coding declaration doesn't count on the third line. source = "\n\n# coding=cp850\n\n" - self.assertEqual(source_encoding(source), self.default_encoding) + self.assertEqual(source_encoding(source), 'ascii') def test_detect_source_encoding_of_empty_file(self): # An important edge case. - self.assertEqual(source_encoding(""), self.default_encoding) + self.assertEqual(source_encoding(""), 'ascii') def test_bom(self): # A BOM means utf-8. diff --git a/tests/test_process.py b/tests/test_process.py index c49d90a9..ddbbafd6 100644 --- a/tests/test_process.py +++ b/tests/test_process.py @@ -35,7 +35,7 @@ class ProcessTest(CoverageTest): import covmod1 import covmodzip1 a = 1 - print ('done') + print('done') """) self.assert_doesnt_exist(".coverage") @@ -52,7 +52,7 @@ class ProcessTest(CoverageTest): else: c = 1 d = 1 - print ('done') + print('done') """) out = self.run_command("coverage -x -p b_or_c.py b") @@ -88,7 +88,7 @@ class ProcessTest(CoverageTest): else: c = 1 d = 1 - print ('done') + print('done') """) out = self.run_command("coverage -x -p b_or_c.py b") @@ -128,7 +128,7 @@ class ProcessTest(CoverageTest): else: c = 1 d = 1 - print ('done') + print('done') """) self.make_file(".coveragerc", """\ @@ -270,7 +270,7 @@ class ProcessTest(CoverageTest): if '__pypy__' in sys.builtin_module_names: # Pypy has an extra frame in the traceback for some reason lines2 = out2.splitlines() - out2 = "".join([l+"\n" for l in lines2 if "toplevel" not in l]) + out2 = "".join(l+"\n" for l in lines2 if "toplevel" not in l) self.assertMultiLineEqual(out, out2) # But also make sure that the output is what we expect. @@ -324,23 +324,20 @@ class ProcessTest(CoverageTest): out_py = self.run_command("python run_me.py") self.assertMultiLineEqual(out_cov, out_py) - if sys.version_info >= (2, 6): - # Doesn't work in 2.5, and I don't care! For some reason, python -m - # in 2.5 has __builtins__ as a dictionary instead of a module? - def test_coverage_run_dashm_is_like_python_dashm(self): - # These -m commands assume the coverage tree is on the path. - out_cov = self.run_command("coverage run -m tests.try_execfile") - out_py = self.run_command("python -m tests.try_execfile") - self.assertMultiLineEqual(out_cov, out_py) + def test_coverage_run_dashm_is_like_python_dashm(self): + # These -m commands assume the coverage tree is on the path. + out_cov = self.run_command("coverage run -m tests.try_execfile") + out_py = self.run_command("python -m tests.try_execfile") + self.assertMultiLineEqual(out_cov, out_py) - def test_coverage_run_dashm_is_like_python_dashm_off_path(self): - # https://bitbucket.org/ned/coveragepy/issue/242 - tryfile = os.path.join(here, "try_execfile.py") - self.make_file("sub/__init__.py", "") - self.make_file("sub/run_me.py", open(tryfile).read()) - out_cov = self.run_command("coverage run -m sub.run_me") - out_py = self.run_command("python -m sub.run_me") - self.assertMultiLineEqual(out_cov, out_py) + def test_coverage_run_dashm_is_like_python_dashm_off_path(self): + # https://bitbucket.org/ned/coveragepy/issue/242 + tryfile = os.path.join(here, "try_execfile.py") + self.make_file("sub/__init__.py", "") + self.make_file("sub/run_me.py", open(tryfile).read()) + out_cov = self.run_command("coverage run -m sub.run_me") + out_py = self.run_command("python -m sub.run_me") + self.assertMultiLineEqual(out_cov, out_py) if sys.version_info >= (2, 7): # Coverage isn't bug-for-bug compatible in the behavior of -m for @@ -575,16 +572,13 @@ class ProcessStartupTest(CoverageTest): g = glob.glob(os.path.join(d, "*.pth")) if g: pth_path = os.path.join(d, "subcover.pth") - pth = open(pth_path, "w") - try: + with open(pth_path, "w") as pth: try: pth.write(pth_contents) self.pth_path = pth_path break except (IOError, OSError): # pragma: not covered pass - finally: - pth.close() else: # pragma: not covered raise Exception("Couldn't find a place for the .pth file") diff --git a/tests/test_summary.py b/tests/test_summary.py index 8035513e..29167bf8 100644 --- a/tests/test_summary.py +++ b/tests/test_summary.py @@ -16,7 +16,7 @@ class SummaryTest(CoverageTest): import covmod1 import covmodzip1 a = 1 - print ('done') + print('done') """) # Parent class saves and restores sys.path, we can just modify it. sys.path.append(self.nice_file(os.path.dirname(__file__), 'modules')) diff --git a/tests/test_testing.py b/tests/test_testing.py index c56d8110..64dca617 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -2,11 +2,10 @@ """Tests that our test infrastructure is really working!""" import os, sys -from coverage.backward import to_bytes, rpartition +from coverage.backward import to_bytes from tests.backunittest import TestCase from tests.coveragetest import CoverageTest -from coverage.backward import set # pylint: disable=W0622 class TestingTest(TestCase): """Tests of helper methods on `backunittest.TestCase`.""" @@ -184,11 +183,11 @@ class CoverageTestTest(CoverageTest): # Try it with a "coverage debug sys" command. out = self.run_command("coverage debug sys").splitlines() # "environment: COV_FOOBAR = XYZZY" or "COV_FOOBAR = XYZZY" - executable = [l for l in out if "executable:" in l][0] + executable = next(l for l in out if "executable:" in l) executable = executable.split(":", 1)[1].strip() self.assertTrue(same_python_executable(executable, sys.executable)) - environ = [l for l in out if "COV_FOOBAR" in l][0] - _, _, environ = rpartition(environ, ":") + environ = next(l for l in out if "COV_FOOBAR" in l) + _, _, environ = environ.rpartition(":") self.assertEqual(environ.strip(), "COV_FOOBAR = XYZZY") |