首页 文章

py.test:如何从@ pytest.fixture中访问test_function的参数

提问于
浏览
0

我的目标是从生成conftest.py的pytest.fixture中获取test_function的“args”,以便在满足特定条件时访问pytest.skip() .

这是conftest.py代码:

# conftest.py
import pytest

def pytest_generate_tests(metafunc):
    if 'param1' in metafunc.fixturenames:
        metafunc.parametrize("param1", [0, 1, 'a', 3, 4])

@pytest.fixture(autouse=True, scope="function")
def skip_if(request):
    # I want to do something like this
    # (but obviously request.node.param1 is not a real attribute):
    if request.node.param1 == 'a':
        xfail()

和test.py代码:

# test.py

def test_isdig(param1):
    assert isinstance(param1, int)

有没有人碰巧知道请求对象是否可以smoehow访问当前的param1值,以便我的autouse skip_if()fixture可以在某些条件下跳过它?我知道我可以将pytest.skip()调用放在test_isdig()中,但我试图以某种方式在夹具内完成它 . 非常感谢任何建议/指导!

1 回答

  • 1

    将参数添加到夹具以及测试功能似乎都有效 .

    测试代码:

    import pytest
    
    def pytest_generate_tests(metafunc):
        if 'param1' in metafunc.fixturenames:
            metafunc.parametrize("param1", [0, 1, 'a', 3, 4])
    
    @pytest.fixture(autouse=True, scope="function")
    def skip_if(param1):
        if param1 == 'a':
            pytest.xfail()
    
    def test_isint(param1):
        assert isinstance(param1, int)
    

    结果:

    ============================= test session starts =============================
    platform win32 -- Python 3.5.2, pytest-3.0.0, py-1.4.31, pluggy-0.3.1
    rootdir: D:\Development\Hacks\StackOverflow\39482428 - Accessing test function p
    arameters from pytest fixture, inifile:
    collected 5 items
    
    test_print_request_contents.py ..x..
    
    ===================== 4 passed, 1 xfailed in 0.10 seconds =====================
    

    但请注意,无论是否具有 param1 参数,都会为所有测试运行此 skip_if fixture,因此可能会出现问题 . 在这种情况下,可能更好的是在相关测试中明确地包含夹具,或者甚至将参数包装在夹具中,以便只有夹具具有 param1 作为参数,然后它返回,并且测试改为夹具作为参数 .

相关问题