In this tutorial, we will learn how to skip specific tests in PyTest. Sometimes, you might want a test to run only under certain conditions. If those conditions are not met, skipping the test ensures it doesn’t run unnecessarily, saving time and resources.
A skip indicates that a test should only proceed if specific conditions are satisfied; otherwise, pytest should bypass running the test entirely. Common examples are skipping windows-only tests on non-windows platforms, or skipping tests that depend on an external resource which is not available at the moment (for example a database).
When you use the pytest.skip() function within a test or setup function, pytest will skip that particular test or the entire test function.
An xfail means that you expect a test to fail for some reason. A common example is a test for a feature not yet implemented, or a bug not yet fixed. When a test passes despite being expected to fail (marked with pytest.mark.xfail), it’s an xpass and will be reported in the test summary.
pytest counts and lists skip and xfail tests separately.
import pytest
@pytest.mark.skip(reason="In Progress")
def test_addition():
a = 6
b = 5
c = 11
assert a + b == 11, "Sum is not 11"
assert a + b == c, "Sum of a and b is not equal to c"
@pytest.mark.skipif(15-4>10, reason="Conditional")
def test_subtraction():
x = 15
y = 4
z = 10
assert x - y == z, "Subtract y from x is equal to z"
@pytest.mark.xfail
def test_multiplication():
a = 6
b = 5
c = 30
assert a * b == c, "Product of 5 and 6 is not 30"
def test_division():
a = 16
b = 2
c = 8
assert a / b == c, "Division of 2 by 6 is not 3"
To run these tests, use the below command:
pytest test_skip_demo.py
The output of the above program is
As we can see in the above example, there are total of 4 tests. 1 test is marked as skip, another test is marked as skipif (the condition of skipif is satisfied, so this test also skips), 3rd tests is marked as xfail and remaining 1 test is passed. Here, I have generated a report also to see the output in the report.html. In this report, Unexpected passes represent the xfail.
Skip all test functions of a class or module
You can also skip all tests in a module or class using the pytest.mark.skip decorator.
import pytest
@pytest.mark.skip("Development in progress")
class test_skip_class:
def test_addition(self):
a = 10.44
b = 5.56
c = 16.00
assert a + b == 16.00, "Sum is not 16"
def test_subtraction(self):
x = 15
y = 4
z = 10
assert x - y == z, "Subtract y from x is equal to z"
The output of the above program is
That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!