Organizing and Running Tests with pytest
Svep för att visa menyn
When you want to write clean, expressive, and easily maintainable test code in Python, pytest is a popular choice. Unlike the built-in unittest framework, which follows a rigid, class-based structure requiring specific assertion methods like self.assertEqual, pytest allows you to use standard Python assert statements within simple functions. This drastically reduces boilerplate code and makes your tests more concise, as you no longer need to wrap logic in complex class hierarchies or memorize dozens of framework-specific assertion names just to verify a simple result.
One of the most powerful features of pytest is its test discovery system. Simply by running pytest in your project directory, it will automatically find all files that match the test_*.py or *_test.py pattern and execute all functions inside those files that start with test_. This means you do not have to manually specify which tests to run - pytest handles it for you.
Another key advantage is the use of fixtures. Fixtures handle the work of preparing and cleaning up resources your tests need, like temporary files or database links, in a way that is easy to reuse. You simply decorate a function with @pytest.fixture and then request it as an input in your test functions. This keeps your code modular and stops you from repeating the same setup logic.
To get started with pytest, you first need to install it. Use the following command in your terminal:
pip install pytest
This will download and install the latest version of pytest so you can begin writing and running your tests right away.
Here is a practical demonstration of how to use it for writing function-based tests and defining reusable fixtures.
import pytest
# A simple function to test
def add(a, b):
return a + b
# Define a fixture that provides test data
@pytest.fixture
def sample_numbers():
return (3, 5)
# Test function using the fixture
def test_add_with_fixture(sample_numbers):
a, b = sample_numbers
result = add(a, b)
assert result == 8
# Another simple test function
def test_add_negative_numbers():
assert add(-2, -4) == -6
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal