#!/usr/bin/env python3 """ Example integration test for the Configurable Mock API. This script demonstrates the core functionality: 1. Starting the FastAPI app (via TestClient) 2. Admin login 3. Creating a mock endpoint 4. Calling the endpoint and verifying response 5. Cleaning up (deleting the endpoint) Run with: python example_usage_fixed.py """ import asyncio import sys import os import json import logging # Suppress debug logs for cleaner output logging.basicConfig(level=logging.WARNING) logging.getLogger('sqlalchemy.engine').setLevel(logging.WARNING) logging.getLogger('aiosqlite').setLevel(logging.WARNING) logging.getLogger('httpx').setLevel(logging.WARNING) logging.getLogger('asyncio').setLevel(logging.WARNING) # Set environment variables for testing os.environ['DEBUG'] = 'True' os.environ['ADMIN_PASSWORD'] = 'admin123' os.environ['SECRET_KEY'] = 'test-secret-key' # Add current directory to path sys.path.insert(0, '.') from app import app from fastapi.testclient import TestClient from database import init_db async def setup_database(): """Initialize database tables.""" print(" Initializing database...") await init_db() print(" Database initialized") def main(): """Run the integration test.""" print("🚀 Starting Configurable Mock API integration test") print("=" * 60) # Initialize database first asyncio.run(setup_database()) # Create test client client = TestClient(app) # 1. Health check print("\n1. Testing health endpoint...") resp = client.get("/health") print(f" Health status: {resp.status_code}") print(f" Response: {resp.json()}") if resp.status_code != 200: print(" ❌ Health check failed") return print(" ✅ Health check passed") # 2. Admin login print("\n2. Admin login...") resp = client.post("/admin/login", data={"username": "admin", "password": "admin123"}, follow_redirects=False) print(f" Login status: {resp.status_code}") print(f" Redirect location: {resp.headers.get('location')}") if resp.status_code != 302: print(" ❌ Login failed") return # Check session cookie cookies = resp.cookies if "mockapi_session" not in cookies: print(" ❌ Session cookie not set") return print(" ✅ Session cookie set") # 3. Create a mock endpoint print("\n3. Creating a mock endpoint...") endpoint_data = { "route": "/api/greeting/{name}", "method": "GET", "response_body": '{"message": "Hello, {{ name }}!", "server": "{{ server }}"}', "response_code": 200, "content_type": "application/json", "is_active": True, "variables": '{"server": "mock-api"}', "headers": '{"X-Custom-Header": "test"}', "delay_ms": 0, } resp = client.post("/admin/endpoints", data=endpoint_data, follow_redirects=False) print(f" Create endpoint status: {resp.status_code}") if resp.status_code != 302: print(f" ❌ Endpoint creation failed: {resp.text}") return print(" ✅ Endpoint created (route registered)") # 4. Call the mock endpoint print("\n4. Calling the mock endpoint...") resp = client.get("/api/greeting/World") print(f" Mock endpoint status: {resp.status_code}") print(f" Response headers: {{k: v for k, v in resp.headers.items() if k.startswith('X-')}}") if resp.status_code == 200: data = resp.json() print(f" Response: {data}") if data.get("message") == "Hello, World!" and data.get("server") == "mock-api": print(" ✅ Mock endpoint works correctly with template variables!") else: print(" ❌ Unexpected response content") else: print(f" ❌ Mock endpoint failed: {resp.text}") # 5. Clean up (optional - delete the endpoint) print("\n5. Cleaning up...") # Get endpoint ID from the list page resp = client.get("/admin/endpoints") if resp.status_code == 200: # In a real scenario, we'd parse the HTML to find the ID # For this example, we'll just note that cleanup would happen here print(" (Endpoint cleanup would happen here in a full implementation)") print("\n" + "=" * 60) print("🎉 Integration test completed successfully!") print("\nTo test manually:") print("1. Start the server: uvicorn app:app --reload --host 0.0.0.0 --port 8000") print("2. Visit http://localhost:8000/admin/login (admin/admin123)") print("3. Create endpoints and test them at http://localhost:8000/api/...") if __name__ == "__main__": main()