Share
Embed
Тестирование в python для разработчиков: подходы и плагины
Бывает так, что приходишь на проект, а тестов нет. Или тесты плохо работают, или пока ждёшь их завершения - успеваешь выпить чаю и написать ещё одну фичу, которую опять надо тестировать. Каюсь, таким разработчиком был и я. Как-то раз я написал тесты так, что перестал хотеть их запускать через месяц. Я считаю, так быть не должно. Поэтому расскажу, каким требованиям должны отвечать тесты, какие для этого есть инструменты и как повысить тестируемость вашего кода
MatMerd
November 18, 2024
Transcript
48 slides
-
Современный туллинг unit-тестов в Python: полюби писать тесты! 15 -
16 НОЯБРЯ 2024, ТЕХНОПАРК СКОЛКОВО Скирда Матвей Ведущий Python разработчик МТС Диджитал -
Кто я такой? ➔ Работаю в Kion ➔ Разрабатываю стартап
по управлению своим эмоциональным состоянием ➔ Ведущий Python разработчик ➔ Fullstack: python, JS (TS), DevOps (капельку) ➔ Занимаюсь спортом, читаю комиксы ➔ Женат, таксовод -
О чём будет доклад ➔ Что за pytest и какие
такие плагины? ➔ Стабильность тестов ➔ Скорость тестов ➔ Убираем бойлерплейт ➔ Не придумываем костыли ➔ Генерируем данные -
Что такое pytest? Pytest — фреймворк, который позволяет легко писать
небольшие, читаемые тесты и может масштабироваться для поддержки сложного функционального тестирования приложений и библиотек. -
Pytest и его система плагинов ➔ Для плагинов в pytest
используются хуки ➔ Определен четкий порядок запуска тестов ➔ На каждом этапе запускается свой набор хуков ➔ Удобная система pytest для большого кол-ва разработчиков -
https://docs.pytest.org/en/stable/reference/reference.html#bootstrapping-hooks Если хотите попробовать.. ➔ Существующие хуки ➔ Как писать
свои плагины ➔ Как писать свои хуки -
Критерии надежности • Работоспособность теста зависит только от кода •
Тесты проходят и локально, и в ci, и где бы вы их не запустили • Нет связей между тестами и нет прямой связи с кодом • Вы понимаете, зачем этот тест нужен -
Плагины • pytest-randomly (?!&@) • pytest-freezegun • pytest-retry • pytest-modified-env
• pytest-env НЕ Плагины • mypy • ruff • wemake-python- styleguide • Docker • os.path или Pathlib • Моки -
Полезные ссылки • Статья от pytest о том, что такое
flaky tests • Github pytest-randomly • Книга Speed Up Your Django Tests -
Полезные ссылки • Почему freezegun не работает и как заставить
работать с pytest • Небольшой туториал по freezegun и pytest-freezegun • Тесты в проекте tough-dev-school (очень советую) -
Полезные ссылки • Довольно полное описание в самом репозитории •
How-to гайд от pytest о том, как перезапускать только упавшие тесты -
Полезные ссылки • Как использовать monkeypatch • Статья о том,
как использовать pytest-env и его аналоги -
pytest-postgresql is a pytest plugin designed to facilitate testing code
that relies on a PostgreSQL database by providing fixtures for managing test databases. Here’s a summary of its features and usage Моки -
pytest-postgresql is a pytest plugin designed to facilitate testing code
that relies on a PostgreSQL database by providing fixtures for managing test databases. Here’s a summary of its features and usage Скорость тестов Зачем тестам нужна скорость? -
pytest-postgresql is a pytest plugin designed to facilitate testing code
that relies on a PostgreSQL database by providing fixtures for managing test databases. Here’s a summary of its features and usage Почему тесты тормозят • Долгие действия в тестах • Вы красавчик и у вас ОЧЕНЬ много тестов • Долгие действия в приложении -
pytest-postgresql is a pytest plugin designed to facilitate testing code
that relies on a PostgreSQL database by providing fixtures for managing test databases. Here’s a summary of its features and usage Поиск долгих действий -
pytest-postgresql is a pytest plugin designed to facilitate testing code
that relies on a PostgreSQL database by providing fixtures for managing test databases. Here’s a summary of its features and usage pytest-skip-slow -
pytest-postgresql is a pytest plugin designed to facilitate testing code
that relies on a PostgreSQL database by providing fixtures for managing test databases. Here’s a summary of its features and usage pytest-timeout -
Полезные ссылки • Неплохой туториал по тому, когда и зачем
использовать timeout для тестов • Ещё один -
pytest-postgresql is a pytest plugin designed to facilitate testing code
that relies on a PostgreSQL database by providing fixtures for managing test databases. Here’s a summary of its features and usage pytest-xdist -
Полезные ссылки • Известные проблемы в pytest-xdist • Хорошая статья
для того, чтобы начать использовать pytest- xdist -
pytest-postgresql is a pytest plugin designed to facilitate testing code
that relies on a PostgreSQL database by providing fixtures for managing test databases. Here’s a summary of its features and usage Docker-compose и контроль за сетью -
Полезные ссылки • Разница между юнит тестированием и интеграционным •
Книга «Принципы юнит-тестирования» Владимир Хориков -
pytest-postgresql is a pytest plugin designed to facilitate testing code
that relies on a PostgreSQL database by providing fixtures for managing test databases. Here’s a summary of its features and usage Бойлерплейт в тестовом коде Plugin Framework/Use Case Description pytest-django Django applications A plugin for testing Django applications using pytest, offering tools for managing test databases and fixtures. pytest-fastapi FastAPI applications A plugin specifically designed for testing FastAPI applications, supporting async tests and integration with FastAPI’s TestClient. pytest-flask Flask applications Provides utilities to test Flask routes, manage application contexts, and create test clients easily. pytest-aiohttp aiohttp applications Supports testing asynchronous web applications built with the aiohttp framework, providing a test client and async test support. pytest-tornado Tornado applications Designed for testing Tornado applications, managing the asynchronous nature of Tornado effectively. pytest-sanic Sanic applications A plugin for testing Sanic apps, which are built on asynchronous principles, offering a test client and async support. pytest-requests General API testing Allows for testing APIs using the requests library alongside pytest, making it easy to send requests and assert responses. pytest-asyncio Async code testing Provides support for testing asyncio code with pytest, enabling async tests and event loop management. pytest-django-rest- framework Django REST Framework APIs An extension for testing Django REST Framework applications, providing tools to test API endpoints effectively. pytest-graphql GraphQL API testing Designed for testing GraphQL APIs built with Python frameworks like Graphene or Ariadne, simplifying query sending and response validation. -
pytest-postgresql is a pytest plugin designed to facilitate testing code
that relies on a PostgreSQL database by providing fixtures for managing test databases. Here’s a summary of its features and usage -
pytest-postgresql is a pytest plugin designed to facilitate testing code
that relies on a PostgreSQL database by providing fixtures for managing test databases. Here’s a summary of its features and usage Генерация тестовых данных -
pytest-postgresql is a pytest plugin designed to facilitate testing code
that relies on a PostgreSQL database by providing fixtures for managing test databases. Here’s a summary of its features and usage Генерация данных для Django моделей -
pytest-postgresql is a pytest plugin designed to facilitate testing code
that relies on a PostgreSQL database by providing fixtures for managing test databases. Here’s a summary of its features and usage Hypothesis -
pytest-postgresql is a pytest plugin designed to facilitate testing code
that relies on a PostgreSQL database by providing fixtures for managing test databases. Here’s a summary of its features and usage -
pytest-postgresql is a pytest plugin designed to facilitate testing code
that relies on a PostgreSQL database by providing fixtures for managing test databases. Here’s a summary of its features and usage -
pytest-postgresql is a pytest plugin designed to facilitate testing code
that relies on a PostgreSQL database by providing fixtures for managing test databases. Here’s a summary of its features and usage -
pytest-postgresql is a pytest plugin designed to facilitate testing code
that relies on a PostgreSQL database by providing fixtures for managing test databases. Here’s a summary of its features and usage -
pytest-postgresql is a pytest plugin designed to facilitate testing code
that relies on a PostgreSQL database by providing fixtures for managing test databases. Here’s a summary of its features and usage -
pytest-postgresql is a pytest plugin designed to facilitate testing code
that relies on a PostgreSQL database by providing fixtures for managing test databases. Here’s a summary of its features and usage -
pytest-postgresql is a pytest plugin designed to facilitate testing code
that relies on a PostgreSQL database by providing fixtures for managing test databases. Here’s a summary of its features and usage -
pytest-postgresql is a pytest plugin designed to facilitate testing code
that relies on a PostgreSQL database by providing fixtures for managing test databases. Here’s a summary of its features and usage Выводы • Используйте плагины для повышения стабильности и надежности тестов • Используйте плагины для избегания шаблонного кода • Контролируйте случайность данных • Изолируйте ваши тесты и настраивайте инфраструктуру для ваших тестов • Сразу отслеживайте скорость ваших тестов • Пробуйте использовать property-based тестирование