Consider the following pseudocode demonstrating my question:
import pytest
@pytest.fixture
def param1():
# return smth
yield "wilma"
@pytest.fixture
def param2():
# return smth
yield "fred"
@pytest.fixture
def bar(param1, param2):
#do smth
return [Bar(param1, param2), Bar(param1, param2)]
@pytest.fixture
def first_bar(bar):
return bar[0]
class Test_first_bar:
# FIXME: how do I do that?
#def setup_smth???(self, first_bar):
# self.bar = first_bar
def test_first_bar_has_wilma(self):
# some meaningful check number 1
assert self.bar.wilma == "wilma"
def test_first_bar_some_other_check(self):
# some meaningful check number 2
assert self.bar.fred == "fred"
Basically I want to pass first_bar
fixture to my Test_first_bar
class in order to reuse that object in all its test methods. How should I go about dealing with such situation?
Python 3, if that matters.
Here, you can define your fixture as autouse
. Which would be called automatically for all the tests of your class. Here, I cant understand what is [Bar(param1, param2), Bar(param1, param2)]
. Well, that's not the point, if rest of the code is working fine than you can try the below solution. I have replaced the code with static variables to verify if it's working or not and it's working fine at my end.
import pytest
@pytest.fixture
def param1():
# return smth
yield "wilma"
@pytest.fixture
def param2():
# return smth
yield "fred"
@pytest.fixture
def bar(param1, param2):
# do smth
return [Bar(param1, param2), Bar(param1, param2)]
@pytest.fixture(scope='function', autouse=True)
def first_bar(bar, request):
request.instance.bar = bar[0]
class Test_first_bar:
def test_first_bar_has_wilma(self,request):
print request.instance.bar
def test_first_bar_some_other_check(self,request):
print request.instance.bar
And if you do not want to make fixture as autouse
, than you can call it before your test. Like,
import pytest
@pytest.fixture
def param1():
# return smth
yield "wilma"
@pytest.fixture
def param2():
# return smth
yield "fred"
@pytest.fixture
def bar(param1, param2):
# do smth
return [Bar(param1, param2), Bar(param1, param2)]
@pytest.fixture(scope='function')
def first_bar(bar, request):
request.instance.bar = bar[0]
class Test_first_bar:
@pytest.mark.usefixtures("first_bar")
def test_first_bar_has_wilma(self,request):
print request.instance.bar
@pytest.mark.usefixtures("first_bar")
def test_first_bar_some_other_check(self,request):
print request.instance.bar
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.