首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在‘pytest.Dependation’中使用test-data/外部变量?

如何在‘pytest.Dependation’中使用test-data/外部变量?
EN

Stack Overflow用户
提问于 2020-07-14 19:17:00
回答 1查看 121关注 0票数 0

下面的pytest代码工作得很好,这增加了value

代码语言:javascript
复制
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)

输出:

代码语言:javascript
复制
Prints
2
3
4

我不想执行test_2,当value=2

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

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

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

代码语言:javascript
复制
    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)

你能指引我吗?这能办到吗?这有可能吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-16 07:35:24

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

代码语言:javascript
复制
@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。这是我得到的输出:

代码语言:javascript
复制
...
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 =========================
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62902460

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档