Coverage for tests/test_tutorial/test_security/test_tutorial001.py: 100%
27 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-05-05 00:03 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2025-05-05 00:03 +0000
1import importlib 1abcdef
3import pytest 1abcdef
4from fastapi.testclient import TestClient 1abcdef
6from ...utils import needs_py39 1abcdef
9@pytest.fixture( 1abcdef
10 name="client",
11 params=[
12 "tutorial001",
13 "tutorial001_an",
14 pytest.param("tutorial001_an_py39", marks=needs_py39),
15 ],
16)
17def get_client(request: pytest.FixtureRequest): 1abcdef
18 mod = importlib.import_module(f"docs_src.security.{request.param}") 1abcdef
20 client = TestClient(mod.app) 1abcdef
21 return client 1abcdef
24def test_no_token(client: TestClient): 1abcdef
25 response = client.get("/items") 1ghijkl
26 assert response.status_code == 401, response.text 1ghijkl
27 assert response.json() == {"detail": "Not authenticated"} 1ghijkl
28 assert response.headers["WWW-Authenticate"] == "Bearer" 1ghijkl
31def test_token(client: TestClient): 1abcdef
32 response = client.get("/items", headers={"Authorization": "Bearer testtoken"}) 1stuvwx
33 assert response.status_code == 200, response.text 1stuvwx
34 assert response.json() == {"token": "testtoken"} 1stuvwx
37def test_incorrect_token(client: TestClient): 1abcdef
38 response = client.get("/items", headers={"Authorization": "Notexistent testtoken"}) 1mnopqr
39 assert response.status_code == 401, response.text 1mnopqr
40 assert response.json() == {"detail": "Not authenticated"} 1mnopqr
41 assert response.headers["WWW-Authenticate"] == "Bearer" 1mnopqr
44def test_openapi_schema(client: TestClient): 1abcdef
45 response = client.get("/openapi.json") 1yzABCD
46 assert response.status_code == 200, response.text 1yzABCD
47 assert response.json() == { 1yzABCD
48 "openapi": "3.1.0",
49 "info": {"title": "FastAPI", "version": "0.1.0"},
50 "paths": {
51 "/items/": {
52 "get": {
53 "responses": {
54 "200": {
55 "description": "Successful Response",
56 "content": {"application/json": {"schema": {}}},
57 }
58 },
59 "summary": "Read Items",
60 "operationId": "read_items_items__get",
61 "security": [{"OAuth2PasswordBearer": []}],
62 }
63 }
64 },
65 "components": {
66 "securitySchemes": {
67 "OAuth2PasswordBearer": {
68 "type": "oauth2",
69 "flows": {"password": {"scopes": {}, "tokenUrl": "token"}},
70 }
71 }
72 },
73 }