首页 > 解决方案 > 如何在“pytest.dependency”中使用测试数据/外部变量?

问题描述

下面的 pytest 代码可以正常工作,它会增加value.

import pytest
pytest.value = 1

def test_1():
    pytest.value +=1
    print(pytest.value)

def test_2():
    pytest.value +=1
    print(pytest.value)

def test_3():
    pytest.value +=1
    print(pytest.value)

输出:

Prints
2
3
4

我不想执行test_2,当value=2

有可能pytest.dependency()吗?value如果是,我该如何使用变量pytest.dependency

如果没有pytest.dependency,还有其他选择吗?

或者有什么更好的方法来处理这种情况?

    import pytest
    pytest.value = 1
    
    def test_1():
        pytest.value +=1
        print(pytest.value)
    
    @pytest.dependency(value=2)  # or @pytest.dependency(pytest.value=2)
    def test_2():
        pytest.value +=1
        print(pytest.value)
    
    def test_3():
        pytest.value +=1
        print(pytest.value)

你能指导我吗?这可以做到吗?这可能吗 ?

标签: python-3.xpytestfixtures

解决方案


如果您可以访问测试之外的值(如您的示例中的情况),则可以根据该值跳过夹具中的测试:

@pytest.fixture(autouse=True)
def skip_unwanted_values():
    if pytest.value == 2:
        pytest.skip(f"Value {pytest.value} shall not be tested")

在上面给出的示例中, wherepytest.value设置为 2 之后,test_1将被跳过。这是我得到的输出:test_2test_3

...
test_skip_tests.py::test_1 PASSED                                        [ 33%]2

test_skip_tests.py::test_2 SKIPPED                                       [ 66%]
Skipped: Value 2 shall not be tested

test_skip_tests.py::test_3 SKIPPED                                       [100%]
Skipped: Value 2 shall not be tested
failed: 0


======================== 1 passed, 2 skipped in 0.06s =========================

推荐阅读