问题
I have a fixture that creates an object I use in many tests.
This Object has a property - priority
(1 - 10)
Now, there are a lot of tests that need to "know" the priority of the object (in order to test various logic paths)
So I could have 10 different fixtures:
@pytest.fixture
def object_priority_1():
return MyObj(priority=1)
@pytest.fixture
def object_priority_2():
return MyObj(priority=2)
//....
@pytest.fixture
def object_priority_10():
return MyObj(priority=10)
But it seems off... I'm sure there is a way to deliver an external param to a fixture each time - I just couldn't find it
Edit: To clarify - I would have wanted something in the area of:
@pytest.fixture
def my_object(<priority as an external param>):
return MyObj(priority)
And then the test would be something like:
def test_foo(my_object(1), my_object(6)):
//...
回答1:
You can do :
@pytest.fixture
def my_object(priority):
return MyObj(priority)
def test_foo(my_object):
obj_1 = my_object(1)
assert something # 1
obj_2 = my_object(2)
assert something # 2
I come with this idea, then I found this Q&A :
py.test: Pass a parameter to a fixture function
I think your question maybe consider a duplicate if your problem is solved.
来源:https://stackoverflow.com/questions/32275347/initing-a-pytest-fixture-with-a-parameter