Jason S
Jason S

Reputation: 189626

parameterizing py.test fixture objects

I have looked at the py.test documentation and so far have been ok. I have tests / test fixtures like this:

@pytest.fixture(scope="session")
def comm_env():
    return CommEnv()

def test_write1(comm_env):
'''Write patterns and read them back.'''
    ... fun stuff goes here ...

so that I can create a custom CommEnv() object and my tests can get access to it.

Now I need to add a command-line parameter to the comm_env() function so I can pass in a communications port name and baud rate. How can I do this? I looked at the parametrizing test fixtures page but my eyes just glaze over.

I did figure out how to add command-line arguments by adding a short conftest.py file in the test directory, but I can't figure out how to connect it to make it available to comm_env().

Upvotes: 2

Views: 1016

Answers (2)

Jason S
Jason S

Reputation: 189626

I figured it out: you can access the config attribute of the fixture request object:

@pytest.fixture(scope="session")
def comm_env(request):
    commport = request.config.getoption('--port')
    baudrate = request.config.getoption('--baud')
    print "params: %s, %s" % (commport, baudrate)
    return CommEnv(commport, baudrate)

and then I just have to do this in the conftest.py:

import pytest

def pytest_addoption(parser):
    parser.addoption('--port',help='serial port e.g. COM1')
    parser.addoption('--baud',help='baud rate',type=int)

Upvotes: 3

Simeon Visser
Simeon Visser

Reputation: 122326

I think you need this section which means it would become:

@pytest.fixture(scope="session", params=[
    (123, 456),
    (456, 789),
])
def comm_env(request):
    val1, val2 = request.param
    return CommEnv()

You can construct the fixture when you have params = [(123, 456), (456, 789)]:

def construct_fixture(params):
    @pytest.fixture(scope="session", params=params)
    def comm_env(request):
        val1, val2 = request.param
        return CommEnv()
    return comm_env

globals()['comm_env'] = construct_fixture(params)

Upvotes: 0

Related Questions