Skip to content

Commit 80d1654

Browse files
author
Joan Massich
committed
Add documentation
1 parent aa6a670 commit 80d1654

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

_pytest/recwarn.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,22 @@ def warns(expected_warning, *args, **kwargs):
100100
101101
>>> with warns(RuntimeWarning):
102102
... warnings.warn("my warning", RuntimeWarning)
103+
104+
In the context manager form you may use the keyword argument ``match`` to assert
105+
that the exception matches a text or regex::
106+
107+
>>> with warns(UserWarning, match='must be 0 or None'):
108+
... warnings.warn("value must be 0 or None", UserWarning)
109+
110+
>>> with warns(UserWarning, match=r'must be \d+$'):
111+
... warnings.warn("value must be 42", UserWarning)
112+
113+
>>> with warns(UserWarning, match=r'must be \d+$'):
114+
... warnings.warn("this is not here", UserWarning)
115+
Traceback (most recent call last):
116+
...
117+
Failed: DID NOT WARN. No warnings of type ...UserWarning... was emitted...
118+
103119
"""
104120
match_expr = None
105121
if not args:

doc/en/warnings.rst

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,20 @@ which works in a similar manner to :ref:`raises <assertraises>`::
168168
with pytest.warns(UserWarning):
169169
warnings.warn("my warning", UserWarning)
170170

171-
The test will fail if the warning in question is not raised.
171+
The test will fail if the warning in question is not raised. The keyword
172+
argument ``match`` to assert that the exception matches a text or regex::
173+
174+
>>> with warns(UserWarning, match='must be 0 or None'):
175+
... warnings.warn("value must be 0 or None", UserWarning)
176+
177+
>>> with warns(UserWarning, match=r'must be \d+$'):
178+
... warnings.warn("value must be 42", UserWarning)
179+
180+
>>> with warns(UserWarning, match=r'must be \d+$'):
181+
... warnings.warn("this is not here", UserWarning)
182+
Traceback (most recent call last):
183+
...
184+
Failed: DID NOT WARN. No warnings of type ...UserWarning... was emitted...
172185

173186
You can also call ``pytest.warns`` on a function or code string::
174187

0 commit comments

Comments
 (0)