Files
blog.pyaqa.ru/tests/AGENTS.md
Sergey Vanyushkin 714342f5ac docs: добавлены workflow для bugfix и refactoring
- blog/AGENTS.md: добавлены Bugfix Lifecycle и Refactoring Lifecycle
- tests/AGENTS.md: добавлены Bugfix Test Workflow и Refactor Test Workflow
- Добавлены правила для regression tests
- Добавлены anti-patterns для багфикса и рефакторинга
- Обновлены commit rules для всех типов задач
2026-05-07 22:31:23 +03:00

164 lines
7.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Tests Knowledge Base
**Generated:** 2026-05-03 22:15 UTC
**Commit:** 41f2a3d
**Branch:** feature/tests
## Overview
Unit test suite mirroring DDD layers. 100% unit coverage; integration, API, and E2E test directories are documented but not yet populated.
## Structure
```
tests/
├── conftest.py # Session fixtures (event_loop_policy, playwright)
└── unit/
├── conftest.py # Shared mocks (repository, transaction_manager)
├── test_main.py # App factory, lifespan, CLI entry
├── domain/ # Entity, VO, exception, role tests
├── application/ # Use case tests
└── infrastructure/ # Config, auth, transaction manager tests
```
## Test Model
The project maintains a **feature-based test model** in Markdown files next to the test code.
Agents MUST consult these files before adding or modifying tests.
| Model File | Scope |
|------------|-------|
| [`TEST_MODEL.md`](TEST_MODEL.md) | Global coverage matrix, risk areas, TC-ID conventions |
| [`FEATURE_POST_LIFECYCLE.md`](FEATURE_POST_LIFECYCLE.md) | CRUD, publish, visibility |
| [`FEATURE_RBAC.md`](FEATURE_RBAC.md) | Roles, permissions, access policies |
| [`FEATURE_DOMAIN_FOUNDATION.md`](FEATURE_DOMAIN_FOUNDATION.md) | Entities, value objects, exceptions |
| [`FEATURE_INFRASTRUCTURE.md`](FEATURE_INFRASTRUCTURE.md) | Config, auth client, bootstrap, tx manager |
### Adding a New Test
1. Pick the relevant feature model file.
2. Assign the next available `TC-UNIT-NNN` or `TC-E2E-NNN` ID.
3. Append a test-case entry with **Type**, **Layer**, **File**, **Steps**, **Expected**, and **Last Verified**.
4. If the test closes a gap, update the `Gaps` section and the coverage matrix in `TEST_MODEL.md`.
## Where to Look
| Task | Location |
|------|----------|
| Check coverage before adding tests | `tests/TEST_MODEL.md` |
| Add a domain test | `tests/unit/domain/` |
| Add a use case test | `tests/unit/application/` |
| Add an infra test | `tests/unit/infrastructure/` |
| Add an E2E test | `tests/e2e/` + update relevant `FEATURE_*.md` |
| Shared mock fixtures | `tests/unit/conftest.py` |
## Conventions
- **Class-per-entity/use-case**: `TestPost`, `TestCreatePostUseCase`, etc.
- **asyncio_mode=auto**: `@pytest.mark.asyncio` is redundant but harmless
- **Return types**: All test functions must have `-> None`
- **Coverage gate**: 70% minimum enforced in CI
- **Mock pattern**: `Mock(spec=Interface)` or `MagicMock(spec=Interface)` — project uses both inconsistently
- **Async mocking**: Use `AsyncMock()` for async methods (commit, rollback, repo methods)
## TDD Test Case Workflow
### Adding a Feature Test
1. **User triggers**: `"начем новую фичу"`
2. **Agent analyzes**: существующий код, затронутые слои, рекомендует тесткейсы
3. **User agrees**: подтверждает или корректирует набор тесткейсов
4. **Agent creates**:
- `pyaqa/feature/{feature-name}.md` — артефакт фичи
- Обновляет `FEATURE_*.md` — добавляет новые TC
5. **Agent writes tests**: в порядке TC-UNIT → TC-API → TC-WEB → TC-E2E
6. **Agent marks**: в артефакте статус "tests-ready"
7. **Agent implements**: фичу по слоям (Domain → Application → Infra → Presentation)
8. **Agent verifies**: линтеры, тесты, coverage
9. **User accepts**: подтверждает приемку
10. **Agent commits**: во все затронутые проекты
### Bugfix Test Workflow
1. **User triggers**: `"исправить баг"`
2. **Agent analyzes**: воспроизводит баг, определяет root cause
3. **Agent creates**: `pyaqa/bugfix/{bug-name}.md` — артефакт бага
4. **Agent writes regression test**:
- Unit тест, воспроизводящий баг (должен падать)
- Дополнительные тесты на уровне бага (API/Web/E2E)
5. **Agent fixes**: минимальный фикс
6. **Agent verifies**: все тесты проходят, coverage не упал
7. **User accepts**: проверяет исправление
8. **Agent commits**: во все затронутые проекты
### Refactor Test Workflow
1. **User triggers**: `"отрефакторить"`
2. **Agent analyzes**: scope рефакторинга, затронутые файлы
3. **Agent creates**: `pyaqa/refactor/{name}.md` (опционально)
4. **Pre-check**: фиксирует baseline (все тесты проходят, coverage)
5. **Agent refactors**: пошаговые изменения
6. **Post-check**: все тесты проходят, coverage не ниже baseline
7. **Agent verifies**: линтеры, нет новых warnings
8. **User accepts**: опционально проверяет поведение
9. **Agent commits**: во все затронутые проекты
### Test Case Assignment Rules
- **TC-UNIT-NNN**: unit тесты (domain, use cases)
- **TC-API-NNN**: API endpoint тесты
- **TC-WEB-NNN**: Web route тесты (HTML responses, redirects)
- **TC-E2E-NNN**: End-to-end тесты (Playwright)
Нумерация внутри каждого уровня последовательная. Пропуски допустимы только при удалении устаревших тестов.
### Test Case Format
```markdown
### TC-UNIT-NNN: Test Name
- **Type:** Positive | Negative | Policy | Regression
- **Layer:** Unit | API | Web | E2E
- **File:** `path/to/test.py::TestClass::test_method`
- **Expected:** Что ожидается
- **Last Verified:** YYYY-MM-DD
```
### Red → Green → Refactor
- **RED**: Написать тест, убедиться что он падает
- **GREEN**: Написать минимальную реализацию, тест проходит
- **REFACTOR**: Улучшить код, тесты остаются зелеными
### Test Coverage Requirements
| Layer | Minimum Coverage | Notes |
|-------|-----------------|-------|
| Unit | 80% | Domain + Application |
| API | 70% | Endpoints + deps |
| Web | 60% | Routes + handlers |
| E2E | Cover all AC | Все acceptance criteria |
### Regression Test Rules
- **Bugfix**: ДОЛЖЕН включать regression test (unit минимум)
- **Refactor**: ВСЕ существующие тесты должны проходить ДО и ПОСЛЕ
- **Coverage**: Не должен упасть после багфикса или рефакторинга
## Anti-Patterns
- Do NOT add `@pytest.mark.asyncio` to `async def` tests (auto mode handles it)
- Do NOT use bare `Mock()` without `spec=` for interface mocks
- Do NOT delete tests to "fix" coverage — this is grounds for rollback
- Do NOT put fixtures in `__init__.py` — use `conftest.py`
- Do NOT write implementation before tests (no TDD bypass)
- Do NOT skip RED phase (tests must fail before implementation)
- Do NOT commit багфикс без regression test
- Do NOT commit рефакторинг с упавшим coverage
## Notes
- `mimesis` is installed but unused in any test
- E2E tests are excluded from default runs (`pyproject.toml` excludes `tests/e2e`)
- Pytest always runs with coverage (`--cov=app` in `addopts`)
- HTML coverage report generated at `htmlcov/index.html`