In this article, we will explore how to execute test files in Pytest, along with various options and techniques to customize test runs.
What is Pytest?
Pytest is a Python-based testing framework designed for creating and running test codes. While it excels in API testing in the current landscape of REST services, Pytest is versatile enough to handle a wide range of tests, from basic to complex. This includes testing APIs, databases, user interfaces, and more.
Pytest Features
- Simple & Easy: Writing tests with Pytest is straightforward. It uses plain Python code, making it easy for developers to get started.
- Automatic Test Discovery: Pytest can automatically discover and run all the test files in your project. It looks for files named test_*.py or *_test.py and identifies functions named test_* as test cases.
- Availability of Plugins: Pytest has a huge set of plugins that can extend its functionality.
- Parameterized Testing: We can run the same test with different sets of inputs using parameterized testing, which helps in testing various scenarios with minimal code repetition. Also, it will be run on different system environments.
- Report Generating: It can generate coverage reports, showing which parts of your code have been tested and which haven't.
Install Pytest in Python
We can install Pytest by writing the following command in the command prompt:
pip install pytest
Creating Test Files
First, create a test file which will be tested named 'my_functions.py'.
- add_numbers(x, y): This function takes two arguments, x and y, and returns their sum.
- subtract_numbers(x, y): This function takes two arguments, x and y, and returns the result of subtracting y from x.
- multiply_numbers(x, y): This function takes two arguments, x and y, and returns their product.
- divide_numbers(x, y): This function takes two arguments, x and y, and performs division. It includes a check to raise a ValueError if y is zero (since division by zero is undefined in mathematics).
Python
def add_numbers(x, y):
return x + y
def subtract_numbers(x, y):
return x - y
def multiply_numbers(x, y):
return x * y
def divide_numbers(x, y):
if y == 0:
raise ValueError("Cannot divide by zero")
return x / y
Writing a Test Function
Create a another new file named 'test_my_functions.py'. Pytest automatically identifies files with this naming convention as containing tests.
In test_my_functions.py write a test function using the pytest syntax.
- test_addition(): This test function checks if the add_numbers function in my_functions.py is working correctly. It calls add_numbers(2, 3) and asserts that the result is 5, as expected.
- test_subtraction(): This test function checks if the subtract_numbers function in my_functions.py is working correctly. It calls subtract_numbers(5, 2) and asserts that the result is 3, as expected.
- test_multiplication(): This test function checks if the multiply_numbers function in my_functions.py is working correctly. It calls multiply_numbers(3, 4) and asserts that the result is 12, as expected.
- test_division(): This test function checks if the divide_numbers function in my_functions.py is working correctly. It calls divide_numbers(10, 2) and asserts that the result is 5, as expected. Additionally, it includes an additional test to handle division by zero by attempting to divide by zero and expecting a ValueError to be raised.
- test_addition_negative(): This test function checks if the add_numbers function handles negative numbers correctly. It calls add_numbers(-2, 3) and asserts that the result is 1, as expected.
Python
import my_functions
def test_addition():
result = my_functions.add_numbers(2, 3)
assert result == 5, f"Expected 5, but got {result}"
def test_subtraction():
result = my_functions.subtract_numbers(5, 2)
assert result == 3, f"Expected 3, but got {result}"
def test_multiplication():
result = my_functions.multiply_numbers(3, 4)
assert result == 12, f"Expected 12, but got {result}"
def test_division():
result = my_functions.divide_numbers(10, 2)
assert result == 5, f"Expected 5, but got {result}"
# Additional test for division by zero
try:
my_functions.divide_numbers(10, 0)
except ValueError as e:
assert str(e) == "Cannot divide by zero", f"Expected 'Cannot divide by zero', but got '{e}'"
def test_addition_negative():
result = my_functions.add_numbers(-2, 3)
assert result == 1, f"Expected 1, but got {result}"
Output
test_my_functions OutputHandling 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:
Python
def add_numbers(x, y):
return x + y
Create a file named test_my_functions.py with the following content:
Python
from my_functions import add_numbers
def test_addition():
result = add_numbers(2, 3)
# This assertion will fail
assert result == 6
Output:
Assertion Error OutputIn 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.
Similar Reads
Pytest Tutorial - Unit Testing in Python using Pytest Framework In the process of development of applications, testing plays a crucial role. It ensures the developers that the application is error-free and the application is running as per the expectation. It should be done to ensure a seamless experience for the user. In this article, we will learn about testin
5 min read
Getting Started with Pytest Python Pytest is a framework based on Python. It is mainly used to write API test cases. It helps you write better programs. In the present days of REST services, Pytest is mainly used for API testing even though we can use Pytest to write simple to complex test cases, i.e., we can write codes to te
5 min read
How to Use Pytest for Unit Testing Unit Testing is an important method when it comes to testing the code we have written. It is an important process, as with testing, we can make sure that our code is working right. In this article, we will see how to use Pytest for Unit Testing in Python. Pytest for Unit TestingStep 1: InstallationT
5 min read
Pytest Fixtures Pytest fixtures are a powerful feature that allows you to set up and tear down resources needed for your tests. They help in creating reusable and maintainable test code by providing a way to define and manage the setup and teardown logic. A Fixture is a piece of code that runs and returns output be
2 min read
Identifying Test files and Functions using Pytest The Python framework used for API testing is called Pytest. For executing and running the tests, it is crucial to identify the test files and functions. Pytest, by default, executes all the test files under a certain package which are of the format test_*.py or *_test.py, in case there is no test fi
2 min read
Conftest in pytest The testing framework in Python that is used to write various types of software tests, including unit tests, integration tests, etc is called Pytest. The Pytest gives the user the ability to use the common input in various Python files, this is possible using Conftest. The conftest.py is the Python
2 min read
Parameterizing Tests in Pytest A testing framework in Python that is used to write API test cases is called Pytest is distinct instances of input and output are possible for a function. In such a case, it is crucial to test the function for all the inputs and outputs. This can be done using the parametrize function in Pytest. Par
2 min read
Setting Up Pytest
Pytest Configuration and Execution
Testing Techniques with Pytest