argumentspytest

pytest use arguments in sessionstart


I have a conftest.py file looking like this:

from testdevice import TestDevice
from pytest import fixture

def pytest_addoption(parser):
    parser.addoption("--n", action="store", default="Name")

@fixture()
def name(request):
    return request.config.getoption("--n")

def pytest_configure(config):
    """
    Allows plugins and conftest files to perform initial configuration.
    This hook is called for every plugin and initial conftest
    file after command line options have been parsed.
    """

def pytest_sessionstart(session):
    """
    Called after the Session object has been created and
    before performing collection and entering the run test loop.
    """

    name = 'device_name'
    TestDevice(name)

def pytest_sessionfinish(session, exitstatus):
    """
    Called after whole test run finished, right before
    returning the exit status to the system.
    """

def pytest_unconfigure(config):
    """
    called before test process is exited.
    """

I am testing an embedded device, using ssh in the tests. Before the test I want to prepare the device, using the class TestDevice(name). "name" is the key of a dictionary containing device information.

Instead of hardcoding name in sessionstart. I have created a fixture where i can access the name argument, however I am only able to use the fixture in the tests. I am not able to access the fixture in "pytest_sessionstart", as i am not able to access the "request" argument.

Can anything be done to access the python arguments on "pytest_sessionstart"?


Solution

  • You don't have to use an extra fixture.

    You can get name in pytest_sessionstart via session object:

    def pytest_addoption(parser):
        parser.addoption("--n", action="store", default="Name")
    
    def pytest_sessionstart(session):
        name = session.config.getoption('--n')
        TestDevice(name)