Reputation: 27574
Is it possible to pass one fixture object to another in Pytest? For example, suppose I want to have two fixture objects: one that's a numpy array, and another that's some model of that array:
import pytest
import numpy as np
@pytest.fixture()
def arr():
np.random.seed(141)
return np.random.seed(141)
@pytest.fixture()
def model(arr):
return arr * 2
def test_multiplication(arr, model):
assert model == arr * 2
Here arr
is type function
but arr()
is NoneType
inside model, which confuseth me.
The use case for this is a case where some tests need access to the raw arr
itself, while others need access to the models.
To make this work, however, one needs to pass one fixture to another (so we can build the model using the array). Is this possible? Any help others can offer would be greatly appreciated!
Upvotes: 10
Views: 7329
Reputation: 27574
Whoops, my sample arr()
function wasn't defining an array! You can share fixtures in the way approached above:
import pytest
import numpy as np
@pytest.fixture()
def arr():
np.random.seed(141)
return np.random.rand(100,2)
@pytest.fixture()
def model(arr):
return arr * 2
def test_multiplication(arr, model):
assert np.all(model == arr * 2)
One can also create a class with various class methods, then return that from a fixture. Then tests can call individual class methods or access class attributes to get access to a larger chunk of shared state. Very nice.
Upvotes: 11