Open In App

An Ultimate Guide To Using Pytest Skip Test And XFail

Last Updated : 04 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The Python framework used for writing and executing test cases is known as Pytest. There are some circumstances when you want to skip tests or run the tests, but not count them during PyTest run, then you can use skip and Xfail tests respectively. In this article, we will discuss how we can use Xfail and skip tests in Pytest.

XFail/ skip tests in Pytest

The syntax for Xfail Tests in Pytest

@pytest.mark.xfail


Syntax for Skip Tests in Pytest

@pytest.mark.skip


Example 1: In this example, we have created a program that has four test cases, checking floor, equality, subtraction, and square root. Here, we have used the skip test on the first test case, and xfail test on the third test case.

Python3




# Importing the math and pytest libraries
import math
import pytest
 
# Creating first test case
@pytest.mark.skip
def test_floor():
   num = 7
   assert num==math.floor(6.34532)
 
# Creating second test case
def test_equal():
   assert 50 == 49
 
# Creating third test case
@pytest.mark.xfail
def test_difference():
   assert 99-43==57
 
# Creating fourth test case
def test_square_root():
   val=8
   assert val==math.sqrt(81)


Run the Program

Now, we will run the following command in terminal.

pytest main.py

Output

Example 2: In this another example, we have defined a string, then we have created 3 unit test cases on it, for removing substrings G, e and o. Here, we have used xfail test on first test case, and skip test on third test case.

Python3




# Import pytest library
import pytest
 
# Define a string
string_match="Geeks For Geeks"
 
# Creating first test case
@pytest.mark.xfail
def test_remove_G():
    assert string_match.replace('G','')=="eeks For eeks"
 
# Creating second test case
def test_remove_e():
    assert string_match.replace('e','')=="Gaks For Gaks"
 
# Creating third test case
@pytest.mark.skip
def test_remove_o():
    assert string_match.replace('o','')=="Geeks For Geeks"


Run the Program

Now, we will run the following command in terminal.

pytest main.py

Output



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads