Search code examples
python-3.xpytestfixtures

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


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 ?


Solution

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