diff --git a/AUTHORS b/AUTHORS index 0b0f10052..49bd6ca85 100644 --- a/AUTHORS +++ b/AUTHORS @@ -28,6 +28,7 @@ Dave Hunt David Mohr Edison Gustavo Muenz Eduardo Schettino +Endre Galaczi Elizaveta Shashkova Eric Hunsberger Eric Siegerman diff --git a/CHANGELOG b/CHANGELOG index d74db53c1..f16c46ec5 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -14,6 +14,7 @@ - Fix issue #411: Add __eq__ method to assertion comparison example. Thanks Ben Webb. +- Fix issue #653: deprecated_call can be used as context manager. - fix issue 877: propperly handle assertion explanations with non-ascii repr Thanks Mathieu Agopian for the report and Ronny Pfannschmidt for the PR. diff --git a/_pytest/recwarn.py b/_pytest/recwarn.py index abefdfac1..5e7cdd84b 100644 --- a/_pytest/recwarn.py +++ b/_pytest/recwarn.py @@ -28,9 +28,17 @@ def pytest_namespace(): 'warns': warns} -def deprecated_call(func, *args, **kwargs): +def deprecated_call(func=None, *args, **kwargs): """Assert that ``func(*args, **kwargs)`` triggers a DeprecationWarning. + + This function can be used as a context manager:: + + >>> with deprecated_call(): + ... myobject.deprecated_method() """ + if not func: + return WarningsChecker(expected_warning=DeprecationWarning) + wrec = WarningsRecorder() with wrec: warnings.simplefilter('always') # ensure all warnings are triggered @@ -149,8 +157,8 @@ class WarningsRecorder(object): self._module.showwarning = showwarning # allow the same warning to be raised more than once - self._module.simplefilter('always', append=True) + self._module.simplefilter('always') return self def __exit__(self, *exc_info): diff --git a/doc/en/recwarn.rst b/doc/en/recwarn.rst index c2a1e65fa..ead162f4e 100644 --- a/doc/en/recwarn.rst +++ b/doc/en/recwarn.rst @@ -114,3 +114,9 @@ command ``warnings.simplefilter('always')``:: warnings.warn("deprecated", DeprecationWarning) assert len(recwarn) == 1 assert recwarn.pop(DeprecationWarning) + +You can also use it as a contextmanager:: + + def test_global(): + with pytest.deprecated_call(): + myobject.deprecated_method() diff --git a/testing/test_recwarn.py b/testing/test_recwarn.py index 644b09ef7..f441187a6 100644 --- a/testing/test_recwarn.py +++ b/testing/test_recwarn.py @@ -79,6 +79,7 @@ def dep_explicit(i): filename="hello", lineno=3) class TestDeprecatedCall(object): + def test_deprecated_call_raises(self): excinfo = pytest.raises(AssertionError, "pytest.deprecated_call(dep, 3)") @@ -111,6 +112,16 @@ class TestDeprecatedCall(object): pytest.deprecated_call(dep_explicit, 0) pytest.deprecated_call(dep_explicit, 0) + def test_deprecated_call_as_context_manager_no_warning(self): + with pytest.raises(pytest.fail.Exception) as ex: + with pytest.deprecated_call(): + dep(1) + assert str(ex.value) == "DID NOT WARN" + + def test_deprecated_call_as_context_manager(self): + with pytest.deprecated_call(): + dep(0) + class TestWarns(object): def test_strings(self):