I wanted to start a real mock server with real instances that I could fine tune for my own needs.
I found a way to start the FastAPI to run the tests agains it, and then kill the uvicorn.
Here an example code 👍
| from fastapi import FastAPI | |
| from starlette.requests import Request | |
| from starlette.responses import StreamingResponse | |
| from starlette.background import BackgroundTask | |
| import httpx | |
| app = FastAPI() | |
| @app.get("/example") | |
| async def example(): | |
| client = httpx.AsyncClient(base_url="https://myotherprovider.com") | |
| response = await client.get("/v1/example") | |
| return response.json() | 
| import time | |
| import uvicorn | |
| import pytest | |
| from multiprocessing import Process | |
| from fastapi.testclient import TestClient | |
| from fastapi import FastAPI | |
| from .main import app, client as c | |
| client = TestClient(app) | |
| mock_port = 7232 | |
| open_api_mock = FastAPI() | |
| open_api_mock.add_api_route("/v1/example", | |
| lambda: {"message": "Hello World"}, | |
| methods=["GET"]) | |
| c.base_url = "http://localhost:" + str(mock_port) | |
| def start_server(): | |
| uvicorn.run(open_api_mock, | |
| host="0.0.0.0", | |
| port=mock_port) | |
| @pytest.fixture(scope="session", autouse=True) | |
| def setup(): | |
| proc = Process(target=start_server, args=()) | |
| proc.start() | |
| time.sleep(1) | |
| yield | |
| proc.terminate() | |
| def test_read_main(): | |
| response = client.get("/example") | |
| assert response.status_code == 200 | |
| assert response.json() == {"message": "Hello World"} |