Skip to content

Commit 4b83a05

Browse files
authored
Merge pull request #10697 from pytest-dev/backport-10695-to-7.2.x
[7.2.x] Clarify docs for `match` regarding escaping
2 parents 76bef68 + 4e14609 commit 4b83a05

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

doc/en/how-to/capture-warnings.rst

+18-4
Original file line numberDiff line numberDiff line change
@@ -270,20 +270,34 @@ which works in a similar manner to :ref:`raises <assertraises>` (except that
270270
warnings.warn("my warning", UserWarning)
271271
272272
The test will fail if the warning in question is not raised. Use the keyword
273-
argument ``match`` to assert that the warning matches a text or regex::
273+
argument ``match`` to assert that the warning matches a text or regex.
274+
To match a literal string that may contain regular expression metacharacters like ``(`` or ``.``, the pattern can
275+
first be escaped with ``re.escape``.
274276

275-
>>> with warns(UserWarning, match='must be 0 or None'):
277+
Some examples:
278+
279+
.. code-block:: pycon
280+
281+
282+
>>> with warns(UserWarning, match="must be 0 or None"):
276283
... warnings.warn("value must be 0 or None", UserWarning)
284+
...
277285
278-
>>> with warns(UserWarning, match=r'must be \d+$'):
286+
>>> with warns(UserWarning, match=r"must be \d+$"):
279287
... warnings.warn("value must be 42", UserWarning)
288+
...
280289
281-
>>> with warns(UserWarning, match=r'must be \d+$'):
290+
>>> with warns(UserWarning, match=r"must be \d+$"):
282291
... warnings.warn("this is not here", UserWarning)
292+
...
283293
Traceback (most recent call last):
284294
...
285295
Failed: DID NOT WARN. No warnings of type ...UserWarning... were emitted...
286296
297+
>>> with warns(UserWarning, match=re.escape("issue with foo() func")):
298+
... warnings.warn("issue with foo() func")
299+
...
300+
287301
You can also call :func:`pytest.warns` on a function or code string:
288302

289303
.. code-block:: python

0 commit comments

Comments
 (0)