mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-30 09:14:03 +09:00
Changes: - Add backend dependencies to root pyproject.toml - Configure pytest to discover tests from tests/, backend/tests/ - Skip emulator/integration tests when services not available - Add run-backend-local.sh for local development - Add comprehensive TESTING-GUIDE.md documentation Now you can: - pytest # Run all 379 tests from repo root - ./scripts/run-backend-local.sh # Run backend locally Emulator tests auto-skip unless emulators are running. Integration tests require RUN_INTEGRATION_TESTS=true.
5.9 KiB
5.9 KiB
Testing Guide
This guide covers how to test the karaoke-gen project, including both the CLI library and the backend API.
Quick Start
Run All Unit Tests
# From repo root - runs both karaoke-gen CLI and backend tests
pytest
Run Specific Test Suites
# CLI library tests only
pytest tests/
# Backend tests only
pytest backend/tests/
# Specific test file
pytest backend/tests/test_models.py -v
Test Organization
karaoke-gen/
├── tests/ # CLI library tests
│ ├── unit/ # Unit tests
│ └── integration/ # Integration tests
├── backend/tests/ # Backend API tests
│ ├── test_models.py # Pydantic model tests
│ ├── test_services.py # Service layer tests
│ ├── test_job_manager.py # JobManager tests
│ ├── test_file_upload.py # File upload tests
│ ├── test_api_integration.py # Live API integration tests
│ ├── test_emulator_integration.py # Emulator tests
│ └── emulator/ # Emulator-specific tests
│ ├── conftest.py
│ └── test_emulator_integration.py
└── scripts/
├── run-tests.sh # Main test runner
├── run-emulator-tests.sh # Emulator tests
└── run-backend-local.sh # Local dev server
Test Types
1. Unit Tests (Fast, No External Dependencies)
- Run by default with
pytest - Mock all external services
- ~30 seconds to complete
- Should catch most bugs before deployment
2. Emulator Tests (Medium, Local Services)
- Require GCP emulators (Firestore, GCS)
- Skip automatically if emulators aren't running
- Start emulators:
./scripts/start-emulators.sh - Run emulator tests:
./scripts/run-emulator-tests.sh
3. Integration Tests (Slow, Live Services)
- Require deployed backend
- Skip by default
- Run with:
RUN_INTEGRATION_TESTS=true pytest backend/tests/test_api_integration.py
Running Tests Locally
Standard Test Run
# Activate poetry environment and run all tests
poetry run pytest
# With verbose output
poetry run pytest -v
# Stop on first failure
poetry run pytest -x
# Run specific test
poetry run pytest backend/tests/test_models.py::TestJob::test_create_job
With GCP Emulators
# Terminal 1: Start emulators
./scripts/start-emulators.sh
# Terminal 2: Run emulator tests
./scripts/run-emulator-tests.sh
# Terminal 3: Run local backend (optional)
./scripts/run-backend-local.sh --with-emulators
Running Backend Locally
# Against real GCP (requires credentials)
./scripts/run-backend-local.sh
# Against emulators
./scripts/run-backend-local.sh --with-emulators
Then test with:
curl http://localhost:8000/api/health
Writing Tests
Best Practices
- Mock external services: Always mock Firestore, GCS, and external APIs
- Test data structures: Validate Pydantic models handle all expected shapes
- Test edge cases: Empty values, nested dicts, type mismatches
- Use fixtures: Share common setup in
conftest.py
Example: Testing a Model Field
def test_file_urls_with_nested_stems(self):
"""Test file_urls handles nested dictionary structure."""
job = Job(
job_id="test123",
status=JobStatus.SEPARATING,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
file_urls={
"stems": {
"instrumental_clean": "gs://bucket/stems/clean.flac",
"vocals": "gs://bucket/stems/vocals.flac"
}
}
)
assert "stems" in job.file_urls
assert job.file_urls["stems"]["instrumental_clean"] == "gs://bucket/stems/clean.flac"
Example: Testing a Service with Mocks
@pytest.fixture
def mock_firestore():
with patch('backend.services.firestore_service.firestore.Client') as mock:
yield mock.return_value
def test_create_job(mock_firestore):
mock_firestore.collection.return_value.document.return_value.set.return_value = None
service = FirestoreService()
# ... test logic
Coverage
Coverage reports are generated automatically:
- Terminal: Shows missing lines
- HTML:
htmlcov/index.html
View coverage:
pytest --cov=backend --cov=karaoke_gen --cov-report=html
open htmlcov/index.html
CI/CD Testing
The GitHub Actions workflow runs:
- Unit Tests: All unit tests for CLI and backend
- Emulator Tests: Against local GCP emulators
- Deploy: To Cloud Run (only on push to main branch)
Why Tests Might Fail in CI but Pass Locally
- Missing dependencies: Check
pyproject.tomlincludes all deps - Environment differences: CI uses Ubuntu, check for path issues
- Timing issues: Tests may need delays for async operations
- Mock leakage: Ensure mocks are properly scoped
Debugging Test Failures
Check Test Output
pytest -v --tb=long backend/tests/test_models.py
Run Single Test
pytest backend/tests/test_models.py::TestJob::test_create_job -v -s
Debug with Print Statements
pytest -v -s # -s shows print output
Check Logs
# For emulator tests
cat /tmp/emulator-logs/firestore.log
cat /tmp/emulator-logs/gcs.log
Common Issues
"ModuleNotFoundError: No module named 'google.cloud.firestore_v1'"
- Run
poetry installto install dependencies - Or run tests via
poetry run pytest
"GCP emulators not running"
- Start emulators:
./scripts/start-emulators.sh - Check ports 8080 (Firestore) and 4443 (GCS) are available
"Connection refused" errors
- Check emulators use
127.0.0.1notlocalhost(IPv6 issues) - Verify environment variables:
FIRESTORE_EMULATOR_HOST,STORAGE_EMULATOR_HOST
"Pydantic validation error"
- Check model field types match actual data structures
- Use
Dict[str, Any]for nested/flexible dicts, notDict[str, str]