diff options
author | Ned Batchelder <ned@nedbatchelder.com> | 2017-04-06 19:05:13 -0400 |
---|---|---|
committer | Ned Batchelder <ned@nedbatchelder.com> | 2017-04-06 19:05:13 -0400 |
commit | 8623486761fd2de4608c668341f2efc0db2e284e (patch) | |
tree | 117cd288f79a95b1e07c8fbc70f0af7ffb651095 | |
parent | 01e12e85608494ec51f5095f56c78dadb28a916b (diff) | |
download | python-coveragepy-8623486761fd2de4608c668341f2efc0db2e284e.tar.gz |
Beef up the assert_warnings test helper
-rw-r--r-- | tests/coveragetest.py | 12 | ||||
-rw-r--r-- | tests/test_testing.py | 11 |
2 files changed, 22 insertions, 1 deletions
diff --git a/tests/coveragetest.py b/tests/coveragetest.py index 7fcc9f9..5f3457f 100644 --- a/tests/coveragetest.py +++ b/tests/coveragetest.py @@ -272,13 +272,17 @@ class CoverageTest( return cov @contextlib.contextmanager - def assert_warnings(self, cov, warnings): + def assert_warnings(self, cov, warnings, not_warnings=()): """A context manager to check that particular warnings happened in `cov`. `cov` is a Coverage instance. `warnings` is a list of regexes. Every regex must match a warning that was issued by `cov`. It is OK for extra warnings to be issued by `cov` that are not matched by any regex. + `not_warnings` is a list of regexes that must not appear in the + warnings. This is only checked if there are some positive warnings to + test for in `warnings`. + If `warnings` is empty, then `cov` is not allowed to issue any warnings. @@ -286,6 +290,8 @@ class CoverageTest( saved_warnings = [] def capture_warning(msg, slug=None): # pylint: disable=unused-argument """A fake implementation of Coverage._warn, to capture warnings.""" + if slug: + msg = "%s (%s)" % (msg, slug) saved_warnings.append(msg) original_warn = cov._warn @@ -303,6 +309,10 @@ class CoverageTest( break else: self.fail("Didn't find warning %r in %r" % (warning_regex, saved_warnings)) + for warning_regex in not_warnings: + for saved in saved_warnings: + if re.search(warning_regex, saved): + self.fail("Found warning %r in %r" % (warning_regex, saved_warnings)) else: # No warnings expected. Raise if any warnings happened. if saved_warnings: diff --git a/tests/test_testing.py b/tests/test_testing.py index d86207e..05bf0c9 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -114,6 +114,17 @@ class CoverageTestTest(CoverageTest): with self.assert_warnings(cov, ["Not me"]): cov._warn("Hello there!") + # Try checking a warning that shouldn't appear: happy case. + with self.assert_warnings(cov, ["Hi"], not_warnings=["Bye"]): + cov._warn("Hi") + + # But it should fail if the unexpected warning does appear. + warn_regex = r"Found warning 'Bye' in \['Hi', 'Bye'\]" + with self.assertRaisesRegex(AssertionError, warn_regex): + with self.assert_warnings(cov, ["Hi"], not_warnings=["Bye"]): + cov._warn("Hi") + cov._warn("Bye") + # assert_warnings shouldn't hide a real exception. with self.assertRaises(ZeroDivisionError): with self.assert_warnings(cov, ["Hello there!"]): |