Skip to content

Commit 2f08350

Browse files
authored
Merge pull request #4709 from namurphy/warns-docs
Document how to customize test failure message for missing warnings
2 parents 3384ffc + 584c052 commit 2f08350

File tree

3 files changed

+25
-2
lines changed

3 files changed

+25
-2
lines changed

AUTHORS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,7 @@ Nathaniel Waisbrot
174174
Ned Batchelder
175175
Neven Mundar
176176
Nicholas Devenish
177+
Nicholas Murphy
177178
Niclas Olofsson
178179
Nicolas Delaby
179180
Oleg Pidsadnyi

changelog/4709.doc.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Document how to customize test failure messages when using
2+
``pytest.warns``.

doc/en/warnings.rst

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ You can also use it as a contextmanager::
233233
.. _warns:
234234

235235
Asserting warnings with the warns function
236-
-----------------------------------------------
236+
------------------------------------------
237237

238238
.. versionadded:: 2.8
239239

@@ -291,7 +291,7 @@ Alternatively, you can examine raised warnings in detail using the
291291
.. _recwarn:
292292

293293
Recording warnings
294-
------------------------
294+
------------------
295295

296296
You can record raised warnings either using ``pytest.warns`` or with
297297
the ``recwarn`` fixture.
@@ -329,6 +329,26 @@ warnings, or index into it to get a particular recorded warning.
329329

330330
Full API: :class:`WarningsRecorder`.
331331

332+
.. _custom_failure_messages:
333+
334+
Custom failure messages
335+
-----------------------
336+
337+
Recording warnings provides an opportunity to produce custom test
338+
failure messages for when no warnings are issued or other conditions
339+
are met.
340+
341+
.. code-block:: python
342+
343+
def test():
344+
with pytest.warns(Warning) as record:
345+
f()
346+
if not record:
347+
pytest.fail("Expected a warning!")
348+
349+
If no warnings are issued when calling ``f``, then ``not record`` will
350+
evaluate to ``True``. You can then call ``pytest.fail`` with a
351+
custom error message.
332352

333353
.. _internal-warnings:
334354

0 commit comments

Comments
 (0)