pytest is a popular testing framework for Python that simplifies the process of writing and running tests. It offers a range of features that make testing more efficient and enjoyable for developers.
To begin using pytest, you'll need to install it first. Open your terminal and run:
pip install pytest
Once installed, you can start writing tests. pytest uses a convention-over-configuration approach, making it easy to get started quickly.
Create a file named test_example.py
and add the following code:
def test_addition():
assert 1 + 1 == 2
def test_subtraction():
assert 3 - 1 == 2
These simple tests demonstrate how easy it is to write assertions in pytest. The assert
statement is used to check if a condition is true.
To run your tests, simply execute the following command in your terminal:
pytest
pytest will automatically discover and run all test files in the current directory and its subdirectories.
pytest follows these conventions for test discovery:
test_*.py
or *_test.py
test_
Test
Fixtures in pytest allow you to set up and tear down test environments. They provide a way to reuse code across multiple tests.
import pytest
@pytest.fixture
def sample_data():
return [1, 2, 3, 4, 5]
def test_sum(sample_data):
assert sum(sample_data) == 15
In this example, sample_data
is a fixture that provides test data to the test_sum
function.
pytest allows you to run the same test with different input values using parameterization:
import pytest
@pytest.mark.parametrize("input,expected", [(1, 2), (2, 4), (3, 6)])
def test_multiplication(input, expected):
assert input * 2 == expected
This test will run three times with different input and expected values.
assert
statements with meaningful error messagespytest integrates well with other Python testing tools and frameworks. It can be used alongside code optimization techniques and profiling to improve overall code quality.
pytest is a powerful and flexible testing framework that can significantly improve your testing workflow. By leveraging its features, you can write more maintainable and efficient tests, leading to higher quality Python code.
To further enhance your testing skills, consider exploring Python unit testing concepts and test-driven development methodologies.