mirror of
https://github.com/fastapi/fastapi.git
synced 2026-05-18 05:15:46 -04:00
✅ Add missing tests for code examples (#14569)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com> Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> Co-authored-by: Nils-Hero Lindemann <nilsherolindemann@proton.me>
This commit is contained in:
71
tests/test_tutorial/test_security/test_tutorial002.py
Normal file
71
tests/test_tutorial/test_security/test_tutorial002.py
Normal file
@@ -0,0 +1,71 @@
|
||||
import importlib
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from ...utils import needs_py310
|
||||
|
||||
|
||||
@pytest.fixture(
|
||||
name="client",
|
||||
params=[
|
||||
pytest.param("tutorial002_py39"),
|
||||
pytest.param("tutorial002_py310", marks=needs_py310),
|
||||
pytest.param("tutorial002_an_py39"),
|
||||
pytest.param("tutorial002_an_py310", marks=needs_py310),
|
||||
],
|
||||
)
|
||||
def get_client(request: pytest.FixtureRequest):
|
||||
mod = importlib.import_module(f"docs_src.security.{request.param}")
|
||||
client = TestClient(mod.app)
|
||||
return client
|
||||
|
||||
|
||||
def test_no_token(client: TestClient):
|
||||
response = client.get("/users/me")
|
||||
assert response.status_code == 401, response.text
|
||||
assert response.json() == {"detail": "Not authenticated"}
|
||||
assert response.headers["WWW-Authenticate"] == "Bearer"
|
||||
|
||||
|
||||
def test_token(client: TestClient):
|
||||
response = client.get("/users/me", headers={"Authorization": "Bearer testtoken"})
|
||||
assert response.status_code == 200, response.text
|
||||
assert response.json() == {
|
||||
"username": "testtokenfakedecoded",
|
||||
"email": "john@example.com",
|
||||
"full_name": "John Doe",
|
||||
"disabled": None,
|
||||
}
|
||||
|
||||
|
||||
def test_openapi_schema(client: TestClient):
|
||||
response = client.get("/openapi.json")
|
||||
assert response.status_code == 200, response.text
|
||||
assert response.json() == {
|
||||
"openapi": "3.1.0",
|
||||
"info": {"title": "FastAPI", "version": "0.1.0"},
|
||||
"paths": {
|
||||
"/users/me": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful Response",
|
||||
"content": {"application/json": {"schema": {}}},
|
||||
}
|
||||
},
|
||||
"summary": "Read Users Me",
|
||||
"operationId": "read_users_me_users_me_get",
|
||||
"security": [{"OAuth2PasswordBearer": []}],
|
||||
}
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
"securitySchemes": {
|
||||
"OAuth2PasswordBearer": {
|
||||
"type": "oauth2",
|
||||
"flows": {"password": {"scopes": {}, "tokenUrl": "token"}},
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
363
tests/test_tutorial/test_security/test_tutorial004.py
Normal file
363
tests/test_tutorial/test_security/test_tutorial004.py
Normal file
@@ -0,0 +1,363 @@
|
||||
import importlib
|
||||
from types import ModuleType
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from ...utils import needs_py310
|
||||
|
||||
|
||||
@pytest.fixture(
|
||||
name="mod",
|
||||
params=[
|
||||
pytest.param("tutorial004_py39"),
|
||||
pytest.param("tutorial004_py310", marks=needs_py310),
|
||||
pytest.param("tutorial004_an_py39"),
|
||||
pytest.param("tutorial004_an_py310", marks=needs_py310),
|
||||
],
|
||||
)
|
||||
def get_mod(request: pytest.FixtureRequest):
|
||||
mod = importlib.import_module(f"docs_src.security.{request.param}")
|
||||
|
||||
return mod
|
||||
|
||||
|
||||
def get_access_token(*, username="johndoe", password="secret", client: TestClient):
|
||||
data = {"username": username, "password": password}
|
||||
response = client.post("/token", data=data)
|
||||
content = response.json()
|
||||
access_token = content.get("access_token")
|
||||
return access_token
|
||||
|
||||
|
||||
def test_login(mod: ModuleType):
|
||||
client = TestClient(mod.app)
|
||||
response = client.post("/token", data={"username": "johndoe", "password": "secret"})
|
||||
assert response.status_code == 200, response.text
|
||||
content = response.json()
|
||||
assert "access_token" in content
|
||||
assert content["token_type"] == "bearer"
|
||||
|
||||
|
||||
def test_login_incorrect_password(mod: ModuleType):
|
||||
client = TestClient(mod.app)
|
||||
response = client.post(
|
||||
"/token", data={"username": "johndoe", "password": "incorrect"}
|
||||
)
|
||||
assert response.status_code == 401, response.text
|
||||
assert response.json() == {"detail": "Incorrect username or password"}
|
||||
|
||||
|
||||
def test_login_incorrect_username(mod: ModuleType):
|
||||
client = TestClient(mod.app)
|
||||
response = client.post("/token", data={"username": "foo", "password": "secret"})
|
||||
assert response.status_code == 401, response.text
|
||||
assert response.json() == {"detail": "Incorrect username or password"}
|
||||
|
||||
|
||||
def test_no_token(mod: ModuleType):
|
||||
client = TestClient(mod.app)
|
||||
response = client.get("/users/me")
|
||||
assert response.status_code == 401, response.text
|
||||
assert response.json() == {"detail": "Not authenticated"}
|
||||
assert response.headers["WWW-Authenticate"] == "Bearer"
|
||||
|
||||
|
||||
def test_token(mod: ModuleType):
|
||||
client = TestClient(mod.app)
|
||||
access_token = get_access_token(client=client)
|
||||
response = client.get(
|
||||
"/users/me", headers={"Authorization": f"Bearer {access_token}"}
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
assert response.json() == {
|
||||
"username": "johndoe",
|
||||
"full_name": "John Doe",
|
||||
"email": "johndoe@example.com",
|
||||
"disabled": False,
|
||||
}
|
||||
|
||||
|
||||
def test_incorrect_token(mod: ModuleType):
|
||||
client = TestClient(mod.app)
|
||||
response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"})
|
||||
assert response.status_code == 401, response.text
|
||||
assert response.json() == {"detail": "Could not validate credentials"}
|
||||
assert response.headers["WWW-Authenticate"] == "Bearer"
|
||||
|
||||
|
||||
def test_incorrect_token_type(mod: ModuleType):
|
||||
client = TestClient(mod.app)
|
||||
response = client.get(
|
||||
"/users/me", headers={"Authorization": "Notexistent testtoken"}
|
||||
)
|
||||
assert response.status_code == 401, response.text
|
||||
assert response.json() == {"detail": "Not authenticated"}
|
||||
assert response.headers["WWW-Authenticate"] == "Bearer"
|
||||
|
||||
|
||||
def test_verify_password(mod: ModuleType):
|
||||
assert mod.verify_password(
|
||||
"secret", mod.fake_users_db["johndoe"]["hashed_password"]
|
||||
)
|
||||
|
||||
|
||||
def test_get_password_hash(mod: ModuleType):
|
||||
assert mod.get_password_hash("johndoe")
|
||||
|
||||
|
||||
def test_create_access_token(mod: ModuleType):
|
||||
access_token = mod.create_access_token(data={"data": "foo"})
|
||||
assert access_token
|
||||
|
||||
|
||||
def test_token_no_sub(mod: ModuleType):
|
||||
client = TestClient(mod.app)
|
||||
|
||||
response = client.get(
|
||||
"/users/me",
|
||||
headers={
|
||||
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiZm9vIn0.9ynBhuYb4e6aW3oJr_K_TBgwcMTDpRToQIE25L57rOE"
|
||||
},
|
||||
)
|
||||
assert response.status_code == 401, response.text
|
||||
assert response.json() == {"detail": "Could not validate credentials"}
|
||||
assert response.headers["WWW-Authenticate"] == "Bearer"
|
||||
|
||||
|
||||
def test_token_no_username(mod: ModuleType):
|
||||
client = TestClient(mod.app)
|
||||
|
||||
response = client.get(
|
||||
"/users/me",
|
||||
headers={
|
||||
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmb28ifQ.NnExK_dlNAYyzACrXtXDrcWOgGY2JuPbI4eDaHdfK5Y"
|
||||
},
|
||||
)
|
||||
assert response.status_code == 401, response.text
|
||||
assert response.json() == {"detail": "Could not validate credentials"}
|
||||
assert response.headers["WWW-Authenticate"] == "Bearer"
|
||||
|
||||
|
||||
def test_token_nonexistent_user(mod: ModuleType):
|
||||
client = TestClient(mod.app)
|
||||
|
||||
response = client.get(
|
||||
"/users/me",
|
||||
headers={
|
||||
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VybmFtZTpib2IifQ.HcfCW67Uda-0gz54ZWTqmtgJnZeNem0Q757eTa9EZuw"
|
||||
},
|
||||
)
|
||||
assert response.status_code == 401, response.text
|
||||
assert response.json() == {"detail": "Could not validate credentials"}
|
||||
assert response.headers["WWW-Authenticate"] == "Bearer"
|
||||
|
||||
|
||||
def test_token_inactive_user(mod: ModuleType):
|
||||
client = TestClient(mod.app)
|
||||
alice_user_data = {
|
||||
"username": "alice",
|
||||
"full_name": "Alice Wonderson",
|
||||
"email": "alice@example.com",
|
||||
"hashed_password": mod.get_password_hash("secretalice"),
|
||||
"disabled": True,
|
||||
}
|
||||
with patch.dict(f"{mod.__name__}.fake_users_db", {"alice": alice_user_data}):
|
||||
access_token = get_access_token(
|
||||
username="alice", password="secretalice", client=client
|
||||
)
|
||||
response = client.get(
|
||||
"/users/me", headers={"Authorization": f"Bearer {access_token}"}
|
||||
)
|
||||
assert response.status_code == 400, response.text
|
||||
assert response.json() == {"detail": "Inactive user"}
|
||||
|
||||
|
||||
def test_read_items(mod: ModuleType):
|
||||
client = TestClient(mod.app)
|
||||
access_token = get_access_token(client=client)
|
||||
response = client.get(
|
||||
"/users/me/items/", headers={"Authorization": f"Bearer {access_token}"}
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
assert response.json() == [{"item_id": "Foo", "owner": "johndoe"}]
|
||||
|
||||
|
||||
def test_openapi_schema(mod: ModuleType):
|
||||
client = TestClient(mod.app)
|
||||
response = client.get("/openapi.json")
|
||||
assert response.status_code == 200, response.text
|
||||
assert response.json() == {
|
||||
"openapi": "3.1.0",
|
||||
"info": {"title": "FastAPI", "version": "0.1.0"},
|
||||
"paths": {
|
||||
"/token": {
|
||||
"post": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful Response",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {"$ref": "#/components/schemas/Token"}
|
||||
}
|
||||
},
|
||||
},
|
||||
"422": {
|
||||
"description": "Validation Error",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HTTPValidationError"
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
"summary": "Login For Access Token",
|
||||
"operationId": "login_for_access_token_token_post",
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/x-www-form-urlencoded": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Body_login_for_access_token_token_post"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": True,
|
||||
},
|
||||
}
|
||||
},
|
||||
"/users/me/": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful Response",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {"$ref": "#/components/schemas/User"}
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
"summary": "Read Users Me",
|
||||
"operationId": "read_users_me_users_me__get",
|
||||
"security": [{"OAuth2PasswordBearer": []}],
|
||||
}
|
||||
},
|
||||
"/users/me/items/": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful Response",
|
||||
"content": {"application/json": {"schema": {}}},
|
||||
}
|
||||
},
|
||||
"summary": "Read Own Items",
|
||||
"operationId": "read_own_items_users_me_items__get",
|
||||
"security": [{"OAuth2PasswordBearer": []}],
|
||||
}
|
||||
},
|
||||
},
|
||||
"components": {
|
||||
"schemas": {
|
||||
"User": {
|
||||
"title": "User",
|
||||
"required": ["username"],
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"username": {"title": "Username", "type": "string"},
|
||||
"email": {
|
||||
"title": "Email",
|
||||
"anyOf": [{"type": "string"}, {"type": "null"}],
|
||||
},
|
||||
"full_name": {
|
||||
"title": "Full Name",
|
||||
"anyOf": [{"type": "string"}, {"type": "null"}],
|
||||
},
|
||||
"disabled": {
|
||||
"title": "Disabled",
|
||||
"anyOf": [{"type": "boolean"}, {"type": "null"}],
|
||||
},
|
||||
},
|
||||
},
|
||||
"Token": {
|
||||
"title": "Token",
|
||||
"required": ["access_token", "token_type"],
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"access_token": {"title": "Access Token", "type": "string"},
|
||||
"token_type": {"title": "Token Type", "type": "string"},
|
||||
},
|
||||
},
|
||||
"Body_login_for_access_token_token_post": {
|
||||
"title": "Body_login_for_access_token_token_post",
|
||||
"required": ["username", "password"],
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"grant_type": {
|
||||
"title": "Grant Type",
|
||||
"anyOf": [
|
||||
{"pattern": "^password$", "type": "string"},
|
||||
{"type": "null"},
|
||||
],
|
||||
},
|
||||
"username": {"title": "Username", "type": "string"},
|
||||
"password": {
|
||||
"title": "Password",
|
||||
"type": "string",
|
||||
"format": "password",
|
||||
},
|
||||
"scope": {"title": "Scope", "type": "string", "default": ""},
|
||||
"client_id": {
|
||||
"title": "Client Id",
|
||||
"anyOf": [{"type": "string"}, {"type": "null"}],
|
||||
},
|
||||
"client_secret": {
|
||||
"title": "Client Secret",
|
||||
"anyOf": [{"type": "string"}, {"type": "null"}],
|
||||
"format": "password",
|
||||
},
|
||||
},
|
||||
},
|
||||
"ValidationError": {
|
||||
"title": "ValidationError",
|
||||
"required": ["loc", "msg", "type"],
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"loc": {
|
||||
"title": "Location",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"anyOf": [{"type": "string"}, {"type": "integer"}]
|
||||
},
|
||||
},
|
||||
"msg": {"title": "Message", "type": "string"},
|
||||
"type": {"title": "Error Type", "type": "string"},
|
||||
},
|
||||
},
|
||||
"HTTPValidationError": {
|
||||
"title": "HTTPValidationError",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"detail": {
|
||||
"title": "Detail",
|
||||
"type": "array",
|
||||
"items": {"$ref": "#/components/schemas/ValidationError"},
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
"securitySchemes": {
|
||||
"OAuth2PasswordBearer": {
|
||||
"type": "oauth2",
|
||||
"flows": {
|
||||
"password": {
|
||||
"scopes": {},
|
||||
"tokenUrl": "token",
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
89
tests/test_tutorial/test_security/test_tutorial007.py
Normal file
89
tests/test_tutorial/test_security/test_tutorial007.py
Normal file
@@ -0,0 +1,89 @@
|
||||
import importlib
|
||||
from base64 import b64encode
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
|
||||
@pytest.fixture(
|
||||
name="client",
|
||||
params=[
|
||||
pytest.param("tutorial007_py39"),
|
||||
pytest.param("tutorial007_an_py39"),
|
||||
],
|
||||
)
|
||||
def get_client(request: pytest.FixtureRequest):
|
||||
mod = importlib.import_module(f"docs_src.security.{request.param}")
|
||||
return TestClient(mod.app)
|
||||
|
||||
|
||||
def test_security_http_basic(client: TestClient):
|
||||
response = client.get("/users/me", auth=("stanleyjobson", "swordfish"))
|
||||
assert response.status_code == 200, response.text
|
||||
assert response.json() == {"username": "stanleyjobson"}
|
||||
|
||||
|
||||
def test_security_http_basic_no_credentials(client: TestClient):
|
||||
response = client.get("/users/me")
|
||||
assert response.json() == {"detail": "Not authenticated"}
|
||||
assert response.status_code == 401, response.text
|
||||
assert response.headers["WWW-Authenticate"] == "Basic"
|
||||
|
||||
|
||||
def test_security_http_basic_invalid_credentials(client: TestClient):
|
||||
response = client.get(
|
||||
"/users/me", headers={"Authorization": "Basic notabase64token"}
|
||||
)
|
||||
assert response.status_code == 401, response.text
|
||||
assert response.headers["WWW-Authenticate"] == "Basic"
|
||||
assert response.json() == {"detail": "Not authenticated"}
|
||||
|
||||
|
||||
def test_security_http_basic_non_basic_credentials(client: TestClient):
|
||||
payload = b64encode(b"johnsecret").decode("ascii")
|
||||
auth_header = f"Basic {payload}"
|
||||
response = client.get("/users/me", headers={"Authorization": auth_header})
|
||||
assert response.status_code == 401, response.text
|
||||
assert response.headers["WWW-Authenticate"] == "Basic"
|
||||
assert response.json() == {"detail": "Not authenticated"}
|
||||
|
||||
|
||||
def test_security_http_basic_invalid_username(client: TestClient):
|
||||
response = client.get("/users/me", auth=("alice", "swordfish"))
|
||||
assert response.status_code == 401, response.text
|
||||
assert response.json() == {"detail": "Incorrect username or password"}
|
||||
assert response.headers["WWW-Authenticate"] == "Basic"
|
||||
|
||||
|
||||
def test_security_http_basic_invalid_password(client: TestClient):
|
||||
response = client.get("/users/me", auth=("stanleyjobson", "wrongpassword"))
|
||||
assert response.status_code == 401, response.text
|
||||
assert response.json() == {"detail": "Incorrect username or password"}
|
||||
assert response.headers["WWW-Authenticate"] == "Basic"
|
||||
|
||||
|
||||
def test_openapi_schema(client: TestClient):
|
||||
response = client.get("/openapi.json")
|
||||
assert response.status_code == 200, response.text
|
||||
assert response.json() == {
|
||||
"openapi": "3.1.0",
|
||||
"info": {"title": "FastAPI", "version": "0.1.0"},
|
||||
"paths": {
|
||||
"/users/me": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful Response",
|
||||
"content": {"application/json": {"schema": {}}},
|
||||
}
|
||||
},
|
||||
"summary": "Read Current User",
|
||||
"operationId": "read_current_user_users_me_get",
|
||||
"security": [{"HTTPBasic": []}],
|
||||
}
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
"securitySchemes": {"HTTPBasic": {"type": "http", "scheme": "basic"}}
|
||||
},
|
||||
}
|
||||
Reference in New Issue
Block a user