From 73702ca88b28d8f83dc7487b87ef6633697cc7a6 Mon Sep 17 00:00:00 2001 From: Adam Johnson Date: Mon, 23 Dec 2019 10:38:27 +0000 Subject: [PATCH] Improve warnings docs * Rearrange section about context manager to be in order * Link to `pytest.warns` and `recwarn` since a reader going top to bottom won't have seen about those yet. * Used only context manager form in the example; the call form is somewhat obsolete and is mentioned in the reference docs already. * Reuse the 'myfunction' from first example on the second one Co-Authored-By: Hugo van Kemenade Co-Authored-By: Hugo van Kemenade --- doc/en/warnings.rst | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/doc/en/warnings.rst b/doc/en/warnings.rst index 4b8be4469..013564c2d 100644 --- a/doc/en/warnings.rst +++ b/doc/en/warnings.rst @@ -198,7 +198,7 @@ the regular expression ``".*U.*mode is deprecated"``. Ensuring code triggers a deprecation warning -------------------------------------------- -You can also call a global helper for checking +You can also use :func:`pytest.deprecated_call` for checking that a certain function call triggers a ``DeprecationWarning`` or ``PendingDeprecationWarning``: @@ -207,13 +207,18 @@ that a certain function call triggers a ``DeprecationWarning`` or import pytest - def test_global(): - pytest.deprecated_call(myfunction, 17) + def test_myfunction_deprecated(): + with pytest.deprecated_call(): + myfunction(17) + +This test will fail if ``myfunction`` does not issue a deprecation warning +when called with a ``17`` argument. By default, ``DeprecationWarning`` and ``PendingDeprecationWarning`` will not be -caught when using ``pytest.warns`` or ``recwarn`` because default Python warnings filters hide -them. If you wish to record them in your own code, use the -command ``warnings.simplefilter('always')``: +caught when using :func:`pytest.warns` or :ref:`recwarn ` because +the default Python warnings filters hide +them. If you wish to record them in your own code, use +``warnings.simplefilter('always')``: .. code-block:: python @@ -223,19 +228,13 @@ command ``warnings.simplefilter('always')``: def test_deprecation(recwarn): warnings.simplefilter("always") - warnings.warn("deprecated", DeprecationWarning) + myfunction(17) assert len(recwarn) == 1 assert recwarn.pop(DeprecationWarning) -You can also use it as a contextmanager: - -.. code-block:: python - - def test_global(): - with pytest.deprecated_call(): - myobject.deprecated_method() - +The :ref:`recwarn ` fixture automatically ensures to reset the warnings +filter at the end of the test, so no global state is leaked. .. _`asserting warnings`: