7
votes

I have a set of fixtures to setup fairly big data set. The result of the setup is stored in a database (scope=function) for a report rendering regression test. The fixtures are not parametrized, so there is only one setup that comes out of it, but the regression test has a few of those interdependent fixtures as parameters to access the objects without additional queries. pytest uses in-memory database and rolls-back after each test, so after finishing the tests, the setup is not available.

I would like to use that database setup outside pytest for demo and front-end automated tests.

How to get the result of the pytest fixture in development database?

An example without details, to show the structure of the fixture:

@pytest.fixture
def customer():
    return mommy.make(Customer, name='Customer LTD')

@pytest.fixture(autouse=True)
def inventory_types(customer):
    return seeder.seed_inventory_types('A,B,C', customer=customer)


@pytest.fixture(autouse=True)
def inventory(
    good,
    bad,
    ugly,
    common,
    ...
):
    return

@pytest.fixture
def good(customer, patterns):
    vehicle = mommy.make(
        Inventory, 
        name='Good', 
        type=inventory_types.A, 
        customer=customer
    )

@pytest.fixture
def bad(customer, patterns):
    return make(
        Inventory, 
        name='Bad', 
        type=inventory_types.A,  
        customer=customer
    )

@pytest.fixture
def ugly(customer, patterns):
    return mommy.make(
        Inventory, 
        name='Ugly', 
        type=inventory_types.B, 
        customer=customer
    )

@pytest.fixture
def common(customer, patterns):
    return mommy.make(
        Inventory, 
        name='Common', 
        type=inventory_types.C, 
        customer=customer
    )


def test(good, customer):
    assert good in customer.inventory
1
Fixtures can't be used outside of pytest context, so I guess the answer is - you can't. You can use fixtures as regular functions in older versions (smth like vehicle = good(customer(), patterns())), but this behaviour is not allowed in pytest>=5 anymore. - hoefling
@hoefling Thanks, good point, maybe I can call it outside pytest context or somehow unwrap the functions. I'll try that. - dhill
I have used subprocess to call a frontend test suite from inside a pytest test_ method. It's hacky and makes debugging more difficult but it's doable. - jstewart379

1 Answers

0
votes

It seems that you can call the function wrapped by the fixture decorator like this: customer.__pytest_wrapped__.obj(). Obviously that's not a public API and so might change.

It looks like an alternative would be to structure your fixture code differently, so that it also exposes a normal function. See the name argument mentioned here: https://docs.pytest.org/en/stable/deprecations.html#calling-fixtures-directly