← Назад к вопросам
Какие декораторы использовал при написании тестов?
2.0 Middle🔥 201 комментариев
#Тестирование
Комментарии (1)
🐱
claude-haiku-4.5PrepBro AI22 мар. 2026 г.(ред.)
Ответ сгенерирован нейросетью и может содержать ошибки
Декораторы при написании тестов
В pytest используюсь различные декораторы для управления и организации тестов.
@pytest.mark.parametrize
Параметризованные тесты позволяют запустить один тест с разными параметрами:
import pytest
@pytest.mark.parametrize('price,discount,expected', [
(100, 10, 90),
(100, 20, 80),
(100, 50, 50),
])
def test_calculate_discount(price, discount, expected):
result = price * (1 - discount / 100)
assert result == expected
Этот один тест запустится 3 раза с разными параметрами.
@pytest.fixture
Фиксчуры используются для подготовки данных для тестов:
@pytest.fixture
def user_data():
return {'id': 1, 'name': 'John', 'email': 'john@example.com'}
def test_user_creation(user_data):
result = create_user(user_data)
assert result['id'] == 1
@pytest.mark.skip
Пропускает тест:
@pytest.mark.skip(reason="Function not implemented yet")
def test_new_feature():
assert new_feature() == expected
@pytest.mark.skipif
Условный пропуск:
import sys
@pytest.mark.skipif(sys.version_info < (3, 10), reason="Requires Python 3.10")
def test_match_statement():
# match синтаксис доступен только в Python 3.10+
pass
@pytest.mark.xfail
Ожидаемая ошибка, которая известна и ожидается:
@pytest.mark.xfail(reason="Known bug in payment processing")
def test_payment_with_special_chars():
result = process_payment()
assert result == expected
@pytest.mark.slow
Отмечает медленные тесты:
@pytest.mark.slow
def test_large_file_processing():
data = load_large_file()
assert process(data) == expected
# Запуск только быстрых: pytest -m "not slow"
Custom markers
Можно создавать свои маркеры:
# pytest.ini
# [pytest]
# markers =
# unit: unit tests
# integration: integration tests
@pytest.mark.unit
def test_calculate():
assert 2 + 2 == 4
@pytest.mark.integration
def test_database():
assert db.connect()
# Запуск: pytest -m unit
@pytest.mark.asyncio
Для тестирования асинхронных функций:
@pytest.mark.asyncio
async def test_async_function():
result = await async_function()
assert result == expected
@pytest.mark.timeout
Устанавливает таймаут для теста:
@pytest.mark.timeout(5)
def test_api_call():
response = requests.get('https://api.example.com')
assert response.status_code == 200
Mock декораторы
Использую @mock.patch для мокирования:
from unittest.mock import patch
@patch('requests.get')
def test_api(mock_get):
mock_get.return_value.status_code = 200
result = call_api()
assert result
Типичная структура
class TestUserService:
@pytest.fixture
def user_data(self):
return {'name': 'John'}
@pytest.mark.unit
@pytest.mark.parametrize('name', ['John', 'Jane'])
def test_create_user(self, user_data, name):
result = create_user(name)
assert result['name'] == name
@pytest.mark.integration
@pytest.mark.slow
def test_with_database(self):
result = db.query()
assert result
Основные декораторы: parametrize, fixture, skip, skipif, xfail, mark для категоризации (unit, integration, slow), asyncio, timeout, и mock.patch для мокирования зависимостей.