diff --git a/CHANGELOG.rst b/CHANGELOG.rst index aab0ae6e3a8..ad5a3c9f903 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -10,7 +10,8 @@ New Features * pytest now warns when a callable ids raises in a parametrized test. Thanks `@fogo`_ for the PR. -* +* ``pytest.warns`` now checks for subclass relationship rather than + class equality. Thanks `@lesteve`_ for the PR (`#2166`_) Changes @@ -42,6 +43,7 @@ Changes .. _@mattduck: https://github.com/mattduck .. _@wheerd: https://github.com/wheerd .. _@fogo: https://github.com/fogo +.. _@lesteve: https://github.com/lesteve .. _#1512: https://github.com/pytest-dev/pytest/issues/1512 .. _#1874: https://github.com/pytest-dev/pytest/pull/1874 @@ -49,7 +51,7 @@ Changes .. _#2007: https://github.com/pytest-dev/pytest/issues/2007 .. _#2013: https://github.com/pytest-dev/pytest/issues/2013 .. _#2101: https://github.com/pytest-dev/pytest/pull/2101 - +.. _#2166: https://github.com/pytest-dev/pytest/pull/2166 3.0.6.dev0 (unreleased) ======================= @@ -69,7 +71,6 @@ Changes * -.. _@lesteve: https://github.com/lesteve .. _@malinoff: https://github.com/malinoff .. _@pelme: https://github.com/pelme diff --git a/_pytest/recwarn.py b/_pytest/recwarn.py index 3421696933e..9031bdbdae4 100644 --- a/_pytest/recwarn.py +++ b/_pytest/recwarn.py @@ -216,7 +216,8 @@ def __exit__(self, *exc_info): # only check if we're not currently handling an exception if all(a is None for a in exc_info): if self.expected_warning is not None: - if not any(r.category in self.expected_warning for r in self): + if not any(issubclass(r.category, self.expected_warning) + for r in self): __tracebackhide__ = True pytest.fail("DID NOT WARN. No warnings of type {0} was emitted. " "The list of emitted warnings is: {1}.".format( diff --git a/testing/test_recwarn.py b/testing/test_recwarn.py index 6c4d73ff7ff..40d11cd0475 100644 --- a/testing/test_recwarn.py +++ b/testing/test_recwarn.py @@ -238,6 +238,28 @@ def test_record_only(self): assert str(record[0].message) == "user" assert str(record[1].message) == "runtime" + def test_record_by_subclass(self): + with pytest.warns(Warning) as record: + warnings.warn("user", UserWarning) + warnings.warn("runtime", RuntimeWarning) + + assert len(record) == 2 + assert str(record[0].message) == "user" + assert str(record[1].message) == "runtime" + + class MyUserWarning(UserWarning): pass + + class MyRuntimeWarning(RuntimeWarning): pass + + with pytest.warns((UserWarning, RuntimeWarning)) as record: + warnings.warn("user", MyUserWarning) + warnings.warn("runtime", MyRuntimeWarning) + + assert len(record) == 2 + assert str(record[0].message) == "user" + assert str(record[1].message) == "runtime" + + def test_double_test(self, testdir): """If a test is run again, the warning should still be raised""" testdir.makepyfile('''