How can I use test-data/external variable in 'pytest.dependency'?

有些话、适合烂在心里 提交于 2020-08-10 19:10:08

问题


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)

Output:

Prints
2
3
4

I don't want to execute test_2, when value=2

Is it possible by pytest.dependency() ? If yes, how can i use variable value in 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 ?


回答1:


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")

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


来源:https://stackoverflow.com/questions/62902460/how-can-i-use-test-data-external-variable-in-pytest-dependency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!