如何向Pytest fixture传递一个值

3

我正在使用Pytest测试一个可执行文件。这个.exe文件在启动时会读取一个配置文件。

我已经编写了一个fixture,用于在每个测试开始时启动该.exe文件,并在测试结束时关闭它。但是,我无法确定如何告诉fixture要使用哪个配置文件。我想让fixture在启动.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()

我该如何告诉测试工具在执行test_1函数时使用foo.xml文件,在执行test_2函数时使用bar.xml文件?

谢谢, 约翰

1个回答

8
一种解决方案是使用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 fixture,将链接的创建委托给测试函数:
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。此外,请注意,后者允许在同一个测试中生成多个可执行文件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接