-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path002_external_api_call_mock.py
46 lines (39 loc) · 1.14 KB
/
002_external_api_call_mock.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from fastapi import FastAPI
import httpx
from pydantic import BaseModel
import pytest
import respx
app = FastAPI()
class Payload(BaseModel):
message: str
class Result(BaseModel):
status: str
data: dict
@app.post("/call")
async def call():
async with httpx.AsyncClient() as client:
response = await client.post(
"http://external-api.com",
json=Payload(message="hello").model_dump()
)
result = Result(**response.json())
return {"status": "success", "data": result.model_dump()}
@pytest.mark.asyncio
async def test_external_call(respx_mock: respx.Router):
respx_mock.post(
"http://external-api.com", json={"message":"hello"}
).mock(
return_value=httpx.Response(
200, json={"status": "ok", "data": {}}
)
)
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app),
base_url="http://testserver/"
) as client:
response = await client.post("/call")
assert response.status_code == 200
assert response.json() == {
"status": "success",
"data": {"status": "ok", "data": {}},
}