Skip to content

Instantly share code, notes, and snippets.

@aleixmorgadas
Last active June 24, 2024 12:30
Show Gist options
  • Save aleixmorgadas/7326db51c6cc2838b147838ec9a23198 to your computer and use it in GitHub Desktop.
Save aleixmorgadas/7326db51c6cc2838b147838ec9a23198 to your computer and use it in GitHub Desktop.
Starting a FastAPI as a server mock

Using FastAPI as Server Mock

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 👍

image

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"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment