Junior — Middle
How can tests be organized and structured when using pytest?
sobes.tech AI
Answer from AI
In pytest, tests are organized as functions, which can be grouped by files and directories. To structure tests, the following are commonly used:
- Files with the prefix
test_or suffix_test.py— pytest automatically finds such files. - Functions starting with
test_— pytest considers them as tests. - Classes starting with
Test, containing test methods (whose names start withtest_). Classes should not have an__init__constructor. - Use of fixtures (
@pytest.fixture) for preparing and cleaning test data, which helps avoid code duplication. - Grouping tests by directories with or without an
__init__.pyfile.
Example of a simple structure:
tests/
test_math.py
test_utils.py
# test_math.py
import pytest
def test_add():
assert 1 + 1 == 2
class TestMultiply:
def test_multiply(self):
assert 2 * 3 == 6
@pytest.fixture
def sample_data():
return [1, 2, 3]
def test_sum(sample_data):
assert sum(sample_data) == 6
This approach makes it easy to scale tests and keep them organized.