Sobes.tech
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 with test_). 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__.py file.

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.