Coverage for tests / test_tutorial / test_security / test_tutorial006.py: 100%
35 statements
« prev ^ index » next coverage.py v7.13.3, created at 2026-02-12 18:15 +0000
« prev ^ index » next coverage.py v7.13.3, created at 2026-02-12 18:15 +0000
1import importlib 1abdc
2from base64 import b64encode 1abdc
4import pytest 1abdc
5from fastapi.testclient import TestClient 1abdc
6from inline_snapshot import snapshot 1abdc
9@pytest.fixture( 1abdc
10 name="client",
11 params=[
12 pytest.param("tutorial006_py310"),
13 pytest.param("tutorial006_an_py310"),
14 ],
15)
16def get_client(request: pytest.FixtureRequest): 1abdc
17 mod = importlib.import_module(f"docs_src.security.{request.param}") 1abc
19 client = TestClient(mod.app) 1abc
20 return client 1abc
23def test_security_http_basic(client: TestClient): 1abdc
24 response = client.get("/users/me", auth=("john", "secret")) 1nop
25 assert response.status_code == 200, response.text 1nop
26 assert response.json() == {"username": "john", "password": "secret"} 1nop
29def test_security_http_basic_no_credentials(client: TestClient): 1abdc
30 response = client.get("/users/me") 1hij
31 assert response.json() == {"detail": "Not authenticated"} 1hij
32 assert response.status_code == 401, response.text 1hij
33 assert response.headers["WWW-Authenticate"] == "Basic" 1hij
36def test_security_http_basic_invalid_credentials(client: TestClient): 1abdc
37 response = client.get( 1klm
38 "/users/me", headers={"Authorization": "Basic notabase64token"}
39 )
40 assert response.status_code == 401, response.text 1klm
41 assert response.headers["WWW-Authenticate"] == "Basic" 1klm
42 assert response.json() == {"detail": "Not authenticated"} 1klm
45def test_security_http_basic_non_basic_credentials(client: TestClient): 1abdc
46 payload = b64encode(b"johnsecret").decode("ascii") 1efg
47 auth_header = f"Basic {payload}" 1efg
48 response = client.get("/users/me", headers={"Authorization": auth_header}) 1efg
49 assert response.status_code == 401, response.text 1efg
50 assert response.headers["WWW-Authenticate"] == "Basic" 1efg
51 assert response.json() == {"detail": "Not authenticated"} 1efg
54def test_openapi_schema(client: TestClient): 1abdc
55 response = client.get("/openapi.json") 1qrs
56 assert response.status_code == 200, response.text 1qrs
57 assert response.json() == snapshot( 1qrs
58 {
59 "openapi": "3.1.0",
60 "info": {"title": "FastAPI", "version": "0.1.0"},
61 "paths": {
62 "/users/me": {
63 "get": {
64 "responses": {
65 "200": {
66 "description": "Successful Response",
67 "content": {"application/json": {"schema": {}}},
68 }
69 },
70 "summary": "Read Current User",
71 "operationId": "read_current_user_users_me_get",
72 "security": [{"HTTPBasic": []}],
73 }
74 }
75 },
76 "components": {
77 "securitySchemes": {"HTTPBasic": {"type": "http", "scheme": "basic"}}
78 },
79 }
80 )