Why is `pytest_sessionfinish` not getting invoked when running tests in pytest?

While running pytest, the pytest_sessionfinish hook isn’t being called even though it’s defined in the same test file.

The goal is to capture the number of passed and failed tests and send them to a Prometheus gateway once the session ends.

However, the hook never executes regardless of flags or environments.

Example code:

import pytest

@pytest.fixture(scope="session")
def my_fixture():
    print("in fun")
    yield

def test_example(my_fixture):
    assert 2 + 2 == 4

@pytest.hookimpl(tryfirst=True)
def pytest_sessionfinish(session, exitstatus):
    print("pytest_sessionfinish called")

Attempts made:

  • Used -s and -v flags to ensure print outputs aren’t suppressed.
  • Enabled debug logging to check for errors.
  • Tried on multiple environments with the same result.

pytest_sessionfinish won’t be triggered if it’s defined inside a test file. It must be placed in a plugin or conftest.py file since pytest only recognizes hook implementations from those locations.

Moving the hook to conftest.py will allow pytest to call it after all tests complete.