Are `pytest_sessionstart()` and `pytest_sessionfinish()` valid hooks in pytest?

I want to know if pytest_sessionstart(session) and pytest_sessionfinish(session) are valid hooks. They aren’t described in the official hook documentation.

What is the difference between them and pytest_configure(config) / pytest_unconfigure(config)?

According to the docs:

  • pytest_configure(config) is called after command line options have been parsed and all plugins and initial conftest files have been loaded.
  • pytest_unconfigure(config) is called before the test process exits.

Is the session parameter in pytest_sessionstart / pytest_sessionfinish the same as the config?

I’ve used both in my plugins. pytest_sessionstart(session) and pytest_sessionfinish(session, exitstatus) are real hooks. The difference is that they receive a session object, not a config object. The session lets you inspect collected items, test outcomes, and the overall test session state, whereas pytest_configure(config) only gives you access to configuration and plugins.

Example:

def pytest_sessionstart(session):
    print(f"Session starting, collected {len(session.items)} tests")

def pytest_sessionfinish(session, exitstatus):
    print(f"Session finished with exit status {exitstatus}")

These hooks are useful when you want to run code specifically tied to the test session lifecycle rather than just configuration.

From my experience, pytest_configure and pytest_unconfigure are more about initializing plugins and global config.

pytest_sessionstart/finish actually wrap the test execution phase. For example, you can access session.items (all collected tests) and manipulate things before any test runs. Config only gives you command-line options and plugin states, so it’s less powerful for test-aware logic.

I used to get confused by this too. The session object is not the same as config. session gives you access to the whole test session, including collected items, hook outcomes, and results, whereas config is static: command-line options, ini files, and plugins. Think of config as setup info, and session as the running test universe.

def pytest_sessionstart(session):
    print(session.items)  # you can inspect all collected test items

If you want, I can write a quick example showing how to combine session hooks with pytest_addoption CLI arguments, which is really handy for plugin development.