Merge pull request #10697 from pytest-dev/backport-10695-to-7.2.x

[7.2.x] Clarify docs for `match` regarding escaping
This commit is contained in:
Bruno Oliveira 2023-01-27 08:47:14 -03:00 committed by GitHub
commit 4b83a05939
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 18 additions and 4 deletions

View File

@ -270,20 +270,34 @@ which works in a similar manner to :ref:`raises <assertraises>` (except that
warnings.warn("my warning", UserWarning) warnings.warn("my warning", UserWarning)
The test will fail if the warning in question is not raised. Use the keyword 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) ... 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) ... 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) ... warnings.warn("this is not here", UserWarning)
...
Traceback (most recent call last): Traceback (most recent call last):
... ...
Failed: DID NOT WARN. No warnings of type ...UserWarning... were emitted... 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: You can also call :func:`pytest.warns` on a function or code string:
.. code-block:: python .. code-block:: python