Browse Source

Cover tutorial002_auth docs example and simplify scope guard

FastAPI enforces 100% coverage. Added tutorial test to exercise
tutorial002_auth_py310.py. Removed redundant http scope guard in
__call__ — Starlette's StaticFiles asserts scope["type"] == "http"
itself, so the extra branch was dead code + uncovered.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
pull/15295/head
faisalsaificode 2 months ago
parent
commit
9d346587d0
  1. 35
      fastapi/staticfiles.py
  2. 37
      tests/test_tutorial/test_static_files/test_tutorial002_auth.py

35
fastapi/staticfiles.py

@ -94,22 +94,21 @@ class AuthStaticFiles(StaticFiles):
self.on_error = on_error
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] == "http":
request = Request(scope, receive)
try:
if self._auth_is_async:
await self.auth(request)
else:
await run_in_threadpool(self.auth, request)
except HTTPException as exc:
if self.on_error is not None:
response = await self.on_error(request, exc)
else:
response = PlainTextResponse(
str(exc.detail),
status_code=exc.status_code,
headers=getattr(exc, "headers", None),
)
await response(scope, receive, send)
return
request = Request(scope, receive)
try:
if self._auth_is_async:
await self.auth(request)
else:
await run_in_threadpool(self.auth, request)
except HTTPException as exc:
if self.on_error is not None:
response = await self.on_error(request, exc)
else:
response = PlainTextResponse(
str(exc.detail),
status_code=exc.status_code,
headers=getattr(exc, "headers", None),
)
await response(scope, receive, send)
return
await super().__call__(scope, receive, send)

37
tests/test_tutorial/test_static_files/test_tutorial002_auth.py

@ -0,0 +1,37 @@
import os
from pathlib import Path
import pytest
from fastapi.testclient import TestClient
from tests.utils import workdir_lock
@pytest.fixture(scope="module")
def client():
private_dir: Path = Path(os.getcwd()) / "private_files"
private_dir.mkdir(exist_ok=True)
sample_file = private_dir / "secret.txt"
sample_file.write_text("This is a private file.")
from docs_src.static_files.tutorial002_auth_py310 import app
with TestClient(app) as client:
yield client
sample_file.unlink()
private_dir.rmdir()
@workdir_lock
def test_without_auth(client: TestClient):
response = client.get("/private/secret.txt")
assert response.status_code == 401, response.text
@workdir_lock
def test_with_valid_auth(client: TestClient):
response = client.get(
"/private/secret.txt",
headers={"Authorization": "Bearer mysecrettoken"},
)
assert response.status_code == 200, response.text
assert response.text == "This is a private file."
Loading…
Cancel
Save