Commits

Ned Batchelder  committed 77c627c

Use assertRaises as a context manager now that we can.

  • Participants
  • Parent commits 70659a3

Comments (0)

Files changed (12)

     + "with" statements
     - .format() ?
     + try/except/finally
-    - with assertRaises
+    + with assertRaises
     + exec statement can look like a function in py2 (since when?)
     - runpy ?
 

File tests/test_cmdline.py

     def test_assert_same_method_calls(self):
         # All the other tests here use self.cmd_executes_same in successful
         # ways, so here we just check that it fails.
-        self.assertRaises(AssertionError, self.cmd_executes_same, "-e", "-c")
+        with self.assertRaises(AssertionError):
+            self.cmd_executes_same("-e", "-c")
 
 
 class ClassicCmdLineTest(CmdLineTest):
         self.assertEqual(err[-2], 'Exception: oh noes!')
 
     def test_internalraise(self):
-        self.assertRaisesRegexp(ValueError,
-            "coverage is broken",
-            coverage.cmdline.main, ['internalraise']
-            )
+        with self.assertRaisesRegexp(ValueError, "coverage is broken"):
+            coverage.cmdline.main(['internalraise'])
 
     def test_exit(self):
         ret = coverage.cmdline.main(['exit'])

File tests/test_config.py

             [run]
             timid = maybe?
             """)
-        self.assertRaises(CoverageException, coverage.coverage)
+        with self.assertRaises(CoverageException):
+            coverage.coverage()
 
     def test_environment_vars_in_config(self):
         # Config files can have $envvars in them.

File tests/test_coverage.py

 
     def test_failed_coverage(self):
         # If the lines are wrong, the message shows right and wrong.
-        self.assertRaisesRegexp(AssertionError,
-            r"\[1, 2] != \[1]",
-            self.check_coverage, """\
+        with self.assertRaisesRegexp(AssertionError, r"\[1, 2] != \[1]"):
+            self.check_coverage("""\
                 a = 1
                 b = 2
                 """,
                 [1]
             )
         # If the list of lines possibilities is wrong, the msg shows right.
-        self.assertRaisesRegexp(AssertionError,
-            r"None of the lines choices matched \[1, 2]",
-            self.check_coverage, """\
+        msg = r"None of the lines choices matched \[1, 2]"
+        with self.assertRaisesRegexp(AssertionError, msg):
+            self.check_coverage("""\
                 a = 1
                 b = 2
                 """,
                 ([1], [2])
             )
         # If the missing lines are wrong, the message shows right and wrong.
-        self.assertRaisesRegexp(AssertionError,
-            r"'3' != '37'",
-            self.check_coverage, """\
+        with self.assertRaisesRegexp(AssertionError, r"'3' != '37'"):
+            self.check_coverage("""\
                 a = 1
                 if a == 2:
                     a = 3
                 missing="37",
             )
         # If the missing lines possibilities are wrong, the msg shows right.
-        self.assertRaisesRegexp(AssertionError,
-            r"None of the missing choices matched '3'",
-            self.check_coverage, """\
+        msg = r"None of the missing choices matched '3'"
+        with self.assertRaisesRegexp(AssertionError, msg):
+            self.check_coverage("""\
                 a = 1
                 if a == 2:
                     a = 3
 
     def test_no_data_to_report_on_annotate(self):
         # Reporting with no data produces a nice message and no output dir.
-        self.assertRaisesRegexp(
-            CoverageException, "No data to report.",
-            self.command_line, "annotate -d ann"
-            )
+        with self.assertRaisesRegexp(CoverageException, "No data to report."):
+            self.command_line("annotate -d ann")
         self.assert_doesnt_exist("ann")
 
         # CoverageTest will yell at us for using a temp directory with no files
 
     def test_no_data_to_report_on_html(self):
         # Reporting with no data produces a nice message and no output dir.
-        self.assertRaisesRegexp(
-            CoverageException, "No data to report.",
-            self.command_line, "html -d htmlcov"
-            )
+        with self.assertRaisesRegexp(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.
-        self.assertRaisesRegexp(
-            CoverageException, "No data to report.",
-            self.command_line, "xml"
-            )
+        with self.assertRaisesRegexp(CoverageException, "No data to report."):
+            self.command_line("xml")
         self.assert_doesnt_exist("coverage.xml")

File tests/test_execfile.py

         self.assertEqual(self.stdout(), "a is 1\n")
 
     def test_no_such_file(self):
-        self.assertRaises(NoSource, run_python_file, "xyzzy.py", [])
+        with self.assertRaises(NoSource):
+            run_python_file("xyzzy.py", [])
 
 
 class RunPycFileTest(CoverageTest):
         fpyc.write(binary_bytes([0x2a, 0xeb, 0x0d, 0x0a]))
         fpyc.close()
 
-        self.assertRaisesRegexp(
-            NoCode, "Bad magic number in .pyc file",
-            run_python_file, pycfile, [pycfile]
-        )
+        with self.assertRaisesRegexp(NoCode, "Bad magic number in .pyc file"):
+            run_python_file(pycfile, [pycfile])
 
     def test_no_such_pyc_file(self):
-        self.assertRaisesRegexp(
-            NoCode, "No file to run: 'xyzzy.pyc'",
-            run_python_file, "xyzzy.pyc", []
-        )
+        with self.assertRaisesRegexp(NoCode, "No file to run: 'xyzzy.pyc'"):
+            run_python_file("xyzzy.pyc", [])
 
 
 class RunModuleTest(CoverageTest):
         self.assertEqual(self.stdout(), "pkg1.sub.__main__: passed hello\n")
 
     def test_no_such_module(self):
-        self.assertRaises(NoSource, run_python_module, "i_dont_exist", [])
-        self.assertRaises(NoSource, run_python_module, "i.dont_exist", [])
-        self.assertRaises(NoSource, run_python_module, "i.dont.exist", [])
+        with self.assertRaises(NoSource):
+            run_python_module("i_dont_exist", [])
+        with self.assertRaises(NoSource):
+            run_python_module("i.dont_exist", [])
+        with self.assertRaises(NoSource):
+            run_python_module("i.dont.exist", [])
 
     def test_no_main(self):
-        self.assertRaises(NoSource, run_python_module, "pkg2", ["pkg2", "hi"])
+        with self.assertRaises(NoSource):
+            run_python_module("pkg2", ["pkg2", "hi"])

File tests/test_files.py

 
     def test_cant_have_wildcard_at_end(self):
         aliases = PathAliases()
-        self.assertRaisesRegexp(
-            CoverageException, "Pattern must not end with wildcards.",
-            aliases.add, "/ned/home/*", "fooey"
-            )
-        self.assertRaisesRegexp(
-            CoverageException, "Pattern must not end with wildcards.",
-            aliases.add, "/ned/home/*/", "fooey"
-            )
-        self.assertRaisesRegexp(
-            CoverageException, "Pattern must not end with wildcards.",
-            aliases.add, "/ned/home/*/*/", "fooey"
-            )
+        msg = "Pattern must not end with wildcards."
+        with self.assertRaisesRegexp(CoverageException, msg):
+            aliases.add("/ned/home/*", "fooey")
+        with self.assertRaisesRegexp(CoverageException, msg):
+            aliases.add("/ned/home/*/", "fooey")
+        with self.assertRaisesRegexp(CoverageException, msg):
+            aliases.add("/ned/home/*/*/", "fooey")
 
     def test_no_accidental_munging(self):
         aliases = PathAliases()

File tests/test_html.py

         cov = coverage.coverage()
         self.start_import_stop(cov, "innocuous")
         self.make_file("innocuous.py", "<h1>This isn't python!</h1>")
-        self.assertRaisesRegexp(
-            NotPython,
-            "Couldn't parse '.*innocuous.py' as Python source: '.*' at line 1",
-            cov.html_report
-            )
+        msg = "Couldn't parse '.*innocuous.py' as Python source: .* at line 1"
+        with self.assertRaisesRegexp(NotPython, msg):
+            cov.html_report()
 
     def test_dotpy_not_python_ignored(self):
         self.make_file("innocuous.py", "a = 2")
 
         missing_file = os.path.join(self.temp_dir, "sub", "another.py")
         missing_file = os.path.realpath(missing_file)
-        self.assertRaisesRegexp(
-            NoSource,
-            "(?i)No source for code: '%s'" % re.escape(missing_file),
-            cov.html_report
-            )
+        msg = "(?i)No source for code: '%s'" % re.escape(missing_file)
+        with self.assertRaisesRegexp(NoSource, msg):
+            cov.html_report()
 
 class HtmlStaticFileTest(CoverageTest):
     """Tests of the static file copying for the HTML report."""
         self.make_file("main.py", "print(17)")
         cov = coverage.coverage()
         self.start_import_stop(cov, "main")
-        self.assertRaisesRegexp(
-            CoverageException, "Couldn't find static file '.*'",
-            cov.html_report
-            )
+        msg = "Couldn't find static file '.*'"
+        with self.assertRaisesRegexp(CoverageException, msg):
+            cov.html_report()

File tests/test_misc.py

     def test_actual_errors(self):
         # Errors can still happen.
         # ". is a directory" on Unix, or "Access denied" on Windows
-        self.assertRaises(OSError, file_be_gone, ".")
+        with self.assertRaises(OSError):
+            file_be_gone(".")
 
 
 class SetupPyTest(CoverageTest):

File tests/test_oddball.py

 
     def test_long_recursion(self):
         # We can't finish a very deep recursion, but we don't crash.
-        self.assertRaises(RuntimeError, self.check_coverage,
-            """\
-            def recur(n):
-                if n == 0:
-                    return 0
-                else:
-                    return recur(n-1)+1
+        with self.assertRaises(RuntimeError):
+            self.check_coverage("""\
+                def recur(n):
+                    if n == 0:
+                        return 0
+                    else:
+                        return recur(n-1)+1
 
-            recur(100000)  # This is definitely too many frames.
-            """,
-            [1,2,3,5,7], "")
+                recur(100000)  # This is definitely too many frames.
+                """,
+                [1,2,3,5,7], ""
+                )
 
     def test_long_recursion_recovery(self):
         # Test the core of bug 93: http://bitbucket.org/ned/coveragepy/issue/93

File tests/test_phystokens.py

 
             # But it has to be the only authority.
             source = "\xEF\xBB\xBF# coding: cp850\n"
-            self.assertRaises(SyntaxError, source_encoding, source)
+            with self.assertRaises(SyntaxError):
+                source_encoding(source)

File tests/test_templite.py

 
     def test_undefined_variables(self):
         # Using undefined names is an error.
-        self.assertRaises(
-            Exception,
-            self.try_render,
-            "Hi, {{name}}!", {}, "xyz"
-        )
+        with self.assertRaises(Exception):
+            self.try_render("Hi, {{name}}!", {}, "xyz")
 
     def test_pipes(self):
         # Variables can be filtered with pipes.
     def test_exception_during_evaluation(self):
         # TypeError: Couldn't evaluate {{ foo.bar.baz }}:
         # 'NoneType' object is unsubscriptable
-        self.assertRaises(TypeError, self.try_render,
-            "Hey {{foo.bar.baz}} there", {'foo': None}, "Hey ??? there"
+        with self.assertRaises(TypeError):
+            self.try_render(
+                "Hey {{foo.bar.baz}} there", {'foo': None}, "Hey ??? there"
             )
 
     def test_bogus_tag_syntax(self):
-        self.assertRaisesRegexp(
-            SyntaxError, "Don't understand tag: 'bogus'",
-            self.try_render,
-            "Huh: {% bogus %}!!{% endbogus %}??", {}, ""
-            )
+        msg = "Don't understand tag: 'bogus'"
+        with self.assertRaisesRegexp(SyntaxError, msg):
+            self.try_render("Huh: {% bogus %}!!{% endbogus %}??", {}, "")
 
     def test_bad_nesting(self):
-        self.assertRaisesRegexp(
-            SyntaxError, "Unmatched action tag: 'if'",
-            self.try_render,
-            "{% if x %}X", {}, ""
-            )
-        self.assertRaisesRegexp(
-            SyntaxError, "Mismatched end tag: 'for'",
-            self.try_render,
-            "{% if x %}X{% endfor %}", {}, ""
-            )
+        msg = "Unmatched action tag: 'if'"
+        with self.assertRaisesRegexp(SyntaxError, msg):
+            self.try_render("{% if x %}X", {}, "")
+        msg = "Mismatched end tag: 'for'"
+        with self.assertRaisesRegexp(SyntaxError, msg):
+            self.try_render("{% if x %}X{% endfor %}", {}, "")

File tests/test_testing.py

     def test_assert_same_elements(self):
         self.assertSameElements(set(), set())
         self.assertSameElements(set([1,2,3]), set([3,1,2]))
-        self.assertRaises(AssertionError, self.assertSameElements,
-            set([1,2,3]), set()
-            )
-        self.assertRaises(AssertionError, self.assertSameElements,
-            set([1,2,3]), set([4,5,6])
-            )
+        with self.assertRaises(AssertionError):
+            self.assertSameElements(set([1,2,3]), set())
+        with self.assertRaises(AssertionError):
+            self.assertSameElements(set([1,2,3]), set([4,5,6]))
 
 
 class CoverageTestTest(CoverageTest):
         self.make_file("whoville.txt", "We are here!")
         self.assert_exists("whoville.txt")
         self.assert_doesnt_exist("shadow.txt")
-        self.assertRaises(
-            AssertionError, self.assert_doesnt_exist, "whoville.txt"
-            )
-        self.assertRaises(AssertionError, self.assert_exists, "shadow.txt")
+        with self.assertRaises(AssertionError):
+            self.assert_doesnt_exist("whoville.txt")
+        with self.assertRaises(AssertionError):
+            self.assert_exists("shadow.txt")
 
     def test_assert_startwith(self):
         self.assert_starts_with("xyzzy", "xy")
         self.assert_starts_with("xyz\nabc", "xy")
         self.assert_starts_with("xyzzy", ("x", "z"))
-        self.assertRaises(
-            AssertionError, self.assert_starts_with, "xyz", "a"
-        )
-        self.assertRaises(
-            AssertionError, self.assert_starts_with, "xyz\nabc", "a"
-        )
+        with self.assertRaises(AssertionError):
+            self.assert_starts_with("xyz", "a")
+        with self.assertRaises(AssertionError):
+            self.assert_starts_with("xyz\nabc", "a")
 
     def test_sub_python_is_this_python(self):
         # Try it with a python command.