Python · Тестирование с pytest · Экспертный
Архитектура большого тест-сьюта
Организуйте большие тест-сьюты для скорости, изоляции и удобства поддержки.
Краткое введение в тему и пояснения перед упражнениями (упражнения ниже):
Архитектура тестов в среднем Django-проекте
#Справочная карточка архитектуры тестов
#Упражнения:
Реорганизовать плоский каталог тестов в unit/ и integration/
## Перечислите новые пути файлов (по одному на строку): # tests/conftest.py # ... # Содержимое pytest.ini: # [pytest] # testpaths = ... # Команда для запуска только интеграционных тестов: # pytest ...
Решение
# Новые пути файлов после реорганизации:
# tests/conftest.py
# tests/unit/conftest.py
# tests/unit/test_models.py
# tests/unit/test_services.py
# tests/integration/conftest.py
# tests/integration/test_api.py
# tests/integration/test_db_queries.py
# pytest.ini (создайте этот файл в корне проекта):
# [pytest]
# testpaths = tests
# Команда для запуска только интеграционных тестов:
# pytest tests/integration/
Зарегистрировать метки и применить их к тестам
## pytest.ini
[pytest]
testpaths = tests
# добавить addopts и markers здесь
# tests/unit/test_pricing.py
import pytest
# добавить pytestmark здесь
def test_discount_applied():
assert apply_discount(100, 0.1) == 90
def test_negative_discount_raises():
with pytest.raises(ValueError):
apply_discount(100, -0.1)
# tests/integration/test_orders.py
import pytest
# добавить pytestmark здесь
def test_order_saved_to_db(db):
order = Order.objects.create(total=100)
assert Order.objects.count() == 1
def test_large_order_sends_email(db, mailoutbox):
Order.objects.create(total=10000)
assert len(mailoutbox) == 1
Решение
# pytest.ini
[pytest]
testpaths = tests
addopts = --strict-markers
markers =
unit: быстрые тесты без I/O
integration: тесты использующие базу данных или сеть
slow: тесты выполняющиеся более 1 секунды
# tests/unit/test_pricing.py
import pytest
pytestmark = [pytest.mark.unit]
def test_discount_applied():
assert apply_discount(100, 0.1) == 90
def test_negative_discount_raises():
with pytest.raises(ValueError):
apply_discount(100, -0.1)
# tests/integration/test_orders.py
import pytest
pytestmark = [pytest.mark.integration]
def test_order_saved_to_db(db):
order = Order.objects.create(total=100)
assert Order.objects.count() == 1
@pytest.mark.slow
def test_large_order_sends_email(db, mailoutbox):
Order.objects.create(total=10000)
assert len(mailoutbox) == 1
Построить иерархию conftest.py с фикстурами разной области
## tests/conftest.py import pytest # фикстура app_config с областью session здесь # tests/unit/conftest.py import pytest # фикстура calculator с областью function здесь # tests/integration/conftest.py import pytest # фикстура db_session с областью function здесь # tests/unit/test_calc.py # использовать app_config и calculator # tests/integration/test_db.py # использовать app_config и db_session
Решение
# tests/conftest.py
import pytest
@pytest.fixture(scope='session')
def app_config():
return {"env": "test", "debug": False}
# tests/unit/conftest.py
import pytest
class Calculator:
def add(self, a, b):
return a + b
@pytest.fixture
def calculator():
return Calculator()
# tests/integration/conftest.py
import pytest
@pytest.fixture
def db_session():
print("opening db")
yield "db_connection"
print("closing db")
# tests/unit/test_calc.py
def test_add(app_config, calculator):
assert app_config["env"] == "test"
assert calculator.add(2, 3) == 5
# tests/integration/test_db.py
def test_connect(app_config, db_session):
assert app_config["env"] == "test"
assert db_session == "db_connection"
Написать Makefile с целями для тестирования
## Makefile .PHONY: ... test-unit: ... test-integration: ... test-fast: ... test-ci: ...
Решение
# Makefile
.PHONY: test-unit test-integration test-fast test-ci
test-unit:
pytest tests/unit/ -q
test-integration:
pytest tests/integration/ -q
test-fast:
pytest tests/unit/ tests/integration/ -m "not slow" -q
test-ci:
pytest --cov=src --cov-report=term-missing --cov-fail-under=80 -q
Найти и исправить зависимость от порядка тестов
## Часть 1 -- Какой тест падает первым в обратном порядке и почему?
# (напишите ответ в комментарии)
#
# Первым падает тест: ...
# Причина: ...
# Часть 2 -- Исправленный test_cart.py
import pytest
# определить фикстуру cart здесь
def test_add_item_to_cart(cart):
pass # реализовать
def test_cart_total(cart):
pass # реализовать
def test_remove_item_from_cart(cart):
pass # реализовать
def test_empty_cart_total(cart):
pass # реализовать
Решение
# Часть 1 -- Какой тест падает первым в обратном порядке?
#
# Первым падает тест: test_cart_total
# Причина: В обратном порядке выполнение:
# test_empty_cart_total -> test_remove_item_from_cart -> test_cart_total -> test_add_item_to_cart
# test_empty_cart_total запускается первым; _cart уже пуст, total == 0 -- случайно ПРОХОДИТ.
# test_remove_item_from_cart очищает уже пустой список -- ПРОХОДИТ.
# test_cart_total запускается следующим; _cart всё ещё пуст, total == 0, а не 20 -- ПАДАЕТ.
#
# Корневая причина: _cart -- список на уровне модуля, общий для всех тестов.
# Тесты неявно коммуницируют через него, поэтому результаты зависят от порядка запуска.
# Часть 2 -- Исправленный test_cart.py
import pytest
@pytest.fixture
def cart():
return []
def test_add_item_to_cart(cart):
cart.append({"id": 1, "name": "Widget", "qty": 2})
assert len(cart) == 1
def test_cart_total(cart):
cart.append({"id": 1, "name": "Widget", "qty": 2})
total = sum(item["qty"] * 10 for item in cart)
assert total == 20
def test_remove_item_from_cart(cart):
cart.append({"id": 1, "name": "Widget", "qty": 2})
cart.clear()
assert len(cart) == 0
def test_empty_cart_total(cart):
total = sum(item["qty"] * 10 for item in cart)
assert total == 0