如何将pytest fixture信息传递给非test_开头的普通函数?
如何在非
test_开头的函数中使用pytest fixture 核心说明
pytest的fixture依赖注入机制仅在测试上下文(即test_开头的测试函数、其他fixture函数)中生效,你期望的两种写法无法直接实现,以下是可行的替代方案:
方案1:在测试函数中传递fixture给普通函数
这是最直接的实现方式,在测试函数中拿到fixture实例后,直接作为参数传给普通函数:
import pytest @pytest.fixture def my_fixture(): return 'Hello world!' # 普通函数 def my_example(content): print(content) # 测试函数中传递fixture def test_one(my_fixture): my_example(my_fixture) assert my_fixture == 'Hello world!'
方案2:让普通函数在测试上下文内获取fixture
如果普通函数需要频繁使用fixture,可通过以下两种方式实现:
子方案2.1:将普通函数转为fixture
把普通函数包装成fixture,让它直接依赖目标fixture:
import pytest @pytest.fixture def my_fixture(): return 'Hello world!' # 转为fixture并依赖my_fixture @pytest.fixture def my_example(my_fixture): print(my_fixture) return my_fixture # 可返回结果供测试函数使用 def test_one(my_example): assert my_example == 'Hello world!'
子方案2.2:通过request对象获取fixture
在测试函数中将request对象传给普通函数,让它通过request.getfixturevalue()获取fixture实例:
import pytest @pytest.fixture def my_fixture(): return 'Hello world!' def my_example(request): fixture_value = request.getfixturevalue('my_fixture') print(fixture_value) return fixture_value def test_one(request): result = my_example(request) assert result == 'Hello world!'
为什么你的两种写法不生效?
@pytest.mark.usefixtures仅对测试函数或fixture函数生效,装饰普通函数时,pytest不会注入fixture,因此my_fixture变量在my_example中未定义。- pytest没有
pytest.get_fixture()这个全局API,fixture的生命周期由pytest管理,只能在测试上下文内获取实例。
内容的提问来源于stack exchange,提问作者garg10may
相关产品推荐
相关产品推荐

