Overview
FKApi uses pytest for testing with comprehensive coverage of API endpoints, models, services, and scrapers. This guide covers running tests, writing new tests, and maintaining test quality.Test Configuration
Pytest Settings
Test configuration is defined inpytest.ini:
Test Settings
Tests use a separate settings file (fkapi/test_settings.py) with:
- SQLite database: Faster than PostgreSQL for testing
- Local memory cache: No Redis required
- Disabled Celery: Tests run synchronously
- Simplified middleware: Only essential middleware enabled
Running Tests
Basic Commands
Using Test Markers
Coverage Reports
Coverage Configuration
Coverage settings are defined inpyproject.toml:
Test Structure
Test Organization
Test File Template
Writing Tests
API Endpoint Tests
Model Tests
Service Tests
Scraper Tests
Cache Tests
Test Fixtures
Using Pytest Fixtures
HTML Fixtures
Store sample HTML infixtures/html_samples.py:
Best Practices
Test Naming
- Use descriptive names:
test_get_kit_returns_404_when_not_found - Follow pattern:
test_[function]_[scenario]_[expected] - Use docstrings to explain complex tests
Test Independence
Mocking External Services
Testing Edge Cases
Continuous Integration
Tests run automatically on:- Every commit (pre-commit hooks)
- Every pull request (GitHub Actions)
- Before deployment
Pre-commit Tests
Coverage Goals
- Overall: >80% coverage
- Critical paths: >90% coverage (API endpoints, models)
- New code: 100% coverage required
- Excluded: Migrations, test files, admin files
Checking Coverage
Troubleshooting Tests
Tests Failing Locally
Import Errors
Ensurepythonpath is set correctly in pytest.ini:
Database Errors
Tests use SQLite by default. Checktest_settings.py is configured correctly.
Cache Issues
Clear cache insetUp() method:
Additional Resources
Remember: Good tests make confident refactoring possible!