"""演示 FastAPI 依赖覆盖(测试替换外部依赖)。""" from __future__ import annotations from fastapi import Depends, FastAPI from fastapi.testclient import TestClient def get_user() -> str: return "real" def create_app() -> FastAPI: app = FastAPI() @app.get("/whoami") def whoami(user: str = Depends(get_user)) -> dict[str, str]: return {"user": user} return app def main() -> None: client = TestClient(create_app()) print(f"default: {client.get('/whoami').json()}") app = create_app() app.dependency_overrides[get_user] = lambda: "fake" client = TestClient(app) print(f"override: {client.get('/whoami').json()}") if __name__ == "__main__": main()