Python Pytest是否可以从fixture访问变量?



在我的conftest.py中我有

@pytest.fixture(scope="function")
def specific_test_setup(request):
my_var = "hello world"

我想要一个特定的测试使用它作为设置。并且,能够使用fixture中定义的变量。例如,我希望它看起来是这样的:

class TestHelloWorld:
def test_hello_world(self, specific_test_setup):
print(self.my_var)

这能实现吗?

一种方法是返回fixture中的变量:

@pytest.fixture(scope="function")
def specific_test_setup(request):
my_var = "hello world"
return my_var

然后在你的测试中使用它:

def test_hello_world(self, specific_test_setup):
print(specific_test_setup)

另一种方法是使用pytest全局变量(不确定它是否未被弃用):

@pytest.fixture(scope="function")
def specific_test_setup(request):
pytest.my_var = "hello world"
def test_hello_world(self, specific_test_setup):
print(pytest.my_var)

最新更新