|
| 1 | +# Testing Guide for FastAPI MongoDB Sample Application |
| 2 | + |
| 3 | +This document describes the testing strategy and how to run tests for the FastAPI MongoDB MFlix sample application. |
| 4 | + |
| 5 | +## Test Structure |
| 6 | + |
| 7 | +The test suite is organized into three categories: |
| 8 | + |
| 9 | +### 1. **Schema Tests** (`test_movie_schemas.py`) |
| 10 | +- Tests Pydantic model validation |
| 11 | +- Validates request/response data structures |
| 12 | +- No database or external dependencies required |
| 13 | +- **10 tests** covering `CreateMovieRequest`, `UpdateMovieRequest`, and `Movie` models |
| 14 | + |
| 15 | +### 2. **Unit Tests** (`test_movie_routes.py`) |
| 16 | +- Tests route handler functions in isolation |
| 17 | +- Uses `unittest.mock.AsyncMock` to mock MongoDB operations |
| 18 | +- No database connection required |
| 19 | +- Fast execution (< 2 seconds) |
| 20 | +- **51 tests** covering: |
| 21 | + - CRUD operations (create, read, update, delete) |
| 22 | + - Batch operations |
| 23 | + - Search functionality |
| 24 | + - Vector search |
| 25 | + - Aggregation pipelines |
| 26 | + |
| 27 | +### 3. **Integration Tests** (`tests/integration/test_movie_routes_integration.py`) |
| 28 | +- Tests the full HTTP request/response cycle |
| 29 | +- Requires a running MongoDB instance with MFlix dataset |
| 30 | +- Uses a real server running in a subprocess |
| 31 | +- Tests are idempotent (clean up after themselves) |
| 32 | +- **8 tests** (7 passing, 1 skipped due to known bug) covering: |
| 33 | + - End-to-end CRUD operations |
| 34 | + - Search against real data |
| 35 | + - Batch operations with cleanup |
| 36 | + - Aggregation queries |
| 37 | + |
| 38 | +## Running Tests |
| 39 | + |
| 40 | +### Prerequisites |
| 41 | + |
| 42 | +1. **For all tests:** |
| 43 | + ```bash |
| 44 | + cd server/python |
| 45 | + source .venv/bin/activate # or `.venv\Scripts\activate` on Windows |
| 46 | + ``` |
| 47 | + |
| 48 | +2. **For integration tests only:** |
| 49 | + - MongoDB instance running with MFlix dataset loaded |
| 50 | + - Connection string configured in `.env` file |
| 51 | + - Port 8001 available (used for test server) |
| 52 | + |
| 53 | +### Run All Tests |
| 54 | + |
| 55 | +```bash |
| 56 | +pytest tests/ -v |
| 57 | +``` |
| 58 | + |
| 59 | +**Expected output:** 68 passed, 1 skipped in ~5 seconds |
| 60 | + |
| 61 | +### Run Only Unit Tests (Fast, No Database Required) |
| 62 | + |
| 63 | +```bash |
| 64 | +pytest -m unit -v |
| 65 | +``` |
| 66 | + |
| 67 | +**Expected output:** 51 passed in ~1 second |
| 68 | + |
| 69 | +### Run Only Integration Tests (Requires Database) |
| 70 | + |
| 71 | +```bash |
| 72 | +pytest -m integration -v |
| 73 | +``` |
| 74 | + |
| 75 | +**Expected output:** 7 passed, 1 skipped in ~4 seconds |
| 76 | + |
| 77 | +### Run Specific Test File |
| 78 | + |
| 79 | +```bash |
| 80 | +# Schema tests |
| 81 | +pytest tests/test_movie_schemas.py -v |
| 82 | + |
| 83 | +# Unit tests |
| 84 | +pytest tests/test_movie_routes.py -v |
| 85 | + |
| 86 | +# Integration tests |
| 87 | +pytest tests/integration/test_movie_routes_integration.py -v |
| 88 | +``` |
| 89 | + |
| 90 | +### Run Specific Test Class or Method |
| 91 | + |
| 92 | +```bash |
| 93 | +# Run a specific test class |
| 94 | +pytest tests/test_movie_routes.py::TestCreateMovie -v |
| 95 | + |
| 96 | +# Run a specific test method |
| 97 | +pytest tests/test_movie_routes.py::TestCreateMovie::test_create_movie_success -v |
| 98 | +``` |
| 99 | + |
| 100 | +## Test Markers |
| 101 | + |
| 102 | +Tests are marked with pytest markers for selective execution: |
| 103 | + |
| 104 | +- `@pytest.mark.unit` - Unit tests with mocked dependencies |
| 105 | +- `@pytest.mark.integration` - Integration tests requiring database |
| 106 | + |
| 107 | +## Integration Test Strategy |
| 108 | + |
| 109 | +### Why Use a Running Server? |
| 110 | + |
| 111 | +The integration tests start a real FastAPI server in a subprocess because: |
| 112 | + |
| 113 | +1. **Event Loop Isolation**: AsyncMongoClient binds to the event loop it was created in. Using a real server avoids event loop conflicts. |
| 114 | +2. **Real-World Testing**: Tests the actual deployment configuration, including middleware, CORS, and startup events. |
| 115 | +3. **Educational Value**: Demonstrates a practical integration testing pattern for async Python applications. |
| 116 | + |
| 117 | +### Idempotent Tests |
| 118 | + |
| 119 | +All integration tests are designed to be idempotent: |
| 120 | + |
| 121 | +- **Create operations**: Tests create new documents with unique identifiers |
| 122 | +- **Cleanup**: Fixtures automatically delete created documents after tests |
| 123 | +- **Read-only tests**: Tests against existing MFlix data don't modify anything |
| 124 | +- **Batch operations**: Create and delete multiple documents with proper cleanup |
| 125 | + |
| 126 | +### Fixtures |
| 127 | + |
| 128 | +Integration tests use pytest fixtures for test data lifecycle management: |
| 129 | + |
| 130 | +- `client`: AsyncClient connected to the test server |
| 131 | +- `test_movie_data`: Sample movie data for creating test documents |
| 132 | +- `created_movie`: Creates a movie and cleans it up automatically |
| 133 | +- `multiple_test_movies`: Creates 3 movies for batch operation testing |
| 134 | + |
| 135 | +## Known Issues |
| 136 | + |
| 137 | +### Batch Create Bug (Skipped Test) |
| 138 | + |
| 139 | +The `test_batch_create_movies` test is currently skipped due to a known bug in the API: |
| 140 | + |
| 141 | +- **Issue**: `create_movies_batch` function calls `insert_many` twice (lines 1006 and 1015 in `movies.py`) |
| 142 | +- **Impact**: Causes 500 error on batch create operations |
| 143 | +- **Status**: To be fixed in a separate PR |
| 144 | +- **Test behavior**: Test detects the error and skips gracefully |
| 145 | + |
| 146 | +## Troubleshooting |
| 147 | + |
| 148 | +### Integration Tests Fail to Start Server |
| 149 | + |
| 150 | +**Error**: `Port 8001 is already in use` |
| 151 | + |
| 152 | +**Solution**: |
| 153 | +- Kill any process using port 8001: `lsof -ti:8001 | xargs kill -9` |
| 154 | +- Or change the port in `tests/integration/conftest.py` |
| 155 | + |
| 156 | +### Integration Tests Can't Connect to MongoDB |
| 157 | + |
| 158 | +**Error**: Connection timeout or authentication error |
| 159 | + |
| 160 | +**Solution**: |
| 161 | +- Verify MongoDB is running |
| 162 | +- Check `.env` file has correct `MONGODB_URI` |
| 163 | +- Ensure MFlix dataset is loaded |
| 164 | +- Test connection: `mongosh <your-connection-string>` |
| 165 | + |
| 166 | +### Unit Tests Fail with Import Errors |
| 167 | + |
| 168 | +**Error**: `ModuleNotFoundError` |
| 169 | + |
| 170 | +**Solution**: |
| 171 | +- Ensure virtual environment is activated |
| 172 | +- Install dependencies: `pip install -r requirements.txt` |
| 173 | +- Run from `server/python` directory |
| 174 | + |
| 175 | +## Contributing |
| 176 | + |
| 177 | +When adding new routes or functionality: |
| 178 | + |
| 179 | +1. **Add unit tests** in `test_movie_routes.py` with mocked dependencies |
| 180 | +2. **Add integration tests** in `tests/integration/test_movie_routes_integration.py` for end-to-end validation |
| 181 | +3. **Use appropriate markers** (`@pytest.mark.unit` or `@pytest.mark.integration`) |
| 182 | +4. **Follow fixture patterns** for test data lifecycle management |
| 183 | +5. **Ensure idempotency** - tests should clean up after themselves |
| 184 | +6. **Document test purpose** with clear docstrings |
| 185 | + |
| 186 | +## Additional Resources |
| 187 | + |
| 188 | +- [pytest documentation](https://docs.pytest.org/) |
| 189 | +- [pytest-asyncio documentation](https://pytest-asyncio.readthedocs.io/) |
| 190 | +- [FastAPI testing guide](https://fastapi.tiangolo.com/tutorial/testing/) |
| 191 | +- [MongoDB Motor documentation](https://motor.readthedocs.io/) |
| 192 | + |
0 commit comments