File size: 10,756 Bytes
cc036ff | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 | # Test Infrastructure Standards
**Purpose**: Comprehensive guide for test infrastructure standards and patterns in Atom.
**Last Updated**: 2026-03-23
---
## Overview
This document outlines the test infrastructure standards for the Atom project, covering:
- Test fixtures and patterns
- Database isolation and test data management
- Failure artifact capture (screenshots, videos)
- Test reporting (Allure, HTML, JSON)
- Parallel execution patterns
- Test cleanup and teardown
**Target Audience**: Test engineers, developers writing tests, CI/CD engineers
---
## Test Fixtures Standards
### Fixture Scope
**Session-scoped fixtures** (expensive, shared):
```python
@pytest.fixture(scope="session")
def browser():
"""Shared browser instance for all tests."""
# Use for: Browser launch, server startup
```
**Function-scoped fixtures** (default, isolated):
```python
@pytest.fixture(scope="function")
def page(browser):
"""New page for each test."""
# Use for: Page objects, test data
```
**Autouse fixtures** (automatic):
```python
@pytest.fixture(autouse=True)
def track_page_for_screenshots(request, page):
"""Track page for automatic screenshot capture."""
# Runs for every test automatically
```
### Fixture Naming Conventions
- Descriptive names: `screenshot_page`, not `sp`
- Return type hints in docstrings
- Yield for cleanup, return for values
---
## Database Isolation Patterns
### Worker-Specific Database Isolation
All tests automatically get worker-specific database isolation via `db_session` fixture:
```python
@pytest.fixture(scope="function")
def db_session():
"""
Worker-specific database session with automatic rollback.
Each pytest-xdist worker gets its own database file to prevent
test data collisions during parallel execution.
"""
# Worker ID: gw0, gw1, gw2, etc.
# Database: atom_test_<worker_id>.db
# Automatic rollback after each test
```
**Key Benefits**:
- No test data collisions between workers
- No cleanup code needed in tests
- Full parallel execution support
**Usage**:
```python
def test_create_agent(db_session):
agent = AgentRegistry(id="test-agent", name="Test")
db_session.add(agent)
db_session.commit()
# Auto-rollback after test
```
---
## Failure Artifacts (INFRA-04)
### Automatic Capture
Failed E2E tests automatically capture:
- **Screenshot**: Full-page screenshot saved to `artifacts/screenshots/`
- **Video**: Browser recording saved to `artifacts/videos/` (CI only)
- **Allure Report**: Artifacts attached to test result for easy viewing
### Screenshot Format
- Filename: `{timestamp}_{test_name}.png`
- Full page capture (includes scrolled content)
- Available in: `artifacts/screenshots/`
**Example**:
```
20260323_170120_test_login_success.png
```
### Video Recording
- Enabled in CI only (GITHUB_ACTIONS=true)
- Format: WEBM
- Available in: `artifacts/videos/`
- Accessed via: `page.video.path()`
**Example**:
```
20260323_170120_test_login_success.webm
```
### Allure Integration
```python
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
"""Attach screenshots/videos to Allure on failure."""
outcome = yield
rep = outcome.get_result()
if rep.when == "call" and rep.failed:
# Capture and attach artifacts
allure.attach.file(screenshot_path, ...)
allure.attach.file(video_path, ...)
```
**Benefits**:
- Artifacts embedded in test report
- One-click viewing in Allure UI
- No manual file searching
### Viewing Artifacts
```bash
# Local: Check artifacts directory
ls artifacts/screenshots/
ls artifacts/videos/
# CI: Download from workflow run artifacts
# Allure: Open report and click failed test
allure open allure-report
```
### Manual Screenshot Capture
```python
def test_manual_screenshot(page):
page.screenshot(path="custom-screenshot.png")
# Attach to Allure
allure.attach.file(
"custom-screenshot.png",
name="Custom Screenshot",
attachment_type=allure.attachment_type.PNG
)
```
---
## Test Cleanup Patterns
### Automatic Cleanup
Use fixtures with yield for cleanup:
```python
@pytest.fixture(scope="function")
def temp_file():
"""Create temp file and clean up after test."""
path = "/tmp/test-file.txt"
with open(path, "w") as f:
f.write("test data")
yield path
# Cleanup
os.remove(path)
```
### Database Cleanup
Use transaction rollback (automatic):
```python
def test_create_agent(db_session):
agent = AgentRegistry(id="test", name="Test")
db_session.add(agent)
db_session.commit()
# Auto-rollback after test
```
### Resource Cleanup
```python
@pytest.fixture(scope="function")
def server():
"""Start server and stop after test."""
srv = start_server(port=8000)
yield srv
srv.stop() # Cleanup
```
---
## Test Reporting Standards
### Allure Reporting
**Generate Report**:
```bash
pytest tests/ --alluredir=allure-results
allure generate allure-results --clean -o allure-report
allure open allure-report
```
**Benefits**:
- Rich test report with screenshots/videos
- Test history and trends
- Suites, categories, and tags
### HTML Reporting
**Generate Report**:
```bash
pytest tests/ --html=report.html --self-contained-html
```
**Features**:
- Embedded screenshots in failed tests
- Test execution summary
- Test duration and logs
### JSON Reporting
**Generate Report**:
```bash
pytest tests/ --json-report --json-report-file=report.json
```
**Use Case**: CI/CD pass rate parsing
---
## Parallel Execution Standards
### pytest-xdist Configuration
**Run tests in parallel**:
```bash
pytest -n auto # Auto-detect CPU count
pytest -n 4 # Use 4 workers
```
**Worker Isolation**:
- Each worker gets own database file
- Unique resource names via fixtures
- No shared state between workers
### Test Independence
**Requirements**:
- No hardcoded IDs (use fixtures)
- No shared files (use temp files)
- No hardcoded ports (use random ports)
**Bad Example**:
```python
def test_create_agent():
agent = AgentRegistry(id="test-agent", ...) # Collision!
```
**Good Example**:
```python
def test_create_agent(unique_name):
agent = AgentRegistry(id=unique_name(), ...) # Safe
```
---
## CI/CD Integration
### CI-Specific Behavior
**Video Recording**: Enabled in CI only
```python
if is_ci_environment():
context_args["record_video_dir"] = video_dir
```
**Test Retries**: Enabled in CI only
```python
if is_ci_environment():
sys.argv.extend(["--reruns", "2"])
```
**Artifact Upload**: Screenshots and videos uploaded as workflow artifacts
### GitHub Actions Example
```yaml
- name: Run E2E tests
run: pytest tests/e2e_ui/ -n auto
- name: Upload screenshots
if: failure()
uses: actions/upload-artifact@v3
with:
name: screenshots
path: backend/tests/e2e_ui/artifacts/screenshots/
```
---
## Best Practices
### DO ✅
- Use fixtures for setup/teardown
- Write isolated tests (no dependencies)
- Use unique resource names
- Leverage automatic rollback
- Attach screenshots to Allure on failure
### DON'T ❌
- Hardcode IDs or ports
- Share state between tests
- Manually cleanup database
- Skip fixture cleanup
- Ignore flaky tests (fix them)
---
## Troubleshooting
### Screenshots Not Capturing
**Check**:
1. Is `page` fixture available?
2. Is `allure-pytest` installed?
3. Is `allure-results` directory writable?
**Fix**:
```bash
pip install allure-pytest
mkdir -p allure-results
```
### Videos Not Recording
**Check**:
1. Is running in CI (GITHUB_ACTIONS=true)?
2. Is video dir created?
3. Is browser context configured for video?
**Fix**:
```python
if is_ci_environment():
os.makedirs(video_dir, exist_ok=True)
context_args["record_video_dir"] = video_dir
```
### Tests Failing in Parallel but Passing Sequentially
**Check**:
1. Are resources uniquely named?
2. Is database isolation enabled?
3. Are ports hardcoded?
**Fix**:
```python
# Use unique_name fixture
agent = AgentRegistry(id=unique_name(), ...)
# Use db_session fixture (auto-isolation)
def test_something(db_session):
...
```
---
## Additional Resources
- **Test Isolation Patterns**: `TEST_ISOLATION_PATTERNS.md`
- **Flaky Test Guide**: `FLAKY_TEST_GUIDE.md`
- **Parallel Execution Guide**: `PARALLEL_EXECUTION_GUIDE.md`
- **Coverage Guide**: `COVERAGE_GUIDE.md`
## Unified Test Runner (INFRA-08, INFRA-09, INFRA-10)
### Overview
Single entry point for running all platform tests with unified Allure reporting.
### Usage
```bash
# Run all platforms
python backend/tests/scripts/test_runner.py
# Run specific platform
python backend/tests/scripts/test_runner.py --platform backend
python backend/tests/scripts/test_runner.py --platform web
python backend/tests/scripts/test_runner.py --platform mobile
# Configure parallelism
python backend/tests/scripts/test_runner.py --workers 8
# Skip Allure report (faster iteration)
python backend/tests/scripts/test_runner.py --no-report
# Extra pytest arguments
python backend/tests/scripts/test_runner.py --extra "-k test_agent"
```
### Platforms
| Platform | Test Framework | Allure Directory |
|----------|---------------|------------------|
| Backend | pytest | allure-results/backend/ |
| Web E2E | pytest-playwright | allure-results/web/ |
| Mobile API | pytest | allure-results/mobile/ |
| Desktop | cargo test | (separate workflow) |
### Allure Report
```bash
# Generate report manually
python backend/tests/scripts/allure_aggregator.py aggregate-allure \
--backend allure-results/backend/ \
--web allure-results/web/ \
--mobile allure-results/mobile/ \
--output allure-results/
# View report (auto-refreshes)
allure open allure-report
# Serve report on port 8080
allure serve allure-results
```
### CI Integration
- GitHub Actions runs unified-tests job per platform
- generate-report job aggregates results
- Report uploaded as artifact for viewing
### Output
- Allure results: `allure-results/`
- Allure report: `allure-report/index.html`
- Screenshots: `artifacts/screenshots/` (on failure)
- Videos: `artifacts/videos/` (on failure, CI only)
---
*Last Updated: 2026-03-23*
*Phase: 233 - Test Infrastructure Foundation*
*Plan: 05 - Unified Test Runner with Allure Cross-Platform Reporting*
|