From 86a1beba072cb72c1a265ec523cbed84f377913a Mon Sep 17 00:00:00 2001 From: vin01 <30344579+vin01@users.noreply.github.com> Date: Fri, 27 Jan 2023 12:11:00 +0100 Subject: [PATCH] Clarify docs for `match` regarding escaping (#10695) Add example using `re.escape` to escape arbitrary literal strings which might contain regular expression characters like `.` or `)`. Closes #10595 --- doc/en/how-to/capture-warnings.rst | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/doc/en/how-to/capture-warnings.rst b/doc/en/how-to/capture-warnings.rst index 91565002c..51e85badd 100644 --- a/doc/en/how-to/capture-warnings.rst +++ b/doc/en/how-to/capture-warnings.rst @@ -270,20 +270,34 @@ which works in a similar manner to :ref:`raises ` (except that warnings.warn("my warning", UserWarning) The test will fail if the warning in question is not raised. Use the keyword -argument ``match`` to assert that the warning matches a text or regex:: +argument ``match`` to assert that the warning matches a text or regex. +To match a literal string that may contain regular expression metacharacters like ``(`` or ``.``, the pattern can +first be escaped with ``re.escape``. - >>> with warns(UserWarning, match='must be 0 or None'): +Some examples: + +.. code-block:: pycon + + + >>> with warns(UserWarning, match="must be 0 or None"): ... warnings.warn("value must be 0 or None", UserWarning) + ... - >>> with warns(UserWarning, match=r'must be \d+$'): + >>> with warns(UserWarning, match=r"must be \d+$"): ... warnings.warn("value must be 42", UserWarning) + ... - >>> with warns(UserWarning, match=r'must be \d+$'): + >>> with warns(UserWarning, match=r"must be \d+$"): ... warnings.warn("this is not here", UserWarning) + ... Traceback (most recent call last): ... Failed: DID NOT WARN. No warnings of type ...UserWarning... were emitted... + >>> with warns(UserWarning, match=re.escape("issue with foo() func")): + ... warnings.warn("issue with foo() func") + ... + You can also call :func:`pytest.warns` on a function or code string: .. code-block:: python