Skip to content

Commit 532e7b8

Browse files
docs(assert): explain what an early import costs a test module
The "Assertion introspection details" section said only that pytest rewrites the modules it discovers, without saying that an import which beats collection to the module takes that away. The conftest example further up does exactly the top-level import that bit the reporter of issue #1929, so note why it is safe there and what makes it unsafe elsewhere. Co-Authored-By: Claude Opus 5 (1M context) via Claude Code <noreply@anthropic.com>
1 parent 5a88cb7 commit 532e7b8

2 files changed

Lines changed: 19 additions & 0 deletions

File tree

‎changelog/1930.doc.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Documented that a test module which has already been imported when collection reaches it cannot have its assertions rewritten, and how to avoid importing one too early from a ``conftest.py``.

‎doc/en/how-to/assert.rst‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -499,6 +499,16 @@ the conftest file:
499499
FAILED test_foocompare.py::test_compare - assert Comparing Foo instances:
500500
1 failed in 0.12s
501501
502+
.. note::
503+
504+
The ``conftest.py`` above imports the test module at the top level. That is
505+
safe here only because ``test_foocompare.py`` matches the ``python_files``
506+
patterns, so pytest rewrites it whoever imports it first. Importing a module
507+
that pytest would only recognise as a test module for another reason -- because
508+
it was named on the command line, for instance -- costs that module its
509+
assertion introspection; see :ref:`assert-details` below. Moving the import
510+
inside the hook body avoids the question entirely.
511+
502512
.. _`return-not-none`:
503513

504514
Returning non-None value in test functions
@@ -560,6 +570,14 @@ You can manually enable assertion rewriting for an imported module by calling
560570
:ref:`register_assert_rewrite <assertion-rewriting>`
561571
before you import it (a good place to do that is in your root ``conftest.py``).
562572

573+
Rewriting happens on import, so a module which has *already* been imported by the
574+
time collection reaches it cannot be rewritten any more, even if it is a test
575+
module. The usual cause is a top-level ``import`` in a ``conftest.py`` or a
576+
plugin. pytest emits a :class:`pytest.PytestAssertRewriteWarning` when it
577+
collects such a module; either delay the import until after collection -- moving
578+
it into the hook or fixture that needs it -- or call
579+
:func:`pytest.register_assert_rewrite` before it.
580+
563581
For further information, Benjamin Peterson wrote up `Behind the scenes of pytest's new assertion rewriting <http://pybites.blogspot.com/2011/07/behind-scenes-of-pytests-new-assertion.html>`_.
564582

565583
Assertion rewriting caches files on disk

0 commit comments

Comments
 (0)