【问题标题】:How can I use test-data/external variable in 'pytest.dependency'?如何在“pytest.dependency”中使用测试数据/外部变量?
【发布时间】:2020-07-14 19:17:00
【问题描述】:

下面的 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() 可以吗?如果是,我如何在pytest.dependency 中使用变量value

如果不是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)

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

【问题讨论】:

  • 这可以实现吗?有人可以在这里指导吗?
  • 我没用过pytest.dependency,但是从我在文档中看到的,没有这样的选项——至少我找不到。你真正想要实现的是什么?
  • @MrBean:感谢您的回复。场景是每当'value' = 2时跳过所有测试用例。此“值”会根据测试操作不断动态变化。
  • @MrBeanBremen :能想到什么吗?
  • 这能回答你的问题吗? Pytest skip test with certain parameter value

标签: python-3.x pytest fixtures


【解决方案1】:

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

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

在上面给出的示例中,pytest.valuetest_1 之后设置为 2,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 =========================

【讨论】:

  • 'value' 不是静态的。它是动态的。如果您查看上面发布的 sn-p,最初,当“值”为 1 时,它会执行测试用例并根据某些条件更改“值”。当“值”变为 2 时,应跳过所有测试用例。
猜你喜欢
  • 1970-01-01
  • 2023-01-19
  • 1970-01-01
  • 2017-05-26
  • 1970-01-01
  • 1970-01-01
  • 2014-02-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多