Debian Codegraph @

tests/test_tutorial/test_security/test_tutorial006.py

raw
1 import importlib
2 from base64 import b64encode
3
4 import pytest
5 from fastapi.testclient import TestClient
6 from inline_snapshot import snapshot
7
8
9 @pytest.fixture(
10 name="client",
11 params=[
12 pytest.param("tutorial006_py310"),
13 pytest.param("tutorial006_an_py310"),
14 ],
15 )
16 def get_client(request: pytest.FixtureRequest):
17 mod = importlib.import_module(f"docs_src.security.{request.param}")
18
19 client = TestClient(mod.app)
20 return client
21
22
23 def test_security_http_basic(client: TestClient):
24 response = client.get("/users/me", auth=("john", "secret"))
25 assert response.status_code == 200, response.text
26 assert response.json() == {"username": "john", "password": "secret"}
27
28
29 def test_security_http_basic_no_credentials(client: TestClient):
30 response = client.get("/users/me")
31 assert response.json() == {"detail": "Not authenticated"}
32 assert response.status_code == 401, response.text
33 assert response.headers["WWW-Authenticate"] == "Basic"
34
35
36 def test_security_http_basic_invalid_credentials(client: TestClient):
37 response = client.get(
38 "/users/me", headers={"Authorization": "Basic notabase64token"}
39 )
40 assert response.status_code == 401, response.text
41 assert response.headers["WWW-Authenticate"] == "Basic"
42 assert response.json() == {"detail": "Not authenticated"}
43
44
45 def test_security_http_basic_non_basic_credentials(client: TestClient):
46 payload = b64encode(b"johnsecret").decode("ascii")
47 auth_header = f"Basic {payload}"
48 response = client.get("/users/me", headers={"Authorization": auth_header})
49 assert response.status_code == 401, response.text
50 assert response.headers["WWW-Authenticate"] == "Basic"
51 assert response.json() == {"detail": "Not authenticated"}
52
53
54 def test_openapi_schema(client: TestClient):
55 response = client.get("/openapi.json")
56 assert response.status_code == 200, response.text
57 assert response.json() == snapshot(
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 )