Debian Codegraph @

tests/test_tutorial/test_security/test_tutorial002.py

raw
1 import importlib
2
3 import pytest
4 from fastapi.testclient import TestClient
5 from inline_snapshot import snapshot
6
7 from ...utils import needs_py310
8
9
10 @pytest.fixture(
11 name="client",
12 params=[
13 pytest.param("tutorial002_py310", marks=needs_py310),
14 pytest.param("tutorial002_an_py310", marks=needs_py310),
15 ],
16 )
17 def get_client(request: pytest.FixtureRequest):
18 mod = importlib.import_module(f"docs_src.security.{request.param}")
19 client = TestClient(mod.app)
20 return client
21
22
23 def test_no_token(client: TestClient):
24 response = client.get("/users/me")
25 assert response.status_code == 401, response.text
26 assert response.json() == {"detail": "Not authenticated"}
27 assert response.headers["WWW-Authenticate"] == "Bearer"
28
29
30 def test_token(client: TestClient):
31 response = client.get("/users/me", headers={"Authorization": "Bearer testtoken"})
32 assert response.status_code == 200, response.text
33 assert response.json() == {
34 "username": "testtokenfakedecoded",
35 "email": "[email protected]",
36 "full_name": "John Doe",
37 "disabled": None,
38 }
39
40
41 def test_openapi_schema(client: TestClient):
42 response = client.get("/openapi.json")
43 assert response.status_code == 200, response.text
44 assert response.json() == snapshot(
45 {
46 "openapi": "3.1.0",
47 "info": {"title": "FastAPI", "version": "0.1.0"},
48 "paths": {
49 "/users/me": {
50 "get": {
51 "responses": {
52 "200": {
53 "description": "Successful Response",
54 "content": {"application/json": {"schema": {}}},
55 }
56 },
57 "summary": "Read Users Me",
58 "operationId": "read_users_me_users_me_get",
59 "security": [{"OAuth2PasswordBearer": []}],
60 }
61 }
62 },
63 "components": {
64 "securitySchemes": {
65 "OAuth2PasswordBearer": {
66 "type": "oauth2",
67 "flows": {"password": {"scopes": {}, "tokenUrl": "token"}},
68 }
69 },
70 },
71 }
72 )