Coverage for tests / test_tutorial / test_security / test_tutorial002.py: 100%
23 statements
« prev ^ index » next coverage.py v7.13.3, created at 2026-04-06 01:24 +0000
« prev ^ index » next coverage.py v7.13.3, created at 2026-04-06 01:24 +0000
1import importlib 1abcd
3import pytest 1abcd
4from fastapi.testclient import TestClient 1abcd
5from inline_snapshot import snapshot 1abcd
7from ...utils import needs_py310 1abcd
10@pytest.fixture( 1abcd
11 name="client",
12 params=[
13 pytest.param("tutorial002_py310", marks=needs_py310),
14 pytest.param("tutorial002_an_py310", marks=needs_py310),
15 ],
16)
17def get_client(request: pytest.FixtureRequest): 1abcd
18 mod = importlib.import_module(f"docs_src.security.{request.param}") 1mnopqrstuvwxyzABCDEF
19 client = TestClient(mod.app) 1mnopqrstuvwxyzABCDEF
20 return client 1mnopqrstuvwxyzABCDEF
23def test_no_token(client: TestClient): 1abcd
24 response = client.get("/users/me") 1efghijkl
25 assert response.status_code == 401, response.text 1efghijkl
26 assert response.json() == {"detail": "Not authenticated"} 1efghijkl
27 assert response.headers["WWW-Authenticate"] == "Bearer" 1efghijkl
30def test_token(client: TestClient): 1abcd
31 response = client.get("/users/me", headers={"Authorization": "Bearer testtoken"}) 1GHIJKLMN
32 assert response.status_code == 200, response.text 1GHIJKLMN
33 assert response.json() == { 1GHIJKLMN
34 "username": "testtokenfakedecoded",
35 "email": "[email protected]",
36 "full_name": "John Doe",
37 "disabled": None,
38 }
41def test_openapi_schema(client: TestClient): 1abcd
42 response = client.get("/openapi.json") 1OPQRSTUV
43 assert response.status_code == 200, response.text 1OPQRSTUV
44 assert response.json() == snapshot( 1OPQRSTUV
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 )