[英]How to pass a value to a Pytest fixture
我正在使用 Pytest 来测试可执行文件。 此 .exe 文件在启动时读取配置文件。
我已经编写了一个固定装置来在每个测试开始时生成这个 .exe 文件,并在测试结束时关闭它。 但是,我不知道如何告诉夹具使用哪个配置文件。 我希望夹具在生成 .exe 文件之前将指定的配置文件复制到目录中。
@pytest.fixture
def session(request):
copy_config_file(specific_file) # how do I specify the file to use?
link = spawn_exe()
def fin():
close_down_exe()
return link
# needs to use config file foo.xml
def test_1(session):
session.talk_to_exe()
# needs to use config file bar.xml
def test_2(session):
session.talk_to_exe()
我该如何告诉夹具使用foo.xml
为test_1
功能和bar.xml
为test_2
功能?
谢谢约翰
一种解决方案是使用pytest.mark
:
import pytest
@pytest.fixture
def session(request):
m = request.node.get_closest_marker('session_config')
if m is None:
pytest.fail('please use "session_config" marker')
specific_file = m.args[0]
copy_config_file(specific_file)
link = spawn_exe()
yield link
close_down_exe(link)
@pytest.mark.session_config("foo.xml")
def test_1(session):
session.talk_to_exe()
@pytest.mark.session_config("bar.xml")
def test_2(session):
session.talk_to_exe()
另一种方法是稍微更改您的session
装置以将链接的创建委托给测试函数:
import pytest
@pytest.fixture
def session_factory(request):
links = []
def make_link(specific_file):
copy_config_file(specific_file)
link = spawn_exe()
links.append(link)
return link
yield make_link
for link in links:
close_down_exe(link)
def test_1(session_factory):
session = session_factory('foo.xml')
session.talk_to_exe()
def test_2(session):
session = session_factory('bar.xml')
session.talk_to_exe()
我更喜欢后者,因为它更易于理解,并且允许以后进行更多改进,例如,如果您需要在基于配置值的测试中使用@parametrize
。 另请注意,后者允许在同一测试中生成多个可执行文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.