This folder contains all test files for the FastAPI Template project.
| File | Description | Type |
|---|---|---|
| test_context_feature.py | Automated tests for code context feature | Integration |
| File | Description | Type |
|---|---|---|
| test_websocket.py | WebSocket connection tests | Integration |
| test_create_session.py | Session creation tests | Integration |
| test_sessions.sh | Shell script for session testing | Integration |
# From project root
python3 tests/test_context_feature.pyPrerequisites:
- Server must be running (
docker-compose up) - Valid user credentials (default: admin/admin)
- MongoDB accessible
What it tests:
- ✅ User authentication
- ✅ Session creation
- ✅ Zip file upload with sample code
- ✅ Repository URL addition
- ✅ Context information retrieval
- ✅ Context removal
Expected Output:
=== Code Context Feature Test ===
Logging in...
✓ Login successful!
Creating test session...
✓ Session created: 507f1f77bcf86cd799439011
--- Testing Zip Upload ---
✓ Zip uploaded successfully!
Type: zip
Source: test_code.zip
Files: 3 files extracted
--- Testing Repository URL ---
✓ Repository added successfully!
Type: repository
Source: https://github.com/test/repo
--- Testing Context Removal ---
✓ Context removed successfully!
=== Tests Complete ===
python3 tests/test_websocket.py# Shell script
bash tests/test_sessions.sh
# Python script
python3 tests/test_create_session.py# Main test functions
- login() # Authenticate user
- create_session() # Create test session
- create_test_zip() # Generate sample zip file
- test_upload_zip() # Test zip upload
- test_add_repository() # Test repository URL
- test_remove_context() # Test context removal
- test_get_session() # Verify context dataTests use these default values:
API_URL = "http://localhost:8000"
USERNAME = "admin"
PASSWORD = "admin"To customize:
# Set environment variables
export API_URL="http://your-server:8000"
export TEST_USERNAME="your-username"
export TEST_PASSWORD="your-password"
# Run tests
python3 tests/test_context_feature.pyBefore running tests, ensure:
- Server is running
- MongoDB is accessible
- Test user exists (admin/admin)
- No port conflicts (8000)
- Dependencies installed
Solution: Start the server first
docker-compose upSolution: Check credentials or create test user
# Create admin user if needed
python3 -c "from app.controllers.users import create_admin_user; create_admin_user()"Solution: Check MongoDB connection and database name
Solution: Check file size limits and supported extensions
Modify test file:
# Add at top of test file
import logging
logging.basicConfig(level=logging.DEBUG)| Feature | Coverage | Tests |
|---|---|---|
| Code Context - Zip Upload | ✅ | test_context_feature.py |
| Code Context - Repository | ✅ | test_context_feature.py |
| Code Context - Removal | ✅ | test_context_feature.py |
| WebSocket Connection | ✅ | test_websocket.py |
| Session Creation | ✅ | test_create_session.py |
| User Authentication | ✅ | All tests |
- File size limit enforcement
- Invalid file type handling
- Concurrent context updates
- Context with large files
- Malformed zip files
- Invalid repository URLs
- Context persistence after server restart
name: Run Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Start services
run: docker-compose up -d
- name: Wait for services
run: sleep 10
- name: Run tests
run: python3 tests/test_context_feature.py
- name: Stop services
run: docker-compose down#!/usr/bin/env python3
"""
Test script for [Feature Name]
"""
import requests
import sys
API_URL = "http://localhost:8000"
def login(username="admin", password="admin"):
"""Login and get access token"""
response = requests.post(
f"{API_URL}/auths/login",
data={"username": username, "password": password}
)
return response.json()["access_token"] if response.status_code == 200 else None
def test_feature(token):
"""Test your feature"""
print("\n--- Testing [Feature] ---")
# Your test code here
pass
def main():
"""Run all tests"""
print("=== [Feature] Tests ===\n")
token = login()
if not token:
print("Failed to login")
sys.exit(1)
test_feature(token)
print("\n=== Tests Complete ===")
if __name__ == "__main__":
main()- Isolate tests - Each test should be independent
- Clean up - Remove test data after tests
- Use assertions - Validate expected outcomes
- Handle errors - Catch and report exceptions
- Document tests - Explain what each test does
- Use realistic data - Test with real-world scenarios
- Login with valid credentials
- Create new chat session
- Upload zip file with code
- Verify context badge appears
- Send message in chat
- Remove context
- Verify badge removed
- Login and create session
- Add repository URL
- Verify URL is stored
- Replace with different URL
- Remove context
- Try to upload non-zip file
- Try to add invalid URL
- Try to access other user's session
- Try to upload oversized file
import concurrent.futures
import time
def load_test_upload():
"""Test concurrent uploads"""
tokens = [login() for _ in range(10)]
sessions = [create_session(t) for t in tokens]
start = time.time()
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
futures = [
executor.submit(test_upload_zip, tokens[i], sessions[i])
for i in range(10)
]
results = [f.result() for f in futures]
duration = time.time() - start
print(f"10 uploads completed in {duration:.2f}s")When adding new features:
- Write tests first (TDD approach)
- Cover happy path - Normal usage
- Cover edge cases - Boundary conditions
- Cover error cases - Invalid inputs
- Update this README - Document new tests
- Run all tests - Ensure nothing breaks
- Test failures: Check debugging section above
- Adding tests: Follow template and best practices
- CI/CD setup: See integration examples
- Questions: Review existing test files
Happy Testing! 🧪