将pytest fixture定义为上下文管理器。
pytest-contextfixture的Python项目详细描述
pytest contextfixture允许将pytest fixture定义为上下文管理器
contextfixture的工作方式与标准fixture类似,但它允许 作为生成器写入的定义。这样就简化了拆卸过程 代码并允许在fixture中使用其他上下文管理器。
安装
pip安装pytest contextfixture
用法
考虑这个例子,使用标准的pytest.fixture
import pytest @pytest.fixture def dependency(request) def teardown(): # fixture teardown code goes here request.addfinalizer(teardown) return 1234 def test_foo(dependency): assert fn_under_test(dependency) == 'expected'
对于pytest.contextfixture,这相当于:
import pytest @pytest.contextfixture def dependency(request): # fixture setup code goes here yield 1234 # fixture teardown code goes here def test_foo(dependency): assert fn_under_test(dependency) == 'expected'
虽然这是一个稍微好一点的语法,但是在使用其他上下文管理器时 要获取设备的依赖项,这将变得更有用:
@pytest_contextfixture def dependency(request): with setup_something(): with setup_something_else() as d: yield d def test_foo(dependency): assert fn_under_test(dependency) == 'expected'
然后test_foo将在setup_something和 安排其他事情。