pytest 使用夹具作为参数化中的参数 [英] pytest using fixtures as arguments in parametrize

查看:69
本文介绍了pytest 使用夹具作为参数化中的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用夹具作为 pytest.mark.parametrize 的参数或具有相同结果的东西.

I would like to use fixtures as arguments of pytest.mark.parametrize or something that would have the same results.

例如:

import pytest
import my_package

@pytest.fixture
def dir1_fixture():
    return '/dir1'

@pytest.fixture
def dir2_fixture():
    return '/dir2'

@pytest.parametrize('dirname, expected', [(dir1_fixture, 'expected1'), (dir2_fixture, 'expected2')]
def test_directory_command(dirname, expected):
    result = my_package.directory_command(dirname)
    assert result == expected

夹具参数的问题是夹具的每个参数在每次使用时都会运行,但我不希望那样.我希望能够根据测试选择使用哪些装置.

The problem with fixture params is that every param of the fixture will get run every time it's used, but I don't want that. I want to be able to choose which fixtures will get used depending on the test.

推荐答案

如果您使用的是 pytest 3.0 或更高版本,我认为您应该能够通过编写以下代码来解决这个特定场景:

If you're on pytest 3.0 or later, I think you should be able to solve this particular scenario by writing a fixture along the lines of:

@pytest.fixture(params=['dir1_fixture', 'dir2_fixture'])
def dirname(request):
    return request.getfixturevalue(request.param)

文档在这里:http://doc.pytest.org/en/latest/builtin.html#_pytest.fixtures.FixtureRequest.getfixturevalue

但是,如果您尝试动态加载的装置已参数化,则不能使用此方法.

However, you can't use this approach if the fixture you're attempting to dynamically load is parametrized.

或者,您可以使用 pytest_generate_tests 钩子解决问题.不过,我一直无法让自己深入研究.

Alternatively, you might be able to figure something out with the pytest_generate_tests hook. I haven't been able to bring myself to look into that much, though.

这篇关于pytest 使用夹具作为参数化中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆