Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access pytest session or arguments in pytest_runtest_logreport

I am trying to build a pytest plugin that utilizes the pytest_runtest_logreport in order to invoke some code everytime a test fails. I'd like to gate this plugin with a CLI argument I have added using the pytest_addoption hook. Unfortunately I can't seem to figure out how to access the pytest session state or arguments inside the pytest_runtest_logreport hook. Is there a way to do this? I don't see it in the hookspec.

like image 884
Colin Schoen Avatar asked Oct 25 '25 01:10

Colin Schoen


1 Answers

You can't get the session from the standard TestReport object. However, you can introduce a custom wrapper around the pytest_runtest_makereport hook (the one that creates the report object), where you can attach the session yourself. Example:

import pytest


@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    out = yield
    report = out.get_result()
    report.session = item.session


def pytest_runtest_logreport(report):
    print(report.session)

Another example of passing state between hooks is a plugin class. Example with accessing config object in pytest_runtest_logreport:

import pytest


@pytest.mark.tryfirst
def pytest_configure(config):
    p = MyPlugin(config)
    config.pluginmanager.register(p, 'my_plugin')


class MyPlugin:
    def __init__(self, config):
        self.config = config

    def pytest_runtest_logreport(self, report):
        print(report, self.config) 
like image 175
hoefling Avatar answered Oct 27 '25 15:10

hoefling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!