如何在"pytest.dependency"中使用测试数据/外部变量? [英] How can I use test-data/external variable in 'pytest.dependency'?

查看:152
本文介绍了如何在"pytest.dependency"中使用测试数据/外部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Below pytest code works fine, which increments 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

value=2

pytest.dependency()是否可能?如果是,如何在pytest.dependency中使用变量value?

Is it possible by pytest.dependency() ? If yes, how can i use variable value in pytest.dependency ?

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

If not pytest.dependency, Any alternative ?

或任何更好的处理此类情况的方法?

or any better way of handling such scenarios ?

    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)

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

Can you please guide me ? Can this be done ? Is this possible ?

推荐答案

如果您可以访问测试以外的值(例如您的示例),则可以基于值:

If you have access to the value outside of the test (as it is the case in your example), you can skip the tests in a fixture based on the value:

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

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

In the example given above, where pytest.value is set to 2 after test_1, test_2 and test_3 would be skipped. Here is the output I get:

...
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 =========================

这篇关于如何在"pytest.dependency"中使用测试数据/外部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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