Coverage for tests / test_tutorial / test_security / test_tutorial001.py: 100%
27 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
3import pytest 1abdc
4from fastapi.testclient import TestClient 1abdc
5from inline_snapshot import snapshot 1abdc
8@pytest.fixture( 1abdc
9 name="client",
10 params=[
11 pytest.param("tutorial001_py310"),
12 pytest.param("tutorial001_an_py310"),
13 ],
14)
15def get_client(request: pytest.FixtureRequest): 1abdc
16 mod = importlib.import_module(f"docs_src.security.{request.param}") 1abc
18 client = TestClient(mod.app) 1abc
19 return client 1abc
22def test_no_token(client: TestClient): 1abdc
23 response = client.get("/items") 1efg
24 assert response.status_code == 401, response.text 1efg
25 assert response.json() == {"detail": "Not authenticated"} 1efg
26 assert response.headers["WWW-Authenticate"] == "Bearer" 1efg
29def test_token(client: TestClient): 1abdc
30 response = client.get("/items", headers={"Authorization": "Bearer testtoken"}) 1klm
31 assert response.status_code == 200, response.text 1klm
32 assert response.json() == {"token": "testtoken"} 1klm
35def test_incorrect_token(client: TestClient): 1abdc
36 response = client.get("/items", headers={"Authorization": "Notexistent testtoken"}) 1hij
37 assert response.status_code == 401, response.text 1hij
38 assert response.json() == {"detail": "Not authenticated"} 1hij
39 assert response.headers["WWW-Authenticate"] == "Bearer" 1hij
42def test_openapi_schema(client: TestClient): 1abdc
43 response = client.get("/openapi.json") 1nop
44 assert response.status_code == 200, response.text 1nop
45 assert response.json() == snapshot( 1nop
46 {
47 "openapi": "3.1.0",
48 "info": {"title": "FastAPI", "version": "0.1.0"},
49 "paths": {
50 "/items/": {
51 "get": {
52 "responses": {
53 "200": {
54 "description": "Successful Response",
55 "content": {"application/json": {"schema": {}}},
56 }
57 },
58 "summary": "Read Items",
59 "operationId": "read_items_items__get",
60 "security": [{"OAuth2PasswordBearer": []}],
61 }
62 }
63 },
64 "components": {
65 "securitySchemes": {
66 "OAuth2PasswordBearer": {
67 "type": "oauth2",
68 "flows": {"password": {"scopes": {}, "tokenUrl": "token"}},
69 }
70 }
71 },
72 }
73 )