0
0
PyTesttesting~15 mins

@pytest.mark.skipif with condition - Build an Automation Script

Choose your learning style9 modes available
Automate test skipping with @pytest.mark.skipif based on Python version
Preconditions (2)
Step 1: Create a test function decorated with @pytest.mark.skipif
Step 2: Set the skip condition to skip the test if Python version is less than 3.12
Step 3: Inside the test, assert that 1 + 1 equals 2
Step 4: Run the test using pytest
Step 5: Verify that the test is skipped if Python version is less than 3.12
Step 6: Verify that the test runs and passes if Python version is 3.12 or higher
✅ Expected Result: Test is skipped on Python versions below 3.12 and runs successfully on Python 3.12 or higher
Automation Requirements - pytest
Assertions Needed:
Assert 1 + 1 == 2 inside the test
Verify test is skipped or run based on Python version condition
Best Practices:
Use @pytest.mark.skipif with a clear and correct condition
Use sys.version_info for version checking
Keep test function simple and focused
Run tests with pytest CLI to see skip reports
Automated Solution
PyTest
import sys
import pytest

@pytest.mark.skipif(sys.version_info < (3, 12), reason="Requires Python 3.12 or higher")
def test_addition():
    assert 1 + 1 == 2

if __name__ == "__main__":
    import pytest
    pytest.main([__file__])

This script imports sys and pytest. The test function test_addition is decorated with @pytest.mark.skipif that checks if the Python version is less than 3.12. If true, pytest will skip this test and show the reason.

The test itself is simple: it asserts that 1 + 1 equals 2.

Running this script with pytest will skip the test on Python versions below 3.12 and run it on 3.12 or higher, showing a pass result.

Common Mistakes - 3 Pitfalls
Using a string instead of a boolean expression in skipif condition
Not providing a reason parameter in @pytest.mark.skipif
Checking Python version with sys.version instead of sys.version_info
Bonus Challenge

Now add multiple skip conditions to skip the test if Python version is less than 3.12 or if an environment variable 'SKIP_TEST' is set to 'true'

Show Hint