Debian Codegraph @

tests/test_frontend.py

raw
1 import errno
2 import os
3 import runpy
4 from contextlib import AsyncExitStack
5 from pathlib import Path
6 from typing import Literal
7
8 import anyio
9 import pytest
10 from fastapi import (
11 APIRouter,
12 BackgroundTasks,
13 Depends,
14 FastAPI,
15 HTTPException,
16 Request,
17 WebSocket,
18 )
19 from fastapi.testclient import TestClient
20 from starlette.exceptions import HTTPException as StarletteHTTPException
21 from starlette.responses import PlainTextResponse, Response
22 from starlette.routing import BaseRoute, Match, NoMatchFound, Route
23
24
25 def write_file(path: Path, content: str) -> None:
26 path.parent.mkdir(parents=True, exist_ok=True)
27 path.write_text(content)
28
29
30 def record_dependency(calls: list[str], name: str):
31 def dependency() -> None:
32 calls.append(name)
33
34 return dependency
35
36
37 def test_frontend_exact_prefix_path_serves_index(tmp_path: Path):
38 dist = tmp_path / "dist"
39 write_file(dist / "index.html", "app")
40 app = FastAPI()
41 app.frontend("/", directory=dist)
42
43 response = TestClient(app).get("/app", headers={"accept": "text/html"})
44
45 assert response.status_code == 200
46 assert response.text == "app"
47
48
49 def test_apirouter_frontend_with_router_prefix_and_frontend_subpath(tmp_path: Path):
50 dist = tmp_path / "dist"
51 write_file(dist / "asset.txt", "asset")
52 router = APIRouter(prefix="/internal")
53 router.frontend("/ui", directory=dist)
54 app = FastAPI()
55 app.include_router(router, prefix="/prefix")
56
57 response = TestClient(app).get("/prefix/internal/ui/asset.txt")
58
59 assert response.status_code == 200
60 assert response.text == "asset"
61
62
63 def test_frontend_fallback_rejects_invalid_fallback(tmp_path: Path):
64 dist = tmp_path / "dist"
65 dist.mkdir()
66 app = FastAPI()
67
68 with pytest.raises(AssertionError, match="fallback"):
69 app.frontend("/", directory=dist, fallback="invalid") # type: ignore[arg-type] # ty: ignore[invalid-argument-type]
70
71
72 def test_index_fallback_ignores_invalid_q_value(tmp_path: Path):
73 dist = tmp_path / "dist"
74 write_file(dist / "index.html", "app shell")
75 app = FastAPI()
76 app.frontend("/", directory=dist, fallback="index.html")
77
78 response = TestClient(app).get(
79 "/dashboard/settings", headers={"accept": "text/html; q=wat"}
80 )
81
82 assert response.status_code == 200
83 assert response.text == "app shell"
84
85
86 def test_frontend_static_files_lookup_errors(monkeypatch, tmp_path: Path):
87 dist = tmp_path / "dist"
88 write_file(dist / "index.html", "app")
89 app = FastAPI()
90 app.frontend("/", directory=dist)
91 frontend_routes = app.router._frontend_routes
92 assert frontend_routes is not None
93 static_files = frontend_routes.routes[0].app
94
95 def raise_permission_error(path: str):
96 raise PermissionError
97
98 monkeypatch.setattr(static_files, "lookup_path", raise_permission_error)
99 response = TestClient(app).get("/asset.txt")
100 assert response.status_code == 401
101
102 def raise_value_error(path: str):
103 raise ValueError
104
105 monkeypatch.setattr(static_files, "lookup_path", raise_value_error)
106 response = TestClient(app).get("/asset.txt")
107 assert response.status_code == 404
108
109 def raise_name_too_long(path: str):
110 raise OSError(errno.ENAMETOOLONG, "name too long")
111
112 monkeypatch.setattr(static_files, "lookup_path", raise_name_too_long)
113 response = TestClient(app).get("/asset.txt")
114 assert response.status_code == 404
115
116 def raise_os_error(path: str):
117 raise OSError(5, "other")
118
119 monkeypatch.setattr(static_files, "lookup_path", raise_os_error)
120 with pytest.raises(OSError):
121 TestClient(app).get("/asset.txt")
122
123
124 def test_frontend_route_group_helpers(tmp_path: Path):
125 dist = tmp_path / "dist"
126 write_file(dist / "index.html", "app")
127 app = FastAPI()
128 app.frontend("/app", directory=dist)
129 route_group = app.router._frontend_routes
130 assert route_group is not None
131
132 match, child_scope = route_group.matches({"type": "websocket", "path": "/"})
133 assert match == Match.NONE
134 assert child_scope == {}
135
136 match, child_scope = route_group.matches_with_prefix(
137 {"type": "http", "path": "/prefix/app", "method": "GET"},
138 "/prefix",
139 )
140 assert match == Match.FULL
141 assert child_scope["fastapi"]["frontend_path"] == ""
142
143 match, child_scope = route_group.routes[0].matches(
144 {"type": "http", "path": "/app", "method": "GET"}
145 )
146 assert match == Match.FULL
147 assert child_scope["fastapi"]["frontend_path"] == ""
148
149 with pytest.raises(StarletteHTTPException) as exc_info:
150 anyio.run(
151 route_group.handle,
152 {"type": "http", "path": "/missing", "method": "GET"},
153 None,
154 None,
155 )
156 assert exc_info.value.status_code == 404
157
158 with pytest.raises(NoMatchFound):
159 route_group.url_path_for("frontend")
160 with pytest.raises(NoMatchFound):
161 route_group.routes[0].url_path_for("frontend")
162
163
164 def test_included_low_priority_routes_cache_is_reused():
165 async def low_priority_endpoint(request: Request):
166 return PlainTextResponse("low")
167
168 router = APIRouter()
169 router._low_priority_routes.append(Route("/low", low_priority_endpoint))
170 router._mark_routes_changed()
171 app = FastAPI()
172 app.include_router(router, prefix="/prefix")
173 included_router = next(
174 route
175 for route in app.router.routes
176 if hasattr(route, "effective_low_priority_routes")
177 )
178
179 first = included_router.effective_low_priority_routes() # ty: ignore[call-non-callable]
180 second = included_router.effective_low_priority_routes() # ty: ignore[call-non-callable]
181 response = TestClient(app).get("/prefix/low")
182
183 assert first is second
184 assert response.status_code == 200
185 assert response.text == "low"
186
187
188 def test_low_priority_api_route_handles_with_context():
189 app = FastAPI()
190
191 async def endpoint(request: Request) -> Response:
192 return PlainTextResponse(request.scope["path_params"]["item_id"])
193
194 route = app.router.route_class("/low/{item_id}", endpoint=endpoint, methods=["GET"])
195 app.router._low_priority_routes.append(route)
196 app.router._mark_routes_changed()
197
198 response = TestClient(app).get("/low/abc")
199
200 assert response.status_code == 200
201 assert response.text == "abc"
202
203
204 def test_included_low_priority_api_route_handles_with_context():
205 router = APIRouter()
206
207 async def endpoint(request: Request) -> Response:
208 return PlainTextResponse(request.scope["path_params"]["item_id"])
209
210 route = router.route_class("/low/{item_id}", endpoint=endpoint, methods=["GET"])
211 router._low_priority_routes.append(route)
212 router._mark_routes_changed()
213 app = FastAPI()
214 app.include_router(router, prefix="/prefix")
215
216 response = TestClient(app).get("/prefix/low/abc")
217
218 assert response.status_code == 200
219 assert response.text == "abc"
220
221
222 def test_normal_route_partial_match_returns_before_frontend(tmp_path: Path):
223 class PartialRoute(BaseRoute):
224 def matches(self, scope):
225 return Match.PARTIAL, {}
226
227 async def handle(self, scope, receive, send):
228 response = PlainTextResponse("partial", status_code=405)
229 await response(scope, receive, send)
230
231 dist = tmp_path / "dist"
232 write_file(dist / "index.html", "frontend")
233 app = FastAPI()
234 app.router.routes.append(PartialRoute())
235 app.frontend("/", directory=dist)
236
237 response = TestClient(app).get("/anything")
238
239 assert response.status_code == 405
240 assert response.text == "partial"
241
242
243 def test_normal_route_partial_match_wins_before_frontend(tmp_path: Path):
244 dist = tmp_path / "dist"
245 write_file(dist / "api", "frontend")
246 app = FastAPI()
247
248 @app.get("/api")
249 def read_api():
250 return {"source": "api"}
251
252 app.frontend("/", directory=dist)
253
254 client = TestClient(app)
255
256 response = client.get("/api")
257 assert response.status_code == 200
258 assert response.json() == {"source": "api"}
259
260 response = client.post("/api")
261 assert response.status_code == 405
262
263
264 def test_basic_file_serving(tmp_path: Path):
265 dist = tmp_path / "dist"
266 write_file(dist / "assets" / "app.js", "console.log('ok')")
267 app = FastAPI()
268 app.frontend("/", directory=dist)
269
270 response = TestClient(app).get("/assets/app.js")
271
272 assert response.status_code == 200
273 assert response.text == "console.log('ok')"
274 assert "etag" in response.headers
275 assert "last-modified" in response.headers
276
277
278 def test_app_frontend_dependencies_protect_root_asset_and_fallback(tmp_path: Path):
279 calls: list[str] = []
280
281 def require_cookie(request: Request) -> None:
282 calls.append(request.url.path)
283 if request.cookies.get("session") != "ok":
284 raise HTTPException(status_code=401)
285
286 dist = tmp_path / "dist"
287 write_file(dist / "index.html", "app")
288 write_file(dist / "assets" / "app.js", "console.log('ok')")
289 app = FastAPI(dependencies=[Depends(require_cookie)])
290 app.frontend("/", directory=dist, fallback="index.html")
291 client = TestClient(app)
292
293 response = client.get("/")
294 assert response.status_code == 401
295
296 response = client.get("/", headers={"cookie": "session=ok"})
297 assert response.status_code == 200
298 assert response.text == "app"
299
300 response = client.get("/assets/app.js", headers={"cookie": "session=ok"})
301 assert response.status_code == 200
302 assert response.text == "console.log('ok')"
303
304 response = client.get(
305 "/dashboard",
306 headers={"accept": "text/html", "cookie": "session=ok"},
307 )
308 assert response.status_code == 200
309 assert response.text == "app"
310 assert calls == ["/", "/", "/assets/app.js", "/dashboard"]
311
312
313 def test_apirouter_frontend_dependencies_protect_prefixed_frontend(tmp_path: Path):
314 def require_cookie(request: Request) -> None:
315 if request.cookies.get("session") != "ok":
316 raise HTTPException(status_code=401)
317
318 dist = tmp_path / "dist"
319 write_file(dist / "index.html", "app")
320 write_file(dist / "assets" / "app.js", "console.log('ok')")
321 router = APIRouter(dependencies=[Depends(require_cookie)])
322 router.frontend("/", directory=dist, fallback="index.html")
323 app = FastAPI()
324 app.include_router(router, prefix="/app")
325 client = TestClient(app)
326
327 response = client.get("/app/")
328 assert response.status_code == 401
329
330 response = client.get("/app/", headers={"cookie": "session=ok"})
331 assert response.status_code == 200
332 assert response.text == "app"
333
334 response = client.get("/app/assets/app.js", headers={"cookie": "session=ok"})
335 assert response.status_code == 200
336 assert response.text == "console.log('ok')"
337
338 response = client.get(
339 "/app/dashboard",
340 headers={"accept": "text/html", "cookie": "session=ok"},
341 )
342 assert response.status_code == 200
343 assert response.text == "app"
344
345
346 def test_included_frontend_does_not_block_url_path_for(tmp_path: Path):
347 dist = tmp_path / "dist"
348 write_file(dist / "index.html", "app")
349 frontend_router = APIRouter()
350 frontend_router.frontend("/", directory=dist)
351 api_router = APIRouter()
352
353 @api_router.get("/api", name="read_api")
354 def read_api():
355 return {"ok": True}
356
357 app = FastAPI()
358 app.include_router(frontend_router, prefix="/app")
359 app.include_router(api_router)
360 included_frontend = next(
361 route
362 for route in app.router.routes
363 if hasattr(route, "effective_low_priority_routes")
364 )
365
366 with pytest.raises(NoMatchFound):
367 included_frontend.url_path_for("missing")
368 assert app.url_path_for("read_api") == "/api"
369 response = TestClient(app).get("/api")
370 assert response.status_code == 200
371 assert response.json() == {"ok": True}
372
373
374 def test_include_router_frontend_dependencies_apply_in_nested_order(tmp_path: Path):
375 calls: list[str] = []
376
377 dist = tmp_path / "dist"
378 write_file(dist / "index.html", "app")
379 child = APIRouter(dependencies=[Depends(record_dependency(calls, "child"))])
380 child.frontend("/ui", directory=dist)
381 parent = APIRouter(dependencies=[Depends(record_dependency(calls, "parent"))])
382 parent.include_router(
383 child,
384 prefix="/child",
385 dependencies=[Depends(record_dependency(calls, "parent-include"))],
386 )
387 app = FastAPI(dependencies=[Depends(record_dependency(calls, "app"))])
388 app.include_router(
389 parent,
390 prefix="/parent",
391 dependencies=[Depends(record_dependency(calls, "app-include"))],
392 )
393
394 response = TestClient(app).get("/parent/child/ui/")
395
396 assert response.status_code == 200
397 assert response.text == "app"
398 assert calls == ["app", "app-include", "parent", "parent-include", "child"]
399
400
401 def test_frontend_dependency_overrides_apply(tmp_path: Path):
402 calls: list[str] = []
403
404 def require_cookie() -> None:
405 raise HTTPException(status_code=401) # pragma: no cover
406
407 def allow_cookie() -> None:
408 calls.append("override")
409
410 dist = tmp_path / "dist"
411 write_file(dist / "index.html", "app")
412 app = FastAPI(dependencies=[Depends(require_cookie)])
413 app.dependency_overrides[require_cookie] = allow_cookie
414 app.frontend("/", directory=dist)
415
416 response = TestClient(app).get("/")
417
418 assert response.status_code == 200
419 assert response.text == "app"
420 assert calls == ["override"]
421
422
423 def test_frontend_dependencies_do_not_run_when_api_route_wins(tmp_path: Path):
424 calls: list[str] = []
425
426 def frontend_dependency() -> None:
427 calls.append("frontend") # pragma: no cover
428
429 dist = tmp_path / "dist"
430 write_file(dist / "api", "frontend")
431 router = APIRouter(dependencies=[Depends(frontend_dependency)])
432 router.frontend("/", directory=dist)
433 app = FastAPI()
434
435 @app.get("/api")
436 def read_api():
437 return {"source": "api"}
438
439 app.include_router(router)
440
441 response = TestClient(app).get("/api")
442
443 assert response.status_code == 200
444 assert response.json() == {"source": "api"}
445 assert calls == []
446
447
448 def test_only_selected_frontend_mount_dependencies_run(tmp_path: Path):
449 calls: list[str] = []
450
451 site = tmp_path / "site"
452 admin = tmp_path / "admin"
453 write_file(site / "index.html", "site")
454 write_file(admin / "index.html", "admin")
455 site_router = APIRouter()
456 site_router.frontend("/", directory=site)
457 admin_router = APIRouter()
458 admin_router.frontend("/", directory=admin)
459 app = FastAPI()
460 app.include_router(
461 site_router, dependencies=[Depends(record_dependency(calls, "site"))]
462 )
463 app.include_router(
464 admin_router,
465 prefix="/admin",
466 dependencies=[Depends(record_dependency(calls, "admin"))],
467 )
468
469 response = TestClient(app).get("/admin/")
470
471 assert response.status_code == 200
472 assert response.text == "admin"
473 assert calls == ["admin"]
474
475
476 def test_app_middleware_still_runs_for_frontend_dependencies(tmp_path: Path):
477 calls: list[str] = []
478
479 def frontend_dependency() -> None:
480 calls.append("dependency")
481
482 dist = tmp_path / "dist"
483 write_file(dist / "index.html", "app")
484 app = FastAPI(dependencies=[Depends(frontend_dependency)])
485
486 @app.middleware("http")
487 async def record_middleware(request: Request, call_next):
488 calls.append("middleware-before")
489 response = await call_next(request)
490 calls.append("middleware-after")
491 return response
492
493 app.frontend("/", directory=dist)
494
495 response = TestClient(app).get("/")
496
497 assert response.status_code == 200
498 assert response.text == "app"
499 assert calls == ["middleware-before", "dependency", "middleware-after"]
500
501
502 def test_frontend_dependency_response_headers_and_background_tasks(tmp_path: Path):
503 calls: list[str] = []
504
505 def frontend_dependency(
506 response: Response, background_tasks: BackgroundTasks
507 ) -> None:
508 response.headers["X-Frontend-Dependency"] = "applied"
509 response.set_cookie("frontend", "dependency")
510 background_tasks.add_task(calls.append, "background")
511
512 dist = tmp_path / "dist"
513 write_file(dist / "index.html", "app")
514 app = FastAPI(dependencies=[Depends(frontend_dependency)])
515 app.frontend("/", directory=dist)
516
517 response = TestClient(app).get("/")
518
519 assert response.status_code == 200
520 assert response.text == "app"
521 assert response.headers["X-Frontend-Dependency"] == "applied"
522 assert response.cookies["frontend"] == "dependency"
523 assert calls == ["background"]
524
525
526 def test_frontend_dependency_validation_errors_return_422(tmp_path: Path):
527 def require_token(token: str) -> None:
528 pass # pragma: no cover
529
530 dist = tmp_path / "dist"
531 write_file(dist / "index.html", "app")
532 app = FastAPI(dependencies=[Depends(require_token)])
533 app.frontend("/", directory=dist)
534
535 response = TestClient(app).get("/")
536
537 assert response.status_code == 422
538 assert response.json() == {
539 "detail": [
540 {
541 "type": "missing",
542 "loc": ["query", "token"],
543 "msg": "Field required",
544 "input": None,
545 }
546 ]
547 }
548
549
550 @pytest.mark.anyio
551 async def test_frontend_dependency_restores_existing_dependency_stacks(
552 tmp_path: Path,
553 ):
554 def frontend_dependency() -> None:
555 pass
556
557 dist = tmp_path / "dist"
558 write_file(dist / "index.html", "app")
559 app = FastAPI(dependencies=[Depends(frontend_dependency)])
560 app.frontend("/", directory=dist)
561 assert app.router._frontend_routes is not None
562 inner_stack = AsyncExitStack()
563 function_stack = AsyncExitStack()
564 scope = {
565 "type": "http",
566 "http_version": "1.1",
567 "method": "GET",
568 "scheme": "http",
569 "path": "/",
570 "root_path": "",
571 "query_string": b"",
572 "headers": [],
573 "client": ("testclient", 50000),
574 "server": ("testserver", 80),
575 "fastapi_inner_astack": inner_stack,
576 "fastapi_function_astack": function_stack,
577 }
578 messages = []
579
580 async def receive():
581 return { # pragma: no cover
582 "type": "http.request",
583 "body": b"",
584 "more_body": False,
585 }
586
587 async def send(message):
588 messages.append(message)
589
590 async with inner_stack, function_stack:
591 await app.router._frontend_routes.handle(scope, receive, send)
592
593 assert scope["fastapi_inner_astack"] is inner_stack
594 assert scope["fastapi_function_astack"] is function_stack
595 assert messages[0]["type"] == "http.response.start"
596 assert messages[0]["status"] == 200
597
598
599 def test_non_frontend_low_priority_route_keeps_order_before_frontend(
600 tmp_path: Path,
601 ):
602 async def low_priority_endpoint(request: Request):
603 return PlainTextResponse("low")
604
605 dist = tmp_path / "dist"
606 write_file(dist / "index.html", "frontend")
607 app = FastAPI()
608 app.router._low_priority_routes.append(Route("/admin", low_priority_endpoint))
609 app.router._mark_routes_changed()
610 app.frontend("/", directory=dist)
611
612 response = TestClient(app).get("/admin")
613
614 assert response.status_code == 200
615 assert response.text == "low"
616
617
618 def test_existing_api_route_wins_over_frontend(tmp_path: Path):
619 dist = tmp_path / "dist"
620 write_file(dist / "api" / "users", "frontend")
621 app = FastAPI()
622
623 @app.get("/api/users")
624 def read_users():
625 return {"source": "api"}
626
627 app.frontend("/", directory=dist)
628
629 response = TestClient(app).get("/api/users")
630
631 assert response.status_code == 200
632 assert response.json() == {"source": "api"}
633
634
635 def test_api_route_404_is_not_replaced_by_frontend_fallback(tmp_path: Path):
636 dist = tmp_path / "dist"
637 write_file(dist / "index.html", "frontend")
638 app = FastAPI()
639
640 @app.get("/api/users")
641 def read_users():
642 raise HTTPException(status_code=404, detail="api missing")
643
644 app.frontend("/", directory=dist, fallback="index.html")
645
646 response = TestClient(app).get("/api/users", headers={"accept": "text/html"})
647
648 assert response.status_code == 404
649 assert response.json() == {"detail": "api missing"}
650
651
652 @pytest.mark.parametrize(
653 ("path", "accept"),
654 [
655 ("/dashboard/settings", "text/html"),
656 ("/users/jane.doe", "text/html"),
657 ("/v/1.2.3", "application/xhtml+xml"),
658 ],
659 )
660 def test_index_fallback_for_navigation_request(tmp_path: Path, path: str, accept: str):
661 dist = tmp_path / "dist"
662 write_file(dist / "index.html", "app shell")
663 app = FastAPI()
664 app.frontend("/", directory=dist, fallback="index.html")
665
666 response = TestClient(app).get(path, headers={"accept": accept})
667
668 assert response.status_code == 200
669 assert response.text == "app shell"
670
671
672 def test_index_fallback_parses_accept_parameters(tmp_path: Path):
673 dist = tmp_path / "dist"
674 write_file(dist / "index.html", "app shell")
675 app = FastAPI()
676 app.frontend("/", directory=dist, fallback="index.html")
677
678 response = TestClient(app).get(
679 "/dashboard/settings",
680 headers={"accept": "text/html; charset=utf-8; q=0.8"},
681 )
682
683 assert response.status_code == 200
684 assert response.text == "app shell"
685
686
687 def test_index_fallback_ignores_q_zero_accept(tmp_path: Path):
688 dist = tmp_path / "dist"
689 write_file(dist / "index.html", "app shell")
690 app = FastAPI()
691 app.frontend("/", directory=dist, fallback="index.html")
692
693 response = TestClient(app).get(
694 "/dashboard/settings", headers={"accept": "text/html; q=0.0"}
695 )
696
697 assert response.status_code == 404
698
699
700 def test_index_fallback_respects_explicit_html_rejection_with_wildcard(
701 tmp_path: Path,
702 ):
703 dist = tmp_path / "dist"
704 write_file(dist / "index.html", "app shell")
705 app = FastAPI()
706 app.frontend("/", directory=dist, fallback="index.html")
707
708 response = TestClient(app).get(
709 "/dashboard/settings",
710 headers={"accept": "text/html; q=0, */*; q=1"},
711 )
712
713 assert response.status_code == 404
714
715
716 def test_index_fallback_respects_explicit_xhtml_rejection_with_wildcard(
717 tmp_path: Path,
718 ):
719 dist = tmp_path / "dist"
720 write_file(dist / "index.html", "app shell")
721 app = FastAPI()
722 app.frontend("/", directory=dist, fallback="index.html")
723
724 response = TestClient(app).get(
725 "/dashboard/settings",
726 headers={"accept": "application/xhtml+xml; q=0, */*; q=1"},
727 )
728
729 assert response.status_code == 404
730
731
732 @pytest.mark.parametrize(
733 ("path", "accept"),
734 [
735 ("/assets/missing.js", "*/*"),
736 ("/assets/missing.css", "text/css"),
737 ("/assets/missing.png", "image/png"),
738 ("/api/missing", "application/json"),
739 ("/dashboard/settings", ""),
740 ],
741 )
742 def test_index_fallback_requires_explicit_html_acceptance(
743 tmp_path: Path, path: str, accept: str
744 ):
745 dist = tmp_path / "dist"
746 write_file(dist / "index.html", "app shell")
747 app = FastAPI()
748 app.frontend("/", directory=dist, fallback="index.html")
749
750 response = TestClient(app).get(path, headers={"accept": accept})
751
752 assert response.status_code == 404
753 assert response.text != "app shell"
754
755
756 def test_404_fallback_handles_missing_assets(tmp_path: Path):
757 dist = tmp_path / "dist"
758 write_file(dist / "404.html", "missing")
759 app = FastAPI()
760 app.frontend("/", directory=dist, fallback="404.html")
761
762 response = TestClient(app).get("/assets/missing.js")
763
764 assert response.status_code == 404
765 assert response.text == "missing"
766
767
768 def test_auto_fallback_prefers_404_over_index(tmp_path: Path):
769 dist = tmp_path / "dist"
770 write_file(dist / "index.html", "app shell")
771 write_file(dist / "404.html", "missing")
772 app = FastAPI()
773 app.frontend("/", directory=dist)
774
775 response = TestClient(app).get("/dashboard", headers={"accept": "text/html"})
776
777 assert response.status_code == 404
778 assert response.text == "missing"
779
780
781 def test_auto_fallback_uses_index_when_404_is_missing(tmp_path: Path):
782 dist = tmp_path / "dist"
783 write_file(dist / "index.html", "app shell")
784 app = FastAPI()
785 app.frontend("/", directory=dist)
786
787 response = TestClient(app).get("/dashboard", headers={"accept": "text/html"})
788
789 assert response.status_code == 200
790 assert response.text == "app shell"
791
792
793 def test_auto_fallback_returns_normal_404_without_fallback_files(tmp_path: Path):
794 dist = tmp_path / "dist"
795 dist.mkdir()
796 app = FastAPI()
797 app.frontend("/", directory=dist)
798
799 response = TestClient(app).get("/dashboard", headers={"accept": "text/html"})
800
801 assert response.status_code == 404
802 assert response.json() == {"detail": "Not Found"}
803
804
805 def test_no_fallback_returns_normal_404(tmp_path: Path):
806 dist = tmp_path / "dist"
807 write_file(dist / "index.html", "app shell")
808 app = FastAPI()
809 app.frontend("/", directory=dist, fallback=None)
810
811 response = TestClient(app).get("/dashboard", headers={"accept": "text/html"})
812
813 assert response.status_code == 404
814 assert response.json() == {"detail": "Not Found"}
815
816
817 def test_directory_index_and_redirect(tmp_path: Path):
818 dist = tmp_path / "dist"
819 write_file(dist / "about" / "index.html", "about")
820 app = FastAPI()
821 app.frontend("/", directory=dist)
822 client = TestClient(app)
823
824 redirect = client.get("/about", follow_redirects=False)
825 response = client.get("/about/")
826
827 assert redirect.status_code == 307
828 assert redirect.headers["location"] == "http://testserver/about/"
829 assert response.status_code == 200
830 assert response.text == "about"
831
832
833 def test_path_validation_and_trailing_slash_normalization(tmp_path: Path):
834 dist = tmp_path / "dist"
835 write_file(dist / "asset.txt", "ok")
836 app = FastAPI()
837
838 with pytest.raises(AssertionError):
839 app.frontend("", directory=dist)
840 with pytest.raises(AssertionError):
841 app.frontend("app", directory=dist)
842
843 app.frontend("/app/", directory=dist)
844 response = TestClient(app).get("/app/asset.txt")
845
846 assert response.status_code == 200
847 assert response.text == "ok"
848
849
850 def test_frontend_path_matching_uses_segment_boundaries(tmp_path: Path):
851 dist = tmp_path / "dist"
852 write_file(dist / "index.html", "app")
853 app = FastAPI()
854 app.frontend("/app", directory=dist, fallback="index.html")
855
856 response = TestClient(app).get("/application", headers={"accept": "text/html"})
857
858 assert response.status_code == 404
859
860
861 def test_multiple_frontends_use_longest_matching_prefix(tmp_path: Path):
862 site = tmp_path / "site"
863 admin = tmp_path / "admin"
864 write_file(site / "index.html", "site")
865 write_file(admin / "index.html", "admin")
866 app = FastAPI()
867 app.frontend("/", directory=site, fallback="index.html")
868 app.frontend("/admin", directory=admin, fallback="index.html")
869
870 response = TestClient(app).get("/admin/settings", headers={"accept": "text/html"})
871
872 assert response.status_code == 200
873 assert response.text == "admin"
874
875
876 def test_apirouter_frontend_uses_include_prefix(tmp_path: Path):
877 dist = tmp_path / "admin"
878 write_file(dist / "index.html", "admin")
879 router = APIRouter()
880 router.frontend("/", directory=dist, fallback="index.html")
881 app = FastAPI()
882 app.include_router(router, prefix="/admin")
883
884 response = TestClient(app).get("/admin/settings", headers={"accept": "text/html"})
885
886 assert response.status_code == 200
887 assert response.text == "admin"
888
889
890 def test_global_priority_across_included_routers(tmp_path: Path):
891 dist = tmp_path / "site"
892 write_file(dist / "index.html", "site")
893 site_router = APIRouter()
894 site_router.frontend("/", directory=dist, fallback="index.html")
895 api_router = APIRouter()
896
897 @api_router.get("/api/users")
898 def read_users():
899 return {"source": "api"}
900
901 app = FastAPI()
902 app.include_router(site_router)
903 app.include_router(api_router)
904
905 response = TestClient(app).get("/api/users", headers={"accept": "text/html"})
906
907 assert response.status_code == 200
908 assert response.json() == {"source": "api"}
909
910
911 def test_nested_apirouter_frontend_uses_all_include_prefixes(tmp_path: Path):
912 dist = tmp_path / "admin"
913 write_file(dist / "index.html", "admin")
914 child_router = APIRouter()
915 child_router.frontend("/", directory=dist, fallback="index.html")
916 parent_router = APIRouter()
917 parent_router.include_router(child_router, prefix="/child")
918 app = FastAPI()
919 app.include_router(parent_router, prefix="/parent")
920
921 response = TestClient(app).get(
922 "/parent/child/settings", headers={"accept": "text/html"}
923 )
924
925 assert response.status_code == 200
926 assert response.text == "admin"
927
928
929 def test_low_priority_cache_updates_after_route_added_to_included_router(
930 tmp_path: Path,
931 ):
932 dist = tmp_path / "site"
933 write_file(dist / "index.html", "site")
934 router = APIRouter()
935 router.frontend("/", directory=dist, fallback="index.html")
936 app = FastAPI()
937 app.include_router(router, prefix="/app")
938 client = TestClient(app)
939
940 frontend_response = client.get("/app/dashboard", headers={"accept": "text/html"})
941
942 @router.get("/dashboard")
943 def read_dashboard():
944 return {"source": "api"}
945
946 api_response = client.get("/app/dashboard", headers={"accept": "text/html"})
947
948 assert frontend_response.status_code == 200
949 assert frontend_response.text == "site"
950 assert api_response.status_code == 200
951 assert api_response.json() == {"source": "api"}
952
953
954 def test_normal_route_slash_redirect_wins_before_frontend_redirect(tmp_path: Path):
955 dist = tmp_path / "site"
956 write_file(dist / "api" / "index.html", "frontend")
957 app = FastAPI()
958
959 @app.get("/api/")
960 def read_api():
961 return {"source": "api"}
962
963 app.frontend("/", directory=dist)
964
965 response = TestClient(app).get("/api", follow_redirects=False)
966
967 assert response.status_code == 307
968 assert response.headers["location"] == "http://testserver/api/"
969
970 followed = TestClient(app).get("/api/")
971 assert followed.status_code == 200
972 assert followed.json() == {"source": "api"}
973
974
975 def test_frontend_respects_root_path(tmp_path: Path):
976 dist = tmp_path / "dist"
977 write_file(dist / "assets" / "app.js", "console.log('ok')")
978 app = FastAPI()
979 app.frontend("/app", directory=dist)
980
981 response = TestClient(app, root_path="/proxy").get("/app/assets/app.js")
982
983 assert response.status_code == 200
984 assert response.text == "console.log('ok')"
985
986
987 def test_websocket_route_wins_over_frontend(tmp_path: Path):
988 dist = tmp_path / "dist"
989 write_file(dist / "ws", "frontend")
990 app = FastAPI()
991
992 @app.websocket("/ws")
993 async def websocket_endpoint(websocket: WebSocket):
994 await websocket.accept()
995 await websocket.send_text("websocket")
996 await websocket.close()
997
998 app.frontend("/", directory=dist)
999
1000 with TestClient(app).websocket_connect("/ws") as websocket:
1001 data = websocket.receive_text()
1002
1003 assert data == "websocket"
1004
1005
1006 def test_head_requests_work(tmp_path: Path):
1007 dist = tmp_path / "dist"
1008 write_file(dist / "asset.txt", "ok")
1009 app = FastAPI()
1010 app.frontend("/", directory=dist)
1011
1012 response = TestClient(app).head("/asset.txt")
1013
1014 assert response.status_code == 200
1015 assert response.text == ""
1016 assert response.headers["content-length"] == "2"
1017
1018
1019 def test_head_fallback_request_works(tmp_path: Path):
1020 dist = tmp_path / "dist"
1021 write_file(dist / "index.html", "app shell")
1022 app = FastAPI()
1023 app.frontend("/", directory=dist, fallback="index.html")
1024
1025 response = TestClient(app).head(
1026 "/dashboard/settings", headers={"accept": "text/html"}
1027 )
1028
1029 assert response.status_code == 200
1030 assert response.text == ""
1031 assert response.headers["content-length"] == "9"
1032
1033
1034 def test_unsupported_methods_return_405(tmp_path: Path):
1035 dist = tmp_path / "dist"
1036 write_file(dist / "asset.txt", "ok")
1037 app = FastAPI()
1038 app.frontend("/", directory=dist)
1039
1040 response = TestClient(app).post("/asset.txt")
1041
1042 assert response.status_code == 405
1043
1044
1045 @pytest.mark.parametrize("method", ["POST", "PUT", "PATCH", "DELETE", "OPTIONS"])
1046 def test_unsupported_methods_to_fallback_only_routes_return_404(
1047 tmp_path: Path, method: str
1048 ):
1049 dist = tmp_path / "dist"
1050 write_file(dist / "index.html", "app shell")
1051 app = FastAPI()
1052 app.frontend("/", directory=dist, fallback="index.html")
1053
1054 response = TestClient(app).request(
1055 method, "/dashboard/settings", headers={"accept": "text/html"}
1056 )
1057
1058 assert response.status_code == 404
1059
1060
1061 def test_unsupported_methods_to_frontend_root_and_directory_index_return_405(
1062 tmp_path: Path,
1063 ):
1064 dist = tmp_path / "dist"
1065 write_file(dist / "index.html", "app")
1066 write_file(dist / "about" / "index.html", "about")
1067 app = FastAPI()
1068 app.frontend("/", directory=dist)
1069 client = TestClient(app)
1070
1071 root_response = client.post("/")
1072 directory_response = client.post("/about/")
1073
1074 assert root_response.status_code == 405
1075 assert directory_response.status_code == 405
1076
1077
1078 def test_unsupported_method_to_directory_without_index_returns_404(tmp_path: Path):
1079 dist = tmp_path / "dist"
1080 (dist / "empty").mkdir(parents=True)
1081 write_file(dist / "index.html", "app")
1082 app = FastAPI()
1083 app.frontend("/", directory=dist)
1084
1085 response = TestClient(app).post("/empty/")
1086
1087 assert response.status_code == 404
1088
1089
1090 def test_unsupported_methods_to_fallback_only_routes_ignore_accept(
1091 tmp_path: Path,
1092 ):
1093 dist = tmp_path / "dist"
1094 write_file(dist / "index.html", "app shell")
1095 app = FastAPI()
1096 app.frontend("/", directory=dist, fallback="index.html")
1097
1098 response = TestClient(app).post(
1099 "/dashboard/settings", headers={"accept": "application/json"}
1100 )
1101
1102 assert response.status_code == 404
1103
1104
1105 @pytest.mark.parametrize(
1106 ("fallback", "files"),
1107 [
1108 ("404.html", {"404.html": "missing"}),
1109 ("auto", {"index.html": "app shell"}),
1110 (None, {"index.html": "app shell"}),
1111 ],
1112 )
1113 def test_unsupported_methods_to_fallback_only_routes_return_404_for_fallback_modes(
1114 tmp_path: Path,
1115 fallback: Literal["auto", "index.html", "404.html"] | None,
1116 files: dict[str, str],
1117 ):
1118 dist = tmp_path / "dist"
1119 for file, content in files.items():
1120 write_file(dist / file, content)
1121 app = FastAPI()
1122 app.frontend("/", directory=dist, fallback=fallback)
1123
1124 response = TestClient(app).post(
1125 "/dashboard/settings", headers={"accept": "text/html"}
1126 )
1127
1128 assert response.status_code == 404
1129
1130
1131 def test_apirouter_frontend_unsupported_method_to_fallback_only_route_returns_404(
1132 tmp_path: Path,
1133 ):
1134 dist = tmp_path / "dist"
1135 write_file(dist / "index.html", "admin")
1136 router = APIRouter()
1137 router.frontend("/", directory=dist, fallback="index.html")
1138 app = FastAPI()
1139 app.include_router(router, prefix="/admin")
1140
1141 response = TestClient(app).post(
1142 "/admin/client-route", headers={"accept": "text/html"}
1143 )
1144
1145 assert response.status_code == 404
1146
1147
1148 def test_unsupported_method_uses_longest_matching_frontend_prefix(tmp_path: Path):
1149 site = tmp_path / "site"
1150 admin = tmp_path / "admin"
1151 write_file(site / "admin" / "client-route", "site asset")
1152 write_file(admin / "index.html", "admin")
1153 app = FastAPI()
1154 app.frontend("/", directory=site)
1155 app.frontend("/admin", directory=admin, fallback="index.html")
1156
1157 response = TestClient(app).post(
1158 "/admin/client-route", headers={"accept": "text/html"}
1159 )
1160
1161 assert response.status_code == 404
1162
1163
1164 @pytest.mark.parametrize(
1165 "path",
1166 [
1167 "/../secret.txt",
1168 "/%2e%2e/secret.txt",
1169 "/..%2fsecret.txt",
1170 "/%5c..%5csecret.txt",
1171 "/..%5csecret.txt",
1172 ],
1173 )
1174 def test_path_traversal_cannot_escape_directory(tmp_path: Path, path: str):
1175 dist = tmp_path / "dist"
1176 write_file(dist / "index.html", "app")
1177 write_file(tmp_path / "secret.txt", "secret")
1178 app = FastAPI()
1179 app.frontend("/", directory=dist)
1180
1181 response = TestClient(app).get(path)
1182
1183 assert response.status_code == 404
1184 assert response.text != "secret"
1185
1186
1187 def test_symlink_outside_directory_is_not_served(tmp_path: Path):
1188 dist = tmp_path / "dist"
1189 dist.mkdir()
1190 outside = tmp_path / "secret.txt"
1191 outside.write_text("secret")
1192 link = dist / "secret.txt"
1193 try:
1194 os.symlink(outside, link)
1195 except (OSError, NotImplementedError): # pragma: no cover
1196 pytest.skip("symlinks are not supported")
1197 app = FastAPI()
1198 app.frontend("/", directory=dist)
1199
1200 response = TestClient(app).get("/secret.txt")
1201
1202 assert response.status_code == 404
1203 assert response.text != "secret"
1204
1205
1206 def test_check_dir_true_fails_early_for_missing_directory(monkeypatch, tmp_path: Path):
1207 app = FastAPI()
1208 monkeypatch.chdir(tmp_path)
1209
1210 with pytest.raises(RuntimeError, match="does not exist") as exc_info:
1211 app.frontend("/", directory="missing", check_dir=True)
1212
1213 message = str(exc_info.value)
1214 assert "'missing'" in message
1215 assert str(tmp_path / "missing") in message
1216
1217
1218 def test_check_dir_auto_warns_in_development(monkeypatch, tmp_path: Path):
1219 monkeypatch.setenv("FASTAPI_ENV", "development")
1220 app = FastAPI()
1221
1222 with pytest.warns(UserWarning, match="does not exist") as warnings:
1223 app.frontend("/", directory=tmp_path / "missing")
1224
1225 assert str(tmp_path / "missing") in str(warnings[0].message)
1226 assert warnings[0].filename == __file__
1227
1228
1229 def test_check_dir_auto_router_warning_points_to_user_code(monkeypatch, tmp_path: Path):
1230 monkeypatch.setenv("FASTAPI_ENV", "development")
1231 router = APIRouter()
1232
1233 with pytest.warns(UserWarning, match="does not exist") as warnings:
1234 router.frontend("/", directory=tmp_path / "missing")
1235
1236 assert warnings[0].filename == __file__
1237
1238
1239 def test_check_dir_true_fails_in_development(monkeypatch, tmp_path: Path):
1240 monkeypatch.setenv("FASTAPI_ENV", "development")
1241 app = FastAPI()
1242
1243 with pytest.raises(RuntimeError, match="does not exist"):
1244 app.frontend("/", directory=tmp_path / "missing", check_dir=True)
1245
1246
1247 def test_check_dir_auto_fails_outside_development(monkeypatch, tmp_path: Path):
1248 monkeypatch.setenv("FASTAPI_ENV", "production")
1249 router = APIRouter()
1250
1251 with pytest.raises(RuntimeError, match="does not exist"):
1252 router.frontend("/", directory=tmp_path / "missing")
1253
1254
1255 def test_check_dir_false_allows_missing_directory_and_fails_on_request(tmp_path: Path):
1256 app = FastAPI()
1257 app.frontend("/", directory=tmp_path / "missing", check_dir=False)
1258
1259 with pytest.raises(RuntimeError, match="does not exist"):
1260 TestClient(app).get("/asset.txt")
1261
1262
1263 def test_explicit_fallback_files_fail_clearly_when_missing(monkeypatch, tmp_path: Path):
1264 dist = tmp_path / "dist"
1265 dist.mkdir()
1266 monkeypatch.chdir(tmp_path)
1267 app = FastAPI()
1268
1269 with pytest.raises(RuntimeError, match="index.html") as exc_info:
1270 app.frontend("/", directory="dist", fallback="index.html")
1271
1272 message = str(exc_info.value)
1273 assert "directory 'dist'" in message
1274 assert str(dist) in message
1275
1276 app = FastAPI()
1277 app.frontend("/", directory="dist", fallback="404.html", check_dir=False)
1278
1279 with pytest.raises(RuntimeError, match="404.html") as exc_info:
1280 TestClient(app).get("/missing.js")
1281
1282 message = str(exc_info.value)
1283 assert "directory 'dist'" in message
1284 assert str(dist) in message
1285
1286
1287 def test_frontend_routes_are_not_in_openapi(tmp_path: Path):
1288 dist = tmp_path / "dist"
1289 write_file(dist / "index.html", "app")
1290 app = FastAPI()
1291
1292 @app.get("/api")
1293 def read_api():
1294 return {"ok": True}
1295
1296 app.frontend("/", directory=dist, fallback="index.html")
1297
1298 schema = TestClient(app).get("/openapi.json").json()
1299
1300 assert set(schema["paths"]) == {"/api"}
1301
1302 response = TestClient(app).get("/api")
1303 assert response.status_code == 200
1304 assert response.json() == {"ok": True}
1305
1306
1307 @pytest.mark.parametrize(
1308 ("example", "files", "path", "status_code", "body"),
1309 [
1310 (
1311 "tutorial001_py310.py",
1312 {"asset.txt": "asset"},
1313 "/asset.txt",
1314 200,
1315 "asset",
1316 ),
1317 (
1318 "tutorial002_py310.py",
1319 {"index.html": "index"},
1320 "/dashboard",
1321 200,
1322 "index",
1323 ),
1324 (
1325 "tutorial003_py310.py",
1326 {"404.html": "missing"},
1327 "/missing",
1328 404,
1329 "missing",
1330 ),
1331 (
1332 "tutorial004_py310.py",
1333 {"index.html": "index"},
1334 "/app/dashboard",
1335 200,
1336 "index",
1337 ),
1338 (
1339 "tutorial005_py310.py",
1340 {"index.html": "index"},
1341 "/dashboard",
1342 404,
1343 '{"detail":"Not Found"}',
1344 ),
1345 (
1346 "tutorial006_py310.py",
1347 {"asset.txt": "asset"},
1348 "/asset.txt",
1349 200,
1350 "asset",
1351 ),
1352 ],
1353 )
1354 def test_docs_frontend_examples(
1355 tmp_path: Path,
1356 monkeypatch,
1357 example: str,
1358 files: dict[str, str],
1359 path: str,
1360 status_code: int,
1361 body: str,
1362 ):
1363 dist = tmp_path / "dist"
1364 for file, content in files.items():
1365 write_file(dist / file, content)
1366 monkeypatch.chdir(tmp_path)
1367
1368 namespace = runpy.run_path(
1369 str(Path(__file__).parents[1] / "docs_src" / "frontend" / example)
1370 )
1371
1372 app = namespace["app"]
1373 assert isinstance(app, FastAPI)
1374 response = TestClient(app).get(path, headers={"accept": "text/html"})
1375 assert response.status_code == status_code
1376 assert response.text == body
1377
1378
1379 def test_low_priority_routes_can_store_non_frontend_routes():
1380 async def low_priority_endpoint(request):
1381 return PlainTextResponse("low")
1382
1383 app = FastAPI()
1384 app.router._low_priority_routes.append(Route("/low", low_priority_endpoint))
1385 app.router._mark_routes_changed()
1386
1387 response = TestClient(app).get("/low")
1388
1389 assert response.status_code == 200
1390 assert response.text == "low"
1391
1392
1393 def test_included_low_priority_routes_can_store_non_frontend_routes():
1394 async def low_priority_endpoint(request):
1395 return PlainTextResponse("low")
1396
1397 router = APIRouter()
1398 router._low_priority_routes.append(Route("/low", low_priority_endpoint))
1399 router._mark_routes_changed()
1400 app = FastAPI()
1401 app.include_router(router, prefix="/prefix")
1402
1403 response = TestClient(app).get("/prefix/low")
1404
1405 assert response.status_code == 200
1406 assert response.text == "low"