Add new setter method to TestClient for scope["client"] #2484
Replies: 1 comment
-
I was just working around the same regression introduced by #2377 when I saw #2430. The change made it harder to test applications which do any sort of modification to the client value (in my case, allowing certain CDN headers to override the IP address) since there isn't an easy hook for overriding the I ended up with an approach like this in my FastAPI app: from fastapi import APIRouter, FastAPI, Request
from fastapi.responses import JSONResponse, PlainTextResponse
from fastapi.testclient import TestClient
from starlette.middleware.base import BaseHTTPMiddleware
from my_app.middleware import use_custom_ip_header
app = FastAPI()
router = APIRouter()
@router.get("/")
def client_address_echo(request: Request) -> PlainTextResponse:
return JSONResponse({"client": request.client}, status_code=200)
app.include_router(router)
app.add_middleware(BaseHTTPMiddleware, dispatch=use_custom_ip_header)
client = TestClient(app)
def test_ip_header_override_on_errors():
response = client.get(
"/",
headers={
"Content-Type": "application/json",
"Connecting-IP": "9.8.7.6",
"X-Forwarded-For": "1.2.3.4",
},
)
assert response.json() == {"client": ["9.8.7.6", 50000]} That works but there are two things I didn't like about it. One is that it means this test – unlike everything else in the test suite – uses a custom application rather than the one which actually runs. The other is that I now have a block of code in my main application code which looks like this, which seems undesirable: if not request.client:
if request.scope["server"][0] != "testserver":
raise SystemExit("This service is not correctly configured!")
else:
request.scope["client"] = Address("testclient", 50000) Obviously that's not the end of the world but it suggests that there should be a way to populate the test client with those parameters so the production application code wouldn't need to include a workaround for this new quirk. |
Beta Was this translation helpful? Give feedback.
-
Related to #2430.
@Kludex @aminalaee since this was rejected, can a new setter method be added to the class? I can write the code/tests of course, just would need a sign off. Really would be nice to be able to change this value in the test suite to test different scenarios.
e.g.
Beta Was this translation helpful? Give feedback.
All reactions