@@ -270,20 +270,34 @@ which works in a similar manner to :ref:`raises <assertraises>` (except that
270
270
warnings.warn(" my warning" , UserWarning )
271
271
272
272
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 ``.
274
276
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"):
276
283
... warnings.warn("value must be 0 or None", UserWarning)
284
+ ...
277
285
278
- >>> with warns(UserWarning, match=r' must be \d+$' ):
286
+ >>> with warns(UserWarning, match=r" must be \d+$" ):
279
287
... warnings.warn("value must be 42", UserWarning)
288
+ ...
280
289
281
- >>> with warns(UserWarning, match=r' must be \d+$' ):
290
+ >>> with warns(UserWarning, match=r" must be \d+$" ):
282
291
... warnings.warn("this is not here", UserWarning)
292
+ ...
283
293
Traceback (most recent call last):
284
294
...
285
295
Failed: DID NOT WARN. No warnings of type ...UserWarning... were emitted...
286
296
297
+ >>> with warns(UserWarning, match=re.escape("issue with foo() func")):
298
+ ... warnings.warn("issue with foo() func")
299
+ ...
300
+
287
301
You can also call :func: `pytest.warns ` on a function or code string:
288
302
289
303
.. code-block :: python
0 commit comments