Clarify docs for `match` regarding escaping

Add example using `re.escape` to escape arbitrary literal strings which might contain regular expression characters like ( or .
This commit is contained in:
vin01 2023-01-26 22:45:59 +01:00
parent ca40380e99
commit d73b49d75d
No known key found for this signature in database
GPG Key ID: 885C28C3B043329D
1 changed files with 8 additions and 1 deletions

View File

@ -270,7 +270,11 @@ 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``.
Some examples:
>>> with warns(UserWarning, match='must be 0 or None'): >>> 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)
@ -284,6 +288,9 @@ argument ``match`` to assert that the warning matches a text or regex::
... ...
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