From 4a69cf2eb6fb900fbd4df8caa0d6d10a2a761c66 Mon Sep 17 00:00:00 2001 From: Liam DeVoe Date: Tue, 6 Jan 2026 06:50:21 -0500 Subject: [PATCH] Clarify `pytest_collection_finish` occurs after setting `session.items` (#14088) (cherry picked from commit 0e9db5fa5a8de151ab43e5d71e0e8192e0456b9d) --- .gitignore | 1 + changelog/14088.doc.rst | 1 + doc/en/reference/reference.rst | 1 + src/_pytest/hookspec.py | 4 ++-- 4 files changed, 5 insertions(+), 2 deletions(-) create mode 100644 changelog/14088.doc.rst diff --git a/.gitignore b/.gitignore index c4557b33a1c..d0e8dc54ba1 100644 --- a/.gitignore +++ b/.gitignore @@ -51,6 +51,7 @@ coverage.xml .vscode __pycache__/ .python-version +.claude/settings.local.json # generated by pip pip-wheel-metadata/ diff --git a/changelog/14088.doc.rst b/changelog/14088.doc.rst new file mode 100644 index 00000000000..3f3a0963516 --- /dev/null +++ b/changelog/14088.doc.rst @@ -0,0 +1 @@ +Clarified that the default :hook:`pytest_collection` hook sets ``session.items`` before it calls :hook:`pytest_collection_finish`, not after. diff --git a/doc/en/reference/reference.rst b/doc/en/reference/reference.rst index 9d14e9147fc..9206e48ca81 100644 --- a/doc/en/reference/reference.rst +++ b/doc/en/reference/reference.rst @@ -757,6 +757,7 @@ items, delete or otherwise amend the test items: If this hook is implemented in ``conftest.py`` files, it always receives all collected items, not only those under the ``conftest.py`` where it is implemented. +.. hook:: pytest_collection_finish .. autofunction:: pytest_collection_finish Test running (runtest) hooks diff --git a/src/_pytest/hookspec.py b/src/_pytest/hookspec.py index c5bcc36ad4b..dab3fb698a2 100644 --- a/src/_pytest/hookspec.py +++ b/src/_pytest/hookspec.py @@ -251,8 +251,8 @@ def pytest_collection(session: Session) -> object | None: 1. ``pytest_deselected(items)`` for any deselected items (may be called multiple times) - 3. ``pytest_collection_finish(session)`` - 4. Set ``session.items`` to the list of collected items + 3. Set ``session.items`` to the list of collected items + 4. ``pytest_collection_finish(session)`` 5. Set ``session.testscollected`` to the number of collected items You can implement this hook to only perform some action before collection,