Handling Test Failure Example
When a test fails in Pytest, it means that the expected outcome did not match the actual outcome. Pytest provides clear feedback to identify the cause of the failure. Understanding these techniques will help you efficiently manage and execute your test suites, ensuring the reliability and quality of your Python applications.
Let’s understand, What If a test fails:
- Pytest will display an error message indicating which test failed, along with any relevant information about the failure.
- It will show the exact location in your code where the assertion failed, helping you pinpoint the issue.
- Pytest will also display the values that were expected and the actual values that were obtained.
Example
Create a file named my_functions.py with the following content:
Python3
def add_numbers(x, y): return x + y |
Create a file named test_my_functions.py with the following content:
Python3
from my_functions import add_numbers def test_addition(): result = add_numbers( 2 , 3 ) # This assertion will fail assert result = = 6 |
Output:
In this example, pytest clearly indicates that the test_addition function failed, and it shows that the assertion assert result == 6 was not met because 5 != 6. This feedback helps you quickly identify what went wrong and where.
File Execution in Pytest
In this article, we will explore how to execute test files in Pytest, along with various options and techniques to customize test runs.