How can I access the pytest session or CLI arguments inside the `pytest_runtest_logreport` hook?

I am building a pytest plugin that uses the pytest_runtest_logreport hook to execute some code whenever a test fails. I want to gate this plugin using a CLI argument added via pytest_addoption.

However, I cannot figure out how to access the pytest session state or the CLI arguments inside pytest_runtest_logreport.

Is there a proper way to access session or arguments from within this hook?

One thing to keep in mind is that every report object passed to pytest_runtest_logreport has a reference to the pytest config. You can use that to fetch CLI options directly:

def pytest_runtest_logreport(report):
    config = report.config
    if config.getoption("--my-flag") and report.failed:
        print(f"Test failed: {report.nodeid}")
````Preformatted text`


This avoids global variables entirely. The key is remembering that report.config gives you access to all CLI arguments and session state without extra hooks.

Another approach that worked well for me is to capture CLI flags in pytest_configure and attach them to the config object:

def pytest_addoption(parser):
    parser.addoption("--enable-feature", action="store_true")

def pytest_configure(config):
    config.enable_feature = config.getoption("--enable-feature")

def pytest_runtest_logreport(report):
    if getattr(report.config, "enable_feature", False) and report.failed:
        print(f"Custom action for {report.nodeid}")

This pattern is nice because you can safely attach any session-level data you need and reference it later in your hooks.

Sometimes pytest_runtest_logreport feels a bit limited. I found using pytest_runtest_makereport easier because it always gives you the item along with the call and report, so accessing CLI options is straightforward:

def pytest_runtest_makereport(item, call):
    report = pytest.TestReport.from_item_and_call(item, call)
    if item.config.getoption("--my-flag") and report.failed:
        print(f"Failed test: {item.nodeid}")
    return report

This way, you have full access to session, item, and CLI args, making it easier to gate custom logic.

If you want, I can also draft three more variations that explain how to combine session-scoped fixtures with CLI options so your plugin behaves consistently across all tests.