@@ -61,6 +61,55 @@ async def test_run_server():
6161 assert response .json () == GREETING
6262
6363
64+ async def test_configure_cors_headers ():
65+ """Test configuring the CORS headers."""
66+ # Configure the FastAPI app with nontrivial CORS settings
67+ cors_config = ApiConfigBase (
68+ cors_allowed_origins = ["http://test.dev" ],
69+ cors_allowed_methods = ["GET" ],
70+ cors_allowed_headers = ["X-Custom-Request-Header" ],
71+ cors_exposed_headers = ["X-Custom-Response-Header" ],
72+ )
73+
74+ app = FastAPI ()
75+ configure_app (app , cors_config )
76+
77+ # Check that the app is configured properly
78+ client = AsyncTestClient (app )
79+
80+ # Add a simple endpoint to test CORS
81+ @app .get ("/test" )
82+ async def test_endpoint ():
83+ return {"message" : "test" }
84+
85+ # Test preflight request
86+ response = await client .options (
87+ "/test" ,
88+ headers = {
89+ "Origin" : "http://test.dev" ,
90+ "Access-Control-Request-Method" : "GET" ,
91+ "Access-Control-Request-Headers" : "X-Custom-Request-Header" ,
92+ },
93+ )
94+
95+ # Verify CORS headers are set correctly
96+ assert response .status_code == 200
97+ headers = response .headers
98+ assert headers ["access-control-allow-origin" ] == "http://test.dev"
99+ assert headers ["access-control-allow-methods" ] == "GET"
100+ allow_headers = headers ["access-control-allow-headers" ].split (", " )
101+ assert "X-Custom-Request-Header" in allow_headers
102+
103+ # Test actual request with CORS headers
104+ response = await client .get ("/test" , headers = {"Origin" : "http://test.dev" })
105+
106+ assert response .status_code == 200
107+ headers = response .headers
108+ assert headers ["access-control-allow-origin" ] == "http://test.dev"
109+ expose_headers = headers ["access-control-expose-headers" ].split (", " )
110+ assert "X-Custom-Response-Header" in expose_headers
111+
112+
64113async def test_configure_exception_handler ():
65114 """Test the exception handler configuration of a FastAPI app."""
66115 # example params for an http exception
0 commit comments