Automate test skipping with @pytest.mark.skipif based on Python version
Preconditions (2)
✅ Expected Result: Test is skipped on Python versions below 3.12 and runs successfully on Python 3.12 or higher
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.
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'
@pytest.mark.skipif in a test?@pytest.mark.skipif is used to skip tests conditionally.@pytest.mark.skipif, not @pytest.skipif.sys.version_info tuple; comparison uses < (less than) and tuple format (3, 8).import sys
import pytest
@pytest.mark.skipif(sys.platform != 'win32', reason='Only runs on Windows')
def test_windows_feature():
assert Truesys.platform != 'win32' means skip if platform is not Windows.sys.platform == 'win32', so condition is False, test runs. On other OS, condition True, test skipped.import pytest
@pytest.mark.skipif(reason='No condition provided')
def test_example():
assert True@pytest.mark.skipif requires a condition argument to decide when to skip.reason is provided, no condition, so syntax is invalid.TEST_ENV is set to production. Which of the following is the correct way to write this using @pytest.mark.skipif?os.getenv('TEST_ENV') to safely get the variable; it returns None if not set.os.getenv('TEST_ENV') == 'production'.Pass the test and this pattern moves unknown