"""Test script for the API.""" import sys import time import subprocess import requests from threading import Thread SERVER_URL = "http://127.0.0.1:8000" def start_server(): """Start the uvicorn server.""" subprocess.run([ "python3", "-m", "uvicorn", "src.main:app", "--host", "127.0.0.1", "--port", "8000" ]) def wait_for_server(timeout=10): """Wait for server to be ready.""" start = time.time() while time.time() - start < timeout: try: response = requests.get(f"{SERVER_URL}/health", timeout=1) if response.status_code == 200: return True except: pass time.sleep(0.5) return False def test_health(): """Test health endpoint.""" response = requests.get(f"{SERVER_URL}/health") assert response.status_code == 200 assert response.json()["status"] == "healthy" print("āœ… Health check passed") def test_login(): """Test login endpoint.""" response = requests.post( f"{SERVER_URL}/api/v1/auth/login", json={"email": "alice@example.com", "password": "SecurePass123!"} ) assert response.status_code == 200 data = response.json() assert data["success"] == True assert "access_token" in data["data"] print("āœ… Login endpoint passed") return data["data"]["access_token"] def test_login_invalid(): """Test login with invalid credentials.""" response = requests.post( f"{SERVER_URL}/api/v1/auth/login", json={"email": "alice@example.com", "password": "WrongPassword!"} ) assert response.status_code == 401 print("āœ… Invalid login returns 401") def test_profile(): """Test profile endpoint.""" response = requests.get(f"{SERVER_URL}/api/v1/profile/me") assert response.status_code == 200 print("āœ… Profile endpoint passed") def run_tests(): """Run all tests.""" print("šŸ”§ Starting server...") server_thread = Thread(target=start_server, daemon=True) server_thread.start() print("ā³ Waiting for server...") if not wait_for_server(): print("āŒ Server failed to start") return False print("āœ… Server is ready!\n") try: test_health() test_login() test_login_invalid() test_profile() print("\nšŸŽ‰ All tests passed!") return True except Exception as e: print(f"\nāŒ Test failed: {e}") return False if __name__ == "__main__": success = run_tests() sys.exit(0 if success else 1)