language stringclasses 4
values | source_code stringlengths 2 986k | test_code stringlengths 125 758k | repo_name stringclasses 97
values |
|---|---|---|---|
python | from typing import Annotated
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
item_id: Annotated[int, Path(title="The ID of the item to get")], q: str
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
| import importlib
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
from ...utils import needs_py39, needs_py310
@pytest.fixture(
name="client",
params=[
"tutorial003",
pytest.param("tutorial003_py310", marks=needs_py310),
"tutorial003_an",
pytest.param("tutorial003_an_py39", marks=needs_py39),
pytest.param("tutorial003_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.header_params.{request.param}")
client = TestClient(mod.app)
return client
@pytest.mark.parametrize(
"path,headers,expected_status,expected_response",
[
("/items", None, 200, {"X-Token values": None}),
("/items", {"x-token": "foo"}, 200, {"X-Token values": ["foo"]}),
(
"/items",
[("x-token", "foo"), ("x-token", "bar")],
200,
{"X-Token values": ["foo", "bar"]},
),
],
)
def test(path, headers, expected_status, expected_response, client: TestClient):
response = client.get(path, headers=headers)
assert response.status_code == expected_status
assert response.json() == expected_response
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"get": {
"summary": "Read Items",
"operationId": "read_items_items__get",
"parameters": [
{
"required": False,
"schema": IsDict(
{
"title": "X-Token",
"anyOf": [
{"type": "array", "items": {"type": "string"}},
{"type": "null"},
],
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"title": "X-Token",
"type": "array",
"items": {"type": "string"},
}
),
"name": "x-token",
"in": "header",
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
"components": {
"schemas": {
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {"$ref": "#/components/schemas/ValidationError"},
}
},
},
"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"},
},
},
}
},
}
| fastapi |
python | from typing import Union
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from typing_extensions import Annotated
app = FastAPI()
async def common_parameters(
q: Union[str, None] = None, skip: int = 0, limit: int = 100
):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Items!", "params": commons}
@app.get("/users/")
async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Users!", "params": commons}
client = TestClient(app)
async def override_dependency(q: Union[str, None] = None):
return {"q": q, "skip": 5, "limit": 10}
app.dependency_overrides[common_parameters] = override_dependency
def test_override_in_items():
response = client.get("/items/")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": None, "skip": 5, "limit": 10},
}
def test_override_in_items_with_q():
response = client.get("/items/?q=foo")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
def test_override_in_items_with_params():
response = client.get("/items/?q=foo&skip=100&limit=200")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
| import importlib
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
"tutorial001",
pytest.param("tutorial001_py310", marks=needs_py310),
"tutorial001_an",
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.header_params.{request.param}")
client = TestClient(mod.app)
return client
@pytest.mark.parametrize(
"path,headers,expected_status,expected_response",
[
("/items", None, 200, {"User-Agent": "testclient"}),
("/items", {"X-Header": "notvalid"}, 200, {"User-Agent": "testclient"}),
("/items", {"User-Agent": "FastAPI test"}, 200, {"User-Agent": "FastAPI test"}),
],
)
def test(path, headers, expected_status, expected_response, client: TestClient):
response = client.get(path, headers=headers)
assert response.status_code == expected_status
assert response.json() == expected_response
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Read Items",
"operationId": "read_items_items__get",
"parameters": [
{
"required": False,
"schema": IsDict(
{
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "User-Agent",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{"title": "User-Agent", "type": "string"}
),
"name": "user-agent",
"in": "header",
}
],
}
}
},
"components": {
"schemas": {
"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"},
}
},
},
}
},
}
| fastapi |
python | from typing import Annotated
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
q: str, item_id: Annotated[int, Path(title="The ID of the item to get")]
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
| import importlib
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
from ...utils import needs_py39, needs_py310
@pytest.fixture(
name="client",
params=[
"tutorial002",
pytest.param("tutorial002_py310", marks=needs_py310),
"tutorial002_an",
pytest.param("tutorial002_an_py39", marks=needs_py39),
pytest.param("tutorial002_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.header_params.{request.param}")
client = TestClient(mod.app)
return client
@pytest.mark.parametrize(
"path,headers,expected_status,expected_response",
[
("/items", None, 200, {"strange_header": None}),
("/items", {"X-Header": "notvalid"}, 200, {"strange_header": None}),
(
"/items",
{"strange_header": "FastAPI test"},
200,
{"strange_header": "FastAPI test"},
),
(
"/items",
{"strange-header": "Not really underscore"},
200,
{"strange_header": None},
),
],
)
def test(path, headers, expected_status, expected_response, client: TestClient):
response = client.get(path, headers=headers)
assert response.status_code == expected_status
assert response.json() == expected_response
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Read Items",
"operationId": "read_items_items__get",
"parameters": [
{
"required": False,
"schema": IsDict(
{
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Strange Header",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{"title": "Strange Header", "type": "string"}
),
"name": "strange_header",
"in": "header",
}
],
}
}
},
"components": {
"schemas": {
"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"},
}
},
},
}
},
}
| fastapi |
python | from typing import Union
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from typing_extensions import Annotated
app = FastAPI()
async def common_parameters(
q: Union[str, None] = None, skip: int = 0, limit: int = 100
):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Items!", "params": commons}
@app.get("/users/")
async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Users!", "params": commons}
client = TestClient(app)
async def override_dependency(q: Union[str, None] = None):
return {"q": q, "skip": 5, "limit": 10}
app.dependency_overrides[common_parameters] = override_dependency
def test_override_in_items():
response = client.get("/items/")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": None, "skip": 5, "limit": 10},
}
def test_override_in_items_with_q():
response = client.get("/items/?q=foo")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
def test_override_in_items_with_params():
response = client.get("/items/?q=foo&skip=100&limit=200")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
| import pytest
from fastapi.testclient import TestClient
from docs_src.first_steps.tutorial001 import app
client = TestClient(app)
@pytest.mark.parametrize(
"path,expected_status,expected_response",
[
("/", 200, {"message": "Hello World"}),
("/nonexistent", 404, {"detail": "Not Found"}),
],
)
def test_get_path(path, expected_status, expected_response):
response = client.get(path)
assert response.status_code == expected_status
assert response.json() == expected_response
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"summary": "Root",
"operationId": "root__get",
}
}
},
}
| fastapi |
python | from typing import Union
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from typing_extensions import Annotated
app = FastAPI()
async def common_parameters(
q: Union[str, None] = None, skip: int = 0, limit: int = 100
):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Items!", "params": commons}
@app.get("/users/")
async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Users!", "params": commons}
client = TestClient(app)
async def override_dependency(q: Union[str, None] = None):
return {"q": q, "skip": 5, "limit": 10}
app.dependency_overrides[common_parameters] = override_dependency
def test_override_in_items():
response = client.get("/items/")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": None, "skip": 5, "limit": 10},
}
def test_override_in_items_with_q():
response = client.get("/items/?q=foo")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
def test_override_in_items_with_params():
response = client.get("/items/?q=foo&skip=100&limit=200")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
| import importlib
import pytest
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from ...utils import needs_py39
@pytest.fixture(
name="client",
params=[
"tutorial001_an",
pytest.param("tutorial001_an_py39", marks=needs_py39),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(
f"docs_src.authentication_error_status_code.{request.param}"
)
client = TestClient(mod.app)
return client
def test_get_me(client: TestClient):
response = client.get("/me", headers={"Authorization": "Bearer secrettoken"})
assert response.status_code == 200
assert response.json() == {
"message": "You are authenticated",
"token": "secrettoken",
}
def test_get_me_no_credentials(client: TestClient):
response = client.get("/me")
assert response.status_code == 403
assert response.json() == {"detail": "Not authenticated"}
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/me": {
"get": {
"summary": "Read Me",
"operationId": "read_me_me_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"security": [{"HTTPBearer403": []}],
}
}
},
"components": {
"securitySchemes": {
"HTTPBearer403": {"type": "http", "scheme": "bearer"}
}
},
}
)
| fastapi |
python | from typing import Union
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(q: Union[str, None] = Query(default=None, alias="item-query")):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
| import importlib
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
from ...utils import needs_py39
@pytest.fixture(
name="client",
params=[
"tutorial009",
pytest.param("tutorial009_py39", marks=needs_py39),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.body_nested_models.{request.param}")
client = TestClient(mod.app)
return client
def test_post_body(client: TestClient):
data = {"2": 2.2, "3": 3.3}
response = client.post("/index-weights/", json=data)
assert response.status_code == 200, response.text
assert response.json() == data
def test_post_invalid_body(client: TestClient):
data = {"foo": 2.2, "3": 3.3}
response = client.post("/index-weights/", json=data)
assert response.status_code == 422, response.text
assert response.json() == IsDict(
{
"detail": [
{
"type": "int_parsing",
"loc": ["body", "foo", "[key]"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "foo",
}
]
}
) | IsDict(
# TODO: remove when deprecating Pydantic v1
{
"detail": [
{
"loc": ["body", "__key__"],
"msg": "value is not a valid integer",
"type": "type_error.integer",
}
]
}
)
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": {
"/index-weights/": {
"post": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Create Index Weights",
"operationId": "create_index_weights_index_weights__post",
"requestBody": {
"content": {
"application/json": {
"schema": {
"title": "Weights",
"type": "object",
"additionalProperties": {"type": "number"},
}
}
},
"required": True,
},
}
}
},
"components": {
"schemas": {
"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"},
}
},
},
}
},
}
| fastapi |
python | from typing import Union
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from typing_extensions import Annotated
app = FastAPI()
async def common_parameters(
q: Union[str, None] = None, skip: int = 0, limit: int = 100
):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Items!", "params": commons}
@app.get("/users/")
async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Users!", "params": commons}
client = TestClient(app)
async def override_dependency(q: Union[str, None] = None):
return {"q": q, "skip": 5, "limit": 10}
app.dependency_overrides[common_parameters] = override_dependency
def test_override_in_items():
response = client.get("/items/")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": None, "skip": 5, "limit": 10},
}
def test_override_in_items_with_q():
response = client.get("/items/?q=foo")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
def test_override_in_items_with_params():
response = client.get("/items/?q=foo&skip=100&limit=200")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
| import importlib
from unittest.mock import patch
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
"tutorial001",
pytest.param("tutorial001_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.body.{request.param}")
client = TestClient(mod.app)
return client
def test_body_float(client: TestClient):
response = client.post("/items/", json={"name": "Foo", "price": 50.5})
assert response.status_code == 200
assert response.json() == {
"name": "Foo",
"price": 50.5,
"description": None,
"tax": None,
}
def test_post_with_str_float(client: TestClient):
response = client.post("/items/", json={"name": "Foo", "price": "50.5"})
assert response.status_code == 200
assert response.json() == {
"name": "Foo",
"price": 50.5,
"description": None,
"tax": None,
}
def test_post_with_str_float_description(client: TestClient):
response = client.post(
"/items/", json={"name": "Foo", "price": "50.5", "description": "Some Foo"}
)
assert response.status_code == 200
assert response.json() == {
"name": "Foo",
"price": 50.5,
"description": "Some Foo",
"tax": None,
}
def test_post_with_str_float_description_tax(client: TestClient):
response = client.post(
"/items/",
json={"name": "Foo", "price": "50.5", "description": "Some Foo", "tax": 0.3},
)
assert response.status_code == 200
assert response.json() == {
"name": "Foo",
"price": 50.5,
"description": "Some Foo",
"tax": 0.3,
}
def test_post_with_only_name(client: TestClient):
response = client.post("/items/", json={"name": "Foo"})
assert response.status_code == 422
assert response.json() == IsDict(
{
"detail": [
{
"type": "missing",
"loc": ["body", "price"],
"msg": "Field required",
"input": {"name": "Foo"},
}
]
}
) | IsDict(
# TODO: remove when deprecating Pydantic v1
{
"detail": [
{
"loc": ["body", "price"],
"msg": "field required",
"type": "value_error.missing",
}
]
}
)
def test_post_with_only_name_price(client: TestClient):
response = client.post("/items/", json={"name": "Foo", "price": "twenty"})
assert response.status_code == 422
assert response.json() == IsDict(
{
"detail": [
{
"type": "float_parsing",
"loc": ["body", "price"],
"msg": "Input should be a valid number, unable to parse string as a number",
"input": "twenty",
}
]
}
) | IsDict(
# TODO: remove when deprecating Pydantic v1
{
"detail": [
{
"loc": ["body", "price"],
"msg": "value is not a valid float",
"type": "type_error.float",
}
]
}
)
def test_post_with_no_data(client: TestClient):
response = client.post("/items/", json={})
assert response.status_code == 422
assert response.json() == IsDict(
{
"detail": [
{
"type": "missing",
"loc": ["body", "name"],
"msg": "Field required",
"input": {},
},
{
"type": "missing",
"loc": ["body", "price"],
"msg": "Field required",
"input": {},
},
]
}
) | IsDict(
# TODO: remove when deprecating Pydantic v1
{
"detail": [
{
"loc": ["body", "name"],
"msg": "field required",
"type": "value_error.missing",
},
{
"loc": ["body", "price"],
"msg": "field required",
"type": "value_error.missing",
},
]
}
)
def test_post_with_none(client: TestClient):
response = client.post("/items/", json=None)
assert response.status_code == 422
assert response.json() == IsDict(
{
"detail": [
{
"type": "missing",
"loc": ["body"],
"msg": "Field required",
"input": None,
}
]
}
) | IsDict(
# TODO: remove when deprecating Pydantic v1
{
"detail": [
{
"loc": ["body"],
"msg": "field required",
"type": "value_error.missing",
}
]
}
)
def test_post_broken_body(client: TestClient):
response = client.post(
"/items/",
headers={"content-type": "application/json"},
content="{some broken json}",
)
assert response.status_code == 422, response.text
assert response.json() == IsDict(
{
"detail": [
{
"type": "json_invalid",
"loc": ["body", 1],
"msg": "JSON decode error",
"input": {},
"ctx": {
"error": "Expecting property name enclosed in double quotes"
},
}
]
}
) | IsDict(
# TODO: remove when deprecating Pydantic v1
{
"detail": [
{
"loc": ["body", 1],
"msg": "Expecting property name enclosed in double quotes: line 1 column 2 (char 1)",
"type": "value_error.jsondecode",
"ctx": {
"msg": "Expecting property name enclosed in double quotes",
"doc": "{some broken json}",
"pos": 1,
"lineno": 1,
"colno": 2,
},
}
]
}
)
def test_post_form_for_json(client: TestClient):
response = client.post("/items/", data={"name": "Foo", "price": 50.5})
assert response.status_code == 422, response.text
assert response.json() == IsDict(
{
"detail": [
{
"type": "model_attributes_type",
"loc": ["body"],
"msg": "Input should be a valid dictionary or object to extract fields from",
"input": "name=Foo&price=50.5",
}
]
}
) | IsDict(
# TODO: remove when deprecating Pydantic v1
{
"detail": [
{
"loc": ["body"],
"msg": "value is not a valid dict",
"type": "type_error.dict",
}
]
}
)
def test_explicit_content_type(client: TestClient):
response = client.post(
"/items/",
content='{"name": "Foo", "price": 50.5}',
headers={"Content-Type": "application/json"},
)
assert response.status_code == 200, response.text
def test_geo_json(client: TestClient):
response = client.post(
"/items/",
content='{"name": "Foo", "price": 50.5}',
headers={"Content-Type": "application/geo+json"},
)
assert response.status_code == 200, response.text
def test_no_content_type_is_json(client: TestClient):
response = client.post(
"/items/",
content='{"name": "Foo", "price": 50.5}',
)
assert response.status_code == 200, response.text
assert response.json() == {
"name": "Foo",
"description": None,
"price": 50.5,
"tax": None,
}
def test_wrong_headers(client: TestClient):
data = '{"name": "Foo", "price": 50.5}'
response = client.post(
"/items/", content=data, headers={"Content-Type": "text/plain"}
)
assert response.status_code == 422, response.text
assert response.json() == IsDict(
{
"detail": [
{
"type": "model_attributes_type",
"loc": ["body"],
"msg": "Input should be a valid dictionary or object to extract fields from",
"input": '{"name": "Foo", "price": 50.5}',
}
]
}
) | IsDict(
# TODO: remove when deprecating Pydantic v1
{
"detail": [
{
"loc": ["body"],
"msg": "value is not a valid dict",
"type": "type_error.dict",
}
]
}
)
response = client.post(
"/items/", content=data, headers={"Content-Type": "application/geo+json-seq"}
)
assert response.status_code == 422, response.text
assert response.json() == IsDict(
{
"detail": [
{
"type": "model_attributes_type",
"loc": ["body"],
"msg": "Input should be a valid dictionary or object to extract fields from",
"input": '{"name": "Foo", "price": 50.5}',
}
]
}
) | IsDict(
# TODO: remove when deprecating Pydantic v1
{
"detail": [
{
"loc": ["body"],
"msg": "value is not a valid dict",
"type": "type_error.dict",
}
]
}
)
response = client.post(
"/items/", content=data, headers={"Content-Type": "application/not-really-json"}
)
assert response.status_code == 422, response.text
assert response.json() == IsDict(
{
"detail": [
{
"type": "model_attributes_type",
"loc": ["body"],
"msg": "Input should be a valid dictionary or object to extract fields from",
"input": '{"name": "Foo", "price": 50.5}',
}
]
}
) | IsDict(
# TODO: remove when deprecating Pydantic v1
{
"detail": [
{
"loc": ["body"],
"msg": "value is not a valid dict",
"type": "type_error.dict",
}
]
}
)
def test_other_exceptions(client: TestClient):
with patch("json.loads", side_effect=Exception):
response = client.post("/items/", json={"test": "test2"})
assert response.status_code == 400, response.text
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": {
"/items/": {
"post": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Create Item",
"operationId": "create_item_items__post",
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
}
},
"required": True,
},
}
}
},
"components": {
"schemas": {
"Item": {
"title": "Item",
"required": ["name", "price"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"price": {"title": "Price", "type": "number"},
"description": IsDict(
{
"title": "Description",
"anyOf": [{"type": "string"}, {"type": "null"}],
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{"title": "Description", "type": "string"}
),
"tax": IsDict(
{
"title": "Tax",
"anyOf": [{"type": "number"}, {"type": "null"}],
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{"title": "Tax", "type": "number"}
),
},
},
"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"},
}
},
},
}
},
}
| fastapi |
python | from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
*,
item_id: int = Path(title="The ID of the item to get", gt=0, le=1000),
q: str,
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
| import importlib
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
from ...utils import needs_py39, needs_py310
@pytest.fixture(
name="client",
params=[
"tutorial005",
pytest.param("tutorial005_py310", marks=needs_py310),
"tutorial005_an",
pytest.param("tutorial005_an_py39", marks=needs_py39),
pytest.param("tutorial005_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.schema_extra_example.{request.param}")
client = TestClient(mod.app)
return client
def test_post_body_example(client: TestClient):
response = client.put(
"/items/5",
json={
"name": "Foo",
"description": "A very nice Item",
"price": 35.4,
"tax": 3.2,
},
)
assert response.status_code == 200
def test_openapi_schema(client: TestClient) -> None:
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": {
"/items/{item_id}": {
"put": {
"summary": "Update Item",
"operationId": "update_item_items__item_id__put",
"parameters": [
{
"required": True,
"schema": {"title": "Item Id", "type": "integer"},
"name": "item_id",
"in": "path",
}
],
"requestBody": {
"content": {
"application/json": {
"schema": IsDict({"$ref": "#/components/schemas/Item"})
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"allOf": [
{"$ref": "#/components/schemas/Item"}
],
"title": "Item",
}
),
"examples": {
"normal": {
"summary": "A normal example",
"description": "A **normal** item works correctly.",
"value": {
"name": "Foo",
"description": "A very nice Item",
"price": 35.4,
"tax": 3.2,
},
},
"converted": {
"summary": "An example with converted data",
"description": "FastAPI can convert price `strings` to actual `numbers` automatically",
"value": {"name": "Bar", "price": "35.4"},
},
"invalid": {
"summary": "Invalid data is rejected with an error",
"value": {
"name": "Baz",
"price": "thirty five point four",
},
},
},
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
"components": {
"schemas": {
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {"$ref": "#/components/schemas/ValidationError"},
}
},
},
"Item": {
"title": "Item",
"required": ["name", "price"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"description": IsDict(
{
"title": "Description",
"anyOf": [{"type": "string"}, {"type": "null"}],
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{"title": "Description", "type": "string"}
),
"price": {"title": "Price", "type": "number"},
"tax": IsDict(
{
"title": "Tax",
"anyOf": [{"type": "number"}, {"type": "null"}],
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{"title": "Tax", "type": "number"}
),
},
},
"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"},
},
},
}
},
}
| fastapi |
python | from typing import Union
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from typing_extensions import Annotated
app = FastAPI()
async def common_parameters(
q: Union[str, None] = None, skip: int = 0, limit: int = 100
):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Items!", "params": commons}
@app.get("/users/")
async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Users!", "params": commons}
client = TestClient(app)
async def override_dependency(q: Union[str, None] = None):
return {"q": q, "skip": 5, "limit": 10}
app.dependency_overrides[common_parameters] = override_dependency
def test_override_in_items():
response = client.get("/items/")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": None, "skip": 5, "limit": 10},
}
def test_override_in_items_with_q():
response = client.get("/items/?q=foo")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
def test_override_in_items_with_params():
response = client.get("/items/?q=foo&skip=100&limit=200")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
| import importlib
import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py310, needs_pydanticv2
@pytest.fixture(
name="client",
params=[
"tutorial001",
pytest.param("tutorial001_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.schema_extra_example.{request.param}")
client = TestClient(mod.app)
return client
@needs_pydanticv2
def test_post_body_example(client: TestClient):
response = client.put(
"/items/5",
json={
"name": "Foo",
"description": "A very nice Item",
"price": 35.4,
"tax": 3.2,
},
)
assert response.status_code == 200
@needs_pydanticv2
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
# insert_assert(response.json())
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/{item_id}": {
"put": {
"summary": "Update Item",
"operationId": "update_item_items__item_id__put",
"parameters": [
{
"name": "item_id",
"in": "path",
"required": True,
"schema": {"type": "integer", "title": "Item Id"},
}
],
"requestBody": {
"required": True,
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
}
},
},
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
"components": {
"schemas": {
"HTTPValidationError": {
"properties": {
"detail": {
"items": {"$ref": "#/components/schemas/ValidationError"},
"type": "array",
"title": "Detail",
}
},
"type": "object",
"title": "HTTPValidationError",
},
"Item": {
"properties": {
"name": {"type": "string", "title": "Name"},
"description": {
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Description",
},
"price": {"type": "number", "title": "Price"},
"tax": {
"anyOf": [{"type": "number"}, {"type": "null"}],
"title": "Tax",
},
},
"type": "object",
"required": ["name", "price"],
"title": "Item",
"examples": [
{
"description": "A very nice Item",
"name": "Foo",
"price": 35.4,
"tax": 3.2,
}
],
},
"ValidationError": {
"properties": {
"loc": {
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
"type": "array",
"title": "Location",
},
"msg": {"type": "string", "title": "Message"},
"type": {"type": "string", "title": "Error Type"},
},
"type": "object",
"required": ["loc", "msg", "type"],
"title": "ValidationError",
},
}
},
}
| fastapi |
python | from fastapi import FastAPI
from pydantic import BaseSettings
class Settings(BaseSettings):
app_name: str = "Awesome API"
admin_email: str
items_per_user: int = 50
settings = Settings()
app = FastAPI()
@app.get("/info")
async def info():
return {
"app_name": settings.app_name,
"admin_email": settings.admin_email,
"items_per_user": settings.items_per_user,
}
| import importlib
import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py310, needs_pydanticv1
@pytest.fixture(
name="client",
params=[
"tutorial001_pv1",
pytest.param("tutorial001_pv1_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.schema_extra_example.{request.param}")
client = TestClient(mod.app)
return client
@needs_pydanticv1
def test_post_body_example(client: TestClient):
response = client.put(
"/items/5",
json={
"name": "Foo",
"description": "A very nice Item",
"price": 35.4,
"tax": 3.2,
},
)
assert response.status_code == 200
@needs_pydanticv1
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
# insert_assert(response.json())
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/{item_id}": {
"put": {
"summary": "Update Item",
"operationId": "update_item_items__item_id__put",
"parameters": [
{
"required": True,
"schema": {"type": "integer", "title": "Item Id"},
"name": "item_id",
"in": "path",
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
"components": {
"schemas": {
"HTTPValidationError": {
"properties": {
"detail": {
"items": {"$ref": "#/components/schemas/ValidationError"},
"type": "array",
"title": "Detail",
}
},
"type": "object",
"title": "HTTPValidationError",
},
"Item": {
"properties": {
"name": {"type": "string", "title": "Name"},
"description": {"type": "string", "title": "Description"},
"price": {"type": "number", "title": "Price"},
"tax": {"type": "number", "title": "Tax"},
},
"type": "object",
"required": ["name", "price"],
"title": "Item",
"examples": [
{
"name": "Foo",
"description": "A very nice Item",
"price": 35.4,
"tax": 3.2,
}
],
},
"ValidationError": {
"properties": {
"loc": {
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
"type": "array",
"title": "Location",
},
"msg": {"type": "string", "title": "Message"},
"type": {"type": "string", "title": "Error Type"},
},
"type": "object",
"required": ["loc", "msg", "type"],
"title": "ValidationError",
},
}
},
}
| fastapi |
python | from fastapi import FastAPI, Path
from typing_extensions import Annotated
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
item_id: Annotated[int, Path(title="The ID of the item to get", ge=1)], q: str
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
| import importlib
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
from ...utils import needs_py39, needs_py310
@pytest.fixture(
name="client",
params=[
"tutorial004",
pytest.param("tutorial004_py310", marks=needs_py310),
"tutorial004_an",
pytest.param("tutorial004_an_py39", marks=needs_py39),
pytest.param("tutorial004_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.schema_extra_example.{request.param}")
client = TestClient(mod.app)
return client
def test_post_body_example(client: TestClient):
response = client.put(
"/items/5",
json={
"name": "Foo",
"description": "A very nice Item",
"price": 35.4,
"tax": 3.2,
},
)
assert response.status_code == 200
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": {
"/items/{item_id}": {
"put": {
"summary": "Update Item",
"operationId": "update_item_items__item_id__put",
"parameters": [
{
"required": True,
"schema": {"title": "Item Id", "type": "integer"},
"name": "item_id",
"in": "path",
}
],
"requestBody": {
"content": {
"application/json": {
"schema": IsDict(
{
"$ref": "#/components/schemas/Item",
"examples": [
{
"name": "Foo",
"description": "A very nice Item",
"price": 35.4,
"tax": 3.2,
},
{"name": "Bar", "price": "35.4"},
{
"name": "Baz",
"price": "thirty five point four",
},
],
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"allOf": [
{"$ref": "#/components/schemas/Item"}
],
"title": "Item",
"examples": [
{
"name": "Foo",
"description": "A very nice Item",
"price": 35.4,
"tax": 3.2,
},
{"name": "Bar", "price": "35.4"},
{
"name": "Baz",
"price": "thirty five point four",
},
],
}
)
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
"components": {
"schemas": {
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {"$ref": "#/components/schemas/ValidationError"},
}
},
},
"Item": {
"title": "Item",
"required": ["name", "price"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"description": IsDict(
{
"title": "Description",
"anyOf": [{"type": "string"}, {"type": "null"}],
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{"title": "Description", "type": "string"}
),
"price": {"title": "Price", "type": "number"},
"tax": IsDict(
{
"title": "Tax",
"anyOf": [{"type": "number"}, {"type": "null"}],
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{"title": "Tax", "type": "number"}
),
},
},
"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"},
},
},
}
},
}
| fastapi |
python | from typing import Annotated
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
item_id: Annotated[int, Path(title="The ID of the item to get")], q: str
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
| import importlib
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from tests.utils import needs_py39, needs_py310
@pytest.fixture(
name="client",
params=[
"tutorial003",
pytest.param("tutorial003_py39", marks=needs_py39),
pytest.param("tutorial003_py310", marks=needs_py310),
"tutorial003_an",
pytest.param("tutorial003_an_py39", marks=needs_py39),
pytest.param("tutorial003_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.header_param_models.{request.param}")
client = TestClient(mod.app)
return client
def test_header_param_model(client: TestClient):
response = client.get(
"/items/",
headers=[
("save_data", "true"),
("if_modified_since", "yesterday"),
("traceparent", "123"),
("x_tag", "one"),
("x_tag", "two"),
],
)
assert response.status_code == 200
assert response.json() == {
"host": "testserver",
"save_data": True,
"if_modified_since": "yesterday",
"traceparent": "123",
"x_tag": ["one", "two"],
}
def test_header_param_model_no_underscore(client: TestClient):
response = client.get(
"/items/",
headers=[
("save-data", "true"),
("if-modified-since", "yesterday"),
("traceparent", "123"),
("x-tag", "one"),
("x-tag", "two"),
],
)
assert response.status_code == 422
assert response.json() == snapshot(
{
"detail": [
IsDict(
{
"type": "missing",
"loc": ["header", "save_data"],
"msg": "Field required",
"input": {
"host": "testserver",
"traceparent": "123",
"x_tag": [],
"accept": "*/*",
"accept-encoding": "gzip, deflate",
"connection": "keep-alive",
"user-agent": "testclient",
"save-data": "true",
"if-modified-since": "yesterday",
"x-tag": ["one", "two"],
},
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"type": "value_error.missing",
"loc": ["header", "save_data"],
"msg": "field required",
}
)
]
}
)
def test_header_param_model_defaults(client: TestClient):
response = client.get("/items/", headers=[("save_data", "true")])
assert response.status_code == 200
assert response.json() == {
"host": "testserver",
"save_data": True,
"if_modified_since": None,
"traceparent": None,
"x_tag": [],
}
def test_header_param_model_invalid(client: TestClient):
response = client.get("/items/")
assert response.status_code == 422
assert response.json() == snapshot(
{
"detail": [
IsDict(
{
"type": "missing",
"loc": ["header", "save_data"],
"msg": "Field required",
"input": {
"x_tag": [],
"host": "testserver",
"accept": "*/*",
"accept-encoding": "gzip, deflate",
"connection": "keep-alive",
"user-agent": "testclient",
},
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"type": "value_error.missing",
"loc": ["header", "save_data"],
"msg": "field required",
}
)
]
}
)
def test_header_param_model_extra(client: TestClient):
response = client.get(
"/items/", headers=[("save_data", "true"), ("tool", "plumbus")]
)
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"host": "testserver",
"save_data": True,
"if_modified_since": None,
"traceparent": None,
"x_tag": [],
}
)
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"get": {
"summary": "Read Items",
"operationId": "read_items_items__get",
"parameters": [
{
"name": "host",
"in": "header",
"required": True,
"schema": {"type": "string", "title": "Host"},
},
{
"name": "save_data",
"in": "header",
"required": True,
"schema": {"type": "boolean", "title": "Save Data"},
},
{
"name": "if_modified_since",
"in": "header",
"required": False,
"schema": IsDict(
{
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "If Modified Since",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"type": "string",
"title": "If Modified Since",
}
),
},
{
"name": "traceparent",
"in": "header",
"required": False,
"schema": IsDict(
{
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Traceparent",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"type": "string",
"title": "Traceparent",
}
),
},
{
"name": "x_tag",
"in": "header",
"required": False,
"schema": {
"type": "array",
"items": {"type": "string"},
"default": [],
"title": "X Tag",
},
},
],
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
"components": {
"schemas": {
"HTTPValidationError": {
"properties": {
"detail": {
"items": {
"$ref": "#/components/schemas/ValidationError"
},
"type": "array",
"title": "Detail",
}
},
"type": "object",
"title": "HTTPValidationError",
},
"ValidationError": {
"properties": {
"loc": {
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
"type": "array",
"title": "Location",
},
"msg": {"type": "string", "title": "Message"},
"type": {"type": "string", "title": "Error Type"},
},
"type": "object",
"required": ["loc", "msg", "type"],
"title": "ValidationError",
},
}
},
}
)
| fastapi |
python | from typing import Union
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from typing_extensions import Annotated
app = FastAPI()
async def common_parameters(
q: Union[str, None] = None, skip: int = 0, limit: int = 100
):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Items!", "params": commons}
@app.get("/users/")
async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Users!", "params": commons}
client = TestClient(app)
async def override_dependency(q: Union[str, None] = None):
return {"q": q, "skip": 5, "limit": 10}
app.dependency_overrides[common_parameters] = override_dependency
def test_override_in_items():
response = client.get("/items/")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": None, "skip": 5, "limit": 10},
}
def test_override_in_items_with_q():
response = client.get("/items/?q=foo")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
def test_override_in_items_with_params():
response = client.get("/items/?q=foo&skip=100&limit=200")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
| import importlib
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from tests.utils import needs_py39, needs_py310
@pytest.fixture(
name="client",
params=[
"tutorial001",
pytest.param("tutorial001_py39", marks=needs_py39),
pytest.param("tutorial001_py310", marks=needs_py310),
"tutorial001_an",
pytest.param("tutorial001_an_py39", marks=needs_py39),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.header_param_models.{request.param}")
client = TestClient(mod.app)
return client
def test_header_param_model(client: TestClient):
response = client.get(
"/items/",
headers=[
("save-data", "true"),
("if-modified-since", "yesterday"),
("traceparent", "123"),
("x-tag", "one"),
("x-tag", "two"),
],
)
assert response.status_code == 200
assert response.json() == {
"host": "testserver",
"save_data": True,
"if_modified_since": "yesterday",
"traceparent": "123",
"x_tag": ["one", "two"],
}
def test_header_param_model_defaults(client: TestClient):
response = client.get("/items/", headers=[("save-data", "true")])
assert response.status_code == 200
assert response.json() == {
"host": "testserver",
"save_data": True,
"if_modified_since": None,
"traceparent": None,
"x_tag": [],
}
def test_header_param_model_invalid(client: TestClient):
response = client.get("/items/")
assert response.status_code == 422
assert response.json() == snapshot(
{
"detail": [
IsDict(
{
"type": "missing",
"loc": ["header", "save_data"],
"msg": "Field required",
"input": {
"x_tag": [],
"host": "testserver",
"accept": "*/*",
"accept-encoding": "gzip, deflate",
"connection": "keep-alive",
"user-agent": "testclient",
},
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"type": "value_error.missing",
"loc": ["header", "save_data"],
"msg": "field required",
}
)
]
}
)
def test_header_param_model_extra(client: TestClient):
response = client.get(
"/items/", headers=[("save-data", "true"), ("tool", "plumbus")]
)
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"host": "testserver",
"save_data": True,
"if_modified_since": None,
"traceparent": None,
"x_tag": [],
}
)
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"get": {
"summary": "Read Items",
"operationId": "read_items_items__get",
"parameters": [
{
"name": "host",
"in": "header",
"required": True,
"schema": {"type": "string", "title": "Host"},
},
{
"name": "save-data",
"in": "header",
"required": True,
"schema": {"type": "boolean", "title": "Save Data"},
},
{
"name": "if-modified-since",
"in": "header",
"required": False,
"schema": IsDict(
{
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "If Modified Since",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"type": "string",
"title": "If Modified Since",
}
),
},
{
"name": "traceparent",
"in": "header",
"required": False,
"schema": IsDict(
{
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Traceparent",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"type": "string",
"title": "Traceparent",
}
),
},
{
"name": "x-tag",
"in": "header",
"required": False,
"schema": {
"type": "array",
"items": {"type": "string"},
"default": [],
"title": "X Tag",
},
},
],
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
"components": {
"schemas": {
"HTTPValidationError": {
"properties": {
"detail": {
"items": {
"$ref": "#/components/schemas/ValidationError"
},
"type": "array",
"title": "Detail",
}
},
"type": "object",
"title": "HTTPValidationError",
},
"ValidationError": {
"properties": {
"loc": {
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
"type": "array",
"title": "Location",
},
"msg": {"type": "string", "title": "Message"},
"type": {"type": "string", "title": "Error Type"},
},
"type": "object",
"required": ["loc", "msg", "type"],
"title": "ValidationError",
},
}
},
}
)
| fastapi |
python | from typing import Annotated
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
q: str, item_id: Annotated[int, Path(title="The ID of the item to get")]
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
| import importlib
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from tests.utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial002", marks=needs_pydanticv2),
pytest.param("tutorial002_py310", marks=[needs_py310, needs_pydanticv2]),
pytest.param("tutorial002_an", marks=needs_pydanticv2),
pytest.param("tutorial002_an_py39", marks=[needs_py39, needs_pydanticv2]),
pytest.param("tutorial002_an_py310", marks=[needs_py310, needs_pydanticv2]),
pytest.param("tutorial002_pv1", marks=[needs_pydanticv1, needs_pydanticv1]),
pytest.param("tutorial002_pv1_py310", marks=[needs_py310, needs_pydanticv1]),
pytest.param("tutorial002_pv1_an", marks=[needs_pydanticv1]),
pytest.param("tutorial002_pv1_an_py39", marks=[needs_py39, needs_pydanticv1]),
pytest.param("tutorial002_pv1_an_py310", marks=[needs_py310, needs_pydanticv1]),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.header_param_models.{request.param}")
client = TestClient(mod.app)
client.headers.clear()
return client
def test_header_param_model(client: TestClient):
response = client.get(
"/items/",
headers=[
("save-data", "true"),
("if-modified-since", "yesterday"),
("traceparent", "123"),
("x-tag", "one"),
("x-tag", "two"),
],
)
assert response.status_code == 200, response.text
assert response.json() == {
"host": "testserver",
"save_data": True,
"if_modified_since": "yesterday",
"traceparent": "123",
"x_tag": ["one", "two"],
}
def test_header_param_model_defaults(client: TestClient):
response = client.get("/items/", headers=[("save-data", "true")])
assert response.status_code == 200
assert response.json() == {
"host": "testserver",
"save_data": True,
"if_modified_since": None,
"traceparent": None,
"x_tag": [],
}
def test_header_param_model_invalid(client: TestClient):
response = client.get("/items/")
assert response.status_code == 422
assert response.json() == snapshot(
{
"detail": [
IsDict(
{
"type": "missing",
"loc": ["header", "save_data"],
"msg": "Field required",
"input": {"x_tag": [], "host": "testserver"},
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"type": "value_error.missing",
"loc": ["header", "save_data"],
"msg": "field required",
}
)
]
}
)
def test_header_param_model_extra(client: TestClient):
response = client.get(
"/items/", headers=[("save-data", "true"), ("tool", "plumbus")]
)
assert response.status_code == 422, response.text
assert response.json() == snapshot(
{
"detail": [
IsDict(
{
"type": "extra_forbidden",
"loc": ["header", "tool"],
"msg": "Extra inputs are not permitted",
"input": "plumbus",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"type": "value_error.extra",
"loc": ["header", "tool"],
"msg": "extra fields not permitted",
}
)
]
}
)
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"get": {
"summary": "Read Items",
"operationId": "read_items_items__get",
"parameters": [
{
"name": "host",
"in": "header",
"required": True,
"schema": {"type": "string", "title": "Host"},
},
{
"name": "save-data",
"in": "header",
"required": True,
"schema": {"type": "boolean", "title": "Save Data"},
},
{
"name": "if-modified-since",
"in": "header",
"required": False,
"schema": IsDict(
{
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "If Modified Since",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"type": "string",
"title": "If Modified Since",
}
),
},
{
"name": "traceparent",
"in": "header",
"required": False,
"schema": IsDict(
{
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Traceparent",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"type": "string",
"title": "Traceparent",
}
),
},
{
"name": "x-tag",
"in": "header",
"required": False,
"schema": {
"type": "array",
"items": {"type": "string"},
"default": [],
"title": "X Tag",
},
},
],
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
"components": {
"schemas": {
"HTTPValidationError": {
"properties": {
"detail": {
"items": {
"$ref": "#/components/schemas/ValidationError"
},
"type": "array",
"title": "Detail",
}
},
"type": "object",
"title": "HTTPValidationError",
},
"ValidationError": {
"properties": {
"loc": {
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
"type": "array",
"title": "Location",
},
"msg": {"type": "string", "title": "Message"},
"type": {"type": "string", "title": "Error Type"},
},
"type": "object",
"required": ["loc", "msg", "type"],
"title": "ValidationError",
},
}
},
}
)
| fastapi |
python | from typing import Annotated
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
item_id: Annotated[int, Path(title="The ID of the item to get")], q: str
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
| import pytest
def test_main():
with pytest.warns(DeprecationWarning):
from docs_src.app_testing.tutorial003 import test_read_items
test_read_items()
| fastapi |
python | from typing import Union
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from typing_extensions import Annotated
app = FastAPI()
async def common_parameters(
q: Union[str, None] = None, skip: int = 0, limit: int = 100
):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Items!", "params": commons}
@app.get("/users/")
async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Users!", "params": commons}
client = TestClient(app)
async def override_dependency(q: Union[str, None] = None):
return {"q": q, "skip": 5, "limit": 10}
app.dependency_overrides[common_parameters] = override_dependency
def test_override_in_items():
response = client.get("/items/")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": None, "skip": 5, "limit": 10},
}
def test_override_in_items_with_q():
response = client.get("/items/?q=foo")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
def test_override_in_items_with_params():
response = client.get("/items/?q=foo&skip=100&limit=200")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
| import importlib
from types import ModuleType
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
from ...utils import needs_py39, needs_py310
@pytest.fixture(
name="mod",
params=[
"tutorial001",
pytest.param("tutorial001_py310", marks=needs_py310),
"tutorial001_an",
pytest.param("tutorial001_an_py39", marks=needs_py39),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
def get_mod(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.cookie_params.{request.param}")
return mod
@pytest.mark.parametrize(
"path,cookies,expected_status,expected_response",
[
("/items", None, 200, {"ads_id": None}),
("/items", {"ads_id": "ads_track"}, 200, {"ads_id": "ads_track"}),
(
"/items",
{"ads_id": "ads_track", "session": "cookiesession"},
200,
{"ads_id": "ads_track"},
),
("/items", {"session": "cookiesession"}, 200, {"ads_id": None}),
],
)
def test(path, cookies, expected_status, expected_response, mod: ModuleType):
client = TestClient(mod.app, cookies=cookies)
response = client.get(path)
assert response.status_code == expected_status
assert response.json() == expected_response
def test_openapi_schema(mod: ModuleType):
client = TestClient(mod.app)
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Read Items",
"operationId": "read_items_items__get",
"parameters": [
{
"required": False,
"schema": IsDict(
{
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Ads Id",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{"title": "Ads Id", "type": "string"}
),
"name": "ads_id",
"in": "cookie",
}
],
}
}
},
"components": {
"schemas": {
"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"},
}
},
},
}
},
}
| fastapi |
python | from typing import Union
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from typing_extensions import Annotated
app = FastAPI()
async def common_parameters(
q: Union[str, None] = None, skip: int = 0, limit: int = 100
):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Items!", "params": commons}
@app.get("/users/")
async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Users!", "params": commons}
client = TestClient(app)
async def override_dependency(q: Union[str, None] = None):
return {"q": q, "skip": 5, "limit": 10}
app.dependency_overrides[common_parameters] = override_dependency
def test_override_in_items():
response = client.get("/items/")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": None, "skip": 5, "limit": 10},
}
def test_override_in_items_with_q():
response = client.get("/items/?q=foo")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
def test_override_in_items_with_params():
response = client.get("/items/?q=foo&skip=100&limit=200")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
| import importlib
from types import ModuleType
import pytest
from ...utils import needs_py39, needs_py310
@pytest.fixture(
name="test_module",
params=[
"tutorial001",
pytest.param("tutorial001_py310", marks=needs_py310),
"tutorial001_an",
pytest.param("tutorial001_an_py39", marks=needs_py39),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
def get_test_module(request: pytest.FixtureRequest) -> ModuleType:
mod: ModuleType = importlib.import_module(
f"docs_src.dependency_testing.{request.param}"
)
return mod
def test_override_in_items_run(test_module: ModuleType):
test_override_in_items = test_module.test_override_in_items
test_override_in_items()
def test_override_in_items_with_q_run(test_module: ModuleType):
test_override_in_items_with_q = test_module.test_override_in_items_with_q
test_override_in_items_with_q()
def test_override_in_items_with_params_run(test_module: ModuleType):
test_override_in_items_with_params = test_module.test_override_in_items_with_params
test_override_in_items_with_params()
def test_override_in_users(test_module: ModuleType):
client = test_module.client
response = client.get("/users/")
assert response.status_code == 200, response.text
assert response.json() == {
"message": "Hello Users!",
"params": {"q": None, "skip": 5, "limit": 10},
}
def test_override_in_users_with_q(test_module: ModuleType):
client = test_module.client
response = client.get("/users/?q=foo")
assert response.status_code == 200, response.text
assert response.json() == {
"message": "Hello Users!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
def test_override_in_users_with_params(test_module: ModuleType):
client = test_module.client
response = client.get("/users/?q=foo&skip=100&limit=200")
assert response.status_code == 200, response.text
assert response.json() == {
"message": "Hello Users!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
def test_normal_app(test_module: ModuleType):
app = test_module.app
client = test_module.client
app.dependency_overrides = None
response = client.get("/items/?q=foo&skip=100&limit=200")
assert response.status_code == 200, response.text
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 100, "limit": 200},
}
| fastapi |
python | from typing import Union
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(
hidden_query: Union[str, None] = Query(default=None, include_in_schema=False),
):
if hidden_query:
return {"hidden_query": hidden_query}
else:
return {"hidden_query": "Not found"}
| import importlib
import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py39, needs_py310
@pytest.fixture(
name="client",
params=[
"tutorial014",
pytest.param("tutorial014_py310", marks=needs_py310),
"tutorial014_an",
pytest.param("tutorial014_an_py39", marks=needs_py39),
pytest.param("tutorial014_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(
f"docs_src.query_params_str_validations.{request.param}"
)
client = TestClient(mod.app)
return client
def test_hidden_query(client: TestClient):
response = client.get("/items?hidden_query=somevalue")
assert response.status_code == 200, response.text
assert response.json() == {"hidden_query": "somevalue"}
def test_no_hidden_query(client: TestClient):
response = client.get("/items")
assert response.status_code == 200, response.text
assert response.json() == {"hidden_query": "Not found"}
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": {
"/items/": {
"get": {
"summary": "Read Items",
"operationId": "read_items_items__get",
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
"components": {
"schemas": {
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {"$ref": "#/components/schemas/ValidationError"},
}
},
},
"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"},
},
},
}
},
}
| fastapi |
python | import random
from typing import Annotated, Union
from fastapi import FastAPI
from pydantic import AfterValidator
app = FastAPI()
data = {
"isbn-9781529046137": "The Hitchhiker's Guide to the Galaxy",
"imdb-tt0371724": "The Hitchhiker's Guide to the Galaxy",
"isbn-9781439512982": "Isaac Asimov: The Complete Stories, Vol. 2",
}
def check_valid_id(id: str):
if not id.startswith(("isbn-", "imdb-")):
raise ValueError('Invalid ID format, it must start with "isbn-" or "imdb-"')
return id
@app.get("/items/")
async def read_items(
id: Annotated[Union[str, None], AfterValidator(check_valid_id)] = None,
):
if id:
item = data.get(id)
else:
id, item = random.choice(list(data.items()))
return {"id": id, "name": item}
| import importlib
import pytest
from dirty_equals import IsStr
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from ...utils import needs_py39, needs_py310, needs_pydanticv2
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial015_an", marks=needs_pydanticv2),
pytest.param("tutorial015_an_py310", marks=(needs_py310, needs_pydanticv2)),
pytest.param("tutorial015_an_py39", marks=(needs_py39, needs_pydanticv2)),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(
f"docs_src.query_params_str_validations.{request.param}"
)
client = TestClient(mod.app)
return client
def test_get_random_item(client: TestClient):
response = client.get("/items")
assert response.status_code == 200, response.text
assert response.json() == {"id": IsStr(), "name": IsStr()}
def test_get_item(client: TestClient):
response = client.get("/items?id=isbn-9781529046137")
assert response.status_code == 200, response.text
assert response.json() == {
"id": "isbn-9781529046137",
"name": "The Hitchhiker's Guide to the Galaxy",
}
def test_get_item_does_not_exist(client: TestClient):
response = client.get("/items?id=isbn-nope")
assert response.status_code == 200, response.text
assert response.json() == {"id": "isbn-nope", "name": None}
def test_get_invalid_item(client: TestClient):
response = client.get("/items?id=wtf-yes")
assert response.status_code == 422, response.text
assert response.json() == snapshot(
{
"detail": [
{
"type": "value_error",
"loc": ["query", "id"],
"msg": 'Value error, Invalid ID format, it must start with "isbn-" or "imdb-"',
"input": "wtf-yes",
"ctx": {"error": {}},
}
]
}
)
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"get": {
"summary": "Read Items",
"operationId": "read_items_items__get",
"parameters": [
{
"name": "id",
"in": "query",
"required": False,
"schema": {
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Id",
},
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
"components": {
"schemas": {
"HTTPValidationError": {
"properties": {
"detail": {
"items": {
"$ref": "#/components/schemas/ValidationError"
},
"type": "array",
"title": "Detail",
}
},
"type": "object",
"title": "HTTPValidationError",
},
"ValidationError": {
"properties": {
"loc": {
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
"type": "array",
"title": "Location",
},
"msg": {"type": "string", "title": "Message"},
"type": {"type": "string", "title": "Error Type"},
},
"type": "object",
"required": ["loc", "msg", "type"],
"title": "ValidationError",
},
}
},
}
)
| fastapi |
python | from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(q: list[str] | None = Query(default=None)):
query_items = {"q": q}
return query_items
| import importlib
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
from ...utils import needs_py39, needs_py310
@pytest.fixture(
name="client",
params=[
"tutorial011",
pytest.param("tutorial011_py39", marks=needs_py310),
pytest.param("tutorial011_py310", marks=needs_py310),
"tutorial011_an",
pytest.param("tutorial011_an_py39", marks=needs_py39),
pytest.param("tutorial011_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(
f"docs_src.query_params_str_validations.{request.param}"
)
client = TestClient(mod.app)
return client
def test_multi_query_values(client: TestClient):
url = "/items/?q=foo&q=bar"
response = client.get(url)
assert response.status_code == 200, response.text
assert response.json() == {"q": ["foo", "bar"]}
def test_query_no_values(client: TestClient):
url = "/items/"
response = client.get(url)
assert response.status_code == 200, response.text
assert response.json() == {"q": 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": {
"/items/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Read Items",
"operationId": "read_items_items__get",
"parameters": [
{
"required": False,
"schema": IsDict(
{
"anyOf": [
{"type": "array", "items": {"type": "string"}},
{"type": "null"},
],
"title": "Q",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"title": "Q",
"type": "array",
"items": {"type": "string"},
}
),
"name": "q",
"in": "query",
}
],
}
}
},
"components": {
"schemas": {
"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"},
}
},
},
}
},
}
| fastapi |
python | from fastapi import FastAPI, Query
from typing_extensions import Annotated
app = FastAPI()
@app.get("/items/")
async def read_items(q: Annotated[list, Query()] = []):
query_items = {"q": q}
return query_items
| import importlib
import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py39
@pytest.fixture(
name="client",
params=[
"tutorial013",
"tutorial013_an",
pytest.param("tutorial013_an_py39", marks=needs_py39),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(
f"docs_src.query_params_str_validations.{request.param}"
)
client = TestClient(mod.app)
return client
def test_multi_query_values(client: TestClient):
url = "/items/?q=foo&q=bar"
response = client.get(url)
assert response.status_code == 200, response.text
assert response.json() == {"q": ["foo", "bar"]}
def test_query_no_values(client: TestClient):
url = "/items/"
response = client.get(url)
assert response.status_code == 200, response.text
assert response.json() == {"q": []}
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": {
"/items/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Read Items",
"operationId": "read_items_items__get",
"parameters": [
{
"required": False,
"schema": {
"title": "Q",
"type": "array",
"items": {},
"default": [],
},
"name": "q",
"in": "query",
}
],
}
}
},
"components": {
"schemas": {
"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"},
}
},
},
}
},
}
| fastapi |
python | from typing import List
from fastapi import FastAPI, Query
from typing_extensions import Annotated
app = FastAPI()
@app.get("/items/")
async def read_items(q: Annotated[List[str], Query()] = ["foo", "bar"]):
query_items = {"q": q}
return query_items
| import importlib
import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py39
@pytest.fixture(
name="client",
params=[
"tutorial012",
pytest.param("tutorial012_py39", marks=needs_py39),
"tutorial012_an",
pytest.param("tutorial012_an_py39", marks=needs_py39),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(
f"docs_src.query_params_str_validations.{request.param}"
)
client = TestClient(mod.app)
return client
def test_default_query_values(client: TestClient):
url = "/items/"
response = client.get(url)
assert response.status_code == 200, response.text
assert response.json() == {"q": ["foo", "bar"]}
def test_multi_query_values(client: TestClient):
url = "/items/?q=baz&q=foobar"
response = client.get(url)
assert response.status_code == 200, response.text
assert response.json() == {"q": ["baz", "foobar"]}
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": {
"/items/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Read Items",
"operationId": "read_items_items__get",
"parameters": [
{
"required": False,
"schema": {
"title": "Q",
"type": "array",
"items": {"type": "string"},
"default": ["foo", "bar"],
},
"name": "q",
"in": "query",
}
],
}
}
},
"components": {
"schemas": {
"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"},
}
},
},
}
},
}
| fastapi |
python | from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(
q: str | None = Query(
default=None,
alias="item-query",
title="Query string",
description="Query string for the items to search in the database that have a good match",
min_length=3,
max_length=50,
pattern="^fixedquery$",
deprecated=True,
),
):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
| import importlib
import pytest
from dirty_equals import IsDict
from fastapi._compat import PYDANTIC_VERSION_MINOR_TUPLE
from fastapi.testclient import TestClient
from ...utils import needs_py39, needs_py310
@pytest.fixture(
name="client",
params=[
"tutorial010",
pytest.param("tutorial010_py310", marks=needs_py310),
"tutorial010_an",
pytest.param("tutorial010_an_py39", marks=needs_py39),
pytest.param("tutorial010_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(
f"docs_src.query_params_str_validations.{request.param}"
)
client = TestClient(mod.app)
return client
def test_query_params_str_validations_no_query(client: TestClient):
response = client.get("/items/")
assert response.status_code == 200
assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
def test_query_params_str_validations_item_query_fixedquery(client: TestClient):
response = client.get("/items/", params={"item-query": "fixedquery"})
assert response.status_code == 200
assert response.json() == {
"items": [{"item_id": "Foo"}, {"item_id": "Bar"}],
"q": "fixedquery",
}
def test_query_params_str_validations_q_fixedquery(client: TestClient):
response = client.get("/items/", params={"q": "fixedquery"})
assert response.status_code == 200
assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
def test_query_params_str_validations_item_query_nonregexquery(client: TestClient):
response = client.get("/items/", params={"item-query": "nonregexquery"})
assert response.status_code == 422
assert response.json() == IsDict(
{
"detail": [
{
"type": "string_pattern_mismatch",
"loc": ["query", "item-query"],
"msg": "String should match pattern '^fixedquery$'",
"input": "nonregexquery",
"ctx": {"pattern": "^fixedquery$"},
}
]
}
) | IsDict(
# TODO: remove when deprecating Pydantic v1
{
"detail": [
{
"ctx": {"pattern": "^fixedquery$"},
"loc": ["query", "item-query"],
"msg": 'string does not match regex "^fixedquery$"',
"type": "value_error.str.regex",
}
]
}
)
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": {
"/items/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Read Items",
"operationId": "read_items_items__get",
"parameters": [
{
"description": "Query string for the items to search in the database that have a good match",
"required": False,
"deprecated": True,
"schema": IsDict(
{
"anyOf": [
{
"type": "string",
"minLength": 3,
"maxLength": 50,
"pattern": "^fixedquery$",
},
{"type": "null"},
],
"title": "Query string",
"description": "Query string for the items to search in the database that have a good match",
# See https://github.com/pydantic/pydantic/blob/80353c29a824c55dea4667b328ba8f329879ac9f/tests/test_fastapi.sh#L25-L34.
**(
{"deprecated": True}
if PYDANTIC_VERSION_MINOR_TUPLE >= (2, 10)
else {}
),
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"title": "Query string",
"maxLength": 50,
"minLength": 3,
"pattern": "^fixedquery$",
"type": "string",
"description": "Query string for the items to search in the database that have a good match",
}
),
"name": "item-query",
"in": "query",
}
],
}
}
},
"components": {
"schemas": {
"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"},
}
},
},
}
},
}
| fastapi |
python | from typing import Union
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from typing_extensions import Annotated
app = FastAPI()
async def common_parameters(
q: Union[str, None] = None, skip: int = 0, limit: int = 100
):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Items!", "params": commons}
@app.get("/users/")
async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Users!", "params": commons}
client = TestClient(app)
async def override_dependency(q: Union[str, None] = None):
return {"q": q, "skip": 5, "limit": 10}
app.dependency_overrides[common_parameters] = override_dependency
def test_override_in_items():
response = client.get("/items/")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": None, "skip": 5, "limit": 10},
}
def test_override_in_items_with_q():
response = client.get("/items/?q=foo")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
def test_override_in_items_with_params():
response = client.get("/items/?q=foo&skip=100&limit=200")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
| import importlib
import pytest
from fastapi.testclient import TestClient
from pytest import MonkeyPatch
from ...utils import needs_pydanticv1, needs_pydanticv2
@pytest.fixture(
name="app",
params=[
pytest.param("tutorial001", marks=needs_pydanticv2),
pytest.param("tutorial001_pv1", marks=needs_pydanticv1),
],
)
def get_app(request: pytest.FixtureRequest, monkeypatch: MonkeyPatch):
monkeypatch.setenv("ADMIN_EMAIL", "admin@example.com")
mod = importlib.import_module(f"docs_src.settings.{request.param}")
return mod.app
def test_settings(app):
client = TestClient(app)
response = client.get("/info")
assert response.status_code == 200, response.text
assert response.json() == {
"app_name": "Awesome API",
"admin_email": "admin@example.com",
"items_per_user": 50,
}
| fastapi |
python | from fastapi import Depends, FastAPI
app = FastAPI()
def get_username():
try:
yield "Rick"
finally:
print("Cleanup up before response is sent")
@app.get("/users/me")
def get_user_me(username: str = Depends(get_username, scope="function")):
return username
| import importlib
import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py39
@pytest.fixture(
name="client",
params=[
"tutorial008e",
"tutorial008e_an",
pytest.param("tutorial008e_an_py39", marks=needs_py39),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.dependencies.{request.param}")
client = TestClient(mod.app)
return client
def test_get_users_me(client: TestClient):
response = client.get("/users/me")
assert response.status_code == 200, response.text
assert response.json() == "Rick"
| fastapi |
python | from fastapi import Depends, FastAPI, HTTPException
from typing_extensions import Annotated
app = FastAPI()
class InternalError(Exception):
pass
def get_username():
try:
yield "Rick"
except InternalError:
print("Oops, we didn't raise again, Britney 😱")
@app.get("/items/{item_id}")
def get_item(item_id: str, username: Annotated[str, Depends(get_username)]):
if item_id == "portal-gun":
raise InternalError(
f"The portal gun is too dangerous to be owned by {username}"
)
if item_id != "plumbus":
raise HTTPException(
status_code=404, detail="Item not found, there's only a plumbus here"
)
return item_id
| import importlib
from types import ModuleType
import pytest
from fastapi.exceptions import FastAPIError
from fastapi.testclient import TestClient
from ...utils import needs_py39
@pytest.fixture(
name="mod",
params=[
"tutorial008c",
"tutorial008c_an",
pytest.param("tutorial008c_an_py39", marks=needs_py39),
],
)
def get_mod(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.dependencies.{request.param}")
return mod
def test_get_no_item(mod: ModuleType):
client = TestClient(mod.app)
response = client.get("/items/foo")
assert response.status_code == 404, response.text
assert response.json() == {"detail": "Item not found, there's only a plumbus here"}
def test_get(mod: ModuleType):
client = TestClient(mod.app)
response = client.get("/items/plumbus")
assert response.status_code == 200, response.text
assert response.json() == "plumbus"
def test_fastapi_error(mod: ModuleType):
client = TestClient(mod.app)
with pytest.raises(FastAPIError) as exc_info:
client.get("/items/portal-gun")
assert "raising an exception and a dependency with yield" in exc_info.value.args[0]
def test_internal_server_error(mod: ModuleType):
client = TestClient(mod.app, raise_server_exceptions=False)
response = client.get("/items/portal-gun")
assert response.status_code == 500, response.text
assert response.text == "Internal Server Error"
| fastapi |
python | from typing import Union
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from typing_extensions import Annotated
app = FastAPI()
async def common_parameters(
q: Union[str, None] = None, skip: int = 0, limit: int = 100
):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Items!", "params": commons}
@app.get("/users/")
async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Users!", "params": commons}
client = TestClient(app)
async def override_dependency(q: Union[str, None] = None):
return {"q": q, "skip": 5, "limit": 10}
app.dependency_overrides[common_parameters] = override_dependency
def test_override_in_items():
response = client.get("/items/")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": None, "skip": 5, "limit": 10},
}
def test_override_in_items_with_q():
response = client.get("/items/?q=foo")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
def test_override_in_items_with_params():
response = client.get("/items/?q=foo&skip=100&limit=200")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
| import importlib
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
from ...utils import needs_py39, needs_py310
@pytest.fixture(
name="client",
params=[
"tutorial001",
pytest.param("tutorial001_py310", marks=needs_py310),
"tutorial001_an",
pytest.param("tutorial001_an_py39", marks=needs_py39),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.dependencies.{request.param}")
client = TestClient(mod.app)
return client
@pytest.mark.parametrize(
"path,expected_status,expected_response",
[
("/items", 200, {"q": None, "skip": 0, "limit": 100}),
("/items?q=foo", 200, {"q": "foo", "skip": 0, "limit": 100}),
("/items?q=foo&skip=5", 200, {"q": "foo", "skip": 5, "limit": 100}),
("/items?q=foo&skip=5&limit=30", 200, {"q": "foo", "skip": 5, "limit": 30}),
("/users", 200, {"q": None, "skip": 0, "limit": 100}),
],
)
def test_get(path, expected_status, expected_response, client: TestClient):
response = client.get(path)
assert response.status_code == expected_status
assert response.json() == expected_response
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": {
"/items/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Read Items",
"operationId": "read_items_items__get",
"parameters": [
{
"required": False,
"schema": IsDict(
{
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Q",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{"title": "Q", "type": "string"}
),
"name": "q",
"in": "query",
},
{
"required": False,
"schema": {
"title": "Skip",
"type": "integer",
"default": 0,
},
"name": "skip",
"in": "query",
},
{
"required": False,
"schema": {
"title": "Limit",
"type": "integer",
"default": 100,
},
"name": "limit",
"in": "query",
},
],
}
},
"/users/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Read Users",
"operationId": "read_users_users__get",
"parameters": [
{
"required": False,
"schema": IsDict(
{
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Q",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{"title": "Q", "type": "string"}
),
"name": "q",
"in": "query",
},
{
"required": False,
"schema": {
"title": "Skip",
"type": "integer",
"default": 0,
},
"name": "skip",
"in": "query",
},
{
"required": False,
"schema": {
"title": "Limit",
"type": "integer",
"default": 100,
},
"name": "limit",
"in": "query",
},
],
}
},
},
"components": {
"schemas": {
"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"},
}
},
},
}
},
}
| fastapi |
python | from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException
app = FastAPI()
data = {
"plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"},
"portal-gun": {"description": "Gun to create portals", "owner": "Rick"},
}
class OwnerError(Exception):
pass
def get_username():
try:
yield "Rick"
except OwnerError as e:
raise HTTPException(status_code=400, detail=f"Owner error: {e}")
@app.get("/items/{item_id}")
def get_item(item_id: str, username: Annotated[str, Depends(get_username)]):
if item_id not in data:
raise HTTPException(status_code=404, detail="Item not found")
item = data[item_id]
if item["owner"] != username:
raise OwnerError(username)
return item
| import importlib
import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py39
@pytest.fixture(
name="client",
params=[
"tutorial008b",
"tutorial008b_an",
pytest.param("tutorial008b_an_py39", marks=needs_py39),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.dependencies.{request.param}")
client = TestClient(mod.app)
return client
def test_get_no_item(client: TestClient):
response = client.get("/items/foo")
assert response.status_code == 404, response.text
assert response.json() == {"detail": "Item not found"}
def test_owner_error(client: TestClient):
response = client.get("/items/plumbus")
assert response.status_code == 400, response.text
assert response.json() == {"detail": "Owner error: Rick"}
def test_get_item(client: TestClient):
response = client.get("/items/portal-gun")
assert response.status_code == 200, response.text
assert response.json() == {"description": "Gun to create portals", "owner": "Rick"}
| fastapi |
python | from fastapi import Depends, FastAPI, HTTPException
app = FastAPI()
class InternalError(Exception):
pass
def get_username():
try:
yield "Rick"
except InternalError:
print("We don't swallow the internal error here, we raise again 😎")
raise
@app.get("/items/{item_id}")
def get_item(item_id: str, username: str = Depends(get_username)):
if item_id == "portal-gun":
raise InternalError(
f"The portal gun is too dangerous to be owned by {username}"
)
if item_id != "plumbus":
raise HTTPException(
status_code=404, detail="Item not found, there's only a plumbus here"
)
return item_id
| import importlib
from types import ModuleType
import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py39
@pytest.fixture(
name="mod",
params=[
"tutorial008d",
"tutorial008d_an",
pytest.param("tutorial008d_an_py39", marks=needs_py39),
],
)
def get_mod(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.dependencies.{request.param}")
return mod
def test_get_no_item(mod: ModuleType):
client = TestClient(mod.app)
response = client.get("/items/foo")
assert response.status_code == 404, response.text
assert response.json() == {"detail": "Item not found, there's only a plumbus here"}
def test_get(mod: ModuleType):
client = TestClient(mod.app)
response = client.get("/items/plumbus")
assert response.status_code == 200, response.text
assert response.json() == "plumbus"
def test_internal_error(mod: ModuleType):
client = TestClient(mod.app)
with pytest.raises(mod.InternalError) as exc_info:
client.get("/items/portal-gun")
assert (
exc_info.value.args[0] == "The portal gun is too dangerous to be owned by Rick"
)
def test_internal_server_error(mod: ModuleType):
client = TestClient(mod.app, raise_server_exceptions=False)
response = client.get("/items/portal-gun")
assert response.status_code == 500, response.text
assert response.text == "Internal Server Error"
| fastapi |
python | from fastapi import FastAPI, Path
from typing_extensions import Annotated
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
item_id: Annotated[int, Path(title="The ID of the item to get", ge=1)], q: str
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
| import importlib
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
from ...utils import needs_py39, needs_py310
@pytest.fixture(
name="client",
params=[
"tutorial004",
pytest.param("tutorial004_py310", marks=needs_py310),
"tutorial004_an",
pytest.param("tutorial004_an_py39", marks=needs_py39),
pytest.param("tutorial004_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.dependencies.{request.param}")
client = TestClient(mod.app)
return client
@pytest.mark.parametrize(
"path,expected_status,expected_response",
[
(
"/items",
200,
{
"items": [
{"item_name": "Foo"},
{"item_name": "Bar"},
{"item_name": "Baz"},
]
},
),
(
"/items?q=foo",
200,
{
"items": [
{"item_name": "Foo"},
{"item_name": "Bar"},
{"item_name": "Baz"},
],
"q": "foo",
},
),
(
"/items?q=foo&skip=1",
200,
{"items": [{"item_name": "Bar"}, {"item_name": "Baz"}], "q": "foo"},
),
(
"/items?q=bar&limit=2",
200,
{"items": [{"item_name": "Foo"}, {"item_name": "Bar"}], "q": "bar"},
),
(
"/items?q=bar&skip=1&limit=1",
200,
{"items": [{"item_name": "Bar"}], "q": "bar"},
),
(
"/items?limit=1&q=bar&skip=1",
200,
{"items": [{"item_name": "Bar"}], "q": "bar"},
),
],
)
def test_get(path, expected_status, expected_response, client: TestClient):
response = client.get(path)
assert response.status_code == expected_status
assert response.json() == expected_response
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": {
"/items/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Read Items",
"operationId": "read_items_items__get",
"parameters": [
{
"required": False,
"schema": IsDict(
{
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Q",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{"title": "Q", "type": "string"}
),
"name": "q",
"in": "query",
},
{
"required": False,
"schema": {
"title": "Skip",
"type": "integer",
"default": 0,
},
"name": "skip",
"in": "query",
},
{
"required": False,
"schema": {
"title": "Limit",
"type": "integer",
"default": 100,
},
"name": "limit",
"in": "query",
},
],
}
}
},
"components": {
"schemas": {
"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"},
}
},
},
}
},
}
| fastapi |
python | from typing import List
from fastapi import FastAPI, Query
from typing_extensions import Annotated
app = FastAPI()
@app.get("/items/")
async def read_items(q: Annotated[List[str], Query()] = ["foo", "bar"]):
query_items = {"q": q}
return query_items
| import importlib
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
from ...utils import needs_py39
@pytest.fixture(
name="client",
params=[
"tutorial012",
"tutorial012_an",
pytest.param("tutorial012_an_py39", marks=needs_py39),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.dependencies.{request.param}")
client = TestClient(mod.app)
return client
def test_get_no_headers_items(client: TestClient):
response = client.get("/items/")
assert response.status_code == 422, response.text
assert response.json() == IsDict(
{
"detail": [
{
"type": "missing",
"loc": ["header", "x-token"],
"msg": "Field required",
"input": None,
},
{
"type": "missing",
"loc": ["header", "x-key"],
"msg": "Field required",
"input": None,
},
]
}
) | IsDict(
# TODO: remove when deprecating Pydantic v1
{
"detail": [
{
"loc": ["header", "x-token"],
"msg": "field required",
"type": "value_error.missing",
},
{
"loc": ["header", "x-key"],
"msg": "field required",
"type": "value_error.missing",
},
]
}
)
def test_get_no_headers_users(client: TestClient):
response = client.get("/users/")
assert response.status_code == 422, response.text
assert response.json() == IsDict(
{
"detail": [
{
"type": "missing",
"loc": ["header", "x-token"],
"msg": "Field required",
"input": None,
},
{
"type": "missing",
"loc": ["header", "x-key"],
"msg": "Field required",
"input": None,
},
]
}
) | IsDict(
# TODO: remove when deprecating Pydantic v1
{
"detail": [
{
"loc": ["header", "x-token"],
"msg": "field required",
"type": "value_error.missing",
},
{
"loc": ["header", "x-key"],
"msg": "field required",
"type": "value_error.missing",
},
]
}
)
def test_get_invalid_one_header_items(client: TestClient):
response = client.get("/items/", headers={"X-Token": "invalid"})
assert response.status_code == 400, response.text
assert response.json() == {"detail": "X-Token header invalid"}
def test_get_invalid_one_users(client: TestClient):
response = client.get("/users/", headers={"X-Token": "invalid"})
assert response.status_code == 400, response.text
assert response.json() == {"detail": "X-Token header invalid"}
def test_get_invalid_second_header_items(client: TestClient):
response = client.get(
"/items/", headers={"X-Token": "fake-super-secret-token", "X-Key": "invalid"}
)
assert response.status_code == 400, response.text
assert response.json() == {"detail": "X-Key header invalid"}
def test_get_invalid_second_header_users(client: TestClient):
response = client.get(
"/users/", headers={"X-Token": "fake-super-secret-token", "X-Key": "invalid"}
)
assert response.status_code == 400, response.text
assert response.json() == {"detail": "X-Key header invalid"}
def test_get_valid_headers_items(client: TestClient):
response = client.get(
"/items/",
headers={
"X-Token": "fake-super-secret-token",
"X-Key": "fake-super-secret-key",
},
)
assert response.status_code == 200, response.text
assert response.json() == [{"item": "Portal Gun"}, {"item": "Plumbus"}]
def test_get_valid_headers_users(client: TestClient):
response = client.get(
"/users/",
headers={
"X-Token": "fake-super-secret-token",
"X-Key": "fake-super-secret-key",
},
)
assert response.status_code == 200, response.text
assert response.json() == [{"username": "Rick"}, {"username": "Morty"}]
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": {
"/items/": {
"get": {
"summary": "Read Items",
"operationId": "read_items_items__get",
"parameters": [
{
"required": True,
"schema": {"title": "X-Token", "type": "string"},
"name": "x-token",
"in": "header",
},
{
"required": True,
"schema": {"title": "X-Key", "type": "string"},
"name": "x-key",
"in": "header",
},
],
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
"/users/": {
"get": {
"summary": "Read Users",
"operationId": "read_users_users__get",
"parameters": [
{
"required": True,
"schema": {"title": "X-Token", "type": "string"},
"name": "x-token",
"in": "header",
},
{
"required": True,
"schema": {"title": "X-Key", "type": "string"},
"name": "x-key",
"in": "header",
},
],
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
},
"components": {
"schemas": {
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {"$ref": "#/components/schemas/ValidationError"},
}
},
},
"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"},
},
},
}
},
}
| fastapi |
python | from fastapi import FastAPI, Path, Query
from typing_extensions import Annotated
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
*,
item_id: Annotated[int, Path(title="The ID of the item to get", ge=0, le=1000)],
q: str,
size: Annotated[float, Query(gt=0, lt=10.5)],
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
if size:
results.update({"size": size})
return results
| import importlib
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
from ...utils import needs_py39
@pytest.fixture(
name="client",
params=[
"tutorial006",
"tutorial006_an",
pytest.param("tutorial006_an_py39", marks=needs_py39),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.dependencies.{request.param}")
client = TestClient(mod.app)
return client
def test_get_no_headers(client: TestClient):
response = client.get("/items/")
assert response.status_code == 422, response.text
assert response.json() == IsDict(
{
"detail": [
{
"type": "missing",
"loc": ["header", "x-token"],
"msg": "Field required",
"input": None,
},
{
"type": "missing",
"loc": ["header", "x-key"],
"msg": "Field required",
"input": None,
},
]
}
) | IsDict(
# TODO: remove when deprecating Pydantic v1
{
"detail": [
{
"loc": ["header", "x-token"],
"msg": "field required",
"type": "value_error.missing",
},
{
"loc": ["header", "x-key"],
"msg": "field required",
"type": "value_error.missing",
},
]
}
)
def test_get_invalid_one_header(client: TestClient):
response = client.get("/items/", headers={"X-Token": "invalid"})
assert response.status_code == 400, response.text
assert response.json() == {"detail": "X-Token header invalid"}
def test_get_invalid_second_header(client: TestClient):
response = client.get(
"/items/", headers={"X-Token": "fake-super-secret-token", "X-Key": "invalid"}
)
assert response.status_code == 400, response.text
assert response.json() == {"detail": "X-Key header invalid"}
def test_get_valid_headers(client: TestClient):
response = client.get(
"/items/",
headers={
"X-Token": "fake-super-secret-token",
"X-Key": "fake-super-secret-key",
},
)
assert response.status_code == 200, response.text
assert response.json() == [{"item": "Foo"}, {"item": "Bar"}]
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": {
"/items/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Read Items",
"operationId": "read_items_items__get",
"parameters": [
{
"required": True,
"schema": {"title": "X-Token", "type": "string"},
"name": "x-token",
"in": "header",
},
{
"required": True,
"schema": {"title": "X-Key", "type": "string"},
"name": "x-key",
"in": "header",
},
],
}
}
},
"components": {
"schemas": {
"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"},
}
},
},
}
},
}
| fastapi |
python | from typing import Union
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from typing_extensions import Annotated
app = FastAPI()
async def common_parameters(
q: Union[str, None] = None, skip: int = 0, limit: int = 100
):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Items!", "params": commons}
@app.get("/users/")
async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Users!", "params": commons}
client = TestClient(app)
async def override_dependency(q: Union[str, None] = None):
return {"q": q, "skip": 5, "limit": 10}
app.dependency_overrides[common_parameters] = override_dependency
def test_override_in_items():
response = client.get("/items/")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": None, "skip": 5, "limit": 10},
}
def test_override_in_items_with_q():
response = client.get("/items/?q=foo")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
def test_override_in_items_with_params():
response = client.get("/items/?q=foo&skip=100&limit=200")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
| import importlib
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
from ...utils import needs_py39, needs_py310
@pytest.fixture(
name="client",
params=[
"tutorial001",
pytest.param("tutorial001_py310", marks=needs_py310),
"tutorial001_an",
pytest.param("tutorial001_an_py39", marks=needs_py39),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.body_fields.{request.param}")
client = TestClient(mod.app)
return client
def test_items_5(client: TestClient):
response = client.put("/items/5", json={"item": {"name": "Foo", "price": 3.0}})
assert response.status_code == 200
assert response.json() == {
"item_id": 5,
"item": {"name": "Foo", "price": 3.0, "description": None, "tax": None},
}
def test_items_6(client: TestClient):
response = client.put(
"/items/6",
json={
"item": {
"name": "Bar",
"price": 0.2,
"description": "Some bar",
"tax": "5.4",
}
},
)
assert response.status_code == 200
assert response.json() == {
"item_id": 6,
"item": {
"name": "Bar",
"price": 0.2,
"description": "Some bar",
"tax": 5.4,
},
}
def test_invalid_price(client: TestClient):
response = client.put("/items/5", json={"item": {"name": "Foo", "price": -3.0}})
assert response.status_code == 422
assert response.json() == IsDict(
{
"detail": [
{
"type": "greater_than",
"loc": ["body", "item", "price"],
"msg": "Input should be greater than 0",
"input": -3.0,
"ctx": {"gt": 0.0},
}
]
}
) | IsDict(
# TODO: remove when deprecating Pydantic v1
{
"detail": [
{
"ctx": {"limit_value": 0},
"loc": ["body", "item", "price"],
"msg": "ensure this value is greater than 0",
"type": "value_error.number.not_gt",
}
]
}
)
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": {
"/items/{item_id}": {
"put": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Update Item",
"operationId": "update_item_items__item_id__put",
"parameters": [
{
"required": True,
"schema": {"title": "Item Id", "type": "integer"},
"name": "item_id",
"in": "path",
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Body_update_item_items__item_id__put"
}
}
},
"required": True,
},
}
}
},
"components": {
"schemas": {
"Item": {
"title": "Item",
"required": ["name", "price"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"description": IsDict(
{
"title": "The description of the item",
"anyOf": [
{"maxLength": 300, "type": "string"},
{"type": "null"},
],
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"title": "The description of the item",
"maxLength": 300,
"type": "string",
}
),
"price": {
"title": "Price",
"exclusiveMinimum": 0.0,
"type": "number",
"description": "The price must be greater than zero",
},
"tax": IsDict(
{
"title": "Tax",
"anyOf": [{"type": "number"}, {"type": "null"}],
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{"title": "Tax", "type": "number"}
),
},
},
"Body_update_item_items__item_id__put": {
"title": "Body_update_item_items__item_id__put",
"required": ["item"],
"type": "object",
"properties": {"item": {"$ref": "#/components/schemas/Item"}},
},
"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"},
}
},
},
}
},
}
| fastapi |
python | from typing import Union
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from typing_extensions import Annotated
app = FastAPI()
async def common_parameters(
q: Union[str, None] = None, skip: int = 0, limit: int = 100
):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Items!", "params": commons}
@app.get("/users/")
async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Users!", "params": commons}
client = TestClient(app)
async def override_dependency(q: Union[str, None] = None):
return {"q": q, "skip": 5, "limit": 10}
app.dependency_overrides[common_parameters] = override_dependency
def test_override_in_items():
response = client.get("/items/")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": None, "skip": 5, "limit": 10},
}
def test_override_in_items_with_q():
response = client.get("/items/?q=foo")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
def test_override_in_items_with_params():
response = client.get("/items/?q=foo&skip=100&limit=200")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
| import importlib
import warnings
import pytest
from dirty_equals import IsDict, IsInt
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from sqlalchemy import StaticPool
from sqlmodel import SQLModel, create_engine
from sqlmodel.main import default_registry
from tests.utils import needs_py39, needs_py310
def clear_sqlmodel():
# Clear the tables in the metadata for the default base model
SQLModel.metadata.clear()
# Clear the Models associated with the registry, to avoid warnings
default_registry.dispose()
@pytest.fixture(
name="client",
params=[
"tutorial001",
pytest.param("tutorial001_py39", marks=needs_py39),
pytest.param("tutorial001_py310", marks=needs_py310),
"tutorial001_an",
pytest.param("tutorial001_an_py39", marks=needs_py39),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
clear_sqlmodel()
# TODO: remove when updating SQL tutorial to use new lifespan API
with warnings.catch_warnings(record=True):
warnings.simplefilter("always")
mod = importlib.import_module(f"docs_src.sql_databases.{request.param}")
clear_sqlmodel()
importlib.reload(mod)
mod.sqlite_url = "sqlite://"
mod.engine = create_engine(
mod.sqlite_url, connect_args={"check_same_thread": False}, poolclass=StaticPool
)
with TestClient(mod.app) as c:
yield c
# Clean up connection explicitly to avoid resource warning
mod.engine.dispose()
def test_crud_app(client: TestClient):
# TODO: this warns that SQLModel.from_orm is deprecated in Pydantic v1, refactor
# this if using obj.model_validate becomes independent of Pydantic v2
with warnings.catch_warnings(record=True):
warnings.simplefilter("always")
# No heroes before creating
response = client.get("heroes/")
assert response.status_code == 200, response.text
assert response.json() == []
# Create a hero
response = client.post(
"/heroes/",
json={
"id": 999,
"name": "Dead Pond",
"age": 30,
"secret_name": "Dive Wilson",
},
)
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{"age": 30, "secret_name": "Dive Wilson", "id": 999, "name": "Dead Pond"}
)
# Read a hero
hero_id = response.json()["id"]
response = client.get(f"/heroes/{hero_id}")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{"name": "Dead Pond", "age": 30, "id": 999, "secret_name": "Dive Wilson"}
)
# Read all heroes
# Create more heroes first
response = client.post(
"/heroes/",
json={"name": "Spider-Boy", "age": 18, "secret_name": "Pedro Parqueador"},
)
assert response.status_code == 200, response.text
response = client.post(
"/heroes/", json={"name": "Rusty-Man", "secret_name": "Tommy Sharp"}
)
assert response.status_code == 200, response.text
response = client.get("/heroes/")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
[
{
"name": "Dead Pond",
"age": 30,
"id": IsInt(),
"secret_name": "Dive Wilson",
},
{
"name": "Spider-Boy",
"age": 18,
"id": IsInt(),
"secret_name": "Pedro Parqueador",
},
{
"name": "Rusty-Man",
"age": None,
"id": IsInt(),
"secret_name": "Tommy Sharp",
},
]
)
response = client.get("/heroes/?offset=1&limit=1")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
[
{
"name": "Spider-Boy",
"age": 18,
"id": IsInt(),
"secret_name": "Pedro Parqueador",
}
]
)
# Delete a hero
response = client.delete(f"/heroes/{hero_id}")
assert response.status_code == 200, response.text
assert response.json() == snapshot({"ok": True})
response = client.get(f"/heroes/{hero_id}")
assert response.status_code == 404, response.text
response = client.delete(f"/heroes/{hero_id}")
assert response.status_code == 404, response.text
assert response.json() == snapshot({"detail": "Hero not found"})
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/heroes/": {
"post": {
"summary": "Create Hero",
"operationId": "create_hero_heroes__post",
"requestBody": {
"required": True,
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Hero"}
}
},
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Hero"}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
},
"get": {
"summary": "Read Heroes",
"operationId": "read_heroes_heroes__get",
"parameters": [
{
"name": "offset",
"in": "query",
"required": False,
"schema": {
"type": "integer",
"default": 0,
"title": "Offset",
},
},
{
"name": "limit",
"in": "query",
"required": False,
"schema": {
"type": "integer",
"maximum": 100,
"default": 100,
"title": "Limit",
},
},
],
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Hero"
},
"title": "Response Read Heroes Heroes Get",
}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
},
},
"/heroes/{hero_id}": {
"get": {
"summary": "Read Hero",
"operationId": "read_hero_heroes__hero_id__get",
"parameters": [
{
"name": "hero_id",
"in": "path",
"required": True,
"schema": {"type": "integer", "title": "Hero Id"},
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Hero"}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
},
"delete": {
"summary": "Delete Hero",
"operationId": "delete_hero_heroes__hero_id__delete",
"parameters": [
{
"name": "hero_id",
"in": "path",
"required": True,
"schema": {"type": "integer", "title": "Hero Id"},
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
},
},
},
"components": {
"schemas": {
"HTTPValidationError": {
"properties": {
"detail": {
"items": {
"$ref": "#/components/schemas/ValidationError"
},
"type": "array",
"title": "Detail",
}
},
"type": "object",
"title": "HTTPValidationError",
},
"Hero": {
"properties": {
"id": IsDict(
{
"anyOf": [{"type": "integer"}, {"type": "null"}],
"title": "Id",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"type": "integer",
"title": "Id",
}
),
"name": {"type": "string", "title": "Name"},
"age": IsDict(
{
"anyOf": [{"type": "integer"}, {"type": "null"}],
"title": "Age",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"type": "integer",
"title": "Age",
}
),
"secret_name": {"type": "string", "title": "Secret Name"},
},
"type": "object",
"required": ["name", "secret_name"],
"title": "Hero",
},
"ValidationError": {
"properties": {
"loc": {
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
"type": "array",
"title": "Location",
},
"msg": {"type": "string", "title": "Message"},
"type": {"type": "string", "title": "Error Type"},
},
"type": "object",
"required": ["loc", "msg", "type"],
"title": "ValidationError",
},
}
},
}
)
| fastapi |
python | from typing import Annotated
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
q: str, item_id: Annotated[int, Path(title="The ID of the item to get")]
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
| import importlib
import warnings
import pytest
from dirty_equals import IsDict, IsInt
from fastapi.testclient import TestClient
from inline_snapshot import Is, snapshot
from sqlalchemy import StaticPool
from sqlmodel import SQLModel, create_engine
from sqlmodel.main import default_registry
from tests.utils import needs_py39, needs_py310
def clear_sqlmodel():
# Clear the tables in the metadata for the default base model
SQLModel.metadata.clear()
# Clear the Models associated with the registry, to avoid warnings
default_registry.dispose()
@pytest.fixture(
name="client",
params=[
"tutorial002",
pytest.param("tutorial002_py39", marks=needs_py39),
pytest.param("tutorial002_py310", marks=needs_py310),
"tutorial002_an",
pytest.param("tutorial002_an_py39", marks=needs_py39),
pytest.param("tutorial002_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
clear_sqlmodel()
# TODO: remove when updating SQL tutorial to use new lifespan API
with warnings.catch_warnings(record=True):
warnings.simplefilter("always")
mod = importlib.import_module(f"docs_src.sql_databases.{request.param}")
clear_sqlmodel()
importlib.reload(mod)
mod.sqlite_url = "sqlite://"
mod.engine = create_engine(
mod.sqlite_url, connect_args={"check_same_thread": False}, poolclass=StaticPool
)
with TestClient(mod.app) as c:
yield c
# Clean up connection explicitly to avoid resource warning
mod.engine.dispose()
def test_crud_app(client: TestClient):
# TODO: this warns that SQLModel.from_orm is deprecated in Pydantic v1, refactor
# this if using obj.model_validate becomes independent of Pydantic v2
with warnings.catch_warnings(record=True):
warnings.simplefilter("always")
# No heroes before creating
response = client.get("heroes/")
assert response.status_code == 200, response.text
assert response.json() == []
# Create a hero
response = client.post(
"/heroes/",
json={
"id": 9000,
"name": "Dead Pond",
"age": 30,
"secret_name": "Dive Wilson",
},
)
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{"age": 30, "id": IsInt(), "name": "Dead Pond"}
)
assert response.json()["id"] != 9000, (
"The ID should be generated by the database"
)
# Read a hero
hero_id = response.json()["id"]
response = client.get(f"/heroes/{hero_id}")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{"name": "Dead Pond", "age": 30, "id": IsInt()}
)
# Read all heroes
# Create more heroes first
response = client.post(
"/heroes/",
json={"name": "Spider-Boy", "age": 18, "secret_name": "Pedro Parqueador"},
)
assert response.status_code == 200, response.text
response = client.post(
"/heroes/", json={"name": "Rusty-Man", "secret_name": "Tommy Sharp"}
)
assert response.status_code == 200, response.text
response = client.get("/heroes/")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
[
{"name": "Dead Pond", "age": 30, "id": IsInt()},
{"name": "Spider-Boy", "age": 18, "id": IsInt()},
{"name": "Rusty-Man", "age": None, "id": IsInt()},
]
)
response = client.get("/heroes/?offset=1&limit=1")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
[{"name": "Spider-Boy", "age": 18, "id": IsInt()}]
)
# Update a hero
response = client.patch(
f"/heroes/{hero_id}", json={"name": "Dog Pond", "age": None}
)
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{"name": "Dog Pond", "age": None, "id": Is(hero_id)}
)
# Get updated hero
response = client.get(f"/heroes/{hero_id}")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{"name": "Dog Pond", "age": None, "id": Is(hero_id)}
)
# Delete a hero
response = client.delete(f"/heroes/{hero_id}")
assert response.status_code == 200, response.text
assert response.json() == snapshot({"ok": True})
# The hero is no longer found
response = client.get(f"/heroes/{hero_id}")
assert response.status_code == 404, response.text
# Delete a hero that does not exist
response = client.delete(f"/heroes/{hero_id}")
assert response.status_code == 404, response.text
assert response.json() == snapshot({"detail": "Hero not found"})
# Update a hero that does not exist
response = client.patch(f"/heroes/{hero_id}", json={"name": "Dog Pond"})
assert response.status_code == 404, response.text
assert response.json() == snapshot({"detail": "Hero not found"})
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/heroes/": {
"post": {
"summary": "Create Hero",
"operationId": "create_hero_heroes__post",
"requestBody": {
"required": True,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HeroCreate"
}
}
},
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HeroPublic"
}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
},
"get": {
"summary": "Read Heroes",
"operationId": "read_heroes_heroes__get",
"parameters": [
{
"name": "offset",
"in": "query",
"required": False,
"schema": {
"type": "integer",
"default": 0,
"title": "Offset",
},
},
{
"name": "limit",
"in": "query",
"required": False,
"schema": {
"type": "integer",
"maximum": 100,
"default": 100,
"title": "Limit",
},
},
],
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/HeroPublic"
},
"title": "Response Read Heroes Heroes Get",
}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
},
},
"/heroes/{hero_id}": {
"get": {
"summary": "Read Hero",
"operationId": "read_hero_heroes__hero_id__get",
"parameters": [
{
"name": "hero_id",
"in": "path",
"required": True,
"schema": {"type": "integer", "title": "Hero Id"},
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HeroPublic"
}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
},
"patch": {
"summary": "Update Hero",
"operationId": "update_hero_heroes__hero_id__patch",
"parameters": [
{
"name": "hero_id",
"in": "path",
"required": True,
"schema": {"type": "integer", "title": "Hero Id"},
}
],
"requestBody": {
"required": True,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HeroUpdate"
}
}
},
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HeroPublic"
}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
},
"delete": {
"summary": "Delete Hero",
"operationId": "delete_hero_heroes__hero_id__delete",
"parameters": [
{
"name": "hero_id",
"in": "path",
"required": True,
"schema": {"type": "integer", "title": "Hero Id"},
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
},
},
},
"components": {
"schemas": {
"HTTPValidationError": {
"properties": {
"detail": {
"items": {
"$ref": "#/components/schemas/ValidationError"
},
"type": "array",
"title": "Detail",
}
},
"type": "object",
"title": "HTTPValidationError",
},
"HeroCreate": {
"properties": {
"name": {"type": "string", "title": "Name"},
"age": IsDict(
{
"anyOf": [{"type": "integer"}, {"type": "null"}],
"title": "Age",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"type": "integer",
"title": "Age",
}
),
"secret_name": {"type": "string", "title": "Secret Name"},
},
"type": "object",
"required": ["name", "secret_name"],
"title": "HeroCreate",
},
"HeroPublic": {
"properties": {
"name": {"type": "string", "title": "Name"},
"age": IsDict(
{
"anyOf": [{"type": "integer"}, {"type": "null"}],
"title": "Age",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"type": "integer",
"title": "Age",
}
),
"id": {"type": "integer", "title": "Id"},
},
"type": "object",
"required": ["name", "id"],
"title": "HeroPublic",
},
"HeroUpdate": {
"properties": {
"name": IsDict(
{
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Name",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"type": "string",
"title": "Name",
}
),
"age": IsDict(
{
"anyOf": [{"type": "integer"}, {"type": "null"}],
"title": "Age",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"type": "integer",
"title": "Age",
}
),
"secret_name": IsDict(
{
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Secret Name",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"type": "string",
"title": "Secret Name",
}
),
},
"type": "object",
"title": "HeroUpdate",
},
"ValidationError": {
"properties": {
"loc": {
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
"type": "array",
"title": "Location",
},
"msg": {"type": "string", "title": "Message"},
"type": {"type": "string", "title": "Error Type"},
},
"type": "object",
"required": ["loc", "msg", "type"],
"title": "ValidationError",
},
}
},
}
)
| fastapi |
python | from typing import Annotated
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
item_id: Annotated[int, Path(title="The ID of the item to get")], q: str
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
| import sys
import pytest
from fastapi._compat import PYDANTIC_V2
from inline_snapshot import snapshot
from tests.utils import skip_module_if_py_gte_314
if sys.version_info >= (3, 14):
skip_module_if_py_gte_314()
if not PYDANTIC_V2:
pytest.skip("This test is only for Pydantic v2", allow_module_level=True)
import importlib
from fastapi.testclient import TestClient
from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
"tutorial003_an",
pytest.param("tutorial003_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.pydantic_v1_in_v2.{request.param}")
c = TestClient(mod.app)
return c
def test_call(client: TestClient):
response = client.post("/items/", json={"name": "Foo", "size": 3.4})
assert response.status_code == 200, response.text
assert response.json() == {
"name": "Foo",
"description": None,
"size": 3.4,
}
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"post": {
"summary": "Create Item",
"operationId": "create_item_items__post",
"requestBody": {
"content": {
"application/json": {
"schema": {
"allOf": [
{"$ref": "#/components/schemas/Item"}
],
"title": "Item",
}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ItemV2"
}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
"components": {
"schemas": {
"HTTPValidationError": {
"properties": {
"detail": {
"items": {
"$ref": "#/components/schemas/ValidationError"
},
"type": "array",
"title": "Detail",
}
},
"type": "object",
"title": "HTTPValidationError",
},
"Item": {
"properties": {
"name": {"type": "string", "title": "Name"},
"description": {"type": "string", "title": "Description"},
"size": {"type": "number", "title": "Size"},
},
"type": "object",
"required": ["name", "size"],
"title": "Item",
},
"ItemV2": {
"properties": {
"name": {"type": "string", "title": "Name"},
"description": {
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Description",
},
"size": {"type": "number", "title": "Size"},
},
"type": "object",
"required": ["name", "size"],
"title": "ItemV2",
},
"ValidationError": {
"properties": {
"loc": {
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
"type": "array",
"title": "Location",
},
"msg": {"type": "string", "title": "Message"},
"type": {"type": "string", "title": "Error Type"},
},
"type": "object",
"required": ["loc", "msg", "type"],
"title": "ValidationError",
},
}
},
}
)
| fastapi |
python | from typing import Union
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from typing_extensions import Annotated
app = FastAPI()
async def common_parameters(
q: Union[str, None] = None, skip: int = 0, limit: int = 100
):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Items!", "params": commons}
@app.get("/users/")
async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Users!", "params": commons}
client = TestClient(app)
async def override_dependency(q: Union[str, None] = None):
return {"q": q, "skip": 5, "limit": 10}
app.dependency_overrides[common_parameters] = override_dependency
def test_override_in_items():
response = client.get("/items/")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": None, "skip": 5, "limit": 10},
}
def test_override_in_items_with_q():
response = client.get("/items/?q=foo")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
def test_override_in_items_with_params():
response = client.get("/items/?q=foo&skip=100&limit=200")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
| import sys
from typing import Any
import pytest
from fastapi._compat import PYDANTIC_V2
from tests.utils import skip_module_if_py_gte_314
if sys.version_info >= (3, 14):
skip_module_if_py_gte_314()
if not PYDANTIC_V2:
pytest.skip("This test is only for Pydantic v2", allow_module_level=True)
import importlib
import pytest
from ...utils import needs_py310
@pytest.fixture(
name="mod",
params=[
"tutorial001_an",
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
def get_mod(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.pydantic_v1_in_v2.{request.param}")
return mod
def test_model(mod: Any):
item = mod.Item(name="Foo", size=3.4)
assert item.dict() == {"name": "Foo", "description": None, "size": 3.4}
| fastapi |
python | from typing import Annotated
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
q: str, item_id: Annotated[int, Path(title="The ID of the item to get")]
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
| import sys
import pytest
from fastapi._compat import PYDANTIC_V2
from inline_snapshot import snapshot
from tests.utils import skip_module_if_py_gte_314
if sys.version_info >= (3, 14):
skip_module_if_py_gte_314()
if not PYDANTIC_V2:
pytest.skip("This test is only for Pydantic v2", allow_module_level=True)
import importlib
import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
"tutorial002_an",
pytest.param("tutorial002_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.pydantic_v1_in_v2.{request.param}")
c = TestClient(mod.app)
return c
def test_call(client: TestClient):
response = client.post("/items/", json={"name": "Foo", "size": 3.4})
assert response.status_code == 200, response.text
assert response.json() == {
"name": "Foo",
"description": None,
"size": 3.4,
}
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"post": {
"summary": "Create Item",
"operationId": "create_item_items__post",
"requestBody": {
"content": {
"application/json": {
"schema": {
"allOf": [
{"$ref": "#/components/schemas/Item"}
],
"title": "Item",
}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
"components": {
"schemas": {
"HTTPValidationError": {
"properties": {
"detail": {
"items": {
"$ref": "#/components/schemas/ValidationError"
},
"type": "array",
"title": "Detail",
}
},
"type": "object",
"title": "HTTPValidationError",
},
"Item": {
"properties": {
"name": {"type": "string", "title": "Name"},
"description": {"type": "string", "title": "Description"},
"size": {"type": "number", "title": "Size"},
},
"type": "object",
"required": ["name", "size"],
"title": "Item",
},
"ValidationError": {
"properties": {
"loc": {
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
"type": "array",
"title": "Location",
},
"msg": {"type": "string", "title": "Message"},
"type": {"type": "string", "title": "Error Type"},
},
"type": "object",
"required": ["loc", "msg", "type"],
"title": "ValidationError",
},
}
},
}
)
| fastapi |
python | from fastapi import FastAPI, Path
from typing_extensions import Annotated
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
item_id: Annotated[int, Path(title="The ID of the item to get", ge=1)], q: str
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
| import sys
import pytest
from fastapi._compat import PYDANTIC_V2
from inline_snapshot import snapshot
from tests.utils import skip_module_if_py_gte_314
if sys.version_info >= (3, 14):
skip_module_if_py_gte_314()
if not PYDANTIC_V2:
pytest.skip("This test is only for Pydantic v2", allow_module_level=True)
import importlib
from fastapi.testclient import TestClient
from ...utils import needs_py39, needs_py310
@pytest.fixture(
name="client",
params=[
"tutorial004_an",
pytest.param("tutorial004_an_py39", marks=needs_py39),
pytest.param("tutorial004_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.pydantic_v1_in_v2.{request.param}")
c = TestClient(mod.app)
return c
def test_call(client: TestClient):
response = client.post("/items/", json={"item": {"name": "Foo", "size": 3.4}})
assert response.status_code == 200, response.text
assert response.json() == {
"name": "Foo",
"description": None,
"size": 3.4,
}
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"post": {
"summary": "Create Item",
"operationId": "create_item_items__post",
"requestBody": {
"content": {
"application/json": {
"schema": {
"allOf": [
{
"$ref": "#/components/schemas/Body_create_item_items__post"
}
],
"title": "Body",
}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
"components": {
"schemas": {
"Body_create_item_items__post": {
"properties": {
"item": {
"allOf": [{"$ref": "#/components/schemas/Item"}],
"title": "Item",
}
},
"type": "object",
"required": ["item"],
"title": "Body_create_item_items__post",
},
"HTTPValidationError": {
"properties": {
"detail": {
"items": {
"$ref": "#/components/schemas/ValidationError"
},
"type": "array",
"title": "Detail",
}
},
"type": "object",
"title": "HTTPValidationError",
},
"Item": {
"properties": {
"name": {"type": "string", "title": "Name"},
"description": {"type": "string", "title": "Description"},
"size": {"type": "number", "title": "Size"},
},
"type": "object",
"required": ["name", "size"],
"title": "Item",
},
"ValidationError": {
"properties": {
"loc": {
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
"type": "array",
"title": "Location",
},
"msg": {"type": "string", "title": "Message"},
"type": {"type": "string", "title": "Error Type"},
},
"type": "object",
"required": ["loc", "msg", "type"],
"title": "ValidationError",
},
}
},
}
)
| fastapi |
python | from typing import List
import yaml
from fastapi import FastAPI, HTTPException, Request
from pydantic import BaseModel, ValidationError
app = FastAPI()
class Item(BaseModel):
name: str
tags: List[str]
@app.post(
"/items/",
openapi_extra={
"requestBody": {
"content": {"application/x-yaml": {"schema": Item.schema()}},
"required": True,
},
},
)
async def create_item(request: Request):
raw_body = await request.body()
try:
data = yaml.safe_load(raw_body)
except yaml.YAMLError:
raise HTTPException(status_code=422, detail="Invalid YAML")
try:
item = Item.parse_obj(data)
except ValidationError as e:
raise HTTPException(status_code=422, detail=e.errors())
return item
| import pytest
from fastapi.testclient import TestClient
from ...utils import needs_pydanticv1
@pytest.fixture(name="client")
def get_client():
from docs_src.path_operation_advanced_configuration.tutorial007_pv1 import app
client = TestClient(app)
return client
@needs_pydanticv1
def test_post(client: TestClient):
yaml_data = """
name: Deadpoolio
tags:
- x-force
- x-men
- x-avengers
"""
response = client.post("/items/", content=yaml_data)
assert response.status_code == 200, response.text
assert response.json() == {
"name": "Deadpoolio",
"tags": ["x-force", "x-men", "x-avengers"],
}
@needs_pydanticv1
def test_post_broken_yaml(client: TestClient):
yaml_data = """
name: Deadpoolio
tags:
x - x-force
x - x-men
x - x-avengers
"""
response = client.post("/items/", content=yaml_data)
assert response.status_code == 422, response.text
assert response.json() == {"detail": "Invalid YAML"}
@needs_pydanticv1
def test_post_invalid(client: TestClient):
yaml_data = """
name: Deadpoolio
tags:
- x-force
- x-men
- x-avengers
- sneaky: object
"""
response = client.post("/items/", content=yaml_data)
assert response.status_code == 422, response.text
assert response.json() == {
"detail": [
{"loc": ["tags", 3], "msg": "str type expected", "type": "type_error.str"}
]
}
@needs_pydanticv1
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": {
"/items/": {
"post": {
"summary": "Create Item",
"operationId": "create_item_items__post",
"requestBody": {
"content": {
"application/x-yaml": {
"schema": {
"title": "Item",
"required": ["name", "tags"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"tags": {
"title": "Tags",
"type": "array",
"items": {"type": "string"},
},
},
}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
}
}
},
}
| fastapi |
python | from typing import Union
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(
q: Union[str, None] = Query(default=None, title="Query string", min_length=3),
):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
| import pytest
from fastapi.testclient import TestClient
from ...utils import needs_pydanticv2
@pytest.fixture(name="client")
def get_client():
from docs_src.path_operation_advanced_configuration.tutorial007 import app
client = TestClient(app)
return client
@needs_pydanticv2
def test_post(client: TestClient):
yaml_data = """
name: Deadpoolio
tags:
- x-force
- x-men
- x-avengers
"""
response = client.post("/items/", content=yaml_data)
assert response.status_code == 200, response.text
assert response.json() == {
"name": "Deadpoolio",
"tags": ["x-force", "x-men", "x-avengers"],
}
@needs_pydanticv2
def test_post_broken_yaml(client: TestClient):
yaml_data = """
name: Deadpoolio
tags:
x - x-force
x - x-men
x - x-avengers
"""
response = client.post("/items/", content=yaml_data)
assert response.status_code == 422, response.text
assert response.json() == {"detail": "Invalid YAML"}
@needs_pydanticv2
def test_post_invalid(client: TestClient):
yaml_data = """
name: Deadpoolio
tags:
- x-force
- x-men
- x-avengers
- sneaky: object
"""
response = client.post("/items/", content=yaml_data)
assert response.status_code == 422, response.text
# insert_assert(response.json())
assert response.json() == {
"detail": [
{
"type": "string_type",
"loc": ["tags", 3],
"msg": "Input should be a valid string",
"input": {"sneaky": "object"},
}
]
}
@needs_pydanticv2
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": {
"/items/": {
"post": {
"summary": "Create Item",
"operationId": "create_item_items__post",
"requestBody": {
"content": {
"application/x-yaml": {
"schema": {
"title": "Item",
"required": ["name", "tags"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"tags": {
"title": "Tags",
"type": "array",
"items": {"type": "string"},
},
},
}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
}
}
},
}
| fastapi |
python | from typing import Union
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from typing_extensions import Annotated
app = FastAPI()
async def common_parameters(
q: Union[str, None] = None, skip: int = 0, limit: int = 100
):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Items!", "params": commons}
@app.get("/users/")
async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Users!", "params": commons}
client = TestClient(app)
async def override_dependency(q: Union[str, None] = None):
return {"q": q, "skip": 5, "limit": 10}
app.dependency_overrides[common_parameters] = override_dependency
def test_override_in_items():
response = client.get("/items/")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": None, "skip": 5, "limit": 10},
}
def test_override_in_items_with_q():
response = client.get("/items/?q=foo")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
def test_override_in_items_with_params():
response = client.get("/items/?q=foo&skip=100&limit=200")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
| import importlib
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from tests.utils import needs_py39, needs_py310
@pytest.fixture(
name="client",
params=[
"tutorial001",
pytest.param("tutorial001_py310", marks=needs_py310),
"tutorial001_an",
pytest.param("tutorial001_an_py39", marks=needs_py39),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.cookie_param_models.{request.param}")
client = TestClient(mod.app)
return client
def test_cookie_param_model(client: TestClient):
with client as c:
c.cookies.set("session_id", "123")
c.cookies.set("fatebook_tracker", "456")
c.cookies.set("googall_tracker", "789")
response = c.get("/items/")
assert response.status_code == 200
assert response.json() == {
"session_id": "123",
"fatebook_tracker": "456",
"googall_tracker": "789",
}
def test_cookie_param_model_defaults(client: TestClient):
with client as c:
c.cookies.set("session_id", "123")
response = c.get("/items/")
assert response.status_code == 200
assert response.json() == {
"session_id": "123",
"fatebook_tracker": None,
"googall_tracker": None,
}
def test_cookie_param_model_invalid(client: TestClient):
response = client.get("/items/")
assert response.status_code == 422
assert response.json() == snapshot(
IsDict(
{
"detail": [
{
"type": "missing",
"loc": ["cookie", "session_id"],
"msg": "Field required",
"input": {},
}
]
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"detail": [
{
"type": "value_error.missing",
"loc": ["cookie", "session_id"],
"msg": "field required",
}
]
}
)
)
def test_cookie_param_model_extra(client: TestClient):
with client as c:
c.cookies.set("session_id", "123")
c.cookies.set("extra", "track-me-here-too")
response = c.get("/items/")
assert response.status_code == 200
assert response.json() == snapshot(
{"session_id": "123", "fatebook_tracker": None, "googall_tracker": None}
)
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"get": {
"summary": "Read Items",
"operationId": "read_items_items__get",
"parameters": [
{
"name": "session_id",
"in": "cookie",
"required": True,
"schema": {"type": "string", "title": "Session Id"},
},
{
"name": "fatebook_tracker",
"in": "cookie",
"required": False,
"schema": IsDict(
{
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Fatebook Tracker",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"type": "string",
"title": "Fatebook Tracker",
}
),
},
{
"name": "googall_tracker",
"in": "cookie",
"required": False,
"schema": IsDict(
{
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Googall Tracker",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"type": "string",
"title": "Googall Tracker",
}
),
},
],
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
"components": {
"schemas": {
"HTTPValidationError": {
"properties": {
"detail": {
"items": {
"$ref": "#/components/schemas/ValidationError"
},
"type": "array",
"title": "Detail",
}
},
"type": "object",
"title": "HTTPValidationError",
},
"ValidationError": {
"properties": {
"loc": {
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
"type": "array",
"title": "Location",
},
"msg": {"type": "string", "title": "Message"},
"type": {"type": "string", "title": "Error Type"},
},
"type": "object",
"required": ["loc", "msg", "type"],
"title": "ValidationError",
},
}
},
}
)
| fastapi |
python | from typing import Annotated
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
q: str, item_id: Annotated[int, Path(title="The ID of the item to get")]
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
| import importlib
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from tests.utils import (
needs_py39,
needs_py310,
needs_pydanticv1,
needs_pydanticv2,
pydantic_snapshot,
)
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial002", marks=needs_pydanticv2),
pytest.param("tutorial002_py310", marks=[needs_py310, needs_pydanticv2]),
pytest.param("tutorial002_an", marks=needs_pydanticv2),
pytest.param("tutorial002_an_py39", marks=[needs_py39, needs_pydanticv2]),
pytest.param("tutorial002_an_py310", marks=[needs_py310, needs_pydanticv2]),
pytest.param("tutorial002_pv1", marks=[needs_pydanticv1, needs_pydanticv1]),
pytest.param("tutorial002_pv1_py310", marks=[needs_py310, needs_pydanticv1]),
pytest.param("tutorial002_pv1_an", marks=[needs_pydanticv1]),
pytest.param("tutorial002_pv1_an_py39", marks=[needs_py39, needs_pydanticv1]),
pytest.param("tutorial002_pv1_an_py310", marks=[needs_py310, needs_pydanticv1]),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.cookie_param_models.{request.param}")
client = TestClient(mod.app)
return client
def test_cookie_param_model(client: TestClient):
with client as c:
c.cookies.set("session_id", "123")
c.cookies.set("fatebook_tracker", "456")
c.cookies.set("googall_tracker", "789")
response = c.get("/items/")
assert response.status_code == 200
assert response.json() == {
"session_id": "123",
"fatebook_tracker": "456",
"googall_tracker": "789",
}
def test_cookie_param_model_defaults(client: TestClient):
with client as c:
c.cookies.set("session_id", "123")
response = c.get("/items/")
assert response.status_code == 200
assert response.json() == {
"session_id": "123",
"fatebook_tracker": None,
"googall_tracker": None,
}
def test_cookie_param_model_invalid(client: TestClient):
response = client.get("/items/")
assert response.status_code == 422
assert response.json() == pydantic_snapshot(
v2=snapshot(
{
"detail": [
{
"type": "missing",
"loc": ["cookie", "session_id"],
"msg": "Field required",
"input": {},
}
]
}
),
v1=snapshot(
{
"detail": [
{
"type": "value_error.missing",
"loc": ["cookie", "session_id"],
"msg": "field required",
}
]
}
),
)
def test_cookie_param_model_extra(client: TestClient):
with client as c:
c.cookies.set("session_id", "123")
c.cookies.set("extra", "track-me-here-too")
response = c.get("/items/")
assert response.status_code == 422
assert response.json() == snapshot(
IsDict(
{
"detail": [
{
"type": "extra_forbidden",
"loc": ["cookie", "extra"],
"msg": "Extra inputs are not permitted",
"input": "track-me-here-too",
}
]
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"detail": [
{
"type": "value_error.extra",
"loc": ["cookie", "extra"],
"msg": "extra fields not permitted",
}
]
}
)
)
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"get": {
"summary": "Read Items",
"operationId": "read_items_items__get",
"parameters": [
{
"name": "session_id",
"in": "cookie",
"required": True,
"schema": {"type": "string", "title": "Session Id"},
},
{
"name": "fatebook_tracker",
"in": "cookie",
"required": False,
"schema": pydantic_snapshot(
v2=snapshot(
{
"anyOf": [
{"type": "string"},
{"type": "null"},
],
"title": "Fatebook Tracker",
}
),
v1=snapshot(
# TODO: remove when deprecating Pydantic v1
{
"type": "string",
"title": "Fatebook Tracker",
}
),
),
},
{
"name": "googall_tracker",
"in": "cookie",
"required": False,
"schema": IsDict(
{
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Googall Tracker",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"type": "string",
"title": "Googall Tracker",
}
),
},
],
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
"components": {
"schemas": {
"HTTPValidationError": {
"properties": {
"detail": {
"items": {
"$ref": "#/components/schemas/ValidationError"
},
"type": "array",
"title": "Detail",
}
},
"type": "object",
"title": "HTTPValidationError",
},
"ValidationError": {
"properties": {
"loc": {
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
"type": "array",
"title": "Location",
},
"msg": {"type": "string", "title": "Message"},
"type": {"type": "string", "title": "Error Type"},
},
"type": "object",
"required": ["loc", "msg", "type"],
"title": "ValidationError",
},
}
},
}
)
| fastapi |
python | from typing import Union
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from typing_extensions import Annotated
app = FastAPI()
async def common_parameters(
q: Union[str, None] = None, skip: int = 0, limit: int = 100
):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Items!", "params": commons}
@app.get("/users/")
async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Users!", "params": commons}
client = TestClient(app)
async def override_dependency(q: Union[str, None] = None):
return {"q": q, "skip": 5, "limit": 10}
app.dependency_overrides[common_parameters] = override_dependency
def test_override_in_items():
response = client.get("/items/")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": None, "skip": 5, "limit": 10},
}
def test_override_in_items_with_q():
response = client.get("/items/?q=foo")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
def test_override_in_items_with_params():
response = client.get("/items/?q=foo&skip=100&limit=200")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
| import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
@pytest.fixture(name="app", scope="module")
def get_app():
with pytest.warns(DeprecationWarning):
from docs_src.events.tutorial001 import app
yield app
def test_events(app: FastAPI):
with TestClient(app) as client:
response = client.get("/items/foo")
assert response.status_code == 200, response.text
assert response.json() == {"name": "Fighters"}
def test_openapi_schema(app: FastAPI):
with TestClient(app) as client:
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": {
"/items/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Read Items",
"operationId": "read_items_items__item_id__get",
"parameters": [
{
"required": True,
"schema": {"title": "Item Id", "type": "string"},
"name": "item_id",
"in": "path",
}
],
}
}
},
"components": {
"schemas": {
"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"
},
}
},
},
}
},
}
| fastapi |
python | from typing import Annotated
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
q: str, item_id: Annotated[int, Path(title="The ID of the item to get")]
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
| import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
@pytest.fixture(name="app", scope="module")
def get_app():
with pytest.warns(DeprecationWarning):
from docs_src.events.tutorial002 import app
yield app
def test_events(app: FastAPI):
with TestClient(app) as client:
response = client.get("/items/")
assert response.status_code == 200, response.text
assert response.json() == [{"name": "Foo"}]
with open("log.txt") as log:
assert "Application shutdown" in log.read()
def test_openapi_schema(app: FastAPI):
with TestClient(app) as client:
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": {
"/items/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"summary": "Read Items",
"operationId": "read_items_items__get",
}
}
},
}
| fastapi |
python | from typing import Annotated
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
item_id: Annotated[int, Path(title="The ID of the item to get")], q: str
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
| import importlib
import pytest
from dirty_equals import IsOneOf
from fastapi.testclient import TestClient
from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
"tutorial003",
pytest.param("tutorial003_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.extra_models.{request.param}")
client = TestClient(mod.app)
return client
def test_get_car(client: TestClient):
response = client.get("/items/item1")
assert response.status_code == 200, response.text
assert response.json() == {
"description": "All my friends drive a low rider",
"type": "car",
}
def test_get_plane(client: TestClient):
response = client.get("/items/item2")
assert response.status_code == 200, response.text
assert response.json() == {
"description": "Music is my aeroplane, it's my aeroplane",
"type": "plane",
"size": 5,
}
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": {
"/items/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"title": "Response Read Item Items Item Id Get",
"anyOf": [
{"$ref": "#/components/schemas/PlaneItem"},
{"$ref": "#/components/schemas/CarItem"},
],
}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Read Item",
"operationId": "read_item_items__item_id__get",
"parameters": [
{
"required": True,
"schema": {"title": "Item Id", "type": "string"},
"name": "item_id",
"in": "path",
}
],
}
}
},
"components": {
"schemas": {
"PlaneItem": {
"title": "PlaneItem",
"required": IsOneOf(
["description", "type", "size"],
# TODO: remove when deprecating Pydantic v1
["description", "size"],
),
"type": "object",
"properties": {
"description": {"title": "Description", "type": "string"},
"type": {"title": "Type", "type": "string", "default": "plane"},
"size": {"title": "Size", "type": "integer"},
},
},
"CarItem": {
"title": "CarItem",
"required": IsOneOf(
["description", "type"],
# TODO: remove when deprecating Pydantic v1
["description"],
),
"type": "object",
"properties": {
"description": {"title": "Description", "type": "string"},
"type": {"title": "Type", "type": "string", "default": "car"},
},
},
"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"},
}
},
},
}
},
}
| fastapi |
python | from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
*,
item_id: int = Path(title="The ID of the item to get", gt=0, le=1000),
q: str,
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
| import importlib
import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py39
@pytest.fixture(
name="client",
params=[
"tutorial005",
pytest.param("tutorial005_py39", marks=needs_py39),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.extra_models.{request.param}")
client = TestClient(mod.app)
return client
def test_get_items(client: TestClient):
response = client.get("/keyword-weights/")
assert response.status_code == 200, response.text
assert response.json() == {"foo": 2.3, "bar": 3.4}
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": {
"/keyword-weights/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"title": "Response Read Keyword Weights Keyword Weights Get",
"type": "object",
"additionalProperties": {"type": "number"},
}
}
},
}
},
"summary": "Read Keyword Weights",
"operationId": "read_keyword_weights_keyword_weights__get",
}
}
},
}
| fastapi |
python | from fastapi import FastAPI, Path
from typing_extensions import Annotated
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
item_id: Annotated[int, Path(title="The ID of the item to get", ge=1)], q: str
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
| import importlib
import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py39
@pytest.fixture(
name="client",
params=[
"tutorial004",
pytest.param("tutorial004_py39", marks=needs_py39),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.extra_models.{request.param}")
client = TestClient(mod.app)
return client
def test_get_items(client: TestClient):
response = client.get("/items/")
assert response.status_code == 200, response.text
assert response.json() == [
{"name": "Foo", "description": "There comes my hero"},
{"name": "Red", "description": "It's my aeroplane"},
]
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": {
"/items/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"title": "Response Read Items Items Get",
"type": "array",
"items": {"$ref": "#/components/schemas/Item"},
}
}
},
}
},
"summary": "Read Items",
"operationId": "read_items_items__get",
}
}
},
"components": {
"schemas": {
"Item": {
"title": "Item",
"required": ["name", "description"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"description": {"title": "Description", "type": "string"},
},
}
}
},
}
| fastapi |
python | from typing import Union
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from typing_extensions import Annotated
app = FastAPI()
async def common_parameters(
q: Union[str, None] = None, skip: int = 0, limit: int = 100
):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Items!", "params": commons}
@app.get("/users/")
async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Users!", "params": commons}
client = TestClient(app)
async def override_dependency(q: Union[str, None] = None):
return {"q": q, "skip": 5, "limit": 10}
app.dependency_overrides[common_parameters] = override_dependency
def test_override_in_items():
response = client.get("/items/")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": None, "skip": 5, "limit": 10},
}
def test_override_in_items_with_q():
response = client.get("/items/?q=foo")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
def test_override_in_items_with_params():
response = client.get("/items/?q=foo&skip=100&limit=200")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
| import importlib
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
from ...utils import needs_py39
@pytest.fixture(
name="client",
params=[
"tutorial001",
"tutorial001_an",
pytest.param("tutorial001_an_py39", marks=needs_py39),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.request_forms.{request.param}")
client = TestClient(mod.app)
return client
def test_post_body_form(client: TestClient):
response = client.post("/login/", data={"username": "Foo", "password": "secret"})
assert response.status_code == 200
assert response.json() == {"username": "Foo"}
def test_post_body_form_no_password(client: TestClient):
response = client.post("/login/", data={"username": "Foo"})
assert response.status_code == 422
assert response.json() == IsDict(
{
"detail": [
{
"type": "missing",
"loc": ["body", "password"],
"msg": "Field required",
"input": None,
}
]
}
) | IsDict(
# TODO: remove when deprecating Pydantic v1
{
"detail": [
{
"loc": ["body", "password"],
"msg": "field required",
"type": "value_error.missing",
}
]
}
)
def test_post_body_form_no_username(client: TestClient):
response = client.post("/login/", data={"password": "secret"})
assert response.status_code == 422
assert response.json() == IsDict(
{
"detail": [
{
"type": "missing",
"loc": ["body", "username"],
"msg": "Field required",
"input": None,
}
]
}
) | IsDict(
# TODO: remove when deprecating Pydantic v1
{
"detail": [
{
"loc": ["body", "username"],
"msg": "field required",
"type": "value_error.missing",
}
]
}
)
def test_post_body_form_no_data(client: TestClient):
response = client.post("/login/")
assert response.status_code == 422
assert response.json() == IsDict(
{
"detail": [
{
"type": "missing",
"loc": ["body", "username"],
"msg": "Field required",
"input": None,
},
{
"type": "missing",
"loc": ["body", "password"],
"msg": "Field required",
"input": None,
},
]
}
) | IsDict(
# TODO: remove when deprecating Pydantic v1
{
"detail": [
{
"loc": ["body", "username"],
"msg": "field required",
"type": "value_error.missing",
},
{
"loc": ["body", "password"],
"msg": "field required",
"type": "value_error.missing",
},
]
}
)
def test_post_body_json(client: TestClient):
response = client.post("/login/", json={"username": "Foo", "password": "secret"})
assert response.status_code == 422, response.text
assert response.json() == IsDict(
{
"detail": [
{
"type": "missing",
"loc": ["body", "username"],
"msg": "Field required",
"input": None,
},
{
"type": "missing",
"loc": ["body", "password"],
"msg": "Field required",
"input": None,
},
]
}
) | IsDict(
# TODO: remove when deprecating Pydantic v1
{
"detail": [
{
"loc": ["body", "username"],
"msg": "field required",
"type": "value_error.missing",
},
{
"loc": ["body", "password"],
"msg": "field required",
"type": "value_error.missing",
},
]
}
)
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": {
"/login/": {
"post": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Login",
"operationId": "login_login__post",
"requestBody": {
"content": {
"application/x-www-form-urlencoded": {
"schema": {
"$ref": "#/components/schemas/Body_login_login__post"
}
}
},
"required": True,
},
}
}
},
"components": {
"schemas": {
"Body_login_login__post": {
"title": "Body_login_login__post",
"required": ["username", "password"],
"type": "object",
"properties": {
"username": {"title": "Username", "type": "string"},
"password": {"title": "Password", "type": "string"},
},
},
"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"},
}
},
},
}
},
}
| fastapi |
python | from typing import Annotated
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
item_id: Annotated[int, Path(title="The ID of the item to get")], q: str
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
| import importlib
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
from ...utils import needs_py39, needs_py310
@pytest.fixture(
name="client",
params=[
"tutorial003",
pytest.param("tutorial003_py310", marks=needs_py310),
"tutorial003_an",
pytest.param("tutorial003_an_py39", marks=needs_py39),
pytest.param("tutorial003_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_login(client: TestClient):
response = client.post("/token", data={"username": "johndoe", "password": "secret"})
assert response.status_code == 200, response.text
assert response.json() == {"access_token": "johndoe", "token_type": "bearer"}
def test_login_incorrect_password(client: TestClient):
response = client.post(
"/token", data={"username": "johndoe", "password": "incorrect"}
)
assert response.status_code == 400, response.text
assert response.json() == {"detail": "Incorrect username or password"}
def test_login_incorrect_username(client: TestClient):
response = client.post("/token", data={"username": "foo", "password": "secret"})
assert response.status_code == 400, response.text
assert response.json() == {"detail": "Incorrect username or password"}
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 johndoe"})
assert response.status_code == 200, response.text
assert response.json() == {
"username": "johndoe",
"full_name": "John Doe",
"email": "johndoe@example.com",
"hashed_password": "fakehashedsecret",
"disabled": False,
}
def test_incorrect_token(client: TestClient):
response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"})
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Not authenticated"}
assert response.headers["WWW-Authenticate"] == "Bearer"
def test_incorrect_token_type(client: TestClient):
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_inactive_user(client: TestClient):
response = client.get("/users/me", headers={"Authorization": "Bearer alice"})
assert response.status_code == 400, response.text
assert response.json() == {"detail": "Inactive user"}
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": {
"/token": {
"post": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Login",
"operationId": "login_token_post",
"requestBody": {
"content": {
"application/x-www-form-urlencoded": {
"schema": {
"$ref": "#/components/schemas/Body_login_token_post"
}
}
},
"required": True,
},
}
},
"/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": {
"schemas": {
"Body_login_token_post": {
"title": "Body_login_token_post",
"required": ["username", "password"],
"type": "object",
"properties": {
"grant_type": IsDict(
{
"title": "Grant Type",
"anyOf": [
{"pattern": "^password$", "type": "string"},
{"type": "null"},
],
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"title": "Grant Type",
"pattern": "^password$",
"type": "string",
}
),
"username": {"title": "Username", "type": "string"},
"password": {
"title": "Password",
"type": "string",
"format": "password",
},
"scope": {"title": "Scope", "type": "string", "default": ""},
"client_id": IsDict(
{
"title": "Client Id",
"anyOf": [{"type": "string"}, {"type": "null"}],
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{"title": "Client Id", "type": "string"}
),
"client_secret": IsDict(
{
"title": "Client Secret",
"anyOf": [{"type": "string"}, {"type": "null"}],
"format": "password",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"title": "Client Secret",
"type": "string",
"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"}},
}
},
},
}
| fastapi |
python | from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
*,
item_id: int = Path(title="The ID of the item to get", gt=0, le=1000),
q: str,
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
| import importlib
from types import ModuleType
import pytest
from dirty_equals import IsDict, IsOneOf
from fastapi.testclient import TestClient
from ...utils import needs_py39, needs_py310
@pytest.fixture(
name="mod",
params=[
"tutorial005",
pytest.param("tutorial005_py310", marks=needs_py310),
"tutorial005_an",
pytest.param("tutorial005_py39", marks=needs_py39),
pytest.param("tutorial005_an_py39", marks=needs_py39),
pytest.param("tutorial005_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", scope=None, client: TestClient
):
data = {"username": username, "password": password}
if scope:
data["scope"] = scope
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 == 400, 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 == 400, 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(scope="me", 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 scope="me"'
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("secretalice")
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 scope="me"'
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 scope="me"'
def test_token_no_scope(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 == 401, response.text
assert response.json() == {"detail": "Not enough permissions"}
assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"'
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 scope="me"'
def test_token_inactive_user(mod: ModuleType):
client = TestClient(mod.app)
access_token = get_access_token(
username="alice", password="secretalice", scope="me", 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(scope="me items", 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_read_system_status(mod: ModuleType):
client = TestClient(mod.app)
access_token = get_access_token(client=client)
response = client.get(
"/status/", headers={"Authorization": f"Bearer {access_token}"}
)
assert response.status_code == 200, response.text
assert response.json() == {"status": "ok"}
def test_read_system_status_no_token(mod: ModuleType):
client = TestClient(mod.app)
response = client.get("/status/")
assert response.status_code == 401, response.text
assert response.json() == {"detail": "Not authenticated"}
assert response.headers["WWW-Authenticate"] == "Bearer"
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": ["me"]}],
}
},
"/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": ["items", "me"]}],
}
},
"/status/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"summary": "Read System Status",
"operationId": "read_system_status_status__get",
"security": [{"OAuth2PasswordBearer": []}],
}
},
},
"components": {
"schemas": {
"User": {
"title": "User",
"required": IsOneOf(
["username", "email", "full_name", "disabled"],
# TODO: remove when deprecating Pydantic v1
["username"],
),
"type": "object",
"properties": {
"username": {"title": "Username", "type": "string"},
"email": IsDict(
{
"title": "Email",
"anyOf": [{"type": "string"}, {"type": "null"}],
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{"title": "Email", "type": "string"}
),
"full_name": IsDict(
{
"title": "Full Name",
"anyOf": [{"type": "string"}, {"type": "null"}],
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{"title": "Full Name", "type": "string"}
),
"disabled": IsDict(
{
"title": "Disabled",
"anyOf": [{"type": "boolean"}, {"type": "null"}],
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{"title": "Disabled", "type": "boolean"}
),
},
},
"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": IsDict(
{
"title": "Grant Type",
"anyOf": [
{"pattern": "^password$", "type": "string"},
{"type": "null"},
],
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"title": "Grant Type",
"pattern": "^password$",
"type": "string",
}
),
"username": {"title": "Username", "type": "string"},
"password": {
"title": "Password",
"type": "string",
"format": "password",
},
"scope": {"title": "Scope", "type": "string", "default": ""},
"client_id": IsDict(
{
"title": "Client Id",
"anyOf": [{"type": "string"}, {"type": "null"}],
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{"title": "Client Id", "type": "string"}
),
"client_secret": IsDict(
{
"title": "Client Secret",
"anyOf": [{"type": "string"}, {"type": "null"}],
"format": "password",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"title": "Client Secret",
"type": "string",
"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": {
"me": "Read information about the current user.",
"items": "Read items.",
},
"tokenUrl": "token",
}
},
}
},
},
}
| fastapi |
python | from typing import Union
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from typing_extensions import Annotated
app = FastAPI()
async def common_parameters(
q: Union[str, None] = None, skip: int = 0, limit: int = 100
):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Items!", "params": commons}
@app.get("/users/")
async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Users!", "params": commons}
client = TestClient(app)
async def override_dependency(q: Union[str, None] = None):
return {"q": q, "skip": 5, "limit": 10}
app.dependency_overrides[common_parameters] = override_dependency
def test_override_in_items():
response = client.get("/items/")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": None, "skip": 5, "limit": 10},
}
def test_override_in_items_with_q():
response = client.get("/items/?q=foo")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
def test_override_in_items_with_params():
response = client.get("/items/?q=foo&skip=100&limit=200")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
| import importlib
import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py39
@pytest.fixture(
name="client",
params=[
"tutorial001",
"tutorial001_an",
pytest.param("tutorial001_an_py39", marks=needs_py39),
],
)
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("/items")
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("/items", headers={"Authorization": "Bearer testtoken"})
assert response.status_code == 200, response.text
assert response.json() == {"token": "testtoken"}
def test_incorrect_token(client: TestClient):
response = client.get("/items", 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_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": {
"/items/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"summary": "Read Items",
"operationId": "read_items_items__get",
"security": [{"OAuth2PasswordBearer": []}],
}
}
},
"components": {
"securitySchemes": {
"OAuth2PasswordBearer": {
"type": "oauth2",
"flows": {"password": {"scopes": {}, "tokenUrl": "token"}},
}
}
},
}
| fastapi |
python | from fastapi import FastAPI, Path, Query
from typing_extensions import Annotated
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
*,
item_id: Annotated[int, Path(title="The ID of the item to get", ge=0, le=1000)],
q: str,
size: Annotated[float, Query(gt=0, lt=10.5)],
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
if size:
results.update({"size": size})
return results
| import importlib
from base64 import b64encode
import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py39
@pytest.fixture(
name="client",
params=[
"tutorial006",
"tutorial006_an",
pytest.param("tutorial006_an_py39", marks=needs_py39),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.security.{request.param}")
client = TestClient(mod.app)
return client
def test_security_http_basic(client: TestClient):
response = client.get("/users/me", auth=("john", "secret"))
assert response.status_code == 200, response.text
assert response.json() == {"username": "john", "password": "secret"}
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_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"}}
},
}
| fastapi |
python | from fastapi import FastAPI, Path, Query
from typing_extensions import Annotated
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
*,
item_id: Annotated[int, Path(title="The ID of the item to get", ge=0, le=1000)],
q: str,
size: Annotated[float, Query(gt=0, lt=10.5)],
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
if size:
results.update({"size": size})
return results
| import importlib
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
"tutorial006",
pytest.param("tutorial006_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.query_params.{request.param}")
c = TestClient(mod.app)
return c
def test_foo_needy_very(client: TestClient):
response = client.get("/items/foo?needy=very")
assert response.status_code == 200
assert response.json() == {
"item_id": "foo",
"needy": "very",
"skip": 0,
"limit": None,
}
def test_foo_no_needy(client: TestClient):
response = client.get("/items/foo?skip=a&limit=b")
assert response.status_code == 422
assert response.json() == IsDict(
{
"detail": [
{
"type": "missing",
"loc": ["query", "needy"],
"msg": "Field required",
"input": None,
},
{
"type": "int_parsing",
"loc": ["query", "skip"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "a",
},
{
"type": "int_parsing",
"loc": ["query", "limit"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "b",
},
]
}
) | IsDict(
# TODO: remove when deprecating Pydantic v1
{
"detail": [
{
"loc": ["query", "needy"],
"msg": "field required",
"type": "value_error.missing",
},
{
"loc": ["query", "skip"],
"msg": "value is not a valid integer",
"type": "type_error.integer",
},
{
"loc": ["query", "limit"],
"msg": "value is not a valid integer",
"type": "type_error.integer",
},
]
}
)
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Read User Item",
"operationId": "read_user_item_items__item_id__get",
"parameters": [
{
"required": True,
"schema": {"title": "Item Id", "type": "string"},
"name": "item_id",
"in": "path",
},
{
"required": True,
"schema": {"title": "Needy", "type": "string"},
"name": "needy",
"in": "query",
},
{
"required": False,
"schema": {
"title": "Skip",
"type": "integer",
"default": 0,
},
"name": "skip",
"in": "query",
},
{
"required": False,
"schema": IsDict(
{
"anyOf": [{"type": "integer"}, {"type": "null"}],
"title": "Limit",
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{"title": "Limit", "type": "integer"}
),
"name": "limit",
"in": "query",
},
],
}
}
},
"components": {
"schemas": {
"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"},
}
},
},
}
},
}
| fastapi |
python | from typing import Union
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from typing_extensions import Annotated
app = FastAPI()
async def common_parameters(
q: Union[str, None] = None, skip: int = 0, limit: int = 100
):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Items!", "params": commons}
@app.get("/users/")
async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
return {"message": "Hello Users!", "params": commons}
client = TestClient(app)
async def override_dependency(q: Union[str, None] = None):
return {"q": q, "skip": 5, "limit": 10}
app.dependency_overrides[common_parameters] = override_dependency
def test_override_in_items():
response = client.get("/items/")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": None, "skip": 5, "limit": 10},
}
def test_override_in_items_with_q():
response = client.get("/items/?q=foo")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
def test_override_in_items_with_params():
response = client.get("/items/?q=foo&skip=100&limit=200")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
| import gzip
import json
import pytest
from fastapi import Request
from fastapi.testclient import TestClient
from docs_src.custom_request_and_route.tutorial001 import app
@app.get("/check-class")
async def check_gzip_request(request: Request):
return {"request_class": type(request).__name__}
client = TestClient(app)
@pytest.mark.parametrize("compress", [True, False])
def test_gzip_request(compress):
n = 1000
headers = {}
body = [1] * n
data = json.dumps(body).encode()
if compress:
data = gzip.compress(data)
headers["Content-Encoding"] = "gzip"
headers["Content-Type"] = "application/json"
response = client.post("/sum", content=data, headers=headers)
assert response.json() == {"sum": n}
def test_request_class():
response = client.get("/check-class")
assert response.json() == {"request_class": "GzipRequest"}
| fastapi |
python | from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
*,
item_id: int = Path(title="The ID of the item to get", gt=0, le=1000),
q: str,
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
| import importlib
import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2
@pytest.fixture(
name="client",
params=[
"tutorial005",
pytest.param("tutorial005_py39", marks=needs_py39),
pytest.param("tutorial005_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(
f"docs_src.path_operation_configuration.{request.param}"
)
client = TestClient(mod.app)
return client
def test_query_params_str_validations(client: TestClient):
response = client.post("/items/", json={"name": "Foo", "price": 42})
assert response.status_code == 200, response.text
assert response.json() == {
"name": "Foo",
"price": 42,
"description": None,
"tax": None,
"tags": [],
}
@needs_pydanticv2
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": {
"/items/": {
"post": {
"responses": {
"200": {
"description": "The created item",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Create an item",
"description": "Create an item with all the information:\n\n- **name**: each item must have a name\n- **description**: a long description\n- **price**: required\n- **tax**: if the item doesn't have tax, you can omit this\n- **tags**: a set of unique tag strings for this item",
"operationId": "create_item_items__post",
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
}
},
"required": True,
},
}
}
},
"components": {
"schemas": {
"Item": {
"title": "Item",
"required": ["name", "price"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"description": {
"title": "Description",
"anyOf": [{"type": "string"}, {"type": "null"}],
},
"price": {"title": "Price", "type": "number"},
"tax": {
"title": "Tax",
"anyOf": [{"type": "number"}, {"type": "null"}],
},
"tags": {
"title": "Tags",
"uniqueItems": True,
"type": "array",
"items": {"type": "string"},
"default": [],
},
},
},
"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"},
}
},
},
}
},
}
# TODO: remove when deprecating Pydantic v1
@needs_pydanticv1
def test_openapi_schema_pv1(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": {
"/items/": {
"post": {
"responses": {
"200": {
"description": "The created item",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Create an item",
"description": "Create an item with all the information:\n\n- **name**: each item must have a name\n- **description**: a long description\n- **price**: required\n- **tax**: if the item doesn't have tax, you can omit this\n- **tags**: a set of unique tag strings for this item",
"operationId": "create_item_items__post",
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
}
},
"required": True,
},
}
}
},
"components": {
"schemas": {
"Item": {
"title": "Item",
"required": ["name", "price"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"description": {"title": "Description", "type": "string"},
"price": {"title": "Price", "type": "number"},
"tax": {"title": "Tax", "type": "number"},
"tags": {
"title": "Tags",
"uniqueItems": True,
"type": "array",
"items": {"type": "string"},
"default": [],
},
},
},
"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"},
}
},
},
}
},
}
| fastapi |
python | from fastapi import FastAPI, Path, Query
from typing_extensions import Annotated
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
*,
item_id: Annotated[int, Path(title="The ID of the item to get", ge=0, le=1000)],
q: str,
size: Annotated[float, Query(gt=0, lt=10.5)],
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
if size:
results.update({"size": size})
return results
| import pytest
from fastapi.testclient import TestClient
from docs_src.path_operation_configuration.tutorial006 import app
client = TestClient(app)
@pytest.mark.parametrize(
"path,expected_status,expected_response",
[
("/items/", 200, [{"name": "Foo", "price": 42}]),
("/users/", 200, [{"username": "johndoe"}]),
("/elements/", 200, [{"item_id": "Foo"}]),
],
)
def test_query_params_str_validations(path, expected_status, expected_response):
response = client.get(path)
assert response.status_code == expected_status
assert response.json() == expected_response
def test_openapi_schema():
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": {
"/items/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"tags": ["items"],
"summary": "Read Items",
"operationId": "read_items_items__get",
}
},
"/users/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"tags": ["users"],
"summary": "Read Users",
"operationId": "read_users_users__get",
}
},
"/elements/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"tags": ["items"],
"summary": "Read Elements",
"operationId": "read_elements_elements__get",
"deprecated": True,
}
},
},
}
| fastapi |
python | from __future__ import annotations
import warnings
from collections.abc import Awaitable, Callable, Mapping, Sequence
from typing import Any, ParamSpec, TypeVar
from starlette.datastructures import State, URLPath
from starlette.middleware import Middleware, _MiddlewareFactory
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.middleware.errors import ServerErrorMiddleware
from starlette.middleware.exceptions import ExceptionMiddleware
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import BaseRoute, Router
from starlette.types import ASGIApp, ExceptionHandler, Lifespan, Receive, Scope, Send
from starlette.websockets import WebSocket
AppType = TypeVar("AppType", bound="Starlette")
P = ParamSpec("P")
class Starlette:
"""Creates an Starlette application."""
def __init__(
self: AppType,
debug: bool = False,
routes: Sequence[BaseRoute] | None = None,
middleware: Sequence[Middleware] | None = None,
exception_handlers: Mapping[Any, ExceptionHandler] | None = None,
on_startup: Sequence[Callable[[], Any]] | None = None,
on_shutdown: Sequence[Callable[[], Any]] | None = None,
lifespan: Lifespan[AppType] | None = None,
) -> None:
"""Initializes the application.
Parameters:
debug: Boolean indicating if debug tracebacks should be returned on errors.
routes: A list of routes to serve incoming HTTP and WebSocket requests.
middleware: A list of middleware to run for every request. A starlette
application will always automatically include two middleware classes.
`ServerErrorMiddleware` is added as the very outermost middleware, to handle
any uncaught errors occurring anywhere in the entire stack.
`ExceptionMiddleware` is added as the very innermost middleware, to deal
with handled exception cases occurring in the routing or endpoints.
exception_handlers: A mapping of either integer status codes,
or exception class types onto callables which handle the exceptions.
Exception handler callables should be of the form
`handler(request, exc) -> response` and may be either standard functions, or
async functions.
on_startup: A list of callables to run on application startup.
Startup handler callables do not take any arguments, and may be either
standard functions, or async functions.
on_shutdown: A list of callables to run on application shutdown.
Shutdown handler callables do not take any arguments, and may be either
standard functions, or async functions.
lifespan: A lifespan context function, which can be used to perform
startup and shutdown tasks. This is a newer style that replaces the
`on_startup` and `on_shutdown` handlers. Use one or the other, not both.
"""
# The lifespan context function is a newer style that replaces
# on_startup / on_shutdown handlers. Use one or the other, not both.
assert lifespan is None or (on_startup is None and on_shutdown is None), (
"Use either 'lifespan' or 'on_startup'/'on_shutdown', not both."
)
self.debug = debug
self.state = State()
self.router = Router(routes, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan)
self.exception_handlers = {} if exception_handlers is None else dict(exception_handlers)
self.user_middleware = [] if middleware is None else list(middleware)
self.middleware_stack: ASGIApp | None = None
def build_middleware_stack(self) -> ASGIApp:
debug = self.debug
error_handler = None
exception_handlers: dict[Any, ExceptionHandler] = {}
for key, value in self.exception_handlers.items():
if key in (500, Exception):
error_handler = value
else:
exception_handlers[key] = value
middleware = (
[Middleware(ServerErrorMiddleware, handler=error_handler, debug=debug)]
+ self.user_middleware
+ [Middleware(ExceptionMiddleware, handlers=exception_handlers, debug=debug)]
)
app = self.router
for cls, args, kwargs in reversed(middleware):
app = cls(app, *args, **kwargs)
return app
@property
def routes(self) -> list[BaseRoute]:
return self.router.routes
def url_path_for(self, name: str, /, **path_params: Any) -> URLPath:
return self.router.url_path_for(name, **path_params)
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
scope["app"] = self
if self.middleware_stack is None:
self.middleware_stack = self.build_middleware_stack()
await self.middleware_stack(scope, receive, send)
def on_event(self, event_type: str) -> Callable: # type: ignore[type-arg]
return self.router.on_event(event_type) # pragma: no cover
def mount(self, path: str, app: ASGIApp, name: str | None = None) -> None:
self.router.mount(path, app=app, name=name) # pragma: no cover
def host(self, host: str, app: ASGIApp, name: str | None = None) -> None:
self.router.host(host, app=app, name=name) # pragma: no cover
def add_middleware(
self,
middleware_class: _MiddlewareFactory[P],
*args: P.args,
**kwargs: P.kwargs,
) -> None:
if self.middleware_stack is not None: # pragma: no cover
raise RuntimeError("Cannot add middleware after an application has started")
self.user_middleware.insert(0, Middleware(middleware_class, *args, **kwargs))
def add_exception_handler(
self,
exc_class_or_status_code: int | type[Exception],
handler: ExceptionHandler,
) -> None: # pragma: no cover
self.exception_handlers[exc_class_or_status_code] = handler
def add_event_handler(
self,
event_type: str,
func: Callable, # type: ignore[type-arg]
) -> None: # pragma: no cover
self.router.add_event_handler(event_type, func)
def add_route(
self,
path: str,
route: Callable[[Request], Awaitable[Response] | Response],
methods: list[str] | None = None,
name: str | None = None,
include_in_schema: bool = True,
) -> None: # pragma: no cover
self.router.add_route(path, route, methods=methods, name=name, include_in_schema=include_in_schema)
def add_websocket_route(
self,
path: str,
route: Callable[[WebSocket], Awaitable[None]],
name: str | None = None,
) -> None: # pragma: no cover
self.router.add_websocket_route(path, route, name=name)
def exception_handler(self, exc_class_or_status_code: int | type[Exception]) -> Callable: # type: ignore[type-arg]
warnings.warn(
"The `exception_handler` decorator is deprecated, and will be removed in version 1.0.0. "
"Refer to https://starlette.dev/exceptions/ for the recommended approach.",
DeprecationWarning,
)
def decorator(func: Callable) -> Callable: # type: ignore[type-arg]
self.add_exception_handler(exc_class_or_status_code, func)
return func
return decorator
def route(
self,
path: str,
methods: list[str] | None = None,
name: str | None = None,
include_in_schema: bool = True,
) -> Callable: # type: ignore[type-arg]
"""
We no longer document this decorator style API, and its usage is discouraged.
Instead you should use the following approach:
>>> routes = [Route(path, endpoint=...), ...]
>>> app = Starlette(routes=routes)
"""
warnings.warn(
"The `route` decorator is deprecated, and will be removed in version 1.0.0. "
"Refer to https://starlette.dev/routing/ for the recommended approach.",
DeprecationWarning,
)
def decorator(func: Callable) -> Callable: # type: ignore[type-arg]
self.router.add_route(
path,
func,
methods=methods,
name=name,
include_in_schema=include_in_schema,
)
return func
return decorator
def websocket_route(self, path: str, name: str | None = None) -> Callable: # type: ignore[type-arg]
"""
We no longer document this decorator style API, and its usage is discouraged.
Instead you should use the following approach:
>>> routes = [WebSocketRoute(path, endpoint=...), ...]
>>> app = Starlette(routes=routes)
"""
warnings.warn(
"The `websocket_route` decorator is deprecated, and will be removed in version 1.0.0. "
"Refer to https://starlette.dev/routing/#websocket-routing for the recommended approach.",
DeprecationWarning,
)
def decorator(func: Callable) -> Callable: # type: ignore[type-arg]
self.router.add_websocket_route(path, func, name=name)
return func
return decorator
def middleware(self, middleware_type: str) -> Callable: # type: ignore[type-arg]
"""
We no longer document this decorator style API, and its usage is discouraged.
Instead you should use the following approach:
>>> middleware = [Middleware(...), ...]
>>> app = Starlette(middleware=middleware)
"""
warnings.warn(
"The `middleware` decorator is deprecated, and will be removed in version 1.0.0. "
"Refer to https://starlette.dev/middleware/#using-middleware for recommended approach.",
DeprecationWarning,
)
assert middleware_type == "http", 'Currently only middleware("http") is supported.'
def decorator(func: Callable) -> Callable: # type: ignore[type-arg]
self.add_middleware(BaseHTTPMiddleware, dispatch=func)
return func
return decorator
| from __future__ import annotations
import os
from collections.abc import AsyncGenerator, AsyncIterator, Callable, Generator
from contextlib import asynccontextmanager
from pathlib import Path
import anyio.from_thread
import pytest
from starlette import status
from starlette.applications import Starlette
from starlette.endpoints import HTTPEndpoint
from starlette.exceptions import HTTPException, WebSocketException
from starlette.middleware import Middleware
from starlette.middleware.base import RequestResponseEndpoint
from starlette.middleware.trustedhost import TrustedHostMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse, PlainTextResponse
from starlette.routing import Host, Mount, Route, Router, WebSocketRoute
from starlette.staticfiles import StaticFiles
from starlette.testclient import TestClient, WebSocketDenialResponse
from starlette.types import ASGIApp, Receive, Scope, Send
from starlette.websockets import WebSocket
from tests.types import TestClientFactory
async def error_500(request: Request, exc: HTTPException) -> JSONResponse:
return JSONResponse({"detail": "Server Error"}, status_code=500)
async def method_not_allowed(request: Request, exc: HTTPException) -> JSONResponse:
return JSONResponse({"detail": "Custom message"}, status_code=405)
async def http_exception(request: Request, exc: HTTPException) -> JSONResponse:
return JSONResponse({"detail": exc.detail}, status_code=exc.status_code)
def func_homepage(request: Request) -> PlainTextResponse:
return PlainTextResponse("Hello, world!")
async def async_homepage(request: Request) -> PlainTextResponse:
return PlainTextResponse("Hello, world!")
class Homepage(HTTPEndpoint):
def get(self, request: Request) -> PlainTextResponse:
return PlainTextResponse("Hello, world!")
def all_users_page(request: Request) -> PlainTextResponse:
return PlainTextResponse("Hello, everyone!")
def user_page(request: Request) -> PlainTextResponse:
username = request.path_params["username"]
return PlainTextResponse(f"Hello, {username}!")
def custom_subdomain(request: Request) -> PlainTextResponse:
return PlainTextResponse("Subdomain: " + request.path_params["subdomain"])
def runtime_error(request: Request) -> None:
raise RuntimeError()
async def websocket_endpoint(session: WebSocket) -> None:
await session.accept()
await session.send_text("Hello, world!")
await session.close()
async def websocket_raise_websocket_exception(websocket: WebSocket) -> None:
await websocket.accept()
raise WebSocketException(code=status.WS_1003_UNSUPPORTED_DATA)
async def websocket_raise_http_exception(websocket: WebSocket) -> None:
raise HTTPException(status_code=401, detail="Unauthorized")
class CustomWSException(Exception):
pass
async def websocket_raise_custom(websocket: WebSocket) -> None:
await websocket.accept()
raise CustomWSException()
def custom_ws_exception_handler(websocket: WebSocket, exc: CustomWSException) -> None:
anyio.from_thread.run(websocket.close, status.WS_1013_TRY_AGAIN_LATER)
users = Router(
routes=[
Route("/", endpoint=all_users_page),
Route("/{username}", endpoint=user_page),
]
)
subdomain = Router(
routes=[
Route("/", custom_subdomain),
]
)
exception_handlers = {
500: error_500,
405: method_not_allowed,
HTTPException: http_exception,
CustomWSException: custom_ws_exception_handler,
}
middleware = [Middleware(TrustedHostMiddleware, allowed_hosts=["testserver", "*.example.org"])]
app = Starlette(
routes=[
Route("/func", endpoint=func_homepage),
Route("/async", endpoint=async_homepage),
Route("/class", endpoint=Homepage),
Route("/500", endpoint=runtime_error),
WebSocketRoute("/ws", endpoint=websocket_endpoint),
WebSocketRoute("/ws-raise-websocket", endpoint=websocket_raise_websocket_exception),
WebSocketRoute("/ws-raise-http", endpoint=websocket_raise_http_exception),
WebSocketRoute("/ws-raise-custom", endpoint=websocket_raise_custom),
Mount("/users", app=users),
Host("{subdomain}.example.org", app=subdomain),
],
exception_handlers=exception_handlers, # type: ignore
middleware=middleware,
)
@pytest.fixture
def client(test_client_factory: TestClientFactory) -> Generator[TestClient, None, None]:
with test_client_factory(app) as client:
yield client
def test_url_path_for() -> None:
assert app.url_path_for("func_homepage") == "/func"
def test_func_route(client: TestClient) -> None:
response = client.get("/func")
assert response.status_code == 200
assert response.text == "Hello, world!"
response = client.head("/func")
assert response.status_code == 200
assert response.text == ""
def test_async_route(client: TestClient) -> None:
response = client.get("/async")
assert response.status_code == 200
assert response.text == "Hello, world!"
def test_class_route(client: TestClient) -> None:
response = client.get("/class")
assert response.status_code == 200
assert response.text == "Hello, world!"
def test_mounted_route(client: TestClient) -> None:
response = client.get("/users/")
assert response.status_code == 200
assert response.text == "Hello, everyone!"
def test_mounted_route_path_params(client: TestClient) -> None:
response = client.get("/users/tomchristie")
assert response.status_code == 200
assert response.text == "Hello, tomchristie!"
def test_subdomain_route(test_client_factory: TestClientFactory) -> None:
client = test_client_factory(app, base_url="https://foo.example.org/")
response = client.get("/")
assert response.status_code == 200
assert response.text == "Subdomain: foo"
def test_websocket_route(client: TestClient) -> None:
with client.websocket_connect("/ws") as session:
text = session.receive_text()
assert text == "Hello, world!"
def test_400(client: TestClient) -> None:
response = client.get("/404")
assert response.status_code == 404
assert response.json() == {"detail": "Not Found"}
def test_405(client: TestClient) -> None:
response = client.post("/func")
assert response.status_code == 405
assert response.json() == {"detail": "Custom message"}
response = client.post("/class")
assert response.status_code == 405
assert response.json() == {"detail": "Custom message"}
def test_500(test_client_factory: TestClientFactory) -> None:
client = test_client_factory(app, raise_server_exceptions=False)
response = client.get("/500")
assert response.status_code == 500
assert response.json() == {"detail": "Server Error"}
def test_websocket_raise_websocket_exception(client: TestClient) -> None:
with client.websocket_connect("/ws-raise-websocket") as session:
response = session.receive()
assert response == {
"type": "websocket.close",
"code": status.WS_1003_UNSUPPORTED_DATA,
"reason": "",
}
def test_websocket_raise_http_exception(client: TestClient) -> None:
with pytest.raises(WebSocketDenialResponse) as exc:
with client.websocket_connect("/ws-raise-http"):
pass # pragma: no cover
assert exc.value.status_code == 401
assert exc.value.content == b'{"detail":"Unauthorized"}'
def test_websocket_raise_custom_exception(client: TestClient) -> None:
with client.websocket_connect("/ws-raise-custom") as session:
response = session.receive()
assert response == {
"type": "websocket.close",
"code": status.WS_1013_TRY_AGAIN_LATER,
"reason": "",
}
def test_middleware(test_client_factory: TestClientFactory) -> None:
client = test_client_factory(app, base_url="http://incorrecthost")
response = client.get("/func")
assert response.status_code == 400
assert response.text == "Invalid host header"
def test_routes() -> None:
assert app.routes == [
Route("/func", endpoint=func_homepage, methods=["GET"]),
Route("/async", endpoint=async_homepage, methods=["GET"]),
Route("/class", endpoint=Homepage),
Route("/500", endpoint=runtime_error, methods=["GET"]),
WebSocketRoute("/ws", endpoint=websocket_endpoint),
WebSocketRoute("/ws-raise-websocket", endpoint=websocket_raise_websocket_exception),
WebSocketRoute("/ws-raise-http", endpoint=websocket_raise_http_exception),
WebSocketRoute("/ws-raise-custom", endpoint=websocket_raise_custom),
Mount(
"/users",
app=Router(
routes=[
Route("/", endpoint=all_users_page),
Route("/{username}", endpoint=user_page),
]
),
),
Host(
"{subdomain}.example.org",
app=Router(routes=[Route("/", endpoint=custom_subdomain)]),
),
]
def test_app_mount(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
path = os.path.join(tmpdir, "example.txt")
with open(path, "w") as file:
file.write("<file content>")
app = Starlette(
routes=[
Mount("/static", StaticFiles(directory=tmpdir)),
]
)
client = test_client_factory(app)
response = client.get("/static/example.txt")
assert response.status_code == 200
assert response.text == "<file content>"
response = client.post("/static/example.txt")
assert response.status_code == 405
assert response.text == "Method Not Allowed"
def test_app_debug(test_client_factory: TestClientFactory) -> None:
async def homepage(request: Request) -> None:
raise RuntimeError()
app = Starlette(
routes=[
Route("/", homepage),
],
)
app.debug = True
client = test_client_factory(app, raise_server_exceptions=False)
response = client.get("/")
assert response.status_code == 500
assert "RuntimeError" in response.text
assert app.debug
def test_app_add_route(test_client_factory: TestClientFactory) -> None:
async def homepage(request: Request) -> PlainTextResponse:
return PlainTextResponse("Hello, World!")
app = Starlette(
routes=[
Route("/", endpoint=homepage),
]
)
client = test_client_factory(app)
response = client.get("/")
assert response.status_code == 200
assert response.text == "Hello, World!"
def test_app_add_websocket_route(test_client_factory: TestClientFactory) -> None:
async def websocket_endpoint(session: WebSocket) -> None:
await session.accept()
await session.send_text("Hello, world!")
await session.close()
app = Starlette(
routes=[
WebSocketRoute("/ws", endpoint=websocket_endpoint),
]
)
client = test_client_factory(app)
with client.websocket_connect("/ws") as session:
text = session.receive_text()
assert text == "Hello, world!"
def test_app_add_event_handler(test_client_factory: TestClientFactory) -> None:
startup_complete = False
cleanup_complete = False
def run_startup() -> None:
nonlocal startup_complete
startup_complete = True
def run_cleanup() -> None:
nonlocal cleanup_complete
cleanup_complete = True
with pytest.deprecated_call(match="The on_startup and on_shutdown parameters are deprecated"):
app = Starlette(
on_startup=[run_startup],
on_shutdown=[run_cleanup],
)
assert not startup_complete
assert not cleanup_complete
with test_client_factory(app):
assert startup_complete
assert not cleanup_complete
assert startup_complete
assert cleanup_complete
def test_app_async_cm_lifespan(test_client_factory: TestClientFactory) -> None:
startup_complete = False
cleanup_complete = False
@asynccontextmanager
async def lifespan(app: ASGIApp) -> AsyncGenerator[None, None]:
nonlocal startup_complete, cleanup_complete
startup_complete = True
yield
cleanup_complete = True
app = Starlette(lifespan=lifespan)
assert not startup_complete
assert not cleanup_complete
with test_client_factory(app):
assert startup_complete
assert not cleanup_complete
assert startup_complete
assert cleanup_complete
deprecated_lifespan = pytest.mark.filterwarnings(
r"ignore"
r":(async )?generator function lifespans are deprecated, use an "
r"@contextlib\.asynccontextmanager function instead"
r":DeprecationWarning"
r":starlette.routing"
)
@deprecated_lifespan
def test_app_async_gen_lifespan(test_client_factory: TestClientFactory) -> None:
startup_complete = False
cleanup_complete = False
async def lifespan(app: ASGIApp) -> AsyncGenerator[None, None]:
nonlocal startup_complete, cleanup_complete
startup_complete = True
yield
cleanup_complete = True
app = Starlette(lifespan=lifespan) # type: ignore
assert not startup_complete
assert not cleanup_complete
with test_client_factory(app):
assert startup_complete
assert not cleanup_complete
assert startup_complete
assert cleanup_complete
@deprecated_lifespan
def test_app_sync_gen_lifespan(test_client_factory: TestClientFactory) -> None:
startup_complete = False
cleanup_complete = False
def lifespan(app: ASGIApp) -> Generator[None, None, None]:
nonlocal startup_complete, cleanup_complete
startup_complete = True
yield
cleanup_complete = True
app = Starlette(lifespan=lifespan) # type: ignore
assert not startup_complete
assert not cleanup_complete
with test_client_factory(app):
assert startup_complete
assert not cleanup_complete
assert startup_complete
assert cleanup_complete
def test_decorator_deprecations() -> None:
app = Starlette()
with pytest.deprecated_call(
match=("The `exception_handler` decorator is deprecated, and will be removed in version 1.0.0.")
) as record:
app.exception_handler(500)(http_exception)
assert len(record) == 1
with pytest.deprecated_call(
match=("The `middleware` decorator is deprecated, and will be removed in version 1.0.0.")
) as record:
async def middleware(request: Request, call_next: RequestResponseEndpoint) -> None: ... # pragma: no cover
app.middleware("http")(middleware)
assert len(record) == 1
with pytest.deprecated_call(
match=("The `route` decorator is deprecated, and will be removed in version 1.0.0.")
) as record:
app.route("/")(async_homepage)
assert len(record) == 1
with pytest.deprecated_call(
match=("The `websocket_route` decorator is deprecated, and will be removed in version 1.0.0.")
) as record:
app.websocket_route("/ws")(websocket_endpoint)
assert len(record) == 1
with pytest.deprecated_call(
match=("The `on_event` decorator is deprecated, and will be removed in version 1.0.0.")
) as record:
async def startup() -> None: ... # pragma: no cover
app.on_event("startup")(startup)
assert len(record) == 1
def test_middleware_stack_init(test_client_factory: TestClientFactory) -> None:
class NoOpMiddleware:
def __init__(self, app: ASGIApp):
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
await self.app(scope, receive, send)
class SimpleInitializableMiddleware:
counter = 0
def __init__(self, app: ASGIApp):
self.app = app
SimpleInitializableMiddleware.counter += 1
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
await self.app(scope, receive, send)
def get_app() -> ASGIApp:
app = Starlette()
app.add_middleware(SimpleInitializableMiddleware)
app.add_middleware(NoOpMiddleware)
return app
app = get_app()
with test_client_factory(app):
pass
assert SimpleInitializableMiddleware.counter == 1
test_client_factory(app).get("/foo")
assert SimpleInitializableMiddleware.counter == 1
app = get_app()
test_client_factory(app).get("/foo")
assert SimpleInitializableMiddleware.counter == 2
def test_middleware_args(test_client_factory: TestClientFactory) -> None:
calls: list[str] = []
class MiddlewareWithArgs:
def __init__(self, app: ASGIApp, arg: str) -> None:
self.app = app
self.arg = arg
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
calls.append(self.arg)
await self.app(scope, receive, send)
app = Starlette()
app.add_middleware(MiddlewareWithArgs, "foo")
app.add_middleware(MiddlewareWithArgs, "bar")
with test_client_factory(app):
pass
assert calls == ["bar", "foo"]
def test_middleware_factory(test_client_factory: TestClientFactory) -> None:
calls: list[str] = []
def _middleware_factory(app: ASGIApp, arg: str) -> ASGIApp:
async def _app(scope: Scope, receive: Receive, send: Send) -> None:
calls.append(arg)
await app(scope, receive, send)
return _app
def get_middleware_factory() -> Callable[[ASGIApp, str], ASGIApp]:
return _middleware_factory
app = Starlette()
app.add_middleware(_middleware_factory, arg="foo")
app.add_middleware(get_middleware_factory(), "bar")
with test_client_factory(app):
pass
assert calls == ["bar", "foo"]
def test_lifespan_app_subclass() -> None:
# This test exists to make sure that subclasses of Starlette
# (like FastAPI) are compatible with the types hints for Lifespan
class App(Starlette):
pass
@asynccontextmanager
async def lifespan(app: App) -> AsyncIterator[None]: # pragma: no cover
yield
App(lifespan=lifespan)
| starlette |
python | from __future__ import annotations
import functools
import inspect
from collections.abc import Callable, Sequence
from typing import Any, ParamSpec
from urllib.parse import urlencode
from starlette._utils import is_async_callable
from starlette.exceptions import HTTPException
from starlette.requests import HTTPConnection, Request
from starlette.responses import RedirectResponse
from starlette.websockets import WebSocket
_P = ParamSpec("_P")
def has_required_scope(conn: HTTPConnection, scopes: Sequence[str]) -> bool:
for scope in scopes:
if scope not in conn.auth.scopes:
return False
return True
def requires(
scopes: str | Sequence[str],
status_code: int = 403,
redirect: str | None = None,
) -> Callable[[Callable[_P, Any]], Callable[_P, Any]]:
scopes_list = [scopes] if isinstance(scopes, str) else list(scopes)
def decorator(
func: Callable[_P, Any],
) -> Callable[_P, Any]:
sig = inspect.signature(func)
for idx, parameter in enumerate(sig.parameters.values()):
if parameter.name == "request" or parameter.name == "websocket":
type_ = parameter.name
break
else:
raise Exception(f'No "request" or "websocket" argument on function "{func}"')
if type_ == "websocket":
# Handle websocket functions. (Always async)
@functools.wraps(func)
async def websocket_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> None:
websocket = kwargs.get("websocket", args[idx] if idx < len(args) else None)
assert isinstance(websocket, WebSocket)
if not has_required_scope(websocket, scopes_list):
await websocket.close()
else:
await func(*args, **kwargs)
return websocket_wrapper
elif is_async_callable(func):
# Handle async request/response functions.
@functools.wraps(func)
async def async_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> Any:
request = kwargs.get("request", args[idx] if idx < len(args) else None)
assert isinstance(request, Request)
if not has_required_scope(request, scopes_list):
if redirect is not None:
orig_request_qparam = urlencode({"next": str(request.url)})
next_url = f"{request.url_for(redirect)}?{orig_request_qparam}"
return RedirectResponse(url=next_url, status_code=303)
raise HTTPException(status_code=status_code)
return await func(*args, **kwargs)
return async_wrapper
else:
# Handle sync request/response functions.
@functools.wraps(func)
def sync_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> Any:
request = kwargs.get("request", args[idx] if idx < len(args) else None)
assert isinstance(request, Request)
if not has_required_scope(request, scopes_list):
if redirect is not None:
orig_request_qparam = urlencode({"next": str(request.url)})
next_url = f"{request.url_for(redirect)}?{orig_request_qparam}"
return RedirectResponse(url=next_url, status_code=303)
raise HTTPException(status_code=status_code)
return func(*args, **kwargs)
return sync_wrapper
return decorator
class AuthenticationError(Exception):
pass
class AuthenticationBackend:
async def authenticate(self, conn: HTTPConnection) -> tuple[AuthCredentials, BaseUser] | None:
raise NotImplementedError() # pragma: no cover
class AuthCredentials:
def __init__(self, scopes: Sequence[str] | None = None):
self.scopes = [] if scopes is None else list(scopes)
class BaseUser:
@property
def is_authenticated(self) -> bool:
raise NotImplementedError() # pragma: no cover
@property
def display_name(self) -> str:
raise NotImplementedError() # pragma: no cover
@property
def identity(self) -> str:
raise NotImplementedError() # pragma: no cover
class SimpleUser(BaseUser):
def __init__(self, username: str) -> None:
self.username = username
@property
def is_authenticated(self) -> bool:
return True
@property
def display_name(self) -> str:
return self.username
class UnauthenticatedUser(BaseUser):
@property
def is_authenticated(self) -> bool:
return False
@property
def display_name(self) -> str:
return ""
| from __future__ import annotations
import base64
import binascii
from collections.abc import Awaitable, Callable
from typing import Any
from urllib.parse import urlencode
import pytest
from starlette.applications import Starlette
from starlette.authentication import AuthCredentials, AuthenticationBackend, AuthenticationError, SimpleUser, requires
from starlette.endpoints import HTTPEndpoint
from starlette.middleware import Middleware
from starlette.middleware.authentication import AuthenticationMiddleware
from starlette.requests import HTTPConnection, Request
from starlette.responses import JSONResponse, Response
from starlette.routing import Route, WebSocketRoute
from starlette.websockets import WebSocket, WebSocketDisconnect
from tests.types import TestClientFactory
AsyncEndpoint = Callable[..., Awaitable[Response]]
SyncEndpoint = Callable[..., Response]
class BasicAuth(AuthenticationBackend):
async def authenticate(
self,
request: HTTPConnection,
) -> tuple[AuthCredentials, SimpleUser] | None:
if "Authorization" not in request.headers:
return None
auth = request.headers["Authorization"]
try:
scheme, credentials = auth.split()
decoded = base64.b64decode(credentials).decode("ascii")
except (ValueError, UnicodeDecodeError, binascii.Error):
raise AuthenticationError("Invalid basic auth credentials")
username, _, password = decoded.partition(":")
return AuthCredentials(["authenticated"]), SimpleUser(username)
def homepage(request: Request) -> JSONResponse:
return JSONResponse(
{
"authenticated": request.user.is_authenticated,
"user": request.user.display_name,
}
)
@requires("authenticated")
async def dashboard(request: Request) -> JSONResponse:
return JSONResponse(
{
"authenticated": request.user.is_authenticated,
"user": request.user.display_name,
}
)
@requires("authenticated", redirect="homepage")
async def admin(request: Request) -> JSONResponse:
return JSONResponse(
{
"authenticated": request.user.is_authenticated,
"user": request.user.display_name,
}
)
@requires("authenticated")
def dashboard_sync(request: Request) -> JSONResponse:
return JSONResponse(
{
"authenticated": request.user.is_authenticated,
"user": request.user.display_name,
}
)
class Dashboard(HTTPEndpoint):
@requires("authenticated")
def get(self, request: Request) -> JSONResponse:
return JSONResponse(
{
"authenticated": request.user.is_authenticated,
"user": request.user.display_name,
}
)
@requires("authenticated", redirect="homepage")
def admin_sync(request: Request) -> JSONResponse:
return JSONResponse(
{
"authenticated": request.user.is_authenticated,
"user": request.user.display_name,
}
)
@requires("authenticated")
async def websocket_endpoint(websocket: WebSocket) -> None:
await websocket.accept()
await websocket.send_json(
{
"authenticated": websocket.user.is_authenticated,
"user": websocket.user.display_name,
}
)
def async_inject_decorator(
**kwargs: Any,
) -> Callable[[AsyncEndpoint], Callable[..., Awaitable[Response]]]:
def wrapper(endpoint: AsyncEndpoint) -> Callable[..., Awaitable[Response]]:
async def app(request: Request) -> Response:
return await endpoint(request=request, **kwargs)
return app
return wrapper
@async_inject_decorator(additional="payload")
@requires("authenticated")
async def decorated_async(request: Request, additional: str) -> JSONResponse:
return JSONResponse(
{
"authenticated": request.user.is_authenticated,
"user": request.user.display_name,
"additional": additional,
}
)
def sync_inject_decorator(
**kwargs: Any,
) -> Callable[[SyncEndpoint], Callable[..., Response]]:
def wrapper(endpoint: SyncEndpoint) -> Callable[..., Response]:
def app(request: Request) -> Response:
return endpoint(request=request, **kwargs)
return app
return wrapper
@sync_inject_decorator(additional="payload")
@requires("authenticated")
def decorated_sync(request: Request, additional: str) -> JSONResponse:
return JSONResponse(
{
"authenticated": request.user.is_authenticated,
"user": request.user.display_name,
"additional": additional,
}
)
def ws_inject_decorator(**kwargs: Any) -> Callable[..., AsyncEndpoint]:
def wrapper(endpoint: AsyncEndpoint) -> AsyncEndpoint:
def app(websocket: WebSocket) -> Awaitable[Response]:
return endpoint(websocket=websocket, **kwargs)
return app
return wrapper
@ws_inject_decorator(additional="payload")
@requires("authenticated")
async def websocket_endpoint_decorated(websocket: WebSocket, additional: str) -> None:
await websocket.accept()
await websocket.send_json(
{
"authenticated": websocket.user.is_authenticated,
"user": websocket.user.display_name,
"additional": additional,
}
)
app = Starlette(
middleware=[Middleware(AuthenticationMiddleware, backend=BasicAuth())],
routes=[
Route("/", endpoint=homepage),
Route("/dashboard", endpoint=dashboard),
Route("/admin", endpoint=admin),
Route("/dashboard/sync", endpoint=dashboard_sync),
Route("/dashboard/class", endpoint=Dashboard),
Route("/admin/sync", endpoint=admin_sync),
Route("/dashboard/decorated", endpoint=decorated_async),
Route("/dashboard/decorated/sync", endpoint=decorated_sync),
WebSocketRoute("/ws", endpoint=websocket_endpoint),
WebSocketRoute("/ws/decorated", endpoint=websocket_endpoint_decorated),
],
)
def test_invalid_decorator_usage() -> None:
with pytest.raises(Exception):
@requires("authenticated")
def foo() -> None: # pragma: no cover
pass
def test_user_interface(test_client_factory: TestClientFactory) -> None:
with test_client_factory(app) as client:
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"authenticated": False, "user": ""}
response = client.get("/", auth=("tomchristie", "example"))
assert response.status_code == 200
assert response.json() == {"authenticated": True, "user": "tomchristie"}
def test_authentication_required(test_client_factory: TestClientFactory) -> None:
with test_client_factory(app) as client:
response = client.get("/dashboard")
assert response.status_code == 403
response = client.get("/dashboard", auth=("tomchristie", "example"))
assert response.status_code == 200
assert response.json() == {"authenticated": True, "user": "tomchristie"}
response = client.get("/dashboard/sync")
assert response.status_code == 403
response = client.get("/dashboard/sync", auth=("tomchristie", "example"))
assert response.status_code == 200
assert response.json() == {"authenticated": True, "user": "tomchristie"}
response = client.get("/dashboard/class")
assert response.status_code == 403
response = client.get("/dashboard/class", auth=("tomchristie", "example"))
assert response.status_code == 200
assert response.json() == {"authenticated": True, "user": "tomchristie"}
response = client.get("/dashboard/decorated", auth=("tomchristie", "example"))
assert response.status_code == 200
assert response.json() == {
"authenticated": True,
"user": "tomchristie",
"additional": "payload",
}
response = client.get("/dashboard/decorated")
assert response.status_code == 403
response = client.get("/dashboard/decorated/sync", auth=("tomchristie", "example"))
assert response.status_code == 200
assert response.json() == {
"authenticated": True,
"user": "tomchristie",
"additional": "payload",
}
response = client.get("/dashboard/decorated/sync")
assert response.status_code == 403
response = client.get("/dashboard", headers={"Authorization": "basic foobar"})
assert response.status_code == 400
assert response.text == "Invalid basic auth credentials"
def test_websocket_authentication_required(
test_client_factory: TestClientFactory,
) -> None:
with test_client_factory(app) as client:
with pytest.raises(WebSocketDisconnect):
with client.websocket_connect("/ws"):
pass # pragma: no cover
with pytest.raises(WebSocketDisconnect):
with client.websocket_connect("/ws", headers={"Authorization": "basic foobar"}):
pass # pragma: no cover
with client.websocket_connect("/ws", auth=("tomchristie", "example")) as websocket:
data = websocket.receive_json()
assert data == {"authenticated": True, "user": "tomchristie"}
with pytest.raises(WebSocketDisconnect):
with client.websocket_connect("/ws/decorated"):
pass # pragma: no cover
with pytest.raises(WebSocketDisconnect):
with client.websocket_connect("/ws/decorated", headers={"Authorization": "basic foobar"}):
pass # pragma: no cover
with client.websocket_connect("/ws/decorated", auth=("tomchristie", "example")) as websocket:
data = websocket.receive_json()
assert data == {
"authenticated": True,
"user": "tomchristie",
"additional": "payload",
}
def test_authentication_redirect(test_client_factory: TestClientFactory) -> None:
with test_client_factory(app) as client:
response = client.get("/admin")
assert response.status_code == 200
url = "{}?{}".format("http://testserver/", urlencode({"next": "http://testserver/admin"}))
assert response.url == url
response = client.get("/admin", auth=("tomchristie", "example"))
assert response.status_code == 200
assert response.json() == {"authenticated": True, "user": "tomchristie"}
response = client.get("/admin/sync")
assert response.status_code == 200
url = "{}?{}".format("http://testserver/", urlencode({"next": "http://testserver/admin/sync"}))
assert response.url == url
response = client.get("/admin/sync", auth=("tomchristie", "example"))
assert response.status_code == 200
assert response.json() == {"authenticated": True, "user": "tomchristie"}
def on_auth_error(request: HTTPConnection, exc: AuthenticationError) -> JSONResponse:
return JSONResponse({"error": str(exc)}, status_code=401)
@requires("authenticated")
def control_panel(request: Request) -> JSONResponse:
return JSONResponse(
{
"authenticated": request.user.is_authenticated,
"user": request.user.display_name,
}
)
other_app = Starlette(
routes=[Route("/control-panel", control_panel)],
middleware=[Middleware(AuthenticationMiddleware, backend=BasicAuth(), on_error=on_auth_error)],
)
def test_custom_on_error(test_client_factory: TestClientFactory) -> None:
with test_client_factory(other_app) as client:
response = client.get("/control-panel", auth=("tomchristie", "example"))
assert response.status_code == 200
assert response.json() == {"authenticated": True, "user": "tomchristie"}
response = client.get("/control-panel", headers={"Authorization": "basic foobar"})
assert response.status_code == 401
assert response.json() == {"error": "Invalid basic auth credentials"}
| starlette |
python | from __future__ import annotations
import math
import uuid
from typing import Any, ClassVar, Generic, TypeVar
T = TypeVar("T")
class Convertor(Generic[T]):
regex: ClassVar[str] = ""
def convert(self, value: str) -> T:
raise NotImplementedError() # pragma: no cover
def to_string(self, value: T) -> str:
raise NotImplementedError() # pragma: no cover
class StringConvertor(Convertor[str]):
regex = "[^/]+"
def convert(self, value: str) -> str:
return value
def to_string(self, value: str) -> str:
value = str(value)
assert "/" not in value, "May not contain path separators"
assert value, "Must not be empty"
return value
class PathConvertor(Convertor[str]):
regex = ".*"
def convert(self, value: str) -> str:
return str(value)
def to_string(self, value: str) -> str:
return str(value)
class IntegerConvertor(Convertor[int]):
regex = "[0-9]+"
def convert(self, value: str) -> int:
return int(value)
def to_string(self, value: int) -> str:
value = int(value)
assert value >= 0, "Negative integers are not supported"
return str(value)
class FloatConvertor(Convertor[float]):
regex = r"[0-9]+(\.[0-9]+)?"
def convert(self, value: str) -> float:
return float(value)
def to_string(self, value: float) -> str:
value = float(value)
assert value >= 0.0, "Negative floats are not supported"
assert not math.isnan(value), "NaN values are not supported"
assert not math.isinf(value), "Infinite values are not supported"
return ("%0.20f" % value).rstrip("0").rstrip(".")
class UUIDConvertor(Convertor[uuid.UUID]):
regex = "[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12}"
def convert(self, value: str) -> uuid.UUID:
return uuid.UUID(value)
def to_string(self, value: uuid.UUID) -> str:
return str(value)
CONVERTOR_TYPES: dict[str, Convertor[Any]] = {
"str": StringConvertor(),
"path": PathConvertor(),
"int": IntegerConvertor(),
"float": FloatConvertor(),
"uuid": UUIDConvertor(),
}
def register_url_convertor(key: str, convertor: Convertor[Any]) -> None:
CONVERTOR_TYPES[key] = convertor
| from collections.abc import Iterator
from datetime import datetime
from uuid import UUID
import pytest
from starlette import convertors
from starlette.convertors import Convertor, register_url_convertor
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route, Router
from tests.types import TestClientFactory
@pytest.fixture(scope="module", autouse=True)
def refresh_convertor_types() -> Iterator[None]:
convert_types = convertors.CONVERTOR_TYPES.copy()
yield
convertors.CONVERTOR_TYPES = convert_types
class DateTimeConvertor(Convertor[datetime]):
regex = "[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(.[0-9]+)?"
def convert(self, value: str) -> datetime:
return datetime.strptime(value, "%Y-%m-%dT%H:%M:%S")
def to_string(self, value: datetime) -> str:
return value.strftime("%Y-%m-%dT%H:%M:%S")
@pytest.fixture(scope="function")
def app() -> Router:
register_url_convertor("datetime", DateTimeConvertor())
def datetime_convertor(request: Request) -> JSONResponse:
param = request.path_params["param"]
assert isinstance(param, datetime)
return JSONResponse({"datetime": param.strftime("%Y-%m-%dT%H:%M:%S")})
return Router(
routes=[
Route(
"/datetime/{param:datetime}",
endpoint=datetime_convertor,
name="datetime-convertor",
)
]
)
def test_datetime_convertor(test_client_factory: TestClientFactory, app: Router) -> None:
client = test_client_factory(app)
response = client.get("/datetime/2020-01-01T00:00:00")
assert response.json() == {"datetime": "2020-01-01T00:00:00"}
assert (
app.url_path_for("datetime-convertor", param=datetime(1996, 1, 22, 23, 0, 0)) == "/datetime/1996-01-22T23:00:00"
)
@pytest.mark.parametrize("param, status_code", [("1.0", 200), ("1-0", 404)])
def test_default_float_convertor(test_client_factory: TestClientFactory, param: str, status_code: int) -> None:
def float_convertor(request: Request) -> JSONResponse:
param = request.path_params["param"]
assert isinstance(param, float)
return JSONResponse({"float": param})
app = Router(routes=[Route("/{param:float}", endpoint=float_convertor)])
client = test_client_factory(app)
response = client.get(f"/{param}")
assert response.status_code == status_code
@pytest.mark.parametrize(
"param, status_code",
[
("00000000-aaaa-ffff-9999-000000000000", 200),
("00000000aaaaffff9999000000000000", 200),
("00000000-AAAA-FFFF-9999-000000000000", 200),
("00000000AAAAFFFF9999000000000000", 200),
("not-a-uuid", 404),
],
)
def test_default_uuid_convertor(test_client_factory: TestClientFactory, param: str, status_code: int) -> None:
def uuid_convertor(request: Request) -> JSONResponse:
param = request.path_params["param"]
assert isinstance(param, UUID)
return JSONResponse("ok")
app = Router(routes=[Route("/{param:uuid}", endpoint=uuid_convertor)])
client = test_client_factory(app)
response = client.get(f"/{param}")
assert response.status_code == status_code
| starlette |
python | from __future__ import annotations
from collections.abc import AsyncGenerator
from dataclasses import dataclass, field
from enum import Enum
from tempfile import SpooledTemporaryFile
from typing import TYPE_CHECKING
from urllib.parse import unquote_plus
from starlette.datastructures import FormData, Headers, UploadFile
if TYPE_CHECKING:
import python_multipart as multipart
from python_multipart.multipart import MultipartCallbacks, QuerystringCallbacks, parse_options_header
else:
try:
try:
import python_multipart as multipart
from python_multipart.multipart import parse_options_header
except ModuleNotFoundError: # pragma: no cover
import multipart
from multipart.multipart import parse_options_header
except ModuleNotFoundError: # pragma: no cover
multipart = None
parse_options_header = None
class FormMessage(Enum):
FIELD_START = 1
FIELD_NAME = 2
FIELD_DATA = 3
FIELD_END = 4
END = 5
@dataclass
class MultipartPart:
content_disposition: bytes | None = None
field_name: str = ""
data: bytearray = field(default_factory=bytearray)
file: UploadFile | None = None
item_headers: list[tuple[bytes, bytes]] = field(default_factory=list)
def _user_safe_decode(src: bytes | bytearray, codec: str) -> str:
try:
return src.decode(codec)
except (UnicodeDecodeError, LookupError):
return src.decode("latin-1")
class MultiPartException(Exception):
def __init__(self, message: str) -> None:
self.message = message
class FormParser:
def __init__(self, headers: Headers, stream: AsyncGenerator[bytes, None]) -> None:
assert multipart is not None, "The `python-multipart` library must be installed to use form parsing."
self.headers = headers
self.stream = stream
self.messages: list[tuple[FormMessage, bytes]] = []
def on_field_start(self) -> None:
message = (FormMessage.FIELD_START, b"")
self.messages.append(message)
def on_field_name(self, data: bytes, start: int, end: int) -> None:
message = (FormMessage.FIELD_NAME, data[start:end])
self.messages.append(message)
def on_field_data(self, data: bytes, start: int, end: int) -> None:
message = (FormMessage.FIELD_DATA, data[start:end])
self.messages.append(message)
def on_field_end(self) -> None:
message = (FormMessage.FIELD_END, b"")
self.messages.append(message)
def on_end(self) -> None:
message = (FormMessage.END, b"")
self.messages.append(message)
async def parse(self) -> FormData:
# Callbacks dictionary.
callbacks: QuerystringCallbacks = {
"on_field_start": self.on_field_start,
"on_field_name": self.on_field_name,
"on_field_data": self.on_field_data,
"on_field_end": self.on_field_end,
"on_end": self.on_end,
}
# Create the parser.
parser = multipart.QuerystringParser(callbacks)
field_name = b""
field_value = b""
items: list[tuple[str, str | UploadFile]] = []
# Feed the parser with data from the request.
async for chunk in self.stream:
if chunk:
parser.write(chunk)
else:
parser.finalize()
messages = list(self.messages)
self.messages.clear()
for message_type, message_bytes in messages:
if message_type == FormMessage.FIELD_START:
field_name = b""
field_value = b""
elif message_type == FormMessage.FIELD_NAME:
field_name += message_bytes
elif message_type == FormMessage.FIELD_DATA:
field_value += message_bytes
elif message_type == FormMessage.FIELD_END:
name = unquote_plus(field_name.decode("latin-1"))
value = unquote_plus(field_value.decode("latin-1"))
items.append((name, value))
return FormData(items)
class MultiPartParser:
spool_max_size = 1024 * 1024 # 1MB
"""The maximum size of the spooled temporary file used to store file data."""
max_part_size = 1024 * 1024 # 1MB
"""The maximum size of a part in the multipart request."""
def __init__(
self,
headers: Headers,
stream: AsyncGenerator[bytes, None],
*,
max_files: int | float = 1000,
max_fields: int | float = 1000,
max_part_size: int = 1024 * 1024, # 1MB
) -> None:
assert multipart is not None, "The `python-multipart` library must be installed to use form parsing."
self.headers = headers
self.stream = stream
self.max_files = max_files
self.max_fields = max_fields
self.items: list[tuple[str, str | UploadFile]] = []
self._current_files = 0
self._current_fields = 0
self._current_partial_header_name: bytes = b""
self._current_partial_header_value: bytes = b""
self._current_part = MultipartPart()
self._charset = ""
self._file_parts_to_write: list[tuple[MultipartPart, bytes]] = []
self._file_parts_to_finish: list[MultipartPart] = []
self._files_to_close_on_error: list[SpooledTemporaryFile[bytes]] = []
self.max_part_size = max_part_size
def on_part_begin(self) -> None:
self._current_part = MultipartPart()
def on_part_data(self, data: bytes, start: int, end: int) -> None:
message_bytes = data[start:end]
if self._current_part.file is None:
if len(self._current_part.data) + len(message_bytes) > self.max_part_size:
raise MultiPartException(f"Part exceeded maximum size of {int(self.max_part_size / 1024)}KB.")
self._current_part.data.extend(message_bytes)
else:
self._file_parts_to_write.append((self._current_part, message_bytes))
def on_part_end(self) -> None:
if self._current_part.file is None:
self.items.append(
(
self._current_part.field_name,
_user_safe_decode(self._current_part.data, self._charset),
)
)
else:
self._file_parts_to_finish.append(self._current_part)
# The file can be added to the items right now even though it's not
# finished yet, because it will be finished in the `parse()` method, before
# self.items is used in the return value.
self.items.append((self._current_part.field_name, self._current_part.file))
def on_header_field(self, data: bytes, start: int, end: int) -> None:
self._current_partial_header_name += data[start:end]
def on_header_value(self, data: bytes, start: int, end: int) -> None:
self._current_partial_header_value += data[start:end]
def on_header_end(self) -> None:
field = self._current_partial_header_name.lower()
if field == b"content-disposition":
self._current_part.content_disposition = self._current_partial_header_value
self._current_part.item_headers.append((field, self._current_partial_header_value))
self._current_partial_header_name = b""
self._current_partial_header_value = b""
def on_headers_finished(self) -> None:
disposition, options = parse_options_header(self._current_part.content_disposition)
try:
self._current_part.field_name = _user_safe_decode(options[b"name"], self._charset)
except KeyError:
raise MultiPartException('The Content-Disposition header field "name" must be provided.')
if b"filename" in options:
self._current_files += 1
if self._current_files > self.max_files:
raise MultiPartException(f"Too many files. Maximum number of files is {self.max_files}.")
filename = _user_safe_decode(options[b"filename"], self._charset)
tempfile = SpooledTemporaryFile(max_size=self.spool_max_size)
self._files_to_close_on_error.append(tempfile)
self._current_part.file = UploadFile(
file=tempfile, # type: ignore[arg-type]
size=0,
filename=filename,
headers=Headers(raw=self._current_part.item_headers),
)
else:
self._current_fields += 1
if self._current_fields > self.max_fields:
raise MultiPartException(f"Too many fields. Maximum number of fields is {self.max_fields}.")
self._current_part.file = None
def on_end(self) -> None:
pass
async def parse(self) -> FormData:
# Parse the Content-Type header to get the multipart boundary.
_, params = parse_options_header(self.headers["Content-Type"])
charset = params.get(b"charset", "utf-8")
if isinstance(charset, bytes):
charset = charset.decode("latin-1")
self._charset = charset
try:
boundary = params[b"boundary"]
except KeyError:
raise MultiPartException("Missing boundary in multipart.")
# Callbacks dictionary.
callbacks: MultipartCallbacks = {
"on_part_begin": self.on_part_begin,
"on_part_data": self.on_part_data,
"on_part_end": self.on_part_end,
"on_header_field": self.on_header_field,
"on_header_value": self.on_header_value,
"on_header_end": self.on_header_end,
"on_headers_finished": self.on_headers_finished,
"on_end": self.on_end,
}
# Create the parser.
parser = multipart.MultipartParser(boundary, callbacks)
try:
# Feed the parser with data from the request.
async for chunk in self.stream:
parser.write(chunk)
# Write file data, it needs to use await with the UploadFile methods
# that call the corresponding file methods *in a threadpool*,
# otherwise, if they were called directly in the callback methods above
# (regular, non-async functions), that would block the event loop in
# the main thread.
for part, data in self._file_parts_to_write:
assert part.file # for type checkers
await part.file.write(data)
for part in self._file_parts_to_finish:
assert part.file # for type checkers
await part.file.seek(0)
self._file_parts_to_write.clear()
self._file_parts_to_finish.clear()
except MultiPartException as exc:
# Close all the files if there was an error.
for file in self._files_to_close_on_error:
file.close()
raise exc
parser.finalize()
return FormData(self.items)
| from __future__ import annotations
import os
import threading
from collections.abc import Generator
from contextlib import AbstractContextManager, nullcontext as does_not_raise
from io import BytesIO
from pathlib import Path
from tempfile import SpooledTemporaryFile
from typing import Any, ClassVar
from unittest import mock
import pytest
from starlette.applications import Starlette
from starlette.datastructures import UploadFile
from starlette.formparsers import MultiPartException, MultiPartParser, _user_safe_decode
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Mount
from starlette.types import ASGIApp, Receive, Scope, Send
from tests.types import TestClientFactory
class ForceMultipartDict(dict[Any, Any]):
def __bool__(self) -> bool:
return True
# FORCE_MULTIPART is an empty dict that boolean-evaluates as `True`.
FORCE_MULTIPART = ForceMultipartDict()
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
data = await request.form()
output: dict[str, Any] = {}
for key, value in data.items():
if isinstance(value, UploadFile):
content = await value.read()
output[key] = {
"filename": value.filename,
"size": value.size,
"content": content.decode(),
"content_type": value.content_type,
}
else:
output[key] = value
await request.close()
response = JSONResponse(output)
await response(scope, receive, send)
async def multi_items_app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
data = await request.form()
output: dict[str, list[Any]] = {}
for key, value in data.multi_items():
if key not in output:
output[key] = []
if isinstance(value, UploadFile):
content = await value.read()
output[key].append(
{
"filename": value.filename,
"size": value.size,
"content": content.decode(),
"content_type": value.content_type,
}
)
else:
output[key].append(value)
await request.close()
response = JSONResponse(output)
await response(scope, receive, send)
async def app_with_headers(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
data = await request.form()
output: dict[str, Any] = {}
for key, value in data.items():
if isinstance(value, UploadFile):
content = await value.read()
output[key] = {
"filename": value.filename,
"size": value.size,
"content": content.decode(),
"content_type": value.content_type,
"headers": list(value.headers.items()),
}
else:
output[key] = value
await request.close()
response = JSONResponse(output)
await response(scope, receive, send)
async def app_read_body(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
# Read bytes, to force request.stream() to return the already parsed body
await request.body()
data = await request.form()
output = {}
for key, value in data.items():
output[key] = value
await request.close()
response = JSONResponse(output)
await response(scope, receive, send)
async def app_monitor_thread(scope: Scope, receive: Receive, send: Send) -> None:
"""Helper app to monitor what thread the app was called on.
This can later be used to validate thread/event loop operations.
"""
request = Request(scope, receive)
# Make sure we parse the form
await request.form()
await request.close()
# Send back the current thread id
response = JSONResponse({"thread_ident": threading.current_thread().ident})
await response(scope, receive, send)
def make_app_max_parts(max_files: int = 1000, max_fields: int = 1000, max_part_size: int = 1024 * 1024) -> ASGIApp:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
data = await request.form(max_files=max_files, max_fields=max_fields, max_part_size=max_part_size)
output: dict[str, Any] = {}
for key, value in data.items():
if isinstance(value, UploadFile):
content = await value.read()
output[key] = {
"filename": value.filename,
"size": value.size,
"content": content.decode(),
"content_type": value.content_type,
}
else:
output[key] = value
await request.close()
response = JSONResponse(output)
await response(scope, receive, send)
return app
def test_multipart_request_data(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
client = test_client_factory(app)
response = client.post("/", data={"some": "data"}, files=FORCE_MULTIPART)
assert response.json() == {"some": "data"}
def test_multipart_request_files(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
path = os.path.join(tmpdir, "test.txt")
with open(path, "wb") as file:
file.write(b"<file content>")
client = test_client_factory(app)
with open(path, "rb") as f:
response = client.post("/", files={"test": f})
assert response.json() == {
"test": {
"filename": "test.txt",
"size": 14,
"content": "<file content>",
"content_type": "text/plain",
}
}
def test_multipart_request_files_with_content_type(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
path = os.path.join(tmpdir, "test.txt")
with open(path, "wb") as file:
file.write(b"<file content>")
client = test_client_factory(app)
with open(path, "rb") as f:
response = client.post("/", files={"test": ("test.txt", f, "text/plain")})
assert response.json() == {
"test": {
"filename": "test.txt",
"size": 14,
"content": "<file content>",
"content_type": "text/plain",
}
}
def test_multipart_request_multiple_files(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
path1 = os.path.join(tmpdir, "test1.txt")
with open(path1, "wb") as file:
file.write(b"<file1 content>")
path2 = os.path.join(tmpdir, "test2.txt")
with open(path2, "wb") as file:
file.write(b"<file2 content>")
client = test_client_factory(app)
with open(path1, "rb") as f1, open(path2, "rb") as f2:
response = client.post("/", files={"test1": f1, "test2": ("test2.txt", f2, "text/plain")})
assert response.json() == {
"test1": {
"filename": "test1.txt",
"size": 15,
"content": "<file1 content>",
"content_type": "text/plain",
},
"test2": {
"filename": "test2.txt",
"size": 15,
"content": "<file2 content>",
"content_type": "text/plain",
},
}
def test_multipart_request_multiple_files_with_headers(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
path1 = os.path.join(tmpdir, "test1.txt")
with open(path1, "wb") as file:
file.write(b"<file1 content>")
path2 = os.path.join(tmpdir, "test2.txt")
with open(path2, "wb") as file:
file.write(b"<file2 content>")
client = test_client_factory(app_with_headers)
with open(path1, "rb") as f1, open(path2, "rb") as f2:
response = client.post(
"/",
files=[
("test1", (None, f1)),
("test2", ("test2.txt", f2, "text/plain", {"x-custom": "f2"})),
],
)
assert response.json() == {
"test1": "<file1 content>",
"test2": {
"filename": "test2.txt",
"size": 15,
"content": "<file2 content>",
"content_type": "text/plain",
"headers": [
[
"content-disposition",
'form-data; name="test2"; filename="test2.txt"',
],
["x-custom", "f2"],
["content-type", "text/plain"],
],
},
}
def test_multi_items(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
path1 = os.path.join(tmpdir, "test1.txt")
with open(path1, "wb") as file:
file.write(b"<file1 content>")
path2 = os.path.join(tmpdir, "test2.txt")
with open(path2, "wb") as file:
file.write(b"<file2 content>")
client = test_client_factory(multi_items_app)
with open(path1, "rb") as f1, open(path2, "rb") as f2:
response = client.post(
"/",
data={"test1": "abc"},
files=[("test1", f1), ("test1", ("test2.txt", f2, "text/plain"))],
)
assert response.json() == {
"test1": [
"abc",
{
"filename": "test1.txt",
"size": 15,
"content": "<file1 content>",
"content_type": "text/plain",
},
{
"filename": "test2.txt",
"size": 15,
"content": "<file2 content>",
"content_type": "text/plain",
},
]
}
def test_multipart_request_mixed_files_and_data(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
client = test_client_factory(app)
response = client.post(
"/",
data=(
# data
b"--a7f7ac8d4e2e437c877bb7b8d7cc549c\r\n" # type: ignore
b'Content-Disposition: form-data; name="field0"\r\n\r\n'
b"value0\r\n"
# file
b"--a7f7ac8d4e2e437c877bb7b8d7cc549c\r\n"
b'Content-Disposition: form-data; name="file"; filename="file.txt"\r\n'
b"Content-Type: text/plain\r\n\r\n"
b"<file content>\r\n"
# data
b"--a7f7ac8d4e2e437c877bb7b8d7cc549c\r\n"
b'Content-Disposition: form-data; name="field1"\r\n\r\n'
b"value1\r\n"
b"--a7f7ac8d4e2e437c877bb7b8d7cc549c--\r\n"
),
headers={"Content-Type": ("multipart/form-data; boundary=a7f7ac8d4e2e437c877bb7b8d7cc549c")},
)
assert response.json() == {
"file": {
"filename": "file.txt",
"size": 14,
"content": "<file content>",
"content_type": "text/plain",
},
"field0": "value0",
"field1": "value1",
}
class ThreadTrackingSpooledTemporaryFile(SpooledTemporaryFile[bytes]):
"""Helper class to track which threads performed the rollover operation.
This is not threadsafe/multi-test safe.
"""
rollover_threads: ClassVar[set[int | None]] = set()
def rollover(self) -> None:
ThreadTrackingSpooledTemporaryFile.rollover_threads.add(threading.current_thread().ident)
super().rollover()
@pytest.fixture
def mock_spooled_temporary_file() -> Generator[None]:
try:
with mock.patch("starlette.formparsers.SpooledTemporaryFile", ThreadTrackingSpooledTemporaryFile):
yield
finally:
ThreadTrackingSpooledTemporaryFile.rollover_threads.clear()
def test_multipart_request_large_file_rollover_in_background_thread(
mock_spooled_temporary_file: None, test_client_factory: TestClientFactory
) -> None:
"""Test that Spooled file rollovers happen in background threads."""
data = BytesIO(b" " * (MultiPartParser.spool_max_size + 1))
client = test_client_factory(app_monitor_thread)
response = client.post("/", files=[("test_large", data)])
assert response.status_code == 200
# Parse the event thread id from the API response and ensure we have one
app_thread_ident = response.json().get("thread_ident")
assert app_thread_ident is not None
# Ensure the app thread was not the same as the rollover one and that a rollover thread exists
assert app_thread_ident not in ThreadTrackingSpooledTemporaryFile.rollover_threads
assert len(ThreadTrackingSpooledTemporaryFile.rollover_threads) == 1
def test_multipart_request_with_charset_for_filename(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
client = test_client_factory(app)
response = client.post(
"/",
data=(
# file
b"--a7f7ac8d4e2e437c877bb7b8d7cc549c\r\n" # type: ignore
b'Content-Disposition: form-data; name="file"; filename="\xe6\x96\x87\xe6\x9b\xb8.txt"\r\n'
b"Content-Type: text/plain\r\n\r\n"
b"<file content>\r\n"
b"--a7f7ac8d4e2e437c877bb7b8d7cc549c--\r\n"
),
headers={"Content-Type": ("multipart/form-data; charset=utf-8; boundary=a7f7ac8d4e2e437c877bb7b8d7cc549c")},
)
assert response.json() == {
"file": {
"filename": "文書.txt",
"size": 14,
"content": "<file content>",
"content_type": "text/plain",
}
}
def test_multipart_request_without_charset_for_filename(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
client = test_client_factory(app)
response = client.post(
"/",
data=(
# file
b"--a7f7ac8d4e2e437c877bb7b8d7cc549c\r\n" # type: ignore
b'Content-Disposition: form-data; name="file"; filename="\xe7\x94\xbb\xe5\x83\x8f.jpg"\r\n'
b"Content-Type: image/jpeg\r\n\r\n"
b"<file content>\r\n"
b"--a7f7ac8d4e2e437c877bb7b8d7cc549c--\r\n"
),
headers={"Content-Type": ("multipart/form-data; boundary=a7f7ac8d4e2e437c877bb7b8d7cc549c")},
)
assert response.json() == {
"file": {
"filename": "画像.jpg",
"size": 14,
"content": "<file content>",
"content_type": "image/jpeg",
}
}
def test_multipart_request_with_encoded_value(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
client = test_client_factory(app)
response = client.post(
"/",
data=(
b"--20b303e711c4ab8c443184ac833ab00f\r\n" # type: ignore
b"Content-Disposition: form-data; "
b'name="value"\r\n\r\n'
b"Transf\xc3\xa9rer\r\n"
b"--20b303e711c4ab8c443184ac833ab00f--\r\n"
),
headers={"Content-Type": ("multipart/form-data; charset=utf-8; boundary=20b303e711c4ab8c443184ac833ab00f")},
)
assert response.json() == {"value": "Transférer"}
def test_urlencoded_request_data(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
client = test_client_factory(app)
response = client.post("/", data={"some": "data"})
assert response.json() == {"some": "data"}
def test_no_request_data(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
client = test_client_factory(app)
response = client.post("/")
assert response.json() == {}
def test_urlencoded_percent_encoding(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
client = test_client_factory(app)
response = client.post("/", data={"some": "da ta"})
assert response.json() == {"some": "da ta"}
def test_urlencoded_percent_encoding_keys(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
client = test_client_factory(app)
response = client.post("/", data={"so me": "data"})
assert response.json() == {"so me": "data"}
def test_urlencoded_multi_field_app_reads_body(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
client = test_client_factory(app_read_body)
response = client.post("/", data={"some": "data", "second": "key pair"})
assert response.json() == {"some": "data", "second": "key pair"}
def test_multipart_multi_field_app_reads_body(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
client = test_client_factory(app_read_body)
response = client.post("/", data={"some": "data", "second": "key pair"}, files=FORCE_MULTIPART)
assert response.json() == {"some": "data", "second": "key pair"}
def test_user_safe_decode_helper() -> None:
result = _user_safe_decode(b"\xc4\x99\xc5\xbc\xc4\x87", "utf-8")
assert result == "ężć"
def test_user_safe_decode_ignores_wrong_charset() -> None:
result = _user_safe_decode(b"abc", "latin-8")
assert result == "abc"
@pytest.mark.parametrize(
"app,expectation",
[
(app, pytest.raises(MultiPartException)),
(Starlette(routes=[Mount("/", app=app)]), does_not_raise()),
],
)
def test_missing_boundary_parameter(
app: ASGIApp,
expectation: AbstractContextManager[Exception],
test_client_factory: TestClientFactory,
) -> None:
client = test_client_factory(app)
with expectation:
res = client.post(
"/",
data=(
# file
b'Content-Disposition: form-data; name="file"; filename="\xe6\x96\x87\xe6\x9b\xb8.txt"\r\n' # type: ignore
b"Content-Type: text/plain\r\n\r\n"
b"<file content>\r\n"
),
headers={"Content-Type": "multipart/form-data; charset=utf-8"},
)
assert res.status_code == 400
assert res.text == "Missing boundary in multipart."
@pytest.mark.parametrize(
"app,expectation",
[
(app, pytest.raises(MultiPartException)),
(Starlette(routes=[Mount("/", app=app)]), does_not_raise()),
],
)
def test_missing_name_parameter_on_content_disposition(
app: ASGIApp,
expectation: AbstractContextManager[Exception],
test_client_factory: TestClientFactory,
) -> None:
client = test_client_factory(app)
with expectation:
res = client.post(
"/",
data=(
# data
b"--a7f7ac8d4e2e437c877bb7b8d7cc549c\r\n" # type: ignore
b'Content-Disposition: form-data; ="field0"\r\n\r\n'
b"value0\r\n"
),
headers={"Content-Type": ("multipart/form-data; boundary=a7f7ac8d4e2e437c877bb7b8d7cc549c")},
)
assert res.status_code == 400
assert res.text == 'The Content-Disposition header field "name" must be provided.'
@pytest.mark.parametrize(
"app,expectation",
[
(app, pytest.raises(MultiPartException)),
(Starlette(routes=[Mount("/", app=app)]), does_not_raise()),
],
)
def test_too_many_fields_raise(
app: ASGIApp,
expectation: AbstractContextManager[Exception],
test_client_factory: TestClientFactory,
) -> None:
client = test_client_factory(app)
fields = []
for i in range(1001):
fields.append(f'--B\r\nContent-Disposition: form-data; name="N{i}";\r\n\r\n\r\n')
data = "".join(fields).encode("utf-8")
with expectation:
res = client.post(
"/",
data=data, # type: ignore
headers={"Content-Type": ("multipart/form-data; boundary=B")},
)
assert res.status_code == 400
assert res.text == "Too many fields. Maximum number of fields is 1000."
@pytest.mark.parametrize(
"app,expectation",
[
(app, pytest.raises(MultiPartException)),
(Starlette(routes=[Mount("/", app=app)]), does_not_raise()),
],
)
def test_too_many_files_raise(
app: ASGIApp,
expectation: AbstractContextManager[Exception],
test_client_factory: TestClientFactory,
) -> None:
client = test_client_factory(app)
fields = []
for i in range(1001):
fields.append(f'--B\r\nContent-Disposition: form-data; name="N{i}"; filename="F{i}";\r\n\r\n\r\n')
data = "".join(fields).encode("utf-8")
with expectation:
res = client.post(
"/",
data=data, # type: ignore
headers={"Content-Type": ("multipart/form-data; boundary=B")},
)
assert res.status_code == 400
assert res.text == "Too many files. Maximum number of files is 1000."
@pytest.mark.parametrize(
"app,expectation",
[
(app, pytest.raises(MultiPartException)),
(Starlette(routes=[Mount("/", app=app)]), does_not_raise()),
],
)
def test_too_many_files_single_field_raise(
app: ASGIApp,
expectation: AbstractContextManager[Exception],
test_client_factory: TestClientFactory,
) -> None:
client = test_client_factory(app)
fields = []
for i in range(1001):
# This uses the same field name "N" for all files, equivalent to a
# multifile upload form field
fields.append(f'--B\r\nContent-Disposition: form-data; name="N"; filename="F{i}";\r\n\r\n\r\n')
data = "".join(fields).encode("utf-8")
with expectation:
res = client.post(
"/",
data=data, # type: ignore
headers={"Content-Type": ("multipart/form-data; boundary=B")},
)
assert res.status_code == 400
assert res.text == "Too many files. Maximum number of files is 1000."
@pytest.mark.parametrize(
"app,expectation",
[
(app, pytest.raises(MultiPartException)),
(Starlette(routes=[Mount("/", app=app)]), does_not_raise()),
],
)
def test_too_many_files_and_fields_raise(
app: ASGIApp,
expectation: AbstractContextManager[Exception],
test_client_factory: TestClientFactory,
) -> None:
client = test_client_factory(app)
fields = []
for i in range(1001):
fields.append(f'--B\r\nContent-Disposition: form-data; name="F{i}"; filename="F{i}";\r\n\r\n\r\n')
fields.append(f'--B\r\nContent-Disposition: form-data; name="N{i}";\r\n\r\n\r\n')
data = "".join(fields).encode("utf-8")
with expectation:
res = client.post(
"/",
data=data, # type: ignore
headers={"Content-Type": ("multipart/form-data; boundary=B")},
)
assert res.status_code == 400
assert res.text == "Too many files. Maximum number of files is 1000."
@pytest.mark.parametrize(
"app,expectation",
[
(make_app_max_parts(max_fields=1), pytest.raises(MultiPartException)),
(
Starlette(routes=[Mount("/", app=make_app_max_parts(max_fields=1))]),
does_not_raise(),
),
],
)
def test_max_fields_is_customizable_low_raises(
app: ASGIApp,
expectation: AbstractContextManager[Exception],
test_client_factory: TestClientFactory,
) -> None:
client = test_client_factory(app)
fields = []
for i in range(2):
fields.append(f'--B\r\nContent-Disposition: form-data; name="N{i}";\r\n\r\n\r\n')
data = "".join(fields).encode("utf-8")
with expectation:
res = client.post(
"/",
data=data, # type: ignore
headers={"Content-Type": ("multipart/form-data; boundary=B")},
)
assert res.status_code == 400
assert res.text == "Too many fields. Maximum number of fields is 1."
@pytest.mark.parametrize(
"app,expectation",
[
(make_app_max_parts(max_files=1), pytest.raises(MultiPartException)),
(
Starlette(routes=[Mount("/", app=make_app_max_parts(max_files=1))]),
does_not_raise(),
),
],
)
def test_max_files_is_customizable_low_raises(
app: ASGIApp,
expectation: AbstractContextManager[Exception],
test_client_factory: TestClientFactory,
) -> None:
client = test_client_factory(app)
fields = []
for i in range(2):
fields.append(f'--B\r\nContent-Disposition: form-data; name="F{i}"; filename="F{i}";\r\n\r\n\r\n')
data = "".join(fields).encode("utf-8")
with expectation:
res = client.post(
"/",
data=data, # type: ignore
headers={"Content-Type": ("multipart/form-data; boundary=B")},
)
assert res.status_code == 400
assert res.text == "Too many files. Maximum number of files is 1."
def test_max_fields_is_customizable_high(test_client_factory: TestClientFactory) -> None:
client = test_client_factory(make_app_max_parts(max_fields=2000, max_files=2000))
fields = []
for i in range(2000):
fields.append(f'--B\r\nContent-Disposition: form-data; name="N{i}";\r\n\r\n\r\n')
fields.append(f'--B\r\nContent-Disposition: form-data; name="F{i}"; filename="F{i}";\r\n\r\n\r\n')
data = "".join(fields).encode("utf-8")
data += b"--B--\r\n"
res = client.post(
"/",
data=data, # type: ignore
headers={"Content-Type": ("multipart/form-data; boundary=B")},
)
assert res.status_code == 200
res_data = res.json()
assert res_data["N1999"] == ""
assert res_data["F1999"] == {
"filename": "F1999",
"size": 0,
"content": "",
"content_type": None,
}
@pytest.mark.parametrize(
"app,expectation",
[
(app, pytest.raises(MultiPartException)),
(Starlette(routes=[Mount("/", app=app)]), does_not_raise()),
],
)
def test_max_part_size_exceeds_limit(
app: ASGIApp,
expectation: AbstractContextManager[Exception],
test_client_factory: TestClientFactory,
) -> None:
client = test_client_factory(app)
boundary = "------------------------4K1ON9fZkj9uCUmqLHRbbR"
multipart_data = (
f"--{boundary}\r\n"
f'Content-Disposition: form-data; name="small"\r\n\r\n'
"small content\r\n"
f"--{boundary}\r\n"
f'Content-Disposition: form-data; name="large"\r\n\r\n'
+ ("x" * 1024 * 1024 + "x") # 1MB + 1 byte of data
+ "\r\n"
f"--{boundary}--\r\n"
).encode("utf-8")
headers = {
"Content-Type": f"multipart/form-data; boundary={boundary}",
"Transfer-Encoding": "chunked",
}
with expectation:
response = client.post("/", data=multipart_data, headers=headers) # type: ignore
assert response.status_code == 400
assert response.text == "Part exceeded maximum size of 1024KB."
@pytest.mark.parametrize(
"app,expectation",
[
(make_app_max_parts(max_part_size=1024 * 10), pytest.raises(MultiPartException)),
(
Starlette(routes=[Mount("/", app=make_app_max_parts(max_part_size=1024 * 10))]),
does_not_raise(),
),
],
)
def test_max_part_size_exceeds_custom_limit(
app: ASGIApp,
expectation: AbstractContextManager[Exception],
test_client_factory: TestClientFactory,
) -> None:
client = test_client_factory(app)
boundary = "------------------------4K1ON9fZkj9uCUmqLHRbbR"
multipart_data = (
f"--{boundary}\r\n"
f'Content-Disposition: form-data; name="small"\r\n\r\n'
"small content\r\n"
f"--{boundary}\r\n"
f'Content-Disposition: form-data; name="large"\r\n\r\n'
+ ("x" * 1024 * 10 + "x") # 1MB + 1 byte of data
+ "\r\n"
f"--{boundary}--\r\n"
).encode("utf-8")
headers = {
"Content-Type": f"multipart/form-data; boundary={boundary}",
"Transfer-Encoding": "chunked",
}
with expectation:
response = client.post("/", content=multipart_data, headers=headers)
assert response.status_code == 400
assert response.text == "Part exceeded maximum size of 10KB."
| starlette |
python | from __future__ import annotations
import hashlib
import http.cookies
import json
import os
import stat
import sys
import warnings
from collections.abc import AsyncIterable, Awaitable, Callable, Iterable, Mapping, Sequence
from datetime import datetime
from email.utils import format_datetime, formatdate
from functools import partial
from mimetypes import guess_type
from secrets import token_hex
from typing import Any, Literal
from urllib.parse import quote
import anyio
import anyio.to_thread
from starlette._utils import collapse_excgroups
from starlette.background import BackgroundTask
from starlette.concurrency import iterate_in_threadpool
from starlette.datastructures import URL, Headers, MutableHeaders
from starlette.requests import ClientDisconnect
from starlette.types import Receive, Scope, Send
class Response:
media_type = None
charset = "utf-8"
def __init__(
self,
content: Any = None,
status_code: int = 200,
headers: Mapping[str, str] | None = None,
media_type: str | None = None,
background: BackgroundTask | None = None,
) -> None:
self.status_code = status_code
if media_type is not None:
self.media_type = media_type
self.background = background
self.body = self.render(content)
self.init_headers(headers)
def render(self, content: Any) -> bytes | memoryview:
if content is None:
return b""
if isinstance(content, bytes | memoryview):
return content
return content.encode(self.charset) # type: ignore
def init_headers(self, headers: Mapping[str, str] | None = None) -> None:
if headers is None:
raw_headers: list[tuple[bytes, bytes]] = []
populate_content_length = True
populate_content_type = True
else:
raw_headers = [(k.lower().encode("latin-1"), v.encode("latin-1")) for k, v in headers.items()]
keys = [h[0] for h in raw_headers]
populate_content_length = b"content-length" not in keys
populate_content_type = b"content-type" not in keys
body = getattr(self, "body", None)
if (
body is not None
and populate_content_length
and not (self.status_code < 200 or self.status_code in (204, 304))
):
content_length = str(len(body))
raw_headers.append((b"content-length", content_length.encode("latin-1")))
content_type = self.media_type
if content_type is not None and populate_content_type:
if content_type.startswith("text/") and "charset=" not in content_type.lower():
content_type += "; charset=" + self.charset
raw_headers.append((b"content-type", content_type.encode("latin-1")))
self.raw_headers = raw_headers
@property
def headers(self) -> MutableHeaders:
if not hasattr(self, "_headers"):
self._headers = MutableHeaders(raw=self.raw_headers)
return self._headers
def set_cookie(
self,
key: str,
value: str = "",
max_age: int | None = None,
expires: datetime | str | int | None = None,
path: str | None = "/",
domain: str | None = None,
secure: bool = False,
httponly: bool = False,
samesite: Literal["lax", "strict", "none"] | None = "lax",
partitioned: bool = False,
) -> None:
cookie: http.cookies.BaseCookie[str] = http.cookies.SimpleCookie()
cookie[key] = value
if max_age is not None:
cookie[key]["max-age"] = max_age
if expires is not None:
if isinstance(expires, datetime):
cookie[key]["expires"] = format_datetime(expires, usegmt=True)
else:
cookie[key]["expires"] = expires
if path is not None:
cookie[key]["path"] = path
if domain is not None:
cookie[key]["domain"] = domain
if secure:
cookie[key]["secure"] = True
if httponly:
cookie[key]["httponly"] = True
if samesite is not None:
assert samesite.lower() in [
"strict",
"lax",
"none",
], "samesite must be either 'strict', 'lax' or 'none'"
cookie[key]["samesite"] = samesite
if partitioned:
if sys.version_info < (3, 14):
raise ValueError("Partitioned cookies are only supported in Python 3.14 and above.") # pragma: no cover
cookie[key]["partitioned"] = True # pragma: no cover
cookie_val = cookie.output(header="").strip()
self.raw_headers.append((b"set-cookie", cookie_val.encode("latin-1")))
def delete_cookie(
self,
key: str,
path: str = "/",
domain: str | None = None,
secure: bool = False,
httponly: bool = False,
samesite: Literal["lax", "strict", "none"] | None = "lax",
) -> None:
self.set_cookie(
key,
max_age=0,
expires=0,
path=path,
domain=domain,
secure=secure,
httponly=httponly,
samesite=samesite,
)
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
prefix = "websocket." if scope["type"] == "websocket" else ""
await send(
{
"type": prefix + "http.response.start",
"status": self.status_code,
"headers": self.raw_headers,
}
)
await send({"type": prefix + "http.response.body", "body": self.body})
if self.background is not None:
await self.background()
class HTMLResponse(Response):
media_type = "text/html"
class PlainTextResponse(Response):
media_type = "text/plain"
class JSONResponse(Response):
media_type = "application/json"
def __init__(
self,
content: Any,
status_code: int = 200,
headers: Mapping[str, str] | None = None,
media_type: str | None = None,
background: BackgroundTask | None = None,
) -> None:
super().__init__(content, status_code, headers, media_type, background)
def render(self, content: Any) -> bytes:
return json.dumps(
content,
ensure_ascii=False,
allow_nan=False,
indent=None,
separators=(",", ":"),
).encode("utf-8")
class RedirectResponse(Response):
def __init__(
self,
url: str | URL,
status_code: int = 307,
headers: Mapping[str, str] | None = None,
background: BackgroundTask | None = None,
) -> None:
super().__init__(content=b"", status_code=status_code, headers=headers, background=background)
self.headers["location"] = quote(str(url), safe=":/%#?=@[]!$&'()*+,;")
Content = str | bytes | memoryview
SyncContentStream = Iterable[Content]
AsyncContentStream = AsyncIterable[Content]
ContentStream = AsyncContentStream | SyncContentStream
class StreamingResponse(Response):
body_iterator: AsyncContentStream
def __init__(
self,
content: ContentStream,
status_code: int = 200,
headers: Mapping[str, str] | None = None,
media_type: str | None = None,
background: BackgroundTask | None = None,
) -> None:
if isinstance(content, AsyncIterable):
self.body_iterator = content
else:
self.body_iterator = iterate_in_threadpool(content)
self.status_code = status_code
self.media_type = self.media_type if media_type is None else media_type
self.background = background
self.init_headers(headers)
async def listen_for_disconnect(self, receive: Receive) -> None:
while True:
message = await receive()
if message["type"] == "http.disconnect":
break
async def stream_response(self, send: Send) -> None:
await send(
{
"type": "http.response.start",
"status": self.status_code,
"headers": self.raw_headers,
}
)
async for chunk in self.body_iterator:
if not isinstance(chunk, bytes | memoryview):
chunk = chunk.encode(self.charset)
await send({"type": "http.response.body", "body": chunk, "more_body": True})
await send({"type": "http.response.body", "body": b"", "more_body": False})
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
spec_version = tuple(map(int, scope.get("asgi", {}).get("spec_version", "2.0").split(".")))
if spec_version >= (2, 4):
try:
await self.stream_response(send)
except OSError:
raise ClientDisconnect()
else:
with collapse_excgroups():
async with anyio.create_task_group() as task_group:
async def wrap(func: Callable[[], Awaitable[None]]) -> None:
await func()
task_group.cancel_scope.cancel()
task_group.start_soon(wrap, partial(self.stream_response, send))
await wrap(partial(self.listen_for_disconnect, receive))
if self.background is not None:
await self.background()
class MalformedRangeHeader(Exception):
def __init__(self, content: str = "Malformed range header.") -> None:
self.content = content
class RangeNotSatisfiable(Exception):
def __init__(self, max_size: int) -> None:
self.max_size = max_size
class FileResponse(Response):
chunk_size = 64 * 1024
def __init__(
self,
path: str | os.PathLike[str],
status_code: int = 200,
headers: Mapping[str, str] | None = None,
media_type: str | None = None,
background: BackgroundTask | None = None,
filename: str | None = None,
stat_result: os.stat_result | None = None,
method: str | None = None,
content_disposition_type: str = "attachment",
) -> None:
self.path = path
self.status_code = status_code
self.filename = filename
if method is not None:
warnings.warn(
"The 'method' parameter is not used, and it will be removed.",
DeprecationWarning,
)
if media_type is None:
media_type = guess_type(filename or path)[0] or "text/plain"
self.media_type = media_type
self.background = background
self.init_headers(headers)
self.headers.setdefault("accept-ranges", "bytes")
if self.filename is not None:
content_disposition_filename = quote(self.filename)
if content_disposition_filename != self.filename:
content_disposition = f"{content_disposition_type}; filename*=utf-8''{content_disposition_filename}"
else:
content_disposition = f'{content_disposition_type}; filename="{self.filename}"'
self.headers.setdefault("content-disposition", content_disposition)
self.stat_result = stat_result
if stat_result is not None:
self.set_stat_headers(stat_result)
def set_stat_headers(self, stat_result: os.stat_result) -> None:
content_length = str(stat_result.st_size)
last_modified = formatdate(stat_result.st_mtime, usegmt=True)
etag_base = str(stat_result.st_mtime) + "-" + str(stat_result.st_size)
etag = f'"{hashlib.md5(etag_base.encode(), usedforsecurity=False).hexdigest()}"'
self.headers.setdefault("content-length", content_length)
self.headers.setdefault("last-modified", last_modified)
self.headers.setdefault("etag", etag)
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
send_header_only: bool = scope["method"].upper() == "HEAD"
send_pathsend: bool = "http.response.pathsend" in scope.get("extensions", {})
if self.stat_result is None:
try:
stat_result = await anyio.to_thread.run_sync(os.stat, self.path)
self.set_stat_headers(stat_result)
except FileNotFoundError:
raise RuntimeError(f"File at path {self.path} does not exist.")
else:
mode = stat_result.st_mode
if not stat.S_ISREG(mode):
raise RuntimeError(f"File at path {self.path} is not a file.")
else:
stat_result = self.stat_result
headers = Headers(scope=scope)
http_range = headers.get("range")
http_if_range = headers.get("if-range")
if http_range is None or (http_if_range is not None and not self._should_use_range(http_if_range)):
await self._handle_simple(send, send_header_only, send_pathsend)
else:
try:
ranges = self._parse_range_header(http_range, stat_result.st_size)
except MalformedRangeHeader as exc:
return await PlainTextResponse(exc.content, status_code=400)(scope, receive, send)
except RangeNotSatisfiable as exc:
response = PlainTextResponse(status_code=416, headers={"Content-Range": f"*/{exc.max_size}"})
return await response(scope, receive, send)
if len(ranges) == 1:
start, end = ranges[0]
await self._handle_single_range(send, start, end, stat_result.st_size, send_header_only)
else:
await self._handle_multiple_ranges(send, ranges, stat_result.st_size, send_header_only)
if self.background is not None:
await self.background()
async def _handle_simple(self, send: Send, send_header_only: bool, send_pathsend: bool) -> None:
await send({"type": "http.response.start", "status": self.status_code, "headers": self.raw_headers})
if send_header_only:
await send({"type": "http.response.body", "body": b"", "more_body": False})
elif send_pathsend:
await send({"type": "http.response.pathsend", "path": str(self.path)})
else:
async with await anyio.open_file(self.path, mode="rb") as file:
more_body = True
while more_body:
chunk = await file.read(self.chunk_size)
more_body = len(chunk) == self.chunk_size
await send({"type": "http.response.body", "body": chunk, "more_body": more_body})
async def _handle_single_range(
self, send: Send, start: int, end: int, file_size: int, send_header_only: bool
) -> None:
self.headers["content-range"] = f"bytes {start}-{end - 1}/{file_size}"
self.headers["content-length"] = str(end - start)
await send({"type": "http.response.start", "status": 206, "headers": self.raw_headers})
if send_header_only:
await send({"type": "http.response.body", "body": b"", "more_body": False})
else:
async with await anyio.open_file(self.path, mode="rb") as file:
await file.seek(start)
more_body = True
while more_body:
chunk = await file.read(min(self.chunk_size, end - start))
start += len(chunk)
more_body = len(chunk) == self.chunk_size and start < end
await send({"type": "http.response.body", "body": chunk, "more_body": more_body})
async def _handle_multiple_ranges(
self,
send: Send,
ranges: list[tuple[int, int]],
file_size: int,
send_header_only: bool,
) -> None:
# In firefox and chrome, they use boundary with 95-96 bits entropy (that's roughly 13 bytes).
boundary = token_hex(13)
content_length, header_generator = self.generate_multipart(
ranges, boundary, file_size, self.headers["content-type"]
)
self.headers["content-range"] = f"multipart/byteranges; boundary={boundary}"
self.headers["content-length"] = str(content_length)
await send({"type": "http.response.start", "status": 206, "headers": self.raw_headers})
if send_header_only:
await send({"type": "http.response.body", "body": b"", "more_body": False})
else:
async with await anyio.open_file(self.path, mode="rb") as file:
for start, end in ranges:
await send({"type": "http.response.body", "body": header_generator(start, end), "more_body": True})
await file.seek(start)
while start < end:
chunk = await file.read(min(self.chunk_size, end - start))
start += len(chunk)
await send({"type": "http.response.body", "body": chunk, "more_body": True})
await send({"type": "http.response.body", "body": b"\n", "more_body": True})
await send(
{
"type": "http.response.body",
"body": f"\n--{boundary}--\n".encode("latin-1"),
"more_body": False,
}
)
def _should_use_range(self, http_if_range: str) -> bool:
return http_if_range == self.headers["last-modified"] or http_if_range == self.headers["etag"]
@classmethod
def _parse_range_header(cls, http_range: str, file_size: int) -> list[tuple[int, int]]:
ranges: list[tuple[int, int]] = []
try:
units, range_ = http_range.split("=", 1)
except ValueError:
raise MalformedRangeHeader()
units = units.strip().lower()
if units != "bytes":
raise MalformedRangeHeader("Only support bytes range")
ranges = cls._parse_ranges(range_, file_size)
if len(ranges) == 0:
raise MalformedRangeHeader("Range header: range must be requested")
if any(not (0 <= start < file_size) for start, _ in ranges):
raise RangeNotSatisfiable(file_size)
if any(start > end for start, end in ranges):
raise MalformedRangeHeader("Range header: start must be less than end")
if len(ranges) == 1:
return ranges
# Merge ranges
result: list[tuple[int, int]] = []
for start, end in ranges:
for p in range(len(result)):
p_start, p_end = result[p]
if start > p_end:
continue
elif end < p_start:
result.insert(p, (start, end)) # THIS IS NOT REACHED!
break
else:
result[p] = (min(start, p_start), max(end, p_end))
break
else:
result.append((start, end))
return result
@classmethod
def _parse_ranges(cls, range_: str, file_size: int) -> list[tuple[int, int]]:
ranges: list[tuple[int, int]] = []
for part in range_.split(","):
part = part.strip()
# If the range is empty or a single dash, we ignore it.
if not part or part == "-":
continue
# If the range is not in the format "start-end", we ignore it.
if "-" not in part:
continue
start_str, end_str = part.split("-", 1)
start_str = start_str.strip()
end_str = end_str.strip()
try:
start = int(start_str) if start_str else file_size - int(end_str)
end = int(end_str) + 1 if start_str and end_str and int(end_str) < file_size else file_size
ranges.append((start, end))
except ValueError:
# If the range is not numeric, we ignore it.
continue
return ranges
def generate_multipart(
self,
ranges: Sequence[tuple[int, int]],
boundary: str,
max_size: int,
content_type: str,
) -> tuple[int, Callable[[int, int], bytes]]:
r"""
Multipart response headers generator.
```
--{boundary}\n
Content-Type: {content_type}\n
Content-Range: bytes {start}-{end-1}/{max_size}\n
\n
..........content...........\n
--{boundary}\n
Content-Type: {content_type}\n
Content-Range: bytes {start}-{end-1}/{max_size}\n
\n
..........content...........\n
--{boundary}--\n
```
"""
boundary_len = len(boundary)
static_header_part_len = 44 + boundary_len + len(content_type) + len(str(max_size))
content_length = sum(
(len(str(start)) + len(str(end - 1)) + static_header_part_len) # Headers
+ (end - start) # Content
for start, end in ranges
) + (
5 + boundary_len # --boundary--\n
)
return (
content_length,
lambda start, end: (
f"--{boundary}\nContent-Type: {content_type}\nContent-Range: bytes {start}-{end - 1}/{max_size}\n\n"
).encode("latin-1"),
)
| from __future__ import annotations
import datetime as dt
import sys
import time
from collections.abc import AsyncGenerator, AsyncIterator, Iterator
from http.cookies import SimpleCookie
from pathlib import Path
from typing import Any
import anyio
import pytest
from starlette import status
from starlette.background import BackgroundTask
from starlette.datastructures import Headers
from starlette.requests import ClientDisconnect, Request
from starlette.responses import FileResponse, JSONResponse, RedirectResponse, Response, StreamingResponse
from starlette.testclient import TestClient
from starlette.types import Message, Receive, Scope, Send
from tests.types import TestClientFactory
def test_text_response(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
response = Response("hello, world", media_type="text/plain")
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/")
assert response.text == "hello, world"
def test_bytes_response(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
response = Response(b"xxxxx", media_type="image/png")
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/")
assert response.content == b"xxxxx"
def test_json_none_response(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
response = JSONResponse(None)
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/")
assert response.json() is None
assert response.content == b"null"
def test_redirect_response(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
if scope["path"] == "/":
response = Response("hello, world", media_type="text/plain")
else:
response = RedirectResponse("/")
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/redirect")
assert response.text == "hello, world"
assert response.url == "http://testserver/"
def test_quoting_redirect_response(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
if scope["path"] == "/I ♥ Starlette/":
response = Response("hello, world", media_type="text/plain")
else:
response = RedirectResponse("/I ♥ Starlette/")
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/redirect")
assert response.text == "hello, world"
assert response.url == "http://testserver/I%20%E2%99%A5%20Starlette/"
def test_redirect_response_content_length_header(
test_client_factory: TestClientFactory,
) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
if scope["path"] == "/":
response = Response("hello", media_type="text/plain") # pragma: no cover
else:
response = RedirectResponse("/")
await response(scope, receive, send)
client: TestClient = test_client_factory(app)
response = client.request("GET", "/redirect", follow_redirects=False)
assert response.url == "http://testserver/redirect"
assert response.headers["content-length"] == "0"
def test_streaming_response(test_client_factory: TestClientFactory) -> None:
filled_by_bg_task = ""
async def app(scope: Scope, receive: Receive, send: Send) -> None:
async def numbers(minimum: int, maximum: int) -> AsyncIterator[str]:
for i in range(minimum, maximum + 1):
yield str(i)
if i != maximum:
yield ", "
await anyio.sleep(0)
async def numbers_for_cleanup(start: int = 1, stop: int = 5) -> None:
nonlocal filled_by_bg_task
async for thing in numbers(start, stop):
filled_by_bg_task = filled_by_bg_task + thing
cleanup_task = BackgroundTask(numbers_for_cleanup, start=6, stop=9)
generator = numbers(1, 5)
response = StreamingResponse(generator, media_type="text/plain", background=cleanup_task)
await response(scope, receive, send)
assert filled_by_bg_task == ""
client = test_client_factory(app)
response = client.get("/")
assert response.text == "1, 2, 3, 4, 5"
assert filled_by_bg_task == "6, 7, 8, 9"
def test_streaming_response_custom_iterator(
test_client_factory: TestClientFactory,
) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
class CustomAsyncIterator:
def __init__(self) -> None:
self._called = 0
def __aiter__(self) -> AsyncIterator[str]:
return self
async def __anext__(self) -> str:
if self._called == 5:
raise StopAsyncIteration()
self._called += 1
return str(self._called)
response = StreamingResponse(CustomAsyncIterator(), media_type="text/plain")
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/")
assert response.text == "12345"
def test_streaming_response_custom_iterable(
test_client_factory: TestClientFactory,
) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
class CustomAsyncIterable:
async def __aiter__(self) -> AsyncIterator[str | bytes]:
for i in range(5):
yield str(i + 1)
response = StreamingResponse(CustomAsyncIterable(), media_type="text/plain")
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/")
assert response.text == "12345"
def test_sync_streaming_response(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
def numbers(minimum: int, maximum: int) -> Iterator[str]:
for i in range(minimum, maximum + 1):
yield str(i)
if i != maximum:
yield ", "
generator = numbers(1, 5)
response = StreamingResponse(generator, media_type="text/plain")
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/")
assert response.text == "1, 2, 3, 4, 5"
def test_response_headers(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
headers = {"x-header-1": "123", "x-header-2": "456"}
response = Response("hello, world", media_type="text/plain", headers=headers)
response.headers["x-header-2"] = "789"
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/")
assert response.headers["x-header-1"] == "123"
assert response.headers["x-header-2"] == "789"
def test_response_phrase(test_client_factory: TestClientFactory) -> None:
app = Response(status_code=204)
client = test_client_factory(app)
response = client.get("/")
assert response.reason_phrase == "No Content"
app = Response(b"", status_code=123)
client = test_client_factory(app)
response = client.get("/")
assert response.reason_phrase == ""
def test_file_response(tmp_path: Path, test_client_factory: TestClientFactory) -> None:
path = tmp_path / "xyz"
content = b"<file content>" * 1000
path.write_bytes(content)
filled_by_bg_task = ""
async def numbers(minimum: int, maximum: int) -> AsyncIterator[str]:
for i in range(minimum, maximum + 1):
yield str(i)
if i != maximum:
yield ", "
await anyio.sleep(0)
async def numbers_for_cleanup(start: int = 1, stop: int = 5) -> None:
nonlocal filled_by_bg_task
async for thing in numbers(start, stop):
filled_by_bg_task = filled_by_bg_task + thing
cleanup_task = BackgroundTask(numbers_for_cleanup, start=6, stop=9)
async def app(scope: Scope, receive: Receive, send: Send) -> None:
response = FileResponse(path=path, filename="example.png", background=cleanup_task)
await response(scope, receive, send)
assert filled_by_bg_task == ""
client = test_client_factory(app)
response = client.get("/")
expected_disposition = 'attachment; filename="example.png"'
assert response.status_code == status.HTTP_200_OK
assert response.content == content
assert response.headers["content-type"] == "image/png"
assert response.headers["content-disposition"] == expected_disposition
assert "content-length" in response.headers
assert "last-modified" in response.headers
assert "etag" in response.headers
assert filled_by_bg_task == "6, 7, 8, 9"
@pytest.mark.anyio
async def test_file_response_on_head_method(tmp_path: Path) -> None:
path = tmp_path / "xyz"
content = b"<file content>" * 1000
path.write_bytes(content)
app = FileResponse(path=path, filename="example.png")
async def receive() -> Message: # type: ignore[empty-body]
... # pragma: no cover
async def send(message: Message) -> None:
if message["type"] == "http.response.start":
assert message["status"] == status.HTTP_200_OK
headers = Headers(raw=message["headers"])
assert headers["content-type"] == "image/png"
assert "content-length" in headers
assert "content-disposition" in headers
assert "last-modified" in headers
assert "etag" in headers
elif message["type"] == "http.response.body": # pragma: no branch
assert message["body"] == b""
assert message["more_body"] is False
# Since the TestClient drops the response body on HEAD requests, we need to test
# this directly.
await app({"type": "http", "method": "head", "headers": [(b"key", b"value")]}, receive, send)
def test_file_response_set_media_type(tmp_path: Path, test_client_factory: TestClientFactory) -> None:
path = tmp_path / "xyz"
path.write_bytes(b"<file content>")
# By default, FileResponse will determine the `content-type` based on
# the filename or path, unless a specific `media_type` is provided.
app = FileResponse(path=path, filename="example.png", media_type="image/jpeg")
client: TestClient = test_client_factory(app)
response = client.get("/")
assert response.headers["content-type"] == "image/jpeg"
def test_file_response_with_directory_raises_error(tmp_path: Path, test_client_factory: TestClientFactory) -> None:
app = FileResponse(path=tmp_path, filename="example.png")
client = test_client_factory(app)
with pytest.raises(RuntimeError) as exc_info:
client.get("/")
assert "is not a file" in str(exc_info.value)
def test_file_response_with_missing_file_raises_error(tmp_path: Path, test_client_factory: TestClientFactory) -> None:
path = tmp_path / "404.txt"
app = FileResponse(path=path, filename="404.txt")
client = test_client_factory(app)
with pytest.raises(RuntimeError) as exc_info:
client.get("/")
assert "does not exist" in str(exc_info.value)
def test_file_response_with_chinese_filename(tmp_path: Path, test_client_factory: TestClientFactory) -> None:
content = b"file content"
filename = "你好.txt" # probably "Hello.txt" in Chinese
path = tmp_path / filename
path.write_bytes(content)
app = FileResponse(path=path, filename=filename)
client = test_client_factory(app)
response = client.get("/")
expected_disposition = "attachment; filename*=utf-8''%E4%BD%A0%E5%A5%BD.txt"
assert response.status_code == status.HTTP_200_OK
assert response.content == content
assert response.headers["content-disposition"] == expected_disposition
def test_file_response_with_inline_disposition(tmp_path: Path, test_client_factory: TestClientFactory) -> None:
content = b"file content"
filename = "hello.txt"
path = tmp_path / filename
path.write_bytes(content)
app = FileResponse(path=path, filename=filename, content_disposition_type="inline")
client = test_client_factory(app)
response = client.get("/")
expected_disposition = 'inline; filename="hello.txt"'
assert response.status_code == status.HTTP_200_OK
assert response.content == content
assert response.headers["content-disposition"] == expected_disposition
def test_file_response_with_method_warns(tmp_path: Path) -> None:
with pytest.warns(DeprecationWarning):
FileResponse(path=tmp_path, filename="example.png", method="GET")
def test_file_response_with_range_header(tmp_path: Path, test_client_factory: TestClientFactory) -> None:
content = b"file content"
filename = "hello.txt"
path = tmp_path / filename
path.write_bytes(content)
etag = '"a_non_autogenerated_etag"'
app = FileResponse(path=path, filename=filename, headers={"etag": etag})
client = test_client_factory(app)
response = client.get("/", headers={"range": "bytes=0-4", "if-range": etag})
assert response.status_code == status.HTTP_206_PARTIAL_CONTENT
assert response.content == content[:5]
assert response.headers["etag"] == etag
assert response.headers["content-length"] == "5"
assert response.headers["content-range"] == f"bytes 0-4/{len(content)}"
@pytest.mark.anyio
async def test_file_response_with_pathsend(tmpdir: Path) -> None:
path = tmpdir / "xyz"
content = b"<file content>" * 1000
with open(path, "wb") as file:
file.write(content)
app = FileResponse(path=path, filename="example.png")
async def receive() -> Message: # type: ignore[empty-body]
... # pragma: no cover
async def send(message: Message) -> None:
if message["type"] == "http.response.start":
assert message["status"] == status.HTTP_200_OK
headers = Headers(raw=message["headers"])
assert headers["content-type"] == "image/png"
assert "content-length" in headers
assert "content-disposition" in headers
assert "last-modified" in headers
assert "etag" in headers
elif message["type"] == "http.response.pathsend": # pragma: no branch
assert message["path"] == str(path)
# Since the TestClient doesn't support `pathsend`, we need to test this directly.
await app(
{"type": "http", "method": "get", "headers": [], "extensions": {"http.response.pathsend": {}}},
receive,
send,
)
def test_set_cookie(test_client_factory: TestClientFactory, monkeypatch: pytest.MonkeyPatch) -> None:
# Mock time used as a reference for `Expires` by stdlib `SimpleCookie`.
mocked_now = dt.datetime(2037, 1, 22, 12, 0, 0, tzinfo=dt.timezone.utc)
monkeypatch.setattr(time, "time", lambda: mocked_now.timestamp())
async def app(scope: Scope, receive: Receive, send: Send) -> None:
response = Response("Hello, world!", media_type="text/plain")
response.set_cookie(
"mycookie",
"myvalue",
max_age=10,
expires=10,
path="/",
domain="localhost",
secure=True,
httponly=True,
samesite="none",
partitioned=True if sys.version_info >= (3, 14) else False,
)
await response(scope, receive, send)
partitioned_text = "Partitioned; " if sys.version_info >= (3, 14) else ""
client = test_client_factory(app)
response = client.get("/")
assert response.text == "Hello, world!"
assert (
response.headers["set-cookie"] == "mycookie=myvalue; Domain=localhost; expires=Thu, 22 Jan 2037 12:00:10 GMT; "
f"HttpOnly; Max-Age=10; {partitioned_text}Path=/; SameSite=none; Secure"
)
@pytest.mark.skipif(sys.version_info >= (3, 14), reason="Only relevant for <3.14")
def test_set_cookie_raises_for_invalid_python_version(
test_client_factory: TestClientFactory,
) -> None: # pragma: no cover
async def app(scope: Scope, receive: Receive, send: Send) -> None:
response = Response("Hello, world!", media_type="text/plain")
with pytest.raises(ValueError):
response.set_cookie("mycookie", "myvalue", partitioned=True)
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/")
assert response.text == "Hello, world!"
assert response.headers.get("set-cookie") is None
def test_set_cookie_path_none(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
response = Response("Hello, world!", media_type="text/plain")
response.set_cookie("mycookie", "myvalue", path=None)
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/")
assert response.text == "Hello, world!"
assert response.headers["set-cookie"] == "mycookie=myvalue; SameSite=lax"
def test_set_cookie_samesite_none(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
response = Response("Hello, world!", media_type="text/plain")
response.set_cookie("mycookie", "myvalue", samesite=None)
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/")
assert response.text == "Hello, world!"
assert response.headers["set-cookie"] == "mycookie=myvalue; Path=/"
@pytest.mark.parametrize(
"expires",
[
pytest.param(dt.datetime(2037, 1, 22, 12, 0, 10, tzinfo=dt.timezone.utc), id="datetime"),
pytest.param("Thu, 22 Jan 2037 12:00:10 GMT", id="str"),
pytest.param(10, id="int"),
],
)
def test_expires_on_set_cookie(
test_client_factory: TestClientFactory,
monkeypatch: pytest.MonkeyPatch,
expires: str,
) -> None:
# Mock time used as a reference for `Expires` by stdlib `SimpleCookie`.
mocked_now = dt.datetime(2037, 1, 22, 12, 0, 0, tzinfo=dt.timezone.utc)
monkeypatch.setattr(time, "time", lambda: mocked_now.timestamp())
async def app(scope: Scope, receive: Receive, send: Send) -> None:
response = Response("Hello, world!", media_type="text/plain")
response.set_cookie("mycookie", "myvalue", expires=expires)
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/")
cookie = SimpleCookie(response.headers.get("set-cookie"))
assert cookie["mycookie"]["expires"] == "Thu, 22 Jan 2037 12:00:10 GMT"
def test_delete_cookie(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
response = Response("Hello, world!", media_type="text/plain")
if request.cookies.get("mycookie"):
response.delete_cookie("mycookie")
else:
response.set_cookie("mycookie", "myvalue")
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/")
assert response.cookies["mycookie"]
response = client.get("/")
assert not response.cookies.get("mycookie")
def test_populate_headers(test_client_factory: TestClientFactory) -> None:
app = Response(content="hi", headers={}, media_type="text/html")
client = test_client_factory(app)
response = client.get("/")
assert response.text == "hi"
assert response.headers["content-length"] == "2"
assert response.headers["content-type"] == "text/html; charset=utf-8"
def test_head_method(test_client_factory: TestClientFactory) -> None:
app = Response("hello, world", media_type="text/plain")
client = test_client_factory(app)
response = client.head("/")
assert response.text == ""
def test_empty_response(test_client_factory: TestClientFactory) -> None:
app = Response()
client: TestClient = test_client_factory(app)
response = client.get("/")
assert response.content == b""
assert response.headers["content-length"] == "0"
assert "content-type" not in response.headers
def test_empty_204_response(test_client_factory: TestClientFactory) -> None:
app = Response(status_code=204)
client: TestClient = test_client_factory(app)
response = client.get("/")
assert "content-length" not in response.headers
def test_non_empty_response(test_client_factory: TestClientFactory) -> None:
app = Response(content="hi")
client: TestClient = test_client_factory(app)
response = client.get("/")
assert response.headers["content-length"] == "2"
def test_response_do_not_add_redundant_charset(
test_client_factory: TestClientFactory,
) -> None:
app = Response(media_type="text/plain; charset=utf-8")
client = test_client_factory(app)
response = client.get("/")
assert response.headers["content-type"] == "text/plain; charset=utf-8"
def test_file_response_known_size(tmp_path: Path, test_client_factory: TestClientFactory) -> None:
path = tmp_path / "xyz"
content = b"<file content>" * 1000
path.write_bytes(content)
app = FileResponse(path=path, filename="example.png")
client: TestClient = test_client_factory(app)
response = client.get("/")
assert response.headers["content-length"] == str(len(content))
def test_streaming_response_unknown_size(
test_client_factory: TestClientFactory,
) -> None:
app = StreamingResponse(content=iter(["hello", "world"]))
client: TestClient = test_client_factory(app)
response = client.get("/")
assert "content-length" not in response.headers
def test_streaming_response_known_size(test_client_factory: TestClientFactory) -> None:
app = StreamingResponse(content=iter(["hello", "world"]), headers={"content-length": "10"})
client: TestClient = test_client_factory(app)
response = client.get("/")
assert response.headers["content-length"] == "10"
def test_response_memoryview(test_client_factory: TestClientFactory) -> None:
app = Response(content=memoryview(b"\xc0"))
client: TestClient = test_client_factory(app)
response = client.get("/")
assert response.content == b"\xc0"
def test_streaming_response_memoryview(test_client_factory: TestClientFactory) -> None:
app = StreamingResponse(content=iter([memoryview(b"\xc0"), memoryview(b"\xf5")]))
client: TestClient = test_client_factory(app)
response = client.get("/")
assert response.content == b"\xc0\xf5"
@pytest.mark.anyio
async def test_streaming_response_stops_if_receiving_http_disconnect() -> None:
streamed = 0
disconnected = anyio.Event()
async def receive_disconnect() -> Message:
await disconnected.wait()
return {"type": "http.disconnect"}
async def send(message: Message) -> None:
nonlocal streamed
if message["type"] == "http.response.body":
streamed += len(message.get("body", b""))
# Simulate disconnection after download has started
if streamed >= 16:
disconnected.set()
async def stream_indefinitely() -> AsyncIterator[bytes]:
while True:
# Need a sleep for the event loop to switch to another task
await anyio.sleep(0)
yield b"chunk "
response = StreamingResponse(content=stream_indefinitely())
with anyio.move_on_after(1) as cancel_scope:
await response({}, receive_disconnect, send)
assert not cancel_scope.cancel_called, "Content streaming should stop itself."
@pytest.mark.anyio
async def test_streaming_response_on_client_disconnects() -> None:
chunks = bytearray()
streamed = False
async def receive_disconnect() -> Message:
raise NotImplementedError
async def send(message: Message) -> None:
nonlocal streamed
if message["type"] == "http.response.body":
if not streamed:
chunks.extend(message.get("body", b""))
streamed = True
else:
raise OSError
async def stream_indefinitely() -> AsyncGenerator[bytes, None]:
while True:
await anyio.sleep(0)
yield b"chunk"
stream = stream_indefinitely()
response = StreamingResponse(content=stream)
with anyio.move_on_after(1) as cancel_scope:
with pytest.raises(ClientDisconnect):
await response({"asgi": {"spec_version": "2.4"}}, receive_disconnect, send)
assert not cancel_scope.cancel_called, "Content streaming should stop itself."
assert chunks == b"chunk"
await stream.aclose()
README = """\
# BáiZé
Powerful and exquisite WSGI/ASGI framework/toolkit.
The minimize implementation of methods required in the Web framework. No redundant implementation means that you can freely customize functions without considering the conflict with baize's own implementation.
Under the ASGI/WSGI protocol, the interface of the request object and the response object is almost the same, only need to add or delete `await` in the appropriate place. In addition, it should be noted that ASGI supports WebSocket but WSGI does not.
""" # noqa: E501
@pytest.fixture
def readme_file(tmp_path: Path) -> Path:
filepath = tmp_path / "README.txt"
filepath.write_bytes(README.encode("utf8"))
return filepath
@pytest.fixture
def file_response_client(readme_file: Path, test_client_factory: TestClientFactory) -> TestClient:
return test_client_factory(app=FileResponse(str(readme_file)))
def test_file_response_without_range(file_response_client: TestClient) -> None:
response = file_response_client.get("/")
assert response.status_code == 200
assert response.headers["content-length"] == str(len(README.encode("utf8")))
assert response.text == README
def test_file_response_head(file_response_client: TestClient) -> None:
response = file_response_client.head("/")
assert response.status_code == 200
assert response.headers["content-length"] == str(len(README.encode("utf8")))
assert response.content == b""
def test_file_response_range(file_response_client: TestClient) -> None:
response = file_response_client.get("/", headers={"Range": "bytes=0-100"})
assert response.status_code == 206
assert response.headers["content-range"] == f"bytes 0-100/{len(README.encode('utf8'))}"
assert response.headers["content-length"] == "101"
assert response.content == README.encode("utf8")[:101]
def test_file_response_range_head(file_response_client: TestClient) -> None:
response = file_response_client.head("/", headers={"Range": "bytes=0-100"})
assert response.status_code == 206
assert response.headers["content-length"] == str(101)
assert response.content == b""
def test_file_response_range_multi(file_response_client: TestClient) -> None:
response = file_response_client.get("/", headers={"Range": "bytes=0-100, 200-300"})
assert response.status_code == 206
assert response.headers["content-range"].startswith("multipart/byteranges; boundary=")
assert response.headers["content-length"] == "439"
def test_file_response_range_multi_head(file_response_client: TestClient) -> None:
response = file_response_client.head("/", headers={"Range": "bytes=0-100, 200-300"})
assert response.status_code == 206
assert response.headers["content-length"] == "439"
assert response.content == b""
response = file_response_client.head(
"/",
headers={"Range": "bytes=200-300", "if-range": response.headers["etag"][:-1]},
)
assert response.status_code == 200
response = file_response_client.head(
"/",
headers={"Range": "bytes=200-300", "if-range": response.headers["etag"]},
)
assert response.status_code == 206
def test_file_response_range_invalid(file_response_client: TestClient) -> None:
response = file_response_client.head("/", headers={"Range": "bytes: 0-1000"})
assert response.status_code == 400
def test_file_response_range_head_max(file_response_client: TestClient) -> None:
response = file_response_client.head("/", headers={"Range": f"bytes=0-{len(README.encode('utf8')) + 1}"})
assert response.status_code == 206
def test_file_response_range_416(file_response_client: TestClient) -> None:
response = file_response_client.head("/", headers={"Range": f"bytes={len(README.encode('utf8')) + 1}-"})
assert response.status_code == 416
assert response.headers["Content-Range"] == f"*/{len(README.encode('utf8'))}"
def test_file_response_only_support_bytes_range(file_response_client: TestClient) -> None:
response = file_response_client.get("/", headers={"Range": "items=0-100"})
assert response.status_code == 400
assert response.text == "Only support bytes range"
def test_file_response_range_must_be_requested(file_response_client: TestClient) -> None:
response = file_response_client.get("/", headers={"Range": "bytes="})
assert response.status_code == 400
assert response.text == "Range header: range must be requested"
def test_file_response_start_must_be_less_than_end(file_response_client: TestClient) -> None:
response = file_response_client.get("/", headers={"Range": "bytes=100-0"})
assert response.status_code == 400
assert response.text == "Range header: start must be less than end"
def test_file_response_merge_ranges(file_response_client: TestClient) -> None:
response = file_response_client.get("/", headers={"Range": "bytes=0-100, 50-200"})
assert response.status_code == 206
assert response.headers["content-length"] == "201"
assert response.headers["content-range"] == f"bytes 0-200/{len(README.encode('utf8'))}"
def test_file_response_insert_ranges(file_response_client: TestClient) -> None:
response = file_response_client.get("/", headers={"Range": "bytes=100-200, 0-50"})
assert response.status_code == 206
assert response.headers["content-range"].startswith("multipart/byteranges; boundary=")
boundary = response.headers["content-range"].split("boundary=")[1]
assert response.text.splitlines() == [
f"--{boundary}",
"Content-Type: text/plain; charset=utf-8",
"Content-Range: bytes 0-50/526",
"",
"# BáiZé",
"",
"Powerful and exquisite WSGI/ASGI framewo",
f"--{boundary}",
"Content-Type: text/plain; charset=utf-8",
"Content-Range: bytes 100-200/526",
"",
"ds required in the Web framework. No redundant implementation means that you can freely customize fun",
"",
f"--{boundary}--",
]
def test_file_response_range_without_dash(file_response_client: TestClient) -> None:
response = file_response_client.get("/", headers={"Range": "bytes=100, 0-50"})
assert response.status_code == 206
assert response.headers["content-range"] == f"bytes 0-50/{len(README.encode('utf8'))}"
def test_file_response_range_empty_start_and_end(file_response_client: TestClient) -> None:
response = file_response_client.get("/", headers={"Range": "bytes= - , 0-50"})
assert response.status_code == 206
assert response.headers["content-range"] == f"bytes 0-50/{len(README.encode('utf8'))}"
def test_file_response_range_ignore_non_numeric(file_response_client: TestClient) -> None:
response = file_response_client.get("/", headers={"Range": "bytes=abc-def, 0-50"})
assert response.status_code == 206
assert response.headers["content-range"] == f"bytes 0-50/{len(README.encode('utf8'))}"
def test_file_response_suffix_range(file_response_client: TestClient) -> None:
# Test suffix range (last N bytes) - line 523 with empty start_str
response = file_response_client.get("/", headers={"Range": "bytes=-100"})
assert response.status_code == 206
file_size = len(README.encode("utf8"))
assert response.headers["content-range"] == f"bytes {file_size - 100}-{file_size - 1}/{file_size}"
assert response.headers["content-length"] == "100"
assert response.content == README.encode("utf8")[-100:]
@pytest.mark.anyio
async def test_file_response_multi_small_chunk_size(readme_file: Path) -> None:
class SmallChunkSizeFileResponse(FileResponse):
chunk_size = 10
app = SmallChunkSizeFileResponse(path=str(readme_file))
received_chunks: list[bytes] = []
start_message: dict[str, Any] = {}
async def receive() -> Message:
raise NotImplementedError("Should not be called!")
async def send(message: Message) -> None:
if message["type"] == "http.response.start":
start_message.update(message)
elif message["type"] == "http.response.body": # pragma: no branch
received_chunks.append(message["body"])
await app({"type": "http", "method": "get", "headers": [(b"range", b"bytes=0-15,20-35,35-50")]}, receive, send)
assert start_message["status"] == 206
headers = Headers(raw=start_message["headers"])
assert headers.get("content-type") == "text/plain; charset=utf-8"
assert headers.get("accept-ranges") == "bytes"
assert "content-length" in headers
assert "last-modified" in headers
assert "etag" in headers
assert headers["content-range"].startswith("multipart/byteranges; boundary=")
boundary = headers["content-range"].split("boundary=")[1]
assert received_chunks == [
# Send the part headers.
f"--{boundary}\nContent-Type: text/plain; charset=utf-8\nContent-Range: bytes 0-15/526\n\n".encode(),
# Send the first chunk (10 bytes).
b"# B\xc3\xa1iZ\xc3\xa9\n",
# Send the second chunk (6 bytes).
b"\nPower",
# Send the new line to separate the parts.
b"\n",
# Send the part headers. We merge the ranges 20-35 and 35-50 into a single part.
f"--{boundary}\nContent-Type: text/plain; charset=utf-8\nContent-Range: bytes 20-50/526\n\n".encode(),
# Send the first chunk (10 bytes).
b"and exquis",
# Send the second chunk (10 bytes).
b"ite WSGI/A",
# Send the third chunk (10 bytes).
b"SGI framew",
# Send the last chunk (1 byte).
b"o",
b"\n",
f"\n--{boundary}--\n".encode(),
]
| starlette |
python | from __future__ import annotations
import functools
import sys
from collections.abc import Awaitable, Callable, Generator
from contextlib import AbstractAsyncContextManager, contextmanager
from typing import Any, Generic, Protocol, TypeVar, overload
from starlette.types import Scope
if sys.version_info >= (3, 13): # pragma: no cover
from inspect import iscoroutinefunction
from typing import TypeIs
else: # pragma: no cover
from asyncio import iscoroutinefunction
from typing_extensions import TypeIs
has_exceptiongroups = True
if sys.version_info < (3, 11): # pragma: no cover
try:
from exceptiongroup import BaseExceptionGroup # type: ignore[unused-ignore,import-not-found]
except ImportError:
has_exceptiongroups = False
T = TypeVar("T")
AwaitableCallable = Callable[..., Awaitable[T]]
@overload
def is_async_callable(obj: AwaitableCallable[T]) -> TypeIs[AwaitableCallable[T]]: ...
@overload
def is_async_callable(obj: Any) -> TypeIs[AwaitableCallable[Any]]: ...
def is_async_callable(obj: Any) -> Any:
while isinstance(obj, functools.partial):
obj = obj.func
return iscoroutinefunction(obj) or (callable(obj) and iscoroutinefunction(obj.__call__))
T_co = TypeVar("T_co", covariant=True)
class AwaitableOrContextManager(Awaitable[T_co], AbstractAsyncContextManager[T_co], Protocol[T_co]): ...
class SupportsAsyncClose(Protocol):
async def close(self) -> None: ... # pragma: no cover
SupportsAsyncCloseType = TypeVar("SupportsAsyncCloseType", bound=SupportsAsyncClose, covariant=False)
class AwaitableOrContextManagerWrapper(Generic[SupportsAsyncCloseType]):
__slots__ = ("aw", "entered")
def __init__(self, aw: Awaitable[SupportsAsyncCloseType]) -> None:
self.aw = aw
def __await__(self) -> Generator[Any, None, SupportsAsyncCloseType]:
return self.aw.__await__()
async def __aenter__(self) -> SupportsAsyncCloseType:
self.entered = await self.aw
return self.entered
async def __aexit__(self, *args: Any) -> None | bool:
await self.entered.close()
return None
@contextmanager
def collapse_excgroups() -> Generator[None, None, None]:
try:
yield
except BaseException as exc:
if has_exceptiongroups: # pragma: no cover
while isinstance(exc, BaseExceptionGroup) and len(exc.exceptions) == 1:
exc = exc.exceptions[0]
raise exc
def get_route_path(scope: Scope) -> str:
path: str = scope["path"]
root_path = scope.get("root_path", "")
if not root_path:
return path
if not path.startswith(root_path):
return path
if path == root_path:
return ""
if path[len(root_path)] == "/":
return path[len(root_path) :]
return path
| import functools
from typing import Any
from unittest.mock import create_autospec
import pytest
from starlette._utils import get_route_path, is_async_callable
from starlette.types import Scope
def test_async_func() -> None:
async def async_func() -> None: ... # pragma: no cover
def func() -> None: ... # pragma: no cover
assert is_async_callable(async_func)
assert not is_async_callable(func)
def test_async_partial() -> None:
async def async_func(a: Any, b: Any) -> None: ... # pragma: no cover
def func(a: Any, b: Any) -> None: ... # pragma: no cover
partial = functools.partial(async_func, 1)
assert is_async_callable(partial)
partial = functools.partial(func, 1) # type: ignore
assert not is_async_callable(partial)
def test_async_method() -> None:
class Async:
async def method(self) -> None: ... # pragma: no cover
class Sync:
def method(self) -> None: ... # pragma: no cover
assert is_async_callable(Async().method)
assert not is_async_callable(Sync().method)
def test_async_object_call() -> None:
class Async:
async def __call__(self) -> None: ... # pragma: no cover
class Sync:
def __call__(self) -> None: ... # pragma: no cover
assert is_async_callable(Async())
assert not is_async_callable(Sync())
def test_async_partial_object_call() -> None:
class Async:
async def __call__(
self,
a: Any,
b: Any,
) -> None: ... # pragma: no cover
class Sync:
def __call__(
self,
a: Any,
b: Any,
) -> None: ... # pragma: no cover
partial = functools.partial(Async(), 1)
assert is_async_callable(partial)
partial = functools.partial(Sync(), 1) # type: ignore
assert not is_async_callable(partial)
def test_async_nested_partial() -> None:
async def async_func(
a: Any,
b: Any,
) -> None: ... # pragma: no cover
partial = functools.partial(async_func, b=2)
nested_partial = functools.partial(partial, a=1)
assert is_async_callable(nested_partial)
def test_async_mocked_async_function() -> None:
async def async_func() -> None: ... # pragma: no cover
mock = create_autospec(async_func)
assert is_async_callable(mock)
@pytest.mark.parametrize(
"scope, expected_result",
[
({"path": "/foo-123/bar", "root_path": "/foo"}, "/foo-123/bar"),
({"path": "/foo/bar", "root_path": "/foo"}, "/bar"),
({"path": "/foo", "root_path": "/foo"}, ""),
({"path": "/foo/bar", "root_path": "/bar"}, "/foo/bar"),
],
)
def test_get_route_path(scope: Scope, expected_result: str) -> None:
assert get_route_path(scope) == expected_result
| starlette |
python | from __future__ import annotations
import os
import warnings
from collections.abc import Callable, Iterator, Mapping, MutableMapping
from pathlib import Path
from typing import Any, TypeVar, overload
class undefined:
pass
class EnvironError(Exception):
pass
class Environ(MutableMapping[str, str]):
def __init__(self, environ: MutableMapping[str, str] = os.environ):
self._environ = environ
self._has_been_read: set[str] = set()
def __getitem__(self, key: str) -> str:
self._has_been_read.add(key)
return self._environ.__getitem__(key)
def __setitem__(self, key: str, value: str) -> None:
if key in self._has_been_read:
raise EnvironError(f"Attempting to set environ['{key}'], but the value has already been read.")
self._environ.__setitem__(key, value)
def __delitem__(self, key: str) -> None:
if key in self._has_been_read:
raise EnvironError(f"Attempting to delete environ['{key}'], but the value has already been read.")
self._environ.__delitem__(key)
def __iter__(self) -> Iterator[str]:
return iter(self._environ)
def __len__(self) -> int:
return len(self._environ)
environ = Environ()
T = TypeVar("T")
class Config:
def __init__(
self,
env_file: str | Path | None = None,
environ: Mapping[str, str] = environ,
env_prefix: str = "",
encoding: str = "utf-8",
) -> None:
self.environ = environ
self.env_prefix = env_prefix
self.file_values: dict[str, str] = {}
if env_file is not None:
if not os.path.isfile(env_file):
warnings.warn(f"Config file '{env_file}' not found.")
else:
self.file_values = self._read_file(env_file, encoding)
@overload
def __call__(self, key: str, *, default: None) -> str | None: ...
@overload
def __call__(self, key: str, cast: type[T], default: T = ...) -> T: ...
@overload
def __call__(self, key: str, cast: type[str] = ..., default: str = ...) -> str: ...
@overload
def __call__(
self,
key: str,
cast: Callable[[Any], T] = ...,
default: Any = ...,
) -> T: ...
@overload
def __call__(self, key: str, cast: type[str] = ..., default: T = ...) -> T | str: ...
def __call__(
self,
key: str,
cast: Callable[[Any], Any] | None = None,
default: Any = undefined,
) -> Any:
return self.get(key, cast, default)
def get(
self,
key: str,
cast: Callable[[Any], Any] | None = None,
default: Any = undefined,
) -> Any:
key = self.env_prefix + key
if key in self.environ:
value = self.environ[key]
return self._perform_cast(key, value, cast)
if key in self.file_values:
value = self.file_values[key]
return self._perform_cast(key, value, cast)
if default is not undefined:
return self._perform_cast(key, default, cast)
raise KeyError(f"Config '{key}' is missing, and has no default.")
def _read_file(self, file_name: str | Path, encoding: str) -> dict[str, str]:
file_values: dict[str, str] = {}
with open(file_name, encoding=encoding) as input_file:
for line in input_file.readlines():
line = line.strip()
if "=" in line and not line.startswith("#"):
key, value = line.split("=", 1)
key = key.strip()
value = value.strip().strip("\"'")
file_values[key] = value
return file_values
def _perform_cast(
self,
key: str,
value: Any,
cast: Callable[[Any], Any] | None = None,
) -> Any:
if cast is None or value is None:
return value
elif cast is bool and isinstance(value, str):
mapping = {"true": True, "1": True, "false": False, "0": False}
value = value.lower()
if value not in mapping:
raise ValueError(f"Config '{key}' has value '{value}'. Not a valid bool.")
return mapping[value]
try:
return cast(value)
except (TypeError, ValueError):
raise ValueError(f"Config '{key}' has value '{value}'. Not a valid {cast.__name__}.")
| import os
from pathlib import Path
from typing import Any
import pytest
from typing_extensions import assert_type
from starlette.config import Config, Environ, EnvironError
from starlette.datastructures import URL, Secret
def test_config_types() -> None:
"""
We use `assert_type` to test the types returned by Config via mypy.
"""
config = Config(environ={"STR": "some_str_value", "STR_CAST": "some_str_value", "BOOL": "true"})
assert_type(config("STR"), str)
assert_type(config("STR_DEFAULT", default=""), str)
assert_type(config("STR_CAST", cast=str), str)
assert_type(config("STR_NONE", default=None), str | None)
assert_type(config("STR_CAST_NONE", cast=str, default=None), str | None)
assert_type(config("STR_CAST_STR", cast=str, default=""), str)
assert_type(config("BOOL", cast=bool), bool)
assert_type(config("BOOL_DEFAULT", cast=bool, default=False), bool)
assert_type(config("BOOL_NONE", cast=bool, default=None), bool | None)
def cast_to_int(v: Any) -> int:
return int(v)
# our type annotations allow these `cast` and `default` configurations, but
# the code will error at runtime.
with pytest.raises(ValueError):
config("INT_CAST_DEFAULT_STR", cast=cast_to_int, default="true")
with pytest.raises(ValueError):
config("INT_DEFAULT_STR", cast=int, default="true")
def test_config(tmpdir: Path, monkeypatch: pytest.MonkeyPatch) -> None:
path = os.path.join(tmpdir, ".env")
with open(path, "w") as file:
file.write("# Do not commit to source control\n")
file.write("DATABASE_URL=postgres://user:pass@localhost/dbname\n")
file.write("REQUEST_HOSTNAME=example.com\n")
file.write("SECRET_KEY=12345\n")
file.write("BOOL_AS_INT=0\n")
file.write("\n")
file.write("\n")
config = Config(path, environ={"DEBUG": "true"})
def cast_to_int(v: Any) -> int:
return int(v)
DEBUG = config("DEBUG", cast=bool)
DATABASE_URL = config("DATABASE_URL", cast=URL)
REQUEST_TIMEOUT = config("REQUEST_TIMEOUT", cast=int, default=10)
REQUEST_HOSTNAME = config("REQUEST_HOSTNAME")
MAIL_HOSTNAME = config("MAIL_HOSTNAME", default=None)
SECRET_KEY = config("SECRET_KEY", cast=Secret)
UNSET_SECRET = config("UNSET_SECRET", cast=Secret, default=None)
EMPTY_SECRET = config("EMPTY_SECRET", cast=Secret, default="")
assert config("BOOL_AS_INT", cast=bool) is False
assert config("BOOL_AS_INT", cast=cast_to_int) == 0
assert config("DEFAULTED_BOOL", cast=cast_to_int, default=True) == 1
assert DEBUG is True
assert DATABASE_URL.path == "/dbname"
assert DATABASE_URL.password == "pass"
assert DATABASE_URL.username == "user"
assert REQUEST_TIMEOUT == 10
assert REQUEST_HOSTNAME == "example.com"
assert MAIL_HOSTNAME is None
assert repr(SECRET_KEY) == "Secret('**********')"
assert str(SECRET_KEY) == "12345"
assert bool(SECRET_KEY)
assert not bool(EMPTY_SECRET)
assert not bool(UNSET_SECRET)
with pytest.raises(KeyError):
config.get("MISSING")
with pytest.raises(ValueError):
config.get("DEBUG", cast=int)
with pytest.raises(ValueError):
config.get("REQUEST_HOSTNAME", cast=bool)
config = Config(Path(path))
REQUEST_HOSTNAME = config("REQUEST_HOSTNAME")
assert REQUEST_HOSTNAME == "example.com"
config = Config()
monkeypatch.setenv("STARLETTE_EXAMPLE_TEST", "123")
monkeypatch.setenv("BOOL_AS_INT", "1")
assert config.get("STARLETTE_EXAMPLE_TEST", cast=int) == 123
assert config.get("BOOL_AS_INT", cast=bool) is True
monkeypatch.setenv("BOOL_AS_INT", "2")
with pytest.raises(ValueError):
config.get("BOOL_AS_INT", cast=bool)
def test_missing_env_file_raises(tmpdir: Path) -> None:
path = os.path.join(tmpdir, ".env")
with pytest.warns(UserWarning, match=f"Config file '{path}' not found."):
Config(path)
def test_environ() -> None:
environ = Environ()
# We can mutate the environ at this point.
environ["TESTING"] = "True"
environ["GONE"] = "123"
del environ["GONE"]
# We can read the environ.
assert environ["TESTING"] == "True"
assert "GONE" not in environ
# We cannot mutate these keys now that we've read them.
with pytest.raises(EnvironError):
environ["TESTING"] = "False"
with pytest.raises(EnvironError):
del environ["GONE"]
# Test coverage of abstract methods for MutableMapping.
environ = Environ()
assert list(iter(environ)) == list(iter(os.environ))
assert len(environ) == len(os.environ)
def test_config_with_env_prefix(tmpdir: Path, monkeypatch: pytest.MonkeyPatch) -> None:
config = Config(environ={"APP_DEBUG": "value", "ENVIRONMENT": "dev"}, env_prefix="APP_")
assert config.get("DEBUG") == "value"
with pytest.raises(KeyError):
config.get("ENVIRONMENT")
def test_config_with_encoding(tmpdir: Path) -> None:
path = tmpdir / ".env"
path.write_text("MESSAGE=Hello 世界\n", encoding="utf-8")
config = Config(path, encoding="utf-8")
assert config.get("MESSAGE") == "Hello 世界"
| starlette |
python | from __future__ import annotations
import http
from collections.abc import Mapping
class HTTPException(Exception):
def __init__(self, status_code: int, detail: str | None = None, headers: Mapping[str, str] | None = None) -> None:
if detail is None:
detail = http.HTTPStatus(status_code).phrase
self.status_code = status_code
self.detail = detail
self.headers = headers
def __str__(self) -> str:
return f"{self.status_code}: {self.detail}"
def __repr__(self) -> str:
class_name = self.__class__.__name__
return f"{class_name}(status_code={self.status_code!r}, detail={self.detail!r})"
class WebSocketException(Exception):
def __init__(self, code: int, reason: str | None = None) -> None:
self.code = code
self.reason = reason or ""
def __str__(self) -> str:
return f"{self.code}: {self.reason}"
def __repr__(self) -> str:
class_name = self.__class__.__name__
return f"{class_name}(code={self.code!r}, reason={self.reason!r})"
| from collections.abc import Generator
from typing import Any
import pytest
from pytest import MonkeyPatch
from starlette.exceptions import HTTPException, WebSocketException
from starlette.middleware.exceptions import ExceptionMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse, PlainTextResponse
from starlette.routing import Route, Router, WebSocketRoute
from starlette.testclient import TestClient
from starlette.types import Receive, Scope, Send
from tests.types import TestClientFactory
def raise_runtime_error(request: Request) -> None:
raise RuntimeError("Yikes")
def not_acceptable(request: Request) -> None:
raise HTTPException(status_code=406)
def no_content(request: Request) -> None:
raise HTTPException(status_code=204)
def not_modified(request: Request) -> None:
raise HTTPException(status_code=304)
def with_headers(request: Request) -> None:
raise HTTPException(status_code=200, headers={"x-potato": "always"})
class BadBodyException(HTTPException):
pass
async def read_body_and_raise_exc(request: Request) -> None:
await request.body()
raise BadBodyException(422)
async def handler_that_reads_body(request: Request, exc: BadBodyException) -> JSONResponse:
body = await request.body()
return JSONResponse(status_code=422, content={"body": body.decode()})
class HandledExcAfterResponse:
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
response = PlainTextResponse("OK", status_code=200)
await response(scope, receive, send)
raise HTTPException(status_code=406)
router = Router(
routes=[
Route("/runtime_error", endpoint=raise_runtime_error),
Route("/not_acceptable", endpoint=not_acceptable),
Route("/no_content", endpoint=no_content),
Route("/not_modified", endpoint=not_modified),
Route("/with_headers", endpoint=with_headers),
Route("/handled_exc_after_response", endpoint=HandledExcAfterResponse()),
WebSocketRoute("/runtime_error", endpoint=raise_runtime_error),
Route("/consume_body_in_endpoint_and_handler", endpoint=read_body_and_raise_exc, methods=["POST"]),
]
)
app = ExceptionMiddleware(
router,
handlers={BadBodyException: handler_that_reads_body}, # type: ignore[dict-item]
)
@pytest.fixture
def client(test_client_factory: TestClientFactory) -> Generator[TestClient, None, None]:
with test_client_factory(app) as client:
yield client
def test_not_acceptable(client: TestClient) -> None:
response = client.get("/not_acceptable")
assert response.status_code == 406
assert response.text == "Not Acceptable"
def test_no_content(client: TestClient) -> None:
response = client.get("/no_content")
assert response.status_code == 204
assert "content-length" not in response.headers
def test_not_modified(client: TestClient) -> None:
response = client.get("/not_modified")
assert response.status_code == 304
assert response.text == ""
def test_with_headers(client: TestClient) -> None:
response = client.get("/with_headers")
assert response.status_code == 200
assert response.headers["x-potato"] == "always"
def test_websockets_should_raise(client: TestClient) -> None:
with pytest.raises(RuntimeError):
with client.websocket_connect("/runtime_error"):
pass # pragma: no cover
def test_handled_exc_after_response(test_client_factory: TestClientFactory, client: TestClient) -> None:
# A 406 HttpException is raised *after* the response has already been sent.
# The exception middleware should raise a RuntimeError.
with pytest.raises(RuntimeError, match="Caught handled exception, but response already started."):
client.get("/handled_exc_after_response")
# If `raise_server_exceptions=False` then the test client will still allow
# us to see the response as it will have been seen by the client.
allow_200_client = test_client_factory(app, raise_server_exceptions=False)
response = allow_200_client.get("/handled_exc_after_response")
assert response.status_code == 200
assert response.text == "OK"
def test_force_500_response(test_client_factory: TestClientFactory) -> None:
# use a sentinel variable to make sure we actually
# make it into the endpoint and don't get a 500
# from an incorrect ASGI app signature or something
called = False
async def app(scope: Scope, receive: Receive, send: Send) -> None:
nonlocal called
called = True
raise RuntimeError()
force_500_client = test_client_factory(app, raise_server_exceptions=False)
response = force_500_client.get("/")
assert called
assert response.status_code == 500
assert response.text == ""
def test_http_str() -> None:
assert str(HTTPException(status_code=404)) == "404: Not Found"
assert str(HTTPException(404, "Not Found: foo")) == "404: Not Found: foo"
assert str(HTTPException(404, headers={"key": "value"})) == "404: Not Found"
def test_http_repr() -> None:
assert repr(HTTPException(404)) == ("HTTPException(status_code=404, detail='Not Found')")
assert repr(HTTPException(404, detail="Not Found: foo")) == (
"HTTPException(status_code=404, detail='Not Found: foo')"
)
class CustomHTTPException(HTTPException):
pass
assert repr(CustomHTTPException(500, detail="Something custom")) == (
"CustomHTTPException(status_code=500, detail='Something custom')"
)
def test_websocket_str() -> None:
assert str(WebSocketException(1008)) == "1008: "
assert str(WebSocketException(1008, "Policy Violation")) == "1008: Policy Violation"
def test_websocket_repr() -> None:
assert repr(WebSocketException(1008, reason="Policy Violation")) == (
"WebSocketException(code=1008, reason='Policy Violation')"
)
class CustomWebSocketException(WebSocketException):
pass
assert (
repr(CustomWebSocketException(1013, reason="Something custom"))
== "CustomWebSocketException(code=1013, reason='Something custom')"
)
def test_request_in_app_and_handler_is_the_same_object(client: TestClient) -> None:
response = client.post("/consume_body_in_endpoint_and_handler", content=b"Hello!")
assert response.status_code == 422
assert response.json() == {"body": "Hello!"}
def test_http_exception_does_not_use_threadpool(client: TestClient, monkeypatch: MonkeyPatch) -> None:
"""
Verify that handling HTTPException does not invoke run_in_threadpool,
confirming the handler correctly runs in the main async context.
"""
from starlette import _exception_handler
# Replace run_in_threadpool with a function that raises an error
def mock_run_in_threadpool(*args: Any, **kwargs: Any) -> None:
pytest.fail("run_in_threadpool should not be called for HTTP exceptions") # pragma: no cover
# Apply the monkeypatch only during this test
monkeypatch.setattr(_exception_handler, "run_in_threadpool", mock_run_in_threadpool)
# This should succeed because http_exception is async and won't use run_in_threadpool
response = client.get("/not_acceptable")
assert response.status_code == 406
def test_handlers_annotations() -> None:
"""Check that async exception handlers are accepted by type checkers.
We annotate the handlers' exceptions with plain `Exception` to avoid variance issues
when using other exception types.
"""
async def async_catch_all_handler(request: Request, exc: Exception) -> JSONResponse:
raise NotImplementedError
def sync_catch_all_handler(request: Request, exc: Exception) -> JSONResponse:
raise NotImplementedError
ExceptionMiddleware(router, handlers={Exception: sync_catch_all_handler})
ExceptionMiddleware(router, handlers={Exception: async_catch_all_handler})
| starlette |
python | from __future__ import annotations
import functools
import warnings
from collections.abc import AsyncIterator, Callable, Coroutine, Iterable, Iterator
from typing import ParamSpec, TypeVar
import anyio.to_thread
P = ParamSpec("P")
T = TypeVar("T")
async def run_until_first_complete(*args: tuple[Callable, dict]) -> None: # type: ignore[type-arg]
warnings.warn(
"run_until_first_complete is deprecated and will be removed in a future version.",
DeprecationWarning,
)
async with anyio.create_task_group() as task_group:
async def run(func: Callable[[], Coroutine]) -> None: # type: ignore[type-arg]
await func()
task_group.cancel_scope.cancel()
for func, kwargs in args:
task_group.start_soon(run, functools.partial(func, **kwargs))
async def run_in_threadpool(func: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T:
func = functools.partial(func, *args, **kwargs)
return await anyio.to_thread.run_sync(func)
class _StopIteration(Exception):
pass
def _next(iterator: Iterator[T]) -> T:
# We can't raise `StopIteration` from within the threadpool iterator
# and catch it outside that context, so we coerce them into a different
# exception type.
try:
return next(iterator)
except StopIteration:
raise _StopIteration
async def iterate_in_threadpool(
iterator: Iterable[T],
) -> AsyncIterator[T]:
as_iterator = iter(iterator)
while True:
try:
yield await anyio.to_thread.run_sync(_next, as_iterator)
except _StopIteration:
break
| from collections.abc import Iterator
from contextvars import ContextVar
import anyio
import pytest
from starlette.applications import Starlette
from starlette.concurrency import iterate_in_threadpool, run_until_first_complete
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import Route
from tests.types import TestClientFactory
@pytest.mark.anyio
async def test_run_until_first_complete() -> None:
task1_finished = anyio.Event()
task2_finished = anyio.Event()
async def task1() -> None:
task1_finished.set()
async def task2() -> None:
await task1_finished.wait()
await anyio.sleep(0) # pragma: no cover
task2_finished.set() # pragma: no cover
await run_until_first_complete((task1, {}), (task2, {}))
assert task1_finished.is_set()
assert not task2_finished.is_set()
def test_accessing_context_from_threaded_sync_endpoint(
test_client_factory: TestClientFactory,
) -> None:
ctxvar: ContextVar[bytes] = ContextVar("ctxvar")
ctxvar.set(b"data")
def endpoint(request: Request) -> Response:
return Response(ctxvar.get())
app = Starlette(routes=[Route("/", endpoint)])
client = test_client_factory(app)
resp = client.get("/")
assert resp.content == b"data"
@pytest.mark.anyio
async def test_iterate_in_threadpool() -> None:
class CustomIterable:
def __iter__(self) -> Iterator[int]:
yield from range(3)
assert [v async for v in iterate_in_threadpool(CustomIterable())] == [0, 1, 2]
| starlette |
python | """
HTTP codes
See HTTP Status Code Registry:
https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
And RFC 9110 - https://www.rfc-editor.org/rfc/rfc9110
"""
from __future__ import annotations
import warnings
__all__ = [
"HTTP_100_CONTINUE",
"HTTP_101_SWITCHING_PROTOCOLS",
"HTTP_102_PROCESSING",
"HTTP_103_EARLY_HINTS",
"HTTP_200_OK",
"HTTP_201_CREATED",
"HTTP_202_ACCEPTED",
"HTTP_203_NON_AUTHORITATIVE_INFORMATION",
"HTTP_204_NO_CONTENT",
"HTTP_205_RESET_CONTENT",
"HTTP_206_PARTIAL_CONTENT",
"HTTP_207_MULTI_STATUS",
"HTTP_208_ALREADY_REPORTED",
"HTTP_226_IM_USED",
"HTTP_300_MULTIPLE_CHOICES",
"HTTP_301_MOVED_PERMANENTLY",
"HTTP_302_FOUND",
"HTTP_303_SEE_OTHER",
"HTTP_304_NOT_MODIFIED",
"HTTP_305_USE_PROXY",
"HTTP_306_RESERVED",
"HTTP_307_TEMPORARY_REDIRECT",
"HTTP_308_PERMANENT_REDIRECT",
"HTTP_400_BAD_REQUEST",
"HTTP_401_UNAUTHORIZED",
"HTTP_402_PAYMENT_REQUIRED",
"HTTP_403_FORBIDDEN",
"HTTP_404_NOT_FOUND",
"HTTP_405_METHOD_NOT_ALLOWED",
"HTTP_406_NOT_ACCEPTABLE",
"HTTP_407_PROXY_AUTHENTICATION_REQUIRED",
"HTTP_408_REQUEST_TIMEOUT",
"HTTP_409_CONFLICT",
"HTTP_410_GONE",
"HTTP_411_LENGTH_REQUIRED",
"HTTP_412_PRECONDITION_FAILED",
"HTTP_413_CONTENT_TOO_LARGE",
"HTTP_414_URI_TOO_LONG",
"HTTP_415_UNSUPPORTED_MEDIA_TYPE",
"HTTP_416_RANGE_NOT_SATISFIABLE",
"HTTP_417_EXPECTATION_FAILED",
"HTTP_418_IM_A_TEAPOT",
"HTTP_421_MISDIRECTED_REQUEST",
"HTTP_422_UNPROCESSABLE_CONTENT",
"HTTP_423_LOCKED",
"HTTP_424_FAILED_DEPENDENCY",
"HTTP_425_TOO_EARLY",
"HTTP_426_UPGRADE_REQUIRED",
"HTTP_428_PRECONDITION_REQUIRED",
"HTTP_429_TOO_MANY_REQUESTS",
"HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE",
"HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS",
"HTTP_500_INTERNAL_SERVER_ERROR",
"HTTP_501_NOT_IMPLEMENTED",
"HTTP_502_BAD_GATEWAY",
"HTTP_503_SERVICE_UNAVAILABLE",
"HTTP_504_GATEWAY_TIMEOUT",
"HTTP_505_HTTP_VERSION_NOT_SUPPORTED",
"HTTP_506_VARIANT_ALSO_NEGOTIATES",
"HTTP_507_INSUFFICIENT_STORAGE",
"HTTP_508_LOOP_DETECTED",
"HTTP_510_NOT_EXTENDED",
"HTTP_511_NETWORK_AUTHENTICATION_REQUIRED",
"WS_1000_NORMAL_CLOSURE",
"WS_1001_GOING_AWAY",
"WS_1002_PROTOCOL_ERROR",
"WS_1003_UNSUPPORTED_DATA",
"WS_1005_NO_STATUS_RCVD",
"WS_1006_ABNORMAL_CLOSURE",
"WS_1007_INVALID_FRAME_PAYLOAD_DATA",
"WS_1008_POLICY_VIOLATION",
"WS_1009_MESSAGE_TOO_BIG",
"WS_1010_MANDATORY_EXT",
"WS_1011_INTERNAL_ERROR",
"WS_1012_SERVICE_RESTART",
"WS_1013_TRY_AGAIN_LATER",
"WS_1014_BAD_GATEWAY",
"WS_1015_TLS_HANDSHAKE",
]
HTTP_100_CONTINUE = 100
HTTP_101_SWITCHING_PROTOCOLS = 101
HTTP_102_PROCESSING = 102
HTTP_103_EARLY_HINTS = 103
HTTP_200_OK = 200
HTTP_201_CREATED = 201
HTTP_202_ACCEPTED = 202
HTTP_203_NON_AUTHORITATIVE_INFORMATION = 203
HTTP_204_NO_CONTENT = 204
HTTP_205_RESET_CONTENT = 205
HTTP_206_PARTIAL_CONTENT = 206
HTTP_207_MULTI_STATUS = 207
HTTP_208_ALREADY_REPORTED = 208
HTTP_226_IM_USED = 226
HTTP_300_MULTIPLE_CHOICES = 300
HTTP_301_MOVED_PERMANENTLY = 301
HTTP_302_FOUND = 302
HTTP_303_SEE_OTHER = 303
HTTP_304_NOT_MODIFIED = 304
HTTP_305_USE_PROXY = 305
HTTP_306_RESERVED = 306
HTTP_307_TEMPORARY_REDIRECT = 307
HTTP_308_PERMANENT_REDIRECT = 308
HTTP_400_BAD_REQUEST = 400
HTTP_401_UNAUTHORIZED = 401
HTTP_402_PAYMENT_REQUIRED = 402
HTTP_403_FORBIDDEN = 403
HTTP_404_NOT_FOUND = 404
HTTP_405_METHOD_NOT_ALLOWED = 405
HTTP_406_NOT_ACCEPTABLE = 406
HTTP_407_PROXY_AUTHENTICATION_REQUIRED = 407
HTTP_408_REQUEST_TIMEOUT = 408
HTTP_409_CONFLICT = 409
HTTP_410_GONE = 410
HTTP_411_LENGTH_REQUIRED = 411
HTTP_412_PRECONDITION_FAILED = 412
HTTP_413_CONTENT_TOO_LARGE = 413
HTTP_414_URI_TOO_LONG = 414
HTTP_415_UNSUPPORTED_MEDIA_TYPE = 415
HTTP_416_RANGE_NOT_SATISFIABLE = 416
HTTP_417_EXPECTATION_FAILED = 417
HTTP_418_IM_A_TEAPOT = 418
HTTP_421_MISDIRECTED_REQUEST = 421
HTTP_422_UNPROCESSABLE_CONTENT = 422
HTTP_423_LOCKED = 423
HTTP_424_FAILED_DEPENDENCY = 424
HTTP_425_TOO_EARLY = 425
HTTP_426_UPGRADE_REQUIRED = 426
HTTP_428_PRECONDITION_REQUIRED = 428
HTTP_429_TOO_MANY_REQUESTS = 429
HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE = 431
HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS = 451
HTTP_500_INTERNAL_SERVER_ERROR = 500
HTTP_501_NOT_IMPLEMENTED = 501
HTTP_502_BAD_GATEWAY = 502
HTTP_503_SERVICE_UNAVAILABLE = 503
HTTP_504_GATEWAY_TIMEOUT = 504
HTTP_505_HTTP_VERSION_NOT_SUPPORTED = 505
HTTP_506_VARIANT_ALSO_NEGOTIATES = 506
HTTP_507_INSUFFICIENT_STORAGE = 507
HTTP_508_LOOP_DETECTED = 508
HTTP_510_NOT_EXTENDED = 510
HTTP_511_NETWORK_AUTHENTICATION_REQUIRED = 511
"""
WebSocket codes
https://www.iana.org/assignments/websocket/websocket.xml#close-code-number
https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
"""
WS_1000_NORMAL_CLOSURE = 1000
WS_1001_GOING_AWAY = 1001
WS_1002_PROTOCOL_ERROR = 1002
WS_1003_UNSUPPORTED_DATA = 1003
WS_1005_NO_STATUS_RCVD = 1005
WS_1006_ABNORMAL_CLOSURE = 1006
WS_1007_INVALID_FRAME_PAYLOAD_DATA = 1007
WS_1008_POLICY_VIOLATION = 1008
WS_1009_MESSAGE_TOO_BIG = 1009
WS_1010_MANDATORY_EXT = 1010
WS_1011_INTERNAL_ERROR = 1011
WS_1012_SERVICE_RESTART = 1012
WS_1013_TRY_AGAIN_LATER = 1013
WS_1014_BAD_GATEWAY = 1014
WS_1015_TLS_HANDSHAKE = 1015
__deprecated__ = {
"HTTP_413_REQUEST_ENTITY_TOO_LARGE": 413,
"HTTP_414_REQUEST_URI_TOO_LONG": 414,
"HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE": 416,
"HTTP_422_UNPROCESSABLE_ENTITY": 422,
}
def __getattr__(name: str) -> int:
deprecation_changes = {
"HTTP_413_REQUEST_ENTITY_TOO_LARGE": "HTTP_413_CONTENT_TOO_LARGE",
"HTTP_414_REQUEST_URI_TOO_LONG": "HTTP_414_URI_TOO_LONG",
"HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE": "HTTP_416_RANGE_NOT_SATISFIABLE",
"HTTP_422_UNPROCESSABLE_ENTITY": "HTTP_422_UNPROCESSABLE_CONTENT",
}
deprecated = __deprecated__.get(name)
if deprecated:
warnings.warn(
f"'{name}' is deprecated. Use '{deprecation_changes[name]}' instead.",
category=DeprecationWarning,
stacklevel=3,
)
return deprecated
raise AttributeError(f"module 'starlette.status' has no attribute '{name}'")
def __dir__() -> list[str]:
return sorted(list(__all__) + list(__deprecated__.keys())) # pragma: no cover
| import importlib
import pytest
@pytest.mark.parametrize(
"constant,msg",
(
(
"HTTP_413_REQUEST_ENTITY_TOO_LARGE",
"'HTTP_413_REQUEST_ENTITY_TOO_LARGE' is deprecated. Use 'HTTP_413_CONTENT_TOO_LARGE' instead.",
),
(
"HTTP_414_REQUEST_URI_TOO_LONG",
"'HTTP_414_REQUEST_URI_TOO_LONG' is deprecated. Use 'HTTP_414_URI_TOO_LONG' instead.",
),
),
)
def test_deprecated_types(constant: str, msg: str) -> None:
with pytest.warns(DeprecationWarning) as record:
getattr(importlib.import_module("starlette.status"), constant)
assert len(record) == 1
assert msg in str(record.list[0])
def test_unknown_status() -> None:
with pytest.raises(
AttributeError,
match="module 'starlette.status' has no attribute 'HTTP_999_UNKNOWN_STATUS_CODE'",
):
getattr(importlib.import_module("starlette.status"), "HTTP_999_UNKNOWN_STATUS_CODE")
| starlette |
python | from __future__ import annotations
import json
from collections.abc import AsyncGenerator, Iterator, Mapping
from http import cookies as http_cookies
from typing import TYPE_CHECKING, Any, NoReturn, cast
import anyio
from starlette._utils import AwaitableOrContextManager, AwaitableOrContextManagerWrapper
from starlette.datastructures import URL, Address, FormData, Headers, QueryParams, State
from starlette.exceptions import HTTPException
from starlette.formparsers import FormParser, MultiPartException, MultiPartParser
from starlette.types import Message, Receive, Scope, Send
if TYPE_CHECKING:
from python_multipart.multipart import parse_options_header
from starlette.applications import Starlette
from starlette.routing import Router
else:
try:
try:
from python_multipart.multipart import parse_options_header
except ModuleNotFoundError: # pragma: no cover
from multipart.multipart import parse_options_header
except ModuleNotFoundError: # pragma: no cover
parse_options_header = None
SERVER_PUSH_HEADERS_TO_COPY = {
"accept",
"accept-encoding",
"accept-language",
"cache-control",
"user-agent",
}
def cookie_parser(cookie_string: str) -> dict[str, str]:
"""
This function parses a ``Cookie`` HTTP header into a dict of key/value pairs.
It attempts to mimic browser cookie parsing behavior: browsers and web servers
frequently disregard the spec (RFC 6265) when setting and reading cookies,
so we attempt to suit the common scenarios here.
This function has been adapted from Django 3.1.0.
Note: we are explicitly _NOT_ using `SimpleCookie.load` because it is based
on an outdated spec and will fail on lots of input we want to support
"""
cookie_dict: dict[str, str] = {}
for chunk in cookie_string.split(";"):
if "=" in chunk:
key, val = chunk.split("=", 1)
else:
# Assume an empty name per
# https://bugzilla.mozilla.org/show_bug.cgi?id=169091
key, val = "", chunk
key, val = key.strip(), val.strip()
if key or val:
# unquote using Python's algorithm.
cookie_dict[key] = http_cookies._unquote(val)
return cookie_dict
class ClientDisconnect(Exception):
pass
class HTTPConnection(Mapping[str, Any]):
"""
A base class for incoming HTTP connections, that is used to provide
any functionality that is common to both `Request` and `WebSocket`.
"""
def __init__(self, scope: Scope, receive: Receive | None = None) -> None:
assert scope["type"] in ("http", "websocket")
self.scope = scope
def __getitem__(self, key: str) -> Any:
return self.scope[key]
def __iter__(self) -> Iterator[str]:
return iter(self.scope)
def __len__(self) -> int:
return len(self.scope)
# Don't use the `abc.Mapping.__eq__` implementation.
# Connection instances should never be considered equal
# unless `self is other`.
__eq__ = object.__eq__
__hash__ = object.__hash__
@property
def app(self) -> Any:
return self.scope["app"]
@property
def url(self) -> URL:
if not hasattr(self, "_url"): # pragma: no branch
self._url = URL(scope=self.scope)
return self._url
@property
def base_url(self) -> URL:
if not hasattr(self, "_base_url"):
base_url_scope = dict(self.scope)
# This is used by request.url_for, it might be used inside a Mount which
# would have its own child scope with its own root_path, but the base URL
# for url_for should still be the top level app root path.
app_root_path = base_url_scope.get("app_root_path", base_url_scope.get("root_path", ""))
path = app_root_path
if not path.endswith("/"):
path += "/"
base_url_scope["path"] = path
base_url_scope["query_string"] = b""
base_url_scope["root_path"] = app_root_path
self._base_url = URL(scope=base_url_scope)
return self._base_url
@property
def headers(self) -> Headers:
if not hasattr(self, "_headers"):
self._headers = Headers(scope=self.scope)
return self._headers
@property
def query_params(self) -> QueryParams:
if not hasattr(self, "_query_params"): # pragma: no branch
self._query_params = QueryParams(self.scope["query_string"])
return self._query_params
@property
def path_params(self) -> dict[str, Any]:
return self.scope.get("path_params", {})
@property
def cookies(self) -> dict[str, str]:
if not hasattr(self, "_cookies"):
cookies: dict[str, str] = {}
cookie_headers = self.headers.getlist("cookie")
for header in cookie_headers:
cookies.update(cookie_parser(header))
self._cookies = cookies
return self._cookies
@property
def client(self) -> Address | None:
# client is a 2 item tuple of (host, port), None if missing
host_port = self.scope.get("client")
if host_port is not None:
return Address(*host_port)
return None
@property
def session(self) -> dict[str, Any]:
assert "session" in self.scope, "SessionMiddleware must be installed to access request.session"
return self.scope["session"] # type: ignore[no-any-return]
@property
def auth(self) -> Any:
assert "auth" in self.scope, "AuthenticationMiddleware must be installed to access request.auth"
return self.scope["auth"]
@property
def user(self) -> Any:
assert "user" in self.scope, "AuthenticationMiddleware must be installed to access request.user"
return self.scope["user"]
@property
def state(self) -> State:
if not hasattr(self, "_state"):
# Ensure 'state' has an empty dict if it's not already populated.
self.scope.setdefault("state", {})
# Create a state instance with a reference to the dict in which it should
# store info
self._state = State(self.scope["state"])
return self._state
def url_for(self, name: str, /, **path_params: Any) -> URL:
url_path_provider: Router | Starlette | None = self.scope.get("router") or self.scope.get("app")
if url_path_provider is None:
raise RuntimeError("The `url_for` method can only be used inside a Starlette application or with a router.")
url_path = url_path_provider.url_path_for(name, **path_params)
return url_path.make_absolute_url(base_url=self.base_url)
async def empty_receive() -> NoReturn:
raise RuntimeError("Receive channel has not been made available")
async def empty_send(message: Message) -> NoReturn:
raise RuntimeError("Send channel has not been made available")
class Request(HTTPConnection):
_form: FormData | None
def __init__(self, scope: Scope, receive: Receive = empty_receive, send: Send = empty_send):
super().__init__(scope)
assert scope["type"] == "http"
self._receive = receive
self._send = send
self._stream_consumed = False
self._is_disconnected = False
self._form = None
@property
def method(self) -> str:
return cast(str, self.scope["method"])
@property
def receive(self) -> Receive:
return self._receive
async def stream(self) -> AsyncGenerator[bytes, None]:
if hasattr(self, "_body"):
yield self._body
yield b""
return
if self._stream_consumed:
raise RuntimeError("Stream consumed")
while not self._stream_consumed:
message = await self._receive()
if message["type"] == "http.request":
body = message.get("body", b"")
if not message.get("more_body", False):
self._stream_consumed = True
if body:
yield body
elif message["type"] == "http.disconnect": # pragma: no branch
self._is_disconnected = True
raise ClientDisconnect()
yield b""
async def body(self) -> bytes:
if not hasattr(self, "_body"):
chunks: list[bytes] = []
async for chunk in self.stream():
chunks.append(chunk)
self._body = b"".join(chunks)
return self._body
async def json(self) -> Any:
if not hasattr(self, "_json"): # pragma: no branch
body = await self.body()
self._json = json.loads(body)
return self._json
async def _get_form(
self,
*,
max_files: int | float = 1000,
max_fields: int | float = 1000,
max_part_size: int = 1024 * 1024,
) -> FormData:
if self._form is None: # pragma: no branch
assert parse_options_header is not None, (
"The `python-multipart` library must be installed to use form parsing."
)
content_type_header = self.headers.get("Content-Type")
content_type: bytes
content_type, _ = parse_options_header(content_type_header)
if content_type == b"multipart/form-data":
try:
multipart_parser = MultiPartParser(
self.headers,
self.stream(),
max_files=max_files,
max_fields=max_fields,
max_part_size=max_part_size,
)
self._form = await multipart_parser.parse()
except MultiPartException as exc:
if "app" in self.scope:
raise HTTPException(status_code=400, detail=exc.message)
raise exc
elif content_type == b"application/x-www-form-urlencoded":
form_parser = FormParser(self.headers, self.stream())
self._form = await form_parser.parse()
else:
self._form = FormData()
return self._form
def form(
self,
*,
max_files: int | float = 1000,
max_fields: int | float = 1000,
max_part_size: int = 1024 * 1024,
) -> AwaitableOrContextManager[FormData]:
return AwaitableOrContextManagerWrapper(
self._get_form(max_files=max_files, max_fields=max_fields, max_part_size=max_part_size)
)
async def close(self) -> None:
if self._form is not None: # pragma: no branch
await self._form.close()
async def is_disconnected(self) -> bool:
if not self._is_disconnected:
message: Message = {}
# If message isn't immediately available, move on
with anyio.CancelScope() as cs:
cs.cancel()
message = await self._receive()
if message.get("type") == "http.disconnect":
self._is_disconnected = True
return self._is_disconnected
async def send_push_promise(self, path: str) -> None:
if "http.response.push" in self.scope.get("extensions", {}):
raw_headers: list[tuple[bytes, bytes]] = []
for name in SERVER_PUSH_HEADERS_TO_COPY:
for value in self.headers.getlist(name):
raw_headers.append((name.encode("latin-1"), value.encode("latin-1")))
await self._send({"type": "http.response.push", "path": path, "headers": raw_headers})
| from __future__ import annotations
import sys
from collections.abc import Iterator
from typing import Any
import anyio
import pytest
from starlette.datastructures import URL, Address, State
from starlette.requests import ClientDisconnect, Request
from starlette.responses import JSONResponse, PlainTextResponse, Response
from starlette.types import Message, Receive, Scope, Send
from tests.types import TestClientFactory
def test_request_url(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
data = {"method": request.method, "url": str(request.url)}
response = JSONResponse(data)
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/123?a=abc")
assert response.json() == {"method": "GET", "url": "http://testserver/123?a=abc"}
response = client.get("https://example.org:123/")
assert response.json() == {"method": "GET", "url": "https://example.org:123/"}
def test_request_query_params(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
params = dict(request.query_params)
response = JSONResponse({"params": params})
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/?a=123&b=456")
assert response.json() == {"params": {"a": "123", "b": "456"}}
@pytest.mark.skipif(
any(module in sys.modules for module in ("brotli", "brotlicffi")),
reason='urllib3 includes "br" to the "accept-encoding" headers.',
)
def test_request_headers(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
headers = dict(request.headers)
response = JSONResponse({"headers": headers})
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/", headers={"host": "example.org"})
assert response.json() == {
"headers": {
"host": "example.org",
"user-agent": "testclient",
"accept-encoding": "gzip, deflate",
"accept": "*/*",
"connection": "keep-alive",
}
}
@pytest.mark.parametrize(
"scope,expected_client",
[
({"client": ["client", 42]}, Address("client", 42)),
({"client": None}, None),
({}, None),
],
)
def test_request_client(scope: Scope, expected_client: Address | None) -> None:
scope.update({"type": "http"}) # required by Request's constructor
client = Request(scope).client
assert client == expected_client
def test_request_body(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
body = await request.body()
response = JSONResponse({"body": body.decode()})
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/")
assert response.json() == {"body": ""}
response = client.post("/", json={"a": "123"})
assert response.json() == {"body": '{"a":"123"}'}
response = client.post("/", data="abc") # type: ignore
assert response.json() == {"body": "abc"}
def test_request_stream(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
body = b""
async for chunk in request.stream():
body += chunk
response = JSONResponse({"body": body.decode()})
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/")
assert response.json() == {"body": ""}
response = client.post("/", json={"a": "123"})
assert response.json() == {"body": '{"a":"123"}'}
response = client.post("/", data="abc") # type: ignore
assert response.json() == {"body": "abc"}
def test_request_form_urlencoded(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
form = await request.form()
response = JSONResponse({"form": dict(form)})
await response(scope, receive, send)
client = test_client_factory(app)
response = client.post("/", data={"abc": "123 @"})
assert response.json() == {"form": {"abc": "123 @"}}
def test_request_form_context_manager(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
async with request.form() as form:
response = JSONResponse({"form": dict(form)})
await response(scope, receive, send)
client = test_client_factory(app)
response = client.post("/", data={"abc": "123 @"})
assert response.json() == {"form": {"abc": "123 @"}}
def test_request_body_then_stream(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
body = await request.body()
chunks = b""
async for chunk in request.stream():
chunks += chunk
response = JSONResponse({"body": body.decode(), "stream": chunks.decode()})
await response(scope, receive, send)
client = test_client_factory(app)
response = client.post("/", data="abc") # type: ignore
assert response.json() == {"body": "abc", "stream": "abc"}
def test_request_stream_then_body(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
chunks = b""
async for chunk in request.stream():
chunks += chunk
try:
body = await request.body()
except RuntimeError:
body = b"<stream consumed>"
response = JSONResponse({"body": body.decode(), "stream": chunks.decode()})
await response(scope, receive, send)
client = test_client_factory(app)
response = client.post("/", data="abc") # type: ignore
assert response.json() == {"body": "<stream consumed>", "stream": "abc"}
def test_request_json(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
data = await request.json()
response = JSONResponse({"json": data})
await response(scope, receive, send)
client = test_client_factory(app)
response = client.post("/", json={"a": "123"})
assert response.json() == {"json": {"a": "123"}}
def test_request_scope_interface() -> None:
"""
A Request can be instantiated with a scope, and presents a `Mapping`
interface.
"""
request = Request({"type": "http", "method": "GET", "path": "/abc/"})
assert request["method"] == "GET"
assert dict(request) == {"type": "http", "method": "GET", "path": "/abc/"}
assert len(request) == 3
def test_request_raw_path(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
path = request.scope["path"]
raw_path = request.scope["raw_path"]
response = PlainTextResponse(f"{path}, {raw_path}")
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/he%2Fllo")
assert response.text == "/he/llo, b'/he%2Fllo'"
def test_request_without_setting_receive(
test_client_factory: TestClientFactory,
) -> None:
"""
If Request is instantiated without the receive channel, then .body()
is not available.
"""
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope)
try:
data = await request.json()
except RuntimeError:
data = "Receive channel not available"
response = JSONResponse({"json": data})
await response(scope, receive, send)
client = test_client_factory(app)
response = client.post("/", json={"a": "123"})
assert response.json() == {"json": "Receive channel not available"}
def test_request_disconnect(
anyio_backend_name: str,
anyio_backend_options: dict[str, Any],
) -> None:
"""
If a client disconnect occurs while reading request body
then ClientDisconnect should be raised.
"""
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
await request.body()
async def receiver() -> Message:
return {"type": "http.disconnect"}
scope = {"type": "http", "method": "POST", "path": "/"}
with pytest.raises(ClientDisconnect):
anyio.run(
app, # type: ignore
scope,
receiver,
None,
backend=anyio_backend_name,
backend_options=anyio_backend_options,
)
def test_request_is_disconnected(test_client_factory: TestClientFactory) -> None:
"""
If a client disconnect occurs after reading request body
then request will be set disconnected properly.
"""
disconnected_after_response = None
async def app(scope: Scope, receive: Receive, send: Send) -> None:
nonlocal disconnected_after_response
request = Request(scope, receive)
body = await request.body()
disconnected = await request.is_disconnected()
response = JSONResponse({"body": body.decode(), "disconnected": disconnected})
await response(scope, receive, send)
disconnected_after_response = await request.is_disconnected()
client = test_client_factory(app)
response = client.post("/", content="foo")
assert response.json() == {"body": "foo", "disconnected": False}
assert disconnected_after_response
def test_request_state_object() -> None:
scope = {"state": {"old": "foo"}}
s = State(scope["state"])
s.new = "value"
assert s.new == "value"
del s.new
with pytest.raises(AttributeError):
s.new
def test_request_state(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
request.state.example = 123
response = JSONResponse({"state.example": request.state.example})
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/123?a=abc")
assert response.json() == {"state.example": 123}
def test_request_cookies(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
mycookie = request.cookies.get("mycookie")
if mycookie:
response = Response(mycookie, media_type="text/plain")
else:
response = Response("Hello, world!", media_type="text/plain")
response.set_cookie("mycookie", "Hello, cookies!")
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/")
assert response.text == "Hello, world!"
response = client.get("/")
assert response.text == "Hello, cookies!"
def test_cookie_lenient_parsing(test_client_factory: TestClientFactory) -> None:
"""
The following test is based on a cookie set by Okta, a well-known authorization
service. It turns out that it's common practice to set cookies that would be
invalid according to the spec.
"""
tough_cookie = (
"provider-oauth-nonce=validAsciiblabla; "
'okta-oauth-redirect-params={"responseType":"code","state":"somestate",'
'"nonce":"somenonce","scopes":["openid","profile","email","phone"],'
'"urls":{"issuer":"https://subdomain.okta.com/oauth2/authServer",'
'"authorizeUrl":"https://subdomain.okta.com/oauth2/authServer/v1/authorize",'
'"userinfoUrl":"https://subdomain.okta.com/oauth2/authServer/v1/userinfo"}}; '
"importantCookie=importantValue; sessionCookie=importantSessionValue"
)
expected_keys = {
"importantCookie",
"okta-oauth-redirect-params",
"provider-oauth-nonce",
"sessionCookie",
}
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
response = JSONResponse({"cookies": request.cookies})
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/", headers={"cookie": tough_cookie})
result = response.json()
assert len(result["cookies"]) == 4
assert set(result["cookies"].keys()) == expected_keys
# These test cases copied from Tornado's implementation
@pytest.mark.parametrize(
"set_cookie,expected",
[
("chips=ahoy; vienna=finger", {"chips": "ahoy", "vienna": "finger"}),
# all semicolons are delimiters, even within quotes
(
'keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"',
{"keebler": '"E=mc2', "L": '\\"Loves\\"', "fudge": "\\012", "": '"'},
),
# Illegal cookies that have an '=' char in an unquoted value.
("keebler=E=mc2", {"keebler": "E=mc2"}),
# Cookies with ':' character in their name.
("key:term=value:term", {"key:term": "value:term"}),
# Cookies with '[' and ']'.
("a=b; c=[; d=r; f=h", {"a": "b", "c": "[", "d": "r", "f": "h"}),
# Cookies that RFC6265 allows.
("a=b; Domain=example.com", {"a": "b", "Domain": "example.com"}),
# parse_cookie() keeps only the last cookie with the same name.
("a=b; h=i; a=c", {"a": "c", "h": "i"}),
],
)
def test_cookies_edge_cases(
set_cookie: str,
expected: dict[str, str],
test_client_factory: TestClientFactory,
) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
response = JSONResponse({"cookies": request.cookies})
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/", headers={"cookie": set_cookie})
result = response.json()
assert result["cookies"] == expected
@pytest.mark.parametrize(
"set_cookie,expected",
[
# Chunks without an equals sign appear as unnamed values per
# https://bugzilla.mozilla.org/show_bug.cgi?id=169091
(
"abc=def; unnamed; django_language=en",
{"": "unnamed", "abc": "def", "django_language": "en"},
),
# Even a double quote may be an unamed value.
('a=b; "; c=d', {"a": "b", "": '"', "c": "d"}),
# Spaces in names and values, and an equals sign in values.
("a b c=d e = f; gh=i", {"a b c": "d e = f", "gh": "i"}),
# More characters the spec forbids.
('a b,c<>@:/[]?{}=d " =e,f g', {"a b,c<>@:/[]?{}": 'd " =e,f g'}),
# Unicode characters. The spec only allows ASCII.
# ("saint=André Bessette", {"saint": "André Bessette"}),
# Browsers don't send extra whitespace or semicolons in Cookie headers,
# but cookie_parser() should parse whitespace the same way
# document.cookie parses whitespace.
(" = b ; ; = ; c = ; ", {"": "b", "c": ""}),
],
)
def test_cookies_invalid(
set_cookie: str,
expected: dict[str, str],
test_client_factory: TestClientFactory,
) -> None:
"""
Cookie strings that are against the RFC6265 spec but which browsers will send if set
via document.cookie.
"""
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
response = JSONResponse({"cookies": request.cookies})
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/", headers={"cookie": set_cookie})
result = response.json()
assert result["cookies"] == expected
def test_multiple_cookie_headers(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
scope["headers"] = [(b"cookie", b"a=abc"), (b"cookie", b"b=def"), (b"cookie", b"c=ghi")]
request = Request(scope, receive)
response = JSONResponse({"cookies": request.cookies})
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/")
result = response.json()
assert result["cookies"] == {"a": "abc", "b": "def", "c": "ghi"}
def test_chunked_encoding(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
body = await request.body()
response = JSONResponse({"body": body.decode()})
await response(scope, receive, send)
client = test_client_factory(app)
def post_body() -> Iterator[bytes]:
yield b"foo"
yield b"bar"
response = client.post("/", data=post_body()) # type: ignore
assert response.json() == {"body": "foobar"}
def test_request_send_push_promise(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
# the server is push-enabled
scope["extensions"]["http.response.push"] = {}
request = Request(scope, receive, send)
await request.send_push_promise("/style.css")
response = JSONResponse({"json": "OK"})
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/")
assert response.json() == {"json": "OK"}
def test_request_send_push_promise_without_push_extension(
test_client_factory: TestClientFactory,
) -> None:
"""
If server does not support the `http.response.push` extension,
.send_push_promise() does nothing.
"""
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope)
await request.send_push_promise("/style.css")
response = JSONResponse({"json": "OK"})
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/")
assert response.json() == {"json": "OK"}
def test_request_send_push_promise_without_setting_send(
test_client_factory: TestClientFactory,
) -> None:
"""
If Request is instantiated without the send channel, then
.send_push_promise() is not available.
"""
async def app(scope: Scope, receive: Receive, send: Send) -> None:
# the server is push-enabled
scope["extensions"]["http.response.push"] = {}
data = "OK"
request = Request(scope)
try:
await request.send_push_promise("/style.css")
except RuntimeError:
data = "Send channel not available"
response = JSONResponse({"json": data})
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/")
assert response.json() == {"json": "Send channel not available"}
@pytest.mark.parametrize(
"messages",
[
[{"body": b"123", "more_body": True}, {"body": b""}],
[{"body": b"", "more_body": True}, {"body": b"123"}],
[{"body": b"12", "more_body": True}, {"body": b"3"}],
[
{"body": b"123", "more_body": True},
{"body": b"", "more_body": True},
{"body": b""},
],
],
)
@pytest.mark.anyio
async def test_request_rcv(messages: list[Message]) -> None:
messages = messages.copy()
async def rcv() -> Message:
return {"type": "http.request", **messages.pop(0)}
request = Request({"type": "http"}, rcv)
body = await request.body()
assert body == b"123"
@pytest.mark.anyio
async def test_request_stream_called_twice() -> None:
messages: list[Message] = [
{"type": "http.request", "body": b"1", "more_body": True},
{"type": "http.request", "body": b"2", "more_body": True},
{"type": "http.request", "body": b"3"},
]
async def rcv() -> Message:
return messages.pop(0)
request = Request({"type": "http"}, rcv)
s1 = request.stream()
s2 = request.stream()
msg = await s1.__anext__()
assert msg == b"1"
msg = await s2.__anext__()
assert msg == b"2"
msg = await s1.__anext__()
assert msg == b"3"
# at this point we've consumed the entire body
# so we should not wait for more body (which would hang us forever)
msg = await s1.__anext__()
assert msg == b""
msg = await s2.__anext__()
assert msg == b""
# and now both streams are exhausted
with pytest.raises(StopAsyncIteration):
assert await s2.__anext__()
with pytest.raises(StopAsyncIteration):
await s1.__anext__()
def test_request_url_outside_starlette_context(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
request.url_for("index")
client = test_client_factory(app)
with pytest.raises(
RuntimeError,
match="The `url_for` method can only be used inside a Starlette application or with a router.",
):
client.get("/")
def test_request_url_starlette_context(test_client_factory: TestClientFactory) -> None:
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.routing import Route
from starlette.types import ASGIApp
url_for = None
async def homepage(request: Request) -> Response:
return PlainTextResponse("Hello, world!")
class CustomMiddleware:
def __init__(self, app: ASGIApp) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
nonlocal url_for
request = Request(scope, receive)
url_for = request.url_for("homepage")
await self.app(scope, receive, send)
app = Starlette(routes=[Route("/home", homepage)], middleware=[Middleware(CustomMiddleware)])
client = test_client_factory(app)
client.get("/home")
assert url_for == URL("http://testserver/home")
| starlette |
python | from __future__ import annotations
import json
from collections.abc import Callable, Generator
from typing import Any, Literal
from starlette import status
from starlette._utils import is_async_callable
from starlette.concurrency import run_in_threadpool
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.responses import PlainTextResponse, Response
from starlette.types import Message, Receive, Scope, Send
from starlette.websockets import WebSocket
class HTTPEndpoint:
def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
assert scope["type"] == "http"
self.scope = scope
self.receive = receive
self.send = send
self._allowed_methods = [
method
for method in ("GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
if getattr(self, method.lower(), None) is not None
]
def __await__(self) -> Generator[Any, None, None]:
return self.dispatch().__await__()
async def dispatch(self) -> None:
request = Request(self.scope, receive=self.receive)
handler_name = "get" if request.method == "HEAD" and not hasattr(self, "head") else request.method.lower()
handler: Callable[[Request], Any] = getattr(self, handler_name, self.method_not_allowed)
is_async = is_async_callable(handler)
if is_async:
response = await handler(request)
else:
response = await run_in_threadpool(handler, request)
await response(self.scope, self.receive, self.send)
async def method_not_allowed(self, request: Request) -> Response:
# If we're running inside a starlette application then raise an
# exception, so that the configurable exception handler can deal with
# returning the response. For plain ASGI apps, just return the response.
headers = {"Allow": ", ".join(self._allowed_methods)}
if "app" in self.scope:
raise HTTPException(status_code=405, headers=headers)
return PlainTextResponse("Method Not Allowed", status_code=405, headers=headers)
class WebSocketEndpoint:
encoding: Literal["text", "bytes", "json"] | None = None
def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
assert scope["type"] == "websocket"
self.scope = scope
self.receive = receive
self.send = send
def __await__(self) -> Generator[Any, None, None]:
return self.dispatch().__await__()
async def dispatch(self) -> None:
websocket = WebSocket(self.scope, receive=self.receive, send=self.send)
await self.on_connect(websocket)
close_code = status.WS_1000_NORMAL_CLOSURE
try:
while True:
message = await websocket.receive()
if message["type"] == "websocket.receive":
data = await self.decode(websocket, message)
await self.on_receive(websocket, data)
elif message["type"] == "websocket.disconnect": # pragma: no branch
close_code = int(message.get("code") or status.WS_1000_NORMAL_CLOSURE)
break
except Exception as exc:
close_code = status.WS_1011_INTERNAL_ERROR
raise exc
finally:
await self.on_disconnect(websocket, close_code)
async def decode(self, websocket: WebSocket, message: Message) -> Any:
if self.encoding == "text":
if "text" not in message:
await websocket.close(code=status.WS_1003_UNSUPPORTED_DATA)
raise RuntimeError("Expected text websocket messages, but got bytes")
return message["text"]
elif self.encoding == "bytes":
if "bytes" not in message:
await websocket.close(code=status.WS_1003_UNSUPPORTED_DATA)
raise RuntimeError("Expected bytes websocket messages, but got text")
return message["bytes"]
elif self.encoding == "json":
if message.get("text") is not None:
text = message["text"]
else:
text = message["bytes"].decode("utf-8")
try:
return json.loads(text)
except json.decoder.JSONDecodeError:
await websocket.close(code=status.WS_1003_UNSUPPORTED_DATA)
raise RuntimeError("Malformed JSON data received.")
assert self.encoding is None, f"Unsupported 'encoding' attribute {self.encoding}"
return message["text"] if message.get("text") else message["bytes"]
async def on_connect(self, websocket: WebSocket) -> None:
"""Override to handle an incoming websocket connection"""
await websocket.accept()
async def on_receive(self, websocket: WebSocket, data: Any) -> None:
"""Override to handle an incoming websocket message"""
async def on_disconnect(self, websocket: WebSocket, close_code: int) -> None:
"""Override to handle a disconnecting websocket"""
| from collections.abc import Iterator
import pytest
from starlette.endpoints import HTTPEndpoint, WebSocketEndpoint
from starlette.requests import Request
from starlette.responses import PlainTextResponse
from starlette.routing import Route, Router
from starlette.testclient import TestClient
from starlette.websockets import WebSocket
from tests.types import TestClientFactory
class Homepage(HTTPEndpoint):
async def get(self, request: Request) -> PlainTextResponse:
username = request.path_params.get("username")
if username is None:
return PlainTextResponse("Hello, world!")
return PlainTextResponse(f"Hello, {username}!")
app = Router(routes=[Route("/", endpoint=Homepage), Route("/{username}", endpoint=Homepage)])
@pytest.fixture
def client(test_client_factory: TestClientFactory) -> Iterator[TestClient]:
with test_client_factory(app) as client:
yield client
def test_http_endpoint_route(client: TestClient) -> None:
response = client.get("/")
assert response.status_code == 200
assert response.text == "Hello, world!"
def test_http_endpoint_route_path_params(client: TestClient) -> None:
response = client.get("/tomchristie")
assert response.status_code == 200
assert response.text == "Hello, tomchristie!"
def test_http_endpoint_route_method(client: TestClient) -> None:
response = client.post("/")
assert response.status_code == 405
assert response.text == "Method Not Allowed"
assert response.headers["allow"] == "GET"
def test_websocket_endpoint_on_connect(test_client_factory: TestClientFactory) -> None:
class WebSocketApp(WebSocketEndpoint):
async def on_connect(self, websocket: WebSocket) -> None:
assert websocket["subprotocols"] == ["soap", "wamp"]
await websocket.accept(subprotocol="wamp")
client = test_client_factory(WebSocketApp)
with client.websocket_connect("/ws", subprotocols=["soap", "wamp"]) as websocket:
assert websocket.accepted_subprotocol == "wamp"
def test_websocket_endpoint_on_receive_bytes(
test_client_factory: TestClientFactory,
) -> None:
class WebSocketApp(WebSocketEndpoint):
encoding = "bytes"
async def on_receive(self, websocket: WebSocket, data: bytes) -> None:
await websocket.send_bytes(b"Message bytes was: " + data)
client = test_client_factory(WebSocketApp)
with client.websocket_connect("/ws") as websocket:
websocket.send_bytes(b"Hello, world!")
_bytes = websocket.receive_bytes()
assert _bytes == b"Message bytes was: Hello, world!"
with pytest.raises(RuntimeError):
with client.websocket_connect("/ws") as websocket:
websocket.send_text("Hello world")
def test_websocket_endpoint_on_receive_json(
test_client_factory: TestClientFactory,
) -> None:
class WebSocketApp(WebSocketEndpoint):
encoding = "json"
async def on_receive(self, websocket: WebSocket, data: str) -> None:
await websocket.send_json({"message": data})
client = test_client_factory(WebSocketApp)
with client.websocket_connect("/ws") as websocket:
websocket.send_json({"hello": "world"})
data = websocket.receive_json()
assert data == {"message": {"hello": "world"}}
with pytest.raises(RuntimeError):
with client.websocket_connect("/ws") as websocket:
websocket.send_text("Hello world")
def test_websocket_endpoint_on_receive_json_binary(
test_client_factory: TestClientFactory,
) -> None:
class WebSocketApp(WebSocketEndpoint):
encoding = "json"
async def on_receive(self, websocket: WebSocket, data: str) -> None:
await websocket.send_json({"message": data}, mode="binary")
client = test_client_factory(WebSocketApp)
with client.websocket_connect("/ws") as websocket:
websocket.send_json({"hello": "world"}, mode="binary")
data = websocket.receive_json(mode="binary")
assert data == {"message": {"hello": "world"}}
def test_websocket_endpoint_on_receive_text(
test_client_factory: TestClientFactory,
) -> None:
class WebSocketApp(WebSocketEndpoint):
encoding = "text"
async def on_receive(self, websocket: WebSocket, data: str) -> None:
await websocket.send_text(f"Message text was: {data}")
client = test_client_factory(WebSocketApp)
with client.websocket_connect("/ws") as websocket:
websocket.send_text("Hello, world!")
_text = websocket.receive_text()
assert _text == "Message text was: Hello, world!"
with pytest.raises(RuntimeError):
with client.websocket_connect("/ws") as websocket:
websocket.send_bytes(b"Hello world")
def test_websocket_endpoint_on_default(test_client_factory: TestClientFactory) -> None:
class WebSocketApp(WebSocketEndpoint):
encoding = None
async def on_receive(self, websocket: WebSocket, data: str) -> None:
await websocket.send_text(f"Message text was: {data}")
client = test_client_factory(WebSocketApp)
with client.websocket_connect("/ws") as websocket:
websocket.send_text("Hello, world!")
_text = websocket.receive_text()
assert _text == "Message text was: Hello, world!"
def test_websocket_endpoint_on_disconnect(
test_client_factory: TestClientFactory,
) -> None:
class WebSocketApp(WebSocketEndpoint):
async def on_disconnect(self, websocket: WebSocket, close_code: int) -> None:
assert close_code == 1001
await websocket.close(code=close_code)
client = test_client_factory(WebSocketApp)
with client.websocket_connect("/ws") as websocket:
websocket.close(code=1001)
| starlette |
python | from __future__ import annotations
import contextlib
import functools
import inspect
import re
import traceback
import types
import warnings
from collections.abc import Awaitable, Callable, Collection, Generator, Sequence
from contextlib import AbstractAsyncContextManager, AbstractContextManager, asynccontextmanager
from enum import Enum
from re import Pattern
from typing import Any, TypeVar
from starlette._exception_handler import wrap_app_handling_exceptions
from starlette._utils import get_route_path, is_async_callable
from starlette.concurrency import run_in_threadpool
from starlette.convertors import CONVERTOR_TYPES, Convertor
from starlette.datastructures import URL, Headers, URLPath
from starlette.exceptions import HTTPException
from starlette.middleware import Middleware
from starlette.requests import Request
from starlette.responses import PlainTextResponse, RedirectResponse, Response
from starlette.types import ASGIApp, Lifespan, Receive, Scope, Send
from starlette.websockets import WebSocket, WebSocketClose
class NoMatchFound(Exception):
"""
Raised by `.url_for(name, **path_params)` and `.url_path_for(name, **path_params)`
if no matching route exists.
"""
def __init__(self, name: str, path_params: dict[str, Any]) -> None:
params = ", ".join(list(path_params.keys()))
super().__init__(f'No route exists for name "{name}" and params "{params}".')
class Match(Enum):
NONE = 0
PARTIAL = 1
FULL = 2
def iscoroutinefunction_or_partial(obj: Any) -> bool: # pragma: no cover
"""
Correctly determines if an object is a coroutine function,
including those wrapped in functools.partial objects.
"""
warnings.warn(
"iscoroutinefunction_or_partial is deprecated, and will be removed in a future release.",
DeprecationWarning,
)
while isinstance(obj, functools.partial):
obj = obj.func
return inspect.iscoroutinefunction(obj)
def request_response(
func: Callable[[Request], Awaitable[Response] | Response],
) -> ASGIApp:
"""
Takes a function or coroutine `func(request) -> response`,
and returns an ASGI application.
"""
f: Callable[[Request], Awaitable[Response]] = (
func if is_async_callable(func) else functools.partial(run_in_threadpool, func)
)
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive, send)
async def app(scope: Scope, receive: Receive, send: Send) -> None:
response = await f(request)
await response(scope, receive, send)
await wrap_app_handling_exceptions(app, request)(scope, receive, send)
return app
def websocket_session(
func: Callable[[WebSocket], Awaitable[None]],
) -> ASGIApp:
"""
Takes a coroutine `func(session)`, and returns an ASGI application.
"""
# assert asyncio.iscoroutinefunction(func), "WebSocket endpoints must be async"
async def app(scope: Scope, receive: Receive, send: Send) -> None:
session = WebSocket(scope, receive=receive, send=send)
async def app(scope: Scope, receive: Receive, send: Send) -> None:
await func(session)
await wrap_app_handling_exceptions(app, session)(scope, receive, send)
return app
def get_name(endpoint: Callable[..., Any]) -> str:
return getattr(endpoint, "__name__", endpoint.__class__.__name__)
def replace_params(
path: str,
param_convertors: dict[str, Convertor[Any]],
path_params: dict[str, str],
) -> tuple[str, dict[str, str]]:
for key, value in list(path_params.items()):
if "{" + key + "}" in path:
convertor = param_convertors[key]
value = convertor.to_string(value)
path = path.replace("{" + key + "}", value)
path_params.pop(key)
return path, path_params
# Match parameters in URL paths, eg. '{param}', and '{param:int}'
PARAM_REGEX = re.compile("{([a-zA-Z_][a-zA-Z0-9_]*)(:[a-zA-Z_][a-zA-Z0-9_]*)?}")
def compile_path(
path: str,
) -> tuple[Pattern[str], str, dict[str, Convertor[Any]]]:
"""
Given a path string, like: "/{username:str}",
or a host string, like: "{subdomain}.mydomain.org", return a three-tuple
of (regex, format, {param_name:convertor}).
regex: "/(?P<username>[^/]+)"
format: "/{username}"
convertors: {"username": StringConvertor()}
"""
is_host = not path.startswith("/")
path_regex = "^"
path_format = ""
duplicated_params = set()
idx = 0
param_convertors = {}
for match in PARAM_REGEX.finditer(path):
param_name, convertor_type = match.groups("str")
convertor_type = convertor_type.lstrip(":")
assert convertor_type in CONVERTOR_TYPES, f"Unknown path convertor '{convertor_type}'"
convertor = CONVERTOR_TYPES[convertor_type]
path_regex += re.escape(path[idx : match.start()])
path_regex += f"(?P<{param_name}>{convertor.regex})"
path_format += path[idx : match.start()]
path_format += "{%s}" % param_name
if param_name in param_convertors:
duplicated_params.add(param_name)
param_convertors[param_name] = convertor
idx = match.end()
if duplicated_params:
names = ", ".join(sorted(duplicated_params))
ending = "s" if len(duplicated_params) > 1 else ""
raise ValueError(f"Duplicated param name{ending} {names} at path {path}")
if is_host:
# Align with `Host.matches()` behavior, which ignores port.
hostname = path[idx:].split(":")[0]
path_regex += re.escape(hostname) + "$"
else:
path_regex += re.escape(path[idx:]) + "$"
path_format += path[idx:]
return re.compile(path_regex), path_format, param_convertors
class BaseRoute:
def matches(self, scope: Scope) -> tuple[Match, Scope]:
raise NotImplementedError() # pragma: no cover
def url_path_for(self, name: str, /, **path_params: Any) -> URLPath:
raise NotImplementedError() # pragma: no cover
async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:
raise NotImplementedError() # pragma: no cover
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
"""
A route may be used in isolation as a stand-alone ASGI app.
This is a somewhat contrived case, as they'll almost always be used
within a Router, but could be useful for some tooling and minimal apps.
"""
match, child_scope = self.matches(scope)
if match == Match.NONE:
if scope["type"] == "http":
response = PlainTextResponse("Not Found", status_code=404)
await response(scope, receive, send)
elif scope["type"] == "websocket": # pragma: no branch
websocket_close = WebSocketClose()
await websocket_close(scope, receive, send)
return
scope.update(child_scope)
await self.handle(scope, receive, send)
class Route(BaseRoute):
def __init__(
self,
path: str,
endpoint: Callable[..., Any],
*,
methods: Collection[str] | None = None,
name: str | None = None,
include_in_schema: bool = True,
middleware: Sequence[Middleware] | None = None,
) -> None:
assert path.startswith("/"), "Routed paths must start with '/'"
self.path = path
self.endpoint = endpoint
self.name = get_name(endpoint) if name is None else name
self.include_in_schema = include_in_schema
endpoint_handler = endpoint
while isinstance(endpoint_handler, functools.partial):
endpoint_handler = endpoint_handler.func
if inspect.isfunction(endpoint_handler) or inspect.ismethod(endpoint_handler):
# Endpoint is function or method. Treat it as `func(request) -> response`.
self.app = request_response(endpoint)
if methods is None:
methods = ["GET"]
else:
# Endpoint is a class. Treat it as ASGI.
self.app = endpoint
if middleware is not None:
for cls, args, kwargs in reversed(middleware):
self.app = cls(self.app, *args, **kwargs)
if methods is None:
self.methods = None
else:
self.methods = {method.upper() for method in methods}
if "GET" in self.methods:
self.methods.add("HEAD")
self.path_regex, self.path_format, self.param_convertors = compile_path(path)
def matches(self, scope: Scope) -> tuple[Match, Scope]:
path_params: dict[str, Any]
if scope["type"] == "http":
route_path = get_route_path(scope)
match = self.path_regex.match(route_path)
if match:
matched_params = match.groupdict()
for key, value in matched_params.items():
matched_params[key] = self.param_convertors[key].convert(value)
path_params = dict(scope.get("path_params", {}))
path_params.update(matched_params)
child_scope = {"endpoint": self.endpoint, "path_params": path_params}
if self.methods and scope["method"] not in self.methods:
return Match.PARTIAL, child_scope
else:
return Match.FULL, child_scope
return Match.NONE, {}
def url_path_for(self, name: str, /, **path_params: Any) -> URLPath:
seen_params = set(path_params.keys())
expected_params = set(self.param_convertors.keys())
if name != self.name or seen_params != expected_params:
raise NoMatchFound(name, path_params)
path, remaining_params = replace_params(self.path_format, self.param_convertors, path_params)
assert not remaining_params
return URLPath(path=path, protocol="http")
async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:
if self.methods and scope["method"] not in self.methods:
headers = {"Allow": ", ".join(self.methods)}
if "app" in scope:
raise HTTPException(status_code=405, headers=headers)
else:
response = PlainTextResponse("Method Not Allowed", status_code=405, headers=headers)
await response(scope, receive, send)
else:
await self.app(scope, receive, send)
def __eq__(self, other: Any) -> bool:
return (
isinstance(other, Route)
and self.path == other.path
and self.endpoint == other.endpoint
and self.methods == other.methods
)
def __repr__(self) -> str:
class_name = self.__class__.__name__
methods = sorted(self.methods or [])
path, name = self.path, self.name
return f"{class_name}(path={path!r}, name={name!r}, methods={methods!r})"
class WebSocketRoute(BaseRoute):
def __init__(
self,
path: str,
endpoint: Callable[..., Any],
*,
name: str | None = None,
middleware: Sequence[Middleware] | None = None,
) -> None:
assert path.startswith("/"), "Routed paths must start with '/'"
self.path = path
self.endpoint = endpoint
self.name = get_name(endpoint) if name is None else name
endpoint_handler = endpoint
while isinstance(endpoint_handler, functools.partial):
endpoint_handler = endpoint_handler.func
if inspect.isfunction(endpoint_handler) or inspect.ismethod(endpoint_handler):
# Endpoint is function or method. Treat it as `func(websocket)`.
self.app = websocket_session(endpoint)
else:
# Endpoint is a class. Treat it as ASGI.
self.app = endpoint
if middleware is not None:
for cls, args, kwargs in reversed(middleware):
self.app = cls(self.app, *args, **kwargs)
self.path_regex, self.path_format, self.param_convertors = compile_path(path)
def matches(self, scope: Scope) -> tuple[Match, Scope]:
path_params: dict[str, Any]
if scope["type"] == "websocket":
route_path = get_route_path(scope)
match = self.path_regex.match(route_path)
if match:
matched_params = match.groupdict()
for key, value in matched_params.items():
matched_params[key] = self.param_convertors[key].convert(value)
path_params = dict(scope.get("path_params", {}))
path_params.update(matched_params)
child_scope = {"endpoint": self.endpoint, "path_params": path_params}
return Match.FULL, child_scope
return Match.NONE, {}
def url_path_for(self, name: str, /, **path_params: Any) -> URLPath:
seen_params = set(path_params.keys())
expected_params = set(self.param_convertors.keys())
if name != self.name or seen_params != expected_params:
raise NoMatchFound(name, path_params)
path, remaining_params = replace_params(self.path_format, self.param_convertors, path_params)
assert not remaining_params
return URLPath(path=path, protocol="websocket")
async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:
await self.app(scope, receive, send)
def __eq__(self, other: Any) -> bool:
return isinstance(other, WebSocketRoute) and self.path == other.path and self.endpoint == other.endpoint
def __repr__(self) -> str:
return f"{self.__class__.__name__}(path={self.path!r}, name={self.name!r})"
class Mount(BaseRoute):
def __init__(
self,
path: str,
app: ASGIApp | None = None,
routes: Sequence[BaseRoute] | None = None,
name: str | None = None,
*,
middleware: Sequence[Middleware] | None = None,
) -> None:
assert path == "" or path.startswith("/"), "Routed paths must start with '/'"
assert app is not None or routes is not None, "Either 'app=...', or 'routes=' must be specified"
self.path = path.rstrip("/")
if app is not None:
self._base_app: ASGIApp = app
else:
self._base_app = Router(routes=routes)
self.app = self._base_app
if middleware is not None:
for cls, args, kwargs in reversed(middleware):
self.app = cls(self.app, *args, **kwargs)
self.name = name
self.path_regex, self.path_format, self.param_convertors = compile_path(self.path + "/{path:path}")
@property
def routes(self) -> list[BaseRoute]:
return getattr(self._base_app, "routes", [])
def matches(self, scope: Scope) -> tuple[Match, Scope]:
path_params: dict[str, Any]
if scope["type"] in ("http", "websocket"): # pragma: no branch
root_path = scope.get("root_path", "")
route_path = get_route_path(scope)
match = self.path_regex.match(route_path)
if match:
matched_params = match.groupdict()
for key, value in matched_params.items():
matched_params[key] = self.param_convertors[key].convert(value)
remaining_path = "/" + matched_params.pop("path")
matched_path = route_path[: -len(remaining_path)]
path_params = dict(scope.get("path_params", {}))
path_params.update(matched_params)
child_scope = {
"path_params": path_params,
# app_root_path will only be set at the top level scope,
# initialized with the (optional) value of a root_path
# set above/before Starlette. And even though any
# mount will have its own child scope with its own respective
# root_path, the app_root_path will always be available in all
# the child scopes with the same top level value because it's
# set only once here with a default, any other child scope will
# just inherit that app_root_path default value stored in the
# scope. All this is needed to support Request.url_for(), as it
# uses the app_root_path to build the URL path.
"app_root_path": scope.get("app_root_path", root_path),
"root_path": root_path + matched_path,
"endpoint": self.app,
}
return Match.FULL, child_scope
return Match.NONE, {}
def url_path_for(self, name: str, /, **path_params: Any) -> URLPath:
if self.name is not None and name == self.name and "path" in path_params:
# 'name' matches "<mount_name>".
path_params["path"] = path_params["path"].lstrip("/")
path, remaining_params = replace_params(self.path_format, self.param_convertors, path_params)
if not remaining_params:
return URLPath(path=path)
elif self.name is None or name.startswith(self.name + ":"):
if self.name is None:
# No mount name.
remaining_name = name
else:
# 'name' matches "<mount_name>:<child_name>".
remaining_name = name[len(self.name) + 1 :]
path_kwarg = path_params.get("path")
path_params["path"] = ""
path_prefix, remaining_params = replace_params(self.path_format, self.param_convertors, path_params)
if path_kwarg is not None:
remaining_params["path"] = path_kwarg
for route in self.routes or []:
try:
url = route.url_path_for(remaining_name, **remaining_params)
return URLPath(path=path_prefix.rstrip("/") + str(url), protocol=url.protocol)
except NoMatchFound:
pass
raise NoMatchFound(name, path_params)
async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:
await self.app(scope, receive, send)
def __eq__(self, other: Any) -> bool:
return isinstance(other, Mount) and self.path == other.path and self.app == other.app
def __repr__(self) -> str:
class_name = self.__class__.__name__
name = self.name or ""
return f"{class_name}(path={self.path!r}, name={name!r}, app={self.app!r})"
class Host(BaseRoute):
def __init__(self, host: str, app: ASGIApp, name: str | None = None) -> None:
assert not host.startswith("/"), "Host must not start with '/'"
self.host = host
self.app = app
self.name = name
self.host_regex, self.host_format, self.param_convertors = compile_path(host)
@property
def routes(self) -> list[BaseRoute]:
return getattr(self.app, "routes", [])
def matches(self, scope: Scope) -> tuple[Match, Scope]:
if scope["type"] in ("http", "websocket"): # pragma:no branch
headers = Headers(scope=scope)
host = headers.get("host", "").split(":")[0]
match = self.host_regex.match(host)
if match:
matched_params = match.groupdict()
for key, value in matched_params.items():
matched_params[key] = self.param_convertors[key].convert(value)
path_params = dict(scope.get("path_params", {}))
path_params.update(matched_params)
child_scope = {"path_params": path_params, "endpoint": self.app}
return Match.FULL, child_scope
return Match.NONE, {}
def url_path_for(self, name: str, /, **path_params: Any) -> URLPath:
if self.name is not None and name == self.name and "path" in path_params:
# 'name' matches "<mount_name>".
path = path_params.pop("path")
host, remaining_params = replace_params(self.host_format, self.param_convertors, path_params)
if not remaining_params:
return URLPath(path=path, host=host)
elif self.name is None or name.startswith(self.name + ":"):
if self.name is None:
# No mount name.
remaining_name = name
else:
# 'name' matches "<mount_name>:<child_name>".
remaining_name = name[len(self.name) + 1 :]
host, remaining_params = replace_params(self.host_format, self.param_convertors, path_params)
for route in self.routes or []:
try:
url = route.url_path_for(remaining_name, **remaining_params)
return URLPath(path=str(url), protocol=url.protocol, host=host)
except NoMatchFound:
pass
raise NoMatchFound(name, path_params)
async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:
await self.app(scope, receive, send)
def __eq__(self, other: Any) -> bool:
return isinstance(other, Host) and self.host == other.host and self.app == other.app
def __repr__(self) -> str:
class_name = self.__class__.__name__
name = self.name or ""
return f"{class_name}(host={self.host!r}, name={name!r}, app={self.app!r})"
_T = TypeVar("_T")
class _AsyncLiftContextManager(AbstractAsyncContextManager[_T]):
def __init__(self, cm: AbstractContextManager[_T]):
self._cm = cm
async def __aenter__(self) -> _T:
return self._cm.__enter__()
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
traceback: types.TracebackType | None,
) -> bool | None:
return self._cm.__exit__(exc_type, exc_value, traceback)
def _wrap_gen_lifespan_context(
lifespan_context: Callable[[Any], Generator[Any, Any, Any]],
) -> Callable[[Any], AbstractAsyncContextManager[Any]]:
cmgr = contextlib.contextmanager(lifespan_context)
@functools.wraps(cmgr)
def wrapper(app: Any) -> _AsyncLiftContextManager[Any]:
return _AsyncLiftContextManager(cmgr(app))
return wrapper
class _DefaultLifespan:
def __init__(self, router: Router):
self._router = router
async def __aenter__(self) -> None:
await self._router.startup()
async def __aexit__(self, *exc_info: object) -> None:
await self._router.shutdown()
def __call__(self: _T, app: object) -> _T:
return self
class Router:
def __init__(
self,
routes: Sequence[BaseRoute] | None = None,
redirect_slashes: bool = True,
default: ASGIApp | None = None,
on_startup: Sequence[Callable[[], Any]] | None = None,
on_shutdown: Sequence[Callable[[], Any]] | None = None,
# the generic to Lifespan[AppType] is the type of the top level application
# which the router cannot know statically, so we use Any
lifespan: Lifespan[Any] | None = None,
*,
middleware: Sequence[Middleware] | None = None,
) -> None:
self.routes = [] if routes is None else list(routes)
self.redirect_slashes = redirect_slashes
self.default = self.not_found if default is None else default
self.on_startup = [] if on_startup is None else list(on_startup)
self.on_shutdown = [] if on_shutdown is None else list(on_shutdown)
if on_startup or on_shutdown:
warnings.warn(
"The on_startup and on_shutdown parameters are deprecated, and they "
"will be removed on version 1.0. Use the lifespan parameter instead. "
"See more about it on https://starlette.dev/lifespan/.",
DeprecationWarning,
)
if lifespan:
warnings.warn(
"The `lifespan` parameter cannot be used with `on_startup` or "
"`on_shutdown`. Both `on_startup` and `on_shutdown` will be "
"ignored."
)
if lifespan is None:
self.lifespan_context: Lifespan[Any] = _DefaultLifespan(self)
elif inspect.isasyncgenfunction(lifespan):
warnings.warn(
"async generator function lifespans are deprecated, "
"use an @contextlib.asynccontextmanager function instead",
DeprecationWarning,
)
self.lifespan_context = asynccontextmanager(
lifespan,
)
elif inspect.isgeneratorfunction(lifespan):
warnings.warn(
"generator function lifespans are deprecated, use an @contextlib.asynccontextmanager function instead",
DeprecationWarning,
)
self.lifespan_context = _wrap_gen_lifespan_context(
lifespan,
)
else:
self.lifespan_context = lifespan
self.middleware_stack = self.app
if middleware:
for cls, args, kwargs in reversed(middleware):
self.middleware_stack = cls(self.middleware_stack, *args, **kwargs)
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] == "websocket":
websocket_close = WebSocketClose()
await websocket_close(scope, receive, send)
return
# If we're running inside a starlette application then raise an
# exception, so that the configurable exception handler can deal with
# returning the response. For plain ASGI apps, just return the response.
if "app" in scope:
raise HTTPException(status_code=404)
else:
response = PlainTextResponse("Not Found", status_code=404)
await response(scope, receive, send)
def url_path_for(self, name: str, /, **path_params: Any) -> URLPath:
for route in self.routes:
try:
return route.url_path_for(name, **path_params)
except NoMatchFound:
pass
raise NoMatchFound(name, path_params)
async def startup(self) -> None:
"""
Run any `.on_startup` event handlers.
"""
for handler in self.on_startup:
if is_async_callable(handler):
await handler()
else:
handler()
async def shutdown(self) -> None:
"""
Run any `.on_shutdown` event handlers.
"""
for handler in self.on_shutdown:
if is_async_callable(handler):
await handler()
else:
handler()
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:
"""
Handle ASGI lifespan messages, which allows us to manage application
startup and shutdown events.
"""
started = False
app: Any = scope.get("app")
await receive()
try:
async with self.lifespan_context(app) as maybe_state:
if maybe_state is not None:
if "state" not in scope:
raise RuntimeError('The server does not support "state" in the lifespan scope.')
scope["state"].update(maybe_state)
await send({"type": "lifespan.startup.complete"})
started = True
await receive()
except BaseException:
exc_text = traceback.format_exc()
if started:
await send({"type": "lifespan.shutdown.failed", "message": exc_text})
else:
await send({"type": "lifespan.startup.failed", "message": exc_text})
raise
else:
await send({"type": "lifespan.shutdown.complete"})
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
"""
The main entry point to the Router class.
"""
await self.middleware_stack(scope, receive, send)
async def app(self, scope: Scope, receive: Receive, send: Send) -> None:
assert scope["type"] in ("http", "websocket", "lifespan")
if "router" not in scope:
scope["router"] = self
if scope["type"] == "lifespan":
await self.lifespan(scope, receive, send)
return
partial = None
for route in self.routes:
# Determine if any route matches the incoming scope,
# and hand over to the matching route if found.
match, child_scope = route.matches(scope)
if match == Match.FULL:
scope.update(child_scope)
await route.handle(scope, receive, send)
return
elif match == Match.PARTIAL and partial is None:
partial = route
partial_scope = child_scope
if partial is not None:
# Handle partial matches. These are cases where an endpoint is
# able to handle the request, but is not a preferred option.
# We use this in particular to deal with "405 Method Not Allowed".
scope.update(partial_scope)
await partial.handle(scope, receive, send)
return
route_path = get_route_path(scope)
if scope["type"] == "http" and self.redirect_slashes and route_path != "/":
redirect_scope = dict(scope)
if route_path.endswith("/"):
redirect_scope["path"] = redirect_scope["path"].rstrip("/")
else:
redirect_scope["path"] = redirect_scope["path"] + "/"
for route in self.routes:
match, child_scope = route.matches(redirect_scope)
if match != Match.NONE:
redirect_url = URL(scope=redirect_scope)
response = RedirectResponse(url=str(redirect_url))
await response(scope, receive, send)
return
await self.default(scope, receive, send)
def __eq__(self, other: Any) -> bool:
return isinstance(other, Router) and self.routes == other.routes
def mount(self, path: str, app: ASGIApp, name: str | None = None) -> None: # pragma: no cover
route = Mount(path, app=app, name=name)
self.routes.append(route)
def host(self, host: str, app: ASGIApp, name: str | None = None) -> None: # pragma: no cover
route = Host(host, app=app, name=name)
self.routes.append(route)
def add_route(
self,
path: str,
endpoint: Callable[[Request], Awaitable[Response] | Response],
methods: Collection[str] | None = None,
name: str | None = None,
include_in_schema: bool = True,
) -> None: # pragma: no cover
route = Route(
path,
endpoint=endpoint,
methods=methods,
name=name,
include_in_schema=include_in_schema,
)
self.routes.append(route)
def add_websocket_route(
self,
path: str,
endpoint: Callable[[WebSocket], Awaitable[None]],
name: str | None = None,
) -> None: # pragma: no cover
route = WebSocketRoute(path, endpoint=endpoint, name=name)
self.routes.append(route)
def route(
self,
path: str,
methods: Collection[str] | None = None,
name: str | None = None,
include_in_schema: bool = True,
) -> Callable: # type: ignore[type-arg]
"""
We no longer document this decorator style API, and its usage is discouraged.
Instead you should use the following approach:
>>> routes = [Route(path, endpoint=...), ...]
>>> app = Starlette(routes=routes)
"""
warnings.warn(
"The `route` decorator is deprecated, and will be removed in version 1.0.0."
"Refer to https://starlette.dev/routing/#http-routing for the recommended approach.",
DeprecationWarning,
)
def decorator(func: Callable) -> Callable: # type: ignore[type-arg]
self.add_route(
path,
func,
methods=methods,
name=name,
include_in_schema=include_in_schema,
)
return func
return decorator
def websocket_route(self, path: str, name: str | None = None) -> Callable: # type: ignore[type-arg]
"""
We no longer document this decorator style API, and its usage is discouraged.
Instead you should use the following approach:
>>> routes = [WebSocketRoute(path, endpoint=...), ...]
>>> app = Starlette(routes=routes)
"""
warnings.warn(
"The `websocket_route` decorator is deprecated, and will be removed in version 1.0.0. Refer to "
"https://starlette.dev/routing/#websocket-routing for the recommended approach.",
DeprecationWarning,
)
def decorator(func: Callable) -> Callable: # type: ignore[type-arg]
self.add_websocket_route(path, func, name=name)
return func
return decorator
def add_event_handler(self, event_type: str, func: Callable[[], Any]) -> None: # pragma: no cover
assert event_type in ("startup", "shutdown")
if event_type == "startup":
self.on_startup.append(func)
else:
self.on_shutdown.append(func)
def on_event(self, event_type: str) -> Callable: # type: ignore[type-arg]
warnings.warn(
"The `on_event` decorator is deprecated, and will be removed in version 1.0.0. "
"Refer to https://starlette.dev/lifespan/ for recommended approach.",
DeprecationWarning,
)
def decorator(func: Callable) -> Callable: # type: ignore[type-arg]
self.add_event_handler(event_type, func)
return func
return decorator
| from __future__ import annotations
import contextlib
import functools
import json
import uuid
from collections.abc import AsyncGenerator, AsyncIterator, Callable, Generator
from typing import TypedDict
import pytest
from starlette.applications import Starlette
from starlette.exceptions import HTTPException
from starlette.middleware import Middleware
from starlette.requests import Request
from starlette.responses import JSONResponse, PlainTextResponse, Response
from starlette.routing import Host, Mount, NoMatchFound, Route, Router, WebSocketRoute
from starlette.testclient import TestClient
from starlette.types import ASGIApp, Message, Receive, Scope, Send
from starlette.websockets import WebSocket, WebSocketDisconnect
from tests.types import TestClientFactory
def homepage(request: Request) -> Response:
return Response("Hello, world", media_type="text/plain")
def users(request: Request) -> Response:
return Response("All users", media_type="text/plain")
def user(request: Request) -> Response:
content = "User " + request.path_params["username"]
return Response(content, media_type="text/plain")
def user_me(request: Request) -> Response:
content = "User fixed me"
return Response(content, media_type="text/plain")
def disable_user(request: Request) -> Response:
content = "User " + request.path_params["username"] + " disabled"
return Response(content, media_type="text/plain")
def user_no_match(request: Request) -> Response: # pragma: no cover
content = "User fixed no match"
return Response(content, media_type="text/plain")
async def partial_endpoint(arg: str, request: Request) -> JSONResponse:
return JSONResponse({"arg": arg})
async def partial_ws_endpoint(websocket: WebSocket) -> None:
await websocket.accept()
await websocket.send_json({"url": str(websocket.url)})
await websocket.close()
class PartialRoutes:
@classmethod
async def async_endpoint(cls, arg: str, request: Request) -> JSONResponse:
return JSONResponse({"arg": arg})
@classmethod
async def async_ws_endpoint(cls, websocket: WebSocket) -> None:
await websocket.accept()
await websocket.send_json({"url": str(websocket.url)})
await websocket.close()
def func_homepage(request: Request) -> Response:
return Response("Hello, world!", media_type="text/plain")
def contact(request: Request) -> Response:
return Response("Hello, POST!", media_type="text/plain")
def int_convertor(request: Request) -> JSONResponse:
number = request.path_params["param"]
return JSONResponse({"int": number})
def float_convertor(request: Request) -> JSONResponse:
num = request.path_params["param"]
return JSONResponse({"float": num})
def path_convertor(request: Request) -> JSONResponse:
path = request.path_params["param"]
return JSONResponse({"path": path})
def uuid_converter(request: Request) -> JSONResponse:
uuid_param = request.path_params["param"]
return JSONResponse({"uuid": str(uuid_param)})
def path_with_parentheses(request: Request) -> JSONResponse:
number = request.path_params["param"]
return JSONResponse({"int": number})
async def websocket_endpoint(session: WebSocket) -> None:
await session.accept()
await session.send_text("Hello, world!")
await session.close()
async def websocket_params(session: WebSocket) -> None:
await session.accept()
await session.send_text(f"Hello, {session.path_params['room']}!")
await session.close()
app = Router(
[
Route("/", endpoint=homepage, methods=["GET"]),
Mount(
"/users",
routes=[
Route("/", endpoint=users),
Route("/me", endpoint=user_me),
Route("/{username}", endpoint=user),
Route("/{username}:disable", endpoint=disable_user, methods=["PUT"]),
Route("/nomatch", endpoint=user_no_match),
],
),
Mount(
"/partial",
routes=[
Route("/", endpoint=functools.partial(partial_endpoint, "foo")),
Route(
"/cls",
endpoint=functools.partial(PartialRoutes.async_endpoint, "foo"),
),
WebSocketRoute("/ws", endpoint=functools.partial(partial_ws_endpoint)),
WebSocketRoute(
"/ws/cls",
endpoint=functools.partial(PartialRoutes.async_ws_endpoint),
),
],
),
Mount("/static", app=Response("xxxxx", media_type="image/png")),
Route("/func", endpoint=func_homepage, methods=["GET"]),
Route("/func", endpoint=contact, methods=["POST"]),
Route("/int/{param:int}", endpoint=int_convertor, name="int-convertor"),
Route("/float/{param:float}", endpoint=float_convertor, name="float-convertor"),
Route("/path/{param:path}", endpoint=path_convertor, name="path-convertor"),
Route("/uuid/{param:uuid}", endpoint=uuid_converter, name="uuid-convertor"),
# Route with chars that conflict with regex meta chars
Route(
"/path-with-parentheses({param:int})",
endpoint=path_with_parentheses,
name="path-with-parentheses",
),
WebSocketRoute("/ws", endpoint=websocket_endpoint),
WebSocketRoute("/ws/{room}", endpoint=websocket_params),
]
)
@pytest.fixture
def client(
test_client_factory: TestClientFactory,
) -> Generator[TestClient, None, None]:
with test_client_factory(app) as client:
yield client
@pytest.mark.filterwarnings(
r"ignore"
r":Trying to detect encoding from a tiny portion of \(5\) byte\(s\)\."
r":UserWarning"
r":charset_normalizer.api"
)
def test_router(client: TestClient) -> None:
response = client.get("/")
assert response.status_code == 200
assert response.text == "Hello, world"
response = client.post("/")
assert response.status_code == 405
assert response.text == "Method Not Allowed"
assert set(response.headers["allow"].split(", ")) == {"HEAD", "GET"}
response = client.get("/foo")
assert response.status_code == 404
assert response.text == "Not Found"
response = client.get("/users")
assert response.status_code == 200
assert response.text == "All users"
response = client.get("/users/tomchristie")
assert response.status_code == 200
assert response.text == "User tomchristie"
response = client.get("/users/me")
assert response.status_code == 200
assert response.text == "User fixed me"
response = client.get("/users/tomchristie/")
assert response.status_code == 200
assert response.url == "http://testserver/users/tomchristie"
assert response.text == "User tomchristie"
response = client.put("/users/tomchristie:disable")
assert response.status_code == 200
assert response.url == "http://testserver/users/tomchristie:disable"
assert response.text == "User tomchristie disabled"
response = client.get("/users/nomatch")
assert response.status_code == 200
assert response.text == "User nomatch"
response = client.get("/static/123")
assert response.status_code == 200
assert response.text == "xxxxx"
def test_route_converters(client: TestClient) -> None:
# Test integer conversion
response = client.get("/int/5")
assert response.status_code == 200
assert response.json() == {"int": 5}
assert app.url_path_for("int-convertor", param=5) == "/int/5"
# Test path with parentheses
response = client.get("/path-with-parentheses(7)")
assert response.status_code == 200
assert response.json() == {"int": 7}
assert app.url_path_for("path-with-parentheses", param=7) == "/path-with-parentheses(7)"
# Test float conversion
response = client.get("/float/25.5")
assert response.status_code == 200
assert response.json() == {"float": 25.5}
assert app.url_path_for("float-convertor", param=25.5) == "/float/25.5"
# Test path conversion
response = client.get("/path/some/example")
assert response.status_code == 200
assert response.json() == {"path": "some/example"}
assert app.url_path_for("path-convertor", param="some/example") == "/path/some/example"
# Test UUID conversion
response = client.get("/uuid/ec38df32-ceda-4cfa-9b4a-1aeb94ad551a")
assert response.status_code == 200
assert response.json() == {"uuid": "ec38df32-ceda-4cfa-9b4a-1aeb94ad551a"}
assert (
app.url_path_for("uuid-convertor", param=uuid.UUID("ec38df32-ceda-4cfa-9b4a-1aeb94ad551a"))
== "/uuid/ec38df32-ceda-4cfa-9b4a-1aeb94ad551a"
)
def test_url_path_for() -> None:
assert app.url_path_for("homepage") == "/"
assert app.url_path_for("user", username="tomchristie") == "/users/tomchristie"
assert app.url_path_for("websocket_endpoint") == "/ws"
with pytest.raises(NoMatchFound, match='No route exists for name "broken" and params "".'):
assert app.url_path_for("broken")
with pytest.raises(NoMatchFound, match='No route exists for name "broken" and params "key, key2".'):
assert app.url_path_for("broken", key="value", key2="value2")
with pytest.raises(AssertionError):
app.url_path_for("user", username="tom/christie")
with pytest.raises(AssertionError):
app.url_path_for("user", username="")
def test_url_for() -> None:
assert app.url_path_for("homepage").make_absolute_url(base_url="https://example.org") == "https://example.org/"
assert (
app.url_path_for("homepage").make_absolute_url(base_url="https://example.org/root_path/")
== "https://example.org/root_path/"
)
assert (
app.url_path_for("user", username="tomchristie").make_absolute_url(base_url="https://example.org")
== "https://example.org/users/tomchristie"
)
assert (
app.url_path_for("user", username="tomchristie").make_absolute_url(base_url="https://example.org/root_path/")
== "https://example.org/root_path/users/tomchristie"
)
assert (
app.url_path_for("websocket_endpoint").make_absolute_url(base_url="https://example.org")
== "wss://example.org/ws"
)
def test_router_add_route(client: TestClient) -> None:
response = client.get("/func")
assert response.status_code == 200
assert response.text == "Hello, world!"
def test_router_duplicate_path(client: TestClient) -> None:
response = client.post("/func")
assert response.status_code == 200
assert response.text == "Hello, POST!"
def test_router_add_websocket_route(client: TestClient) -> None:
with client.websocket_connect("/ws") as session:
text = session.receive_text()
assert text == "Hello, world!"
with client.websocket_connect("/ws/test") as session:
text = session.receive_text()
assert text == "Hello, test!"
def test_router_middleware(test_client_factory: TestClientFactory) -> None:
class CustomMiddleware:
def __init__(self, app: ASGIApp) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
response = PlainTextResponse("OK")
await response(scope, receive, send)
app = Router(
routes=[Route("/", homepage)],
middleware=[Middleware(CustomMiddleware)],
)
client = test_client_factory(app)
response = client.get("/")
assert response.status_code == 200
assert response.text == "OK"
def http_endpoint(request: Request) -> Response:
url = request.url_for("http_endpoint")
return Response(f"URL: {url}", media_type="text/plain")
class WebSocketEndpoint:
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope=scope, receive=receive, send=send)
await websocket.accept()
await websocket.send_json({"URL": str(websocket.url_for("websocket_endpoint"))})
await websocket.close()
mixed_protocol_app = Router(
routes=[
Route("/", endpoint=http_endpoint),
WebSocketRoute("/", endpoint=WebSocketEndpoint(), name="websocket_endpoint"),
]
)
def test_protocol_switch(test_client_factory: TestClientFactory) -> None:
client = test_client_factory(mixed_protocol_app)
response = client.get("/")
assert response.status_code == 200
assert response.text == "URL: http://testserver/"
with client.websocket_connect("/") as session:
assert session.receive_json() == {"URL": "ws://testserver/"}
with pytest.raises(WebSocketDisconnect):
with client.websocket_connect("/404"):
pass # pragma: no cover
ok = PlainTextResponse("OK")
def test_mount_urls(test_client_factory: TestClientFactory) -> None:
mounted = Router([Mount("/users", ok, name="users")])
client = test_client_factory(mounted)
assert client.get("/users").status_code == 200
assert client.get("/users").url == "http://testserver/users/"
assert client.get("/users/").status_code == 200
assert client.get("/users/a").status_code == 200
assert client.get("/usersa").status_code == 404
def test_reverse_mount_urls() -> None:
mounted = Router([Mount("/users", ok, name="users")])
assert mounted.url_path_for("users", path="/a") == "/users/a"
users = Router([Route("/{username}", ok, name="user")])
mounted = Router([Mount("/{subpath}/users", users, name="users")])
assert mounted.url_path_for("users:user", subpath="test", username="tom") == "/test/users/tom"
assert mounted.url_path_for("users", subpath="test", path="/tom") == "/test/users/tom"
mounted = Router([Mount("/users", ok, name="users")])
with pytest.raises(NoMatchFound):
mounted.url_path_for("users", path="/a", foo="bar")
mounted = Router([Mount("/users", ok, name="users")])
with pytest.raises(NoMatchFound):
mounted.url_path_for("users")
def test_mount_at_root(test_client_factory: TestClientFactory) -> None:
mounted = Router([Mount("/", ok, name="users")])
client = test_client_factory(mounted)
assert client.get("/").status_code == 200
def users_api(request: Request) -> JSONResponse:
return JSONResponse({"users": [{"username": "tom"}]})
mixed_hosts_app = Router(
routes=[
Host(
"www.example.org",
app=Router(
[
Route("/", homepage, name="homepage"),
Route("/users", users, name="users"),
]
),
),
Host(
"api.example.org",
name="api",
app=Router([Route("/users", users_api, name="users")]),
),
Host(
"port.example.org:3600",
name="port",
app=Router([Route("/", homepage, name="homepage")]),
),
]
)
def test_host_routing(test_client_factory: TestClientFactory) -> None:
client = test_client_factory(mixed_hosts_app, base_url="https://api.example.org/")
response = client.get("/users")
assert response.status_code == 200
assert response.json() == {"users": [{"username": "tom"}]}
response = client.get("/")
assert response.status_code == 404
client = test_client_factory(mixed_hosts_app, base_url="https://www.example.org/")
response = client.get("/users")
assert response.status_code == 200
assert response.text == "All users"
response = client.get("/")
assert response.status_code == 200
client = test_client_factory(mixed_hosts_app, base_url="https://port.example.org:3600/")
response = client.get("/users")
assert response.status_code == 404
response = client.get("/")
assert response.status_code == 200
# Port in requested Host is irrelevant.
client = test_client_factory(mixed_hosts_app, base_url="https://port.example.org/")
response = client.get("/")
assert response.status_code == 200
client = test_client_factory(mixed_hosts_app, base_url="https://port.example.org:5600/")
response = client.get("/")
assert response.status_code == 200
def test_host_reverse_urls() -> None:
assert mixed_hosts_app.url_path_for("homepage").make_absolute_url("https://whatever") == "https://www.example.org/"
assert (
mixed_hosts_app.url_path_for("users").make_absolute_url("https://whatever") == "https://www.example.org/users"
)
assert (
mixed_hosts_app.url_path_for("api:users").make_absolute_url("https://whatever")
== "https://api.example.org/users"
)
assert (
mixed_hosts_app.url_path_for("port:homepage").make_absolute_url("https://whatever")
== "https://port.example.org:3600/"
)
with pytest.raises(NoMatchFound):
mixed_hosts_app.url_path_for("api", path="whatever", foo="bar")
async def subdomain_app(scope: Scope, receive: Receive, send: Send) -> None:
response = JSONResponse({"subdomain": scope["path_params"]["subdomain"]})
await response(scope, receive, send)
subdomain_router = Router(routes=[Host("{subdomain}.example.org", app=subdomain_app, name="subdomains")])
def test_subdomain_routing(test_client_factory: TestClientFactory) -> None:
client = test_client_factory(subdomain_router, base_url="https://foo.example.org/")
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"subdomain": "foo"}
def test_subdomain_reverse_urls() -> None:
assert (
subdomain_router.url_path_for("subdomains", subdomain="foo", path="/homepage").make_absolute_url(
"https://whatever"
)
== "https://foo.example.org/homepage"
)
async def echo_urls(request: Request) -> JSONResponse:
return JSONResponse(
{
"index": str(request.url_for("index")),
"submount": str(request.url_for("mount:submount")),
}
)
echo_url_routes = [
Route("/", echo_urls, name="index", methods=["GET"]),
Mount(
"/submount",
name="mount",
routes=[Route("/", echo_urls, name="submount", methods=["GET"])],
),
]
def test_url_for_with_root_path(test_client_factory: TestClientFactory) -> None:
app = Starlette(routes=echo_url_routes)
client = test_client_factory(app, base_url="https://www.example.org/", root_path="/sub_path")
response = client.get("/sub_path/")
assert response.json() == {
"index": "https://www.example.org/sub_path/",
"submount": "https://www.example.org/sub_path/submount/",
}
response = client.get("/sub_path/submount/")
assert response.json() == {
"index": "https://www.example.org/sub_path/",
"submount": "https://www.example.org/sub_path/submount/",
}
async def stub_app(scope: Scope, receive: Receive, send: Send) -> None:
pass # pragma: no cover
double_mount_routes = [
Mount("/mount", name="mount", routes=[Mount("/static", stub_app, name="static")]),
]
def test_url_for_with_double_mount() -> None:
app = Starlette(routes=double_mount_routes)
url = app.url_path_for("mount:static", path="123")
assert url == "/mount/static/123"
def test_url_for_with_root_path_ending_with_slash(test_client_factory: TestClientFactory) -> None:
def homepage(request: Request) -> JSONResponse:
return JSONResponse({"index": str(request.url_for("homepage"))})
app = Starlette(routes=[Route("/", homepage, name="homepage")])
client = test_client_factory(app, base_url="https://www.example.org/", root_path="/sub_path/")
response = client.get("/sub_path/")
assert response.json() == {"index": "https://www.example.org/sub_path/"}
def test_standalone_route_matches(
test_client_factory: TestClientFactory,
) -> None:
app = Route("/", PlainTextResponse("Hello, World!"))
client = test_client_factory(app)
response = client.get("/")
assert response.status_code == 200
assert response.text == "Hello, World!"
def test_standalone_route_does_not_match(
test_client_factory: Callable[..., TestClient],
) -> None:
app = Route("/", PlainTextResponse("Hello, World!"))
client = test_client_factory(app)
response = client.get("/invalid")
assert response.status_code == 404
assert response.text == "Not Found"
async def ws_helloworld(websocket: WebSocket) -> None:
await websocket.accept()
await websocket.send_text("Hello, world!")
await websocket.close()
def test_standalone_ws_route_matches(
test_client_factory: TestClientFactory,
) -> None:
app = WebSocketRoute("/", ws_helloworld)
client = test_client_factory(app)
with client.websocket_connect("/") as websocket:
text = websocket.receive_text()
assert text == "Hello, world!"
def test_standalone_ws_route_does_not_match(
test_client_factory: TestClientFactory,
) -> None:
app = WebSocketRoute("/", ws_helloworld)
client = test_client_factory(app)
with pytest.raises(WebSocketDisconnect):
with client.websocket_connect("/invalid"):
pass # pragma: no cover
def test_lifespan_async(test_client_factory: TestClientFactory) -> None:
startup_complete = False
shutdown_complete = False
async def hello_world(request: Request) -> PlainTextResponse:
return PlainTextResponse("hello, world")
async def run_startup() -> None:
nonlocal startup_complete
startup_complete = True
async def run_shutdown() -> None:
nonlocal shutdown_complete
shutdown_complete = True
with pytest.deprecated_call(match="The on_startup and on_shutdown parameters are deprecated"):
app = Router(
on_startup=[run_startup],
on_shutdown=[run_shutdown],
routes=[Route("/", hello_world)],
)
assert not startup_complete
assert not shutdown_complete
with test_client_factory(app) as client:
assert startup_complete
assert not shutdown_complete
client.get("/")
assert startup_complete
assert shutdown_complete
def test_lifespan_with_on_events(test_client_factory: TestClientFactory) -> None:
lifespan_called = False
startup_called = False
shutdown_called = False
@contextlib.asynccontextmanager
async def lifespan(app: Starlette) -> AsyncGenerator[None, None]:
nonlocal lifespan_called
lifespan_called = True
yield
# We do not expected, neither of run_startup nor run_shutdown to be called
# we thus mark them as #pragma: no cover, to fulfill test coverage
def run_startup() -> None: # pragma: no cover
nonlocal startup_called
startup_called = True
def run_shutdown() -> None: # pragma: no cover
nonlocal shutdown_called
shutdown_called = True
with pytest.deprecated_call(match="The on_startup and on_shutdown parameters are deprecated"):
with pytest.warns(
UserWarning, match="The `lifespan` parameter cannot be used with `on_startup` or `on_shutdown`."
):
app = Router(on_startup=[run_startup], on_shutdown=[run_shutdown], lifespan=lifespan)
assert not lifespan_called
assert not startup_called
assert not shutdown_called
# Triggers the lifespan events
with test_client_factory(app):
...
assert lifespan_called
assert not startup_called
assert not shutdown_called
def test_lifespan_sync(test_client_factory: TestClientFactory) -> None:
startup_complete = False
shutdown_complete = False
def hello_world(request: Request) -> PlainTextResponse:
return PlainTextResponse("hello, world")
def run_startup() -> None:
nonlocal startup_complete
startup_complete = True
def run_shutdown() -> None:
nonlocal shutdown_complete
shutdown_complete = True
with pytest.deprecated_call(match="The on_startup and on_shutdown parameters are deprecated"):
app = Router(
on_startup=[run_startup],
on_shutdown=[run_shutdown],
routes=[Route("/", hello_world)],
)
assert not startup_complete
assert not shutdown_complete
with test_client_factory(app) as client:
assert startup_complete
assert not shutdown_complete
client.get("/")
assert startup_complete
assert shutdown_complete
def test_lifespan_state_unsupported(
test_client_factory: TestClientFactory,
) -> None:
@contextlib.asynccontextmanager
async def lifespan(
app: ASGIApp,
) -> AsyncGenerator[dict[str, str], None]:
yield {"foo": "bar"}
app = Router(
lifespan=lifespan,
routes=[Mount("/", PlainTextResponse("hello, world"))],
)
async def no_state_wrapper(scope: Scope, receive: Receive, send: Send) -> None:
del scope["state"]
await app(scope, receive, send)
with pytest.raises(RuntimeError, match='The server does not support "state" in the lifespan scope'):
with test_client_factory(no_state_wrapper):
raise AssertionError("Should not be called") # pragma: no cover
def test_lifespan_state_async_cm(test_client_factory: TestClientFactory) -> None:
startup_complete = False
shutdown_complete = False
class State(TypedDict):
count: int
items: list[int]
async def hello_world(request: Request) -> Response:
# modifications to the state should not leak across requests
assert request.state.count == 0
# modify the state, this should not leak to the lifespan or other requests
request.state.count += 1
# since state.items is a mutable object this modification _will_ leak across
# requests and to the lifespan
request.state.items.append(1)
return PlainTextResponse("hello, world")
@contextlib.asynccontextmanager
async def lifespan(app: Starlette) -> AsyncIterator[State]:
nonlocal startup_complete, shutdown_complete
startup_complete = True
state = State(count=0, items=[])
yield state
shutdown_complete = True
# modifications made to the state from a request do not leak to the lifespan
assert state["count"] == 0
# unless of course the request mutates a mutable object that is referenced
# via state
assert state["items"] == [1, 1]
app = Router(
lifespan=lifespan,
routes=[Route("/", hello_world)],
)
assert not startup_complete
assert not shutdown_complete
with test_client_factory(app) as client:
assert startup_complete
assert not shutdown_complete
client.get("/")
# Calling it a second time to ensure that the state is preserved.
client.get("/")
assert startup_complete
assert shutdown_complete
def test_raise_on_startup(test_client_factory: TestClientFactory) -> None:
def run_startup() -> None:
raise RuntimeError()
with pytest.deprecated_call(match="The on_startup and on_shutdown parameters are deprecated"):
router = Router(on_startup=[run_startup])
startup_failed = False
async def app(scope: Scope, receive: Receive, send: Send) -> None:
async def _send(message: Message) -> None:
nonlocal startup_failed
if message["type"] == "lifespan.startup.failed": # pragma: no branch
startup_failed = True
return await send(message)
await router(scope, receive, _send)
with pytest.raises(RuntimeError):
with test_client_factory(app):
pass # pragma: no cover
assert startup_failed
def test_raise_on_shutdown(test_client_factory: TestClientFactory) -> None:
def run_shutdown() -> None:
raise RuntimeError()
with pytest.deprecated_call(match="The on_startup and on_shutdown parameters are deprecated"):
app = Router(on_shutdown=[run_shutdown])
with pytest.raises(RuntimeError):
with test_client_factory(app):
pass # pragma: no cover
def test_partial_async_endpoint(test_client_factory: TestClientFactory) -> None:
test_client = test_client_factory(app)
response = test_client.get("/partial")
assert response.status_code == 200
assert response.json() == {"arg": "foo"}
cls_method_response = test_client.get("/partial/cls")
assert cls_method_response.status_code == 200
assert cls_method_response.json() == {"arg": "foo"}
def test_partial_async_ws_endpoint(
test_client_factory: TestClientFactory,
) -> None:
test_client = test_client_factory(app)
with test_client.websocket_connect("/partial/ws") as websocket:
data = websocket.receive_json()
assert data == {"url": "ws://testserver/partial/ws"}
with test_client.websocket_connect("/partial/ws/cls") as websocket:
data = websocket.receive_json()
assert data == {"url": "ws://testserver/partial/ws/cls"}
def test_duplicated_param_names() -> None:
with pytest.raises(
ValueError,
match="Duplicated param name id at path /{id}/{id}",
):
Route("/{id}/{id}", user)
with pytest.raises(
ValueError,
match="Duplicated param names id, name at path /{id}/{name}/{id}/{name}",
):
Route("/{id}/{name}/{id}/{name}", user)
class Endpoint:
async def my_method(self, request: Request) -> None: ... # pragma: no cover
@classmethod
async def my_classmethod(cls, request: Request) -> None: ... # pragma: no cover
@staticmethod
async def my_staticmethod(request: Request) -> None: ... # pragma: no cover
def __call__(self, request: Request) -> None: ... # pragma: no cover
@pytest.mark.parametrize(
"endpoint, expected_name",
[
pytest.param(func_homepage, "func_homepage", id="function"),
pytest.param(Endpoint().my_method, "my_method", id="method"),
pytest.param(Endpoint.my_classmethod, "my_classmethod", id="classmethod"),
pytest.param(
Endpoint.my_staticmethod,
"my_staticmethod",
id="staticmethod",
),
pytest.param(Endpoint(), "Endpoint", id="object"),
pytest.param(lambda request: ..., "<lambda>", id="lambda"), # pragma: no branch
],
)
def test_route_name(endpoint: Callable[..., Response], expected_name: str) -> None:
assert Route(path="/", endpoint=endpoint).name == expected_name
class AddHeadersMiddleware:
def __init__(self, app: ASGIApp) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
scope["add_headers_middleware"] = True
async def modified_send(msg: Message) -> None:
if msg["type"] == "http.response.start":
msg["headers"].append((b"X-Test", b"Set by middleware"))
await send(msg)
await self.app(scope, receive, modified_send)
def assert_middleware_header_route(request: Request) -> Response:
assert request.scope["add_headers_middleware"] is True
return Response()
route_with_middleware = Starlette(
routes=[
Route(
"/http",
endpoint=assert_middleware_header_route,
methods=["GET"],
middleware=[Middleware(AddHeadersMiddleware)],
),
Route("/home", homepage),
]
)
mounted_routes_with_middleware = Starlette(
routes=[
Mount(
"/http",
routes=[
Route(
"/",
endpoint=assert_middleware_header_route,
methods=["GET"],
name="route",
),
],
middleware=[Middleware(AddHeadersMiddleware)],
),
Route("/home", homepage),
]
)
mounted_app_with_middleware = Starlette(
routes=[
Mount(
"/http",
app=Route(
"/",
endpoint=assert_middleware_header_route,
methods=["GET"],
name="route",
),
middleware=[Middleware(AddHeadersMiddleware)],
),
Route("/home", homepage),
]
)
@pytest.mark.parametrize(
"app",
[
mounted_routes_with_middleware,
mounted_app_with_middleware,
route_with_middleware,
],
)
def test_base_route_middleware(
test_client_factory: TestClientFactory,
app: Starlette,
) -> None:
test_client = test_client_factory(app)
response = test_client.get("/home")
assert response.status_code == 200
assert "X-Test" not in response.headers
response = test_client.get("/http")
assert response.status_code == 200
assert response.headers["X-Test"] == "Set by middleware"
def test_mount_routes_with_middleware_url_path_for() -> None:
"""Checks that url_path_for still works with mounted routes with Middleware"""
assert mounted_routes_with_middleware.url_path_for("route") == "/http/"
def test_mount_asgi_app_with_middleware_url_path_for() -> None:
"""Mounted ASGI apps do not work with url path for,
middleware does not change this
"""
with pytest.raises(NoMatchFound):
mounted_app_with_middleware.url_path_for("route")
def test_add_route_to_app_after_mount(
test_client_factory: Callable[..., TestClient],
) -> None:
"""Checks that Mount will pick up routes
added to the underlying app after it is mounted
"""
inner_app = Router()
app = Mount("/http", app=inner_app)
inner_app.add_route(
"/inner",
endpoint=homepage,
methods=["GET"],
)
client = test_client_factory(app)
response = client.get("/http/inner")
assert response.status_code == 200
def test_exception_on_mounted_apps(
test_client_factory: TestClientFactory,
) -> None:
def exc(request: Request) -> None:
raise Exception("Exc")
sub_app = Starlette(routes=[Route("/", exc)])
app = Starlette(routes=[Mount("/sub", app=sub_app)])
client = test_client_factory(app)
with pytest.raises(Exception) as ctx:
client.get("/sub/")
assert str(ctx.value) == "Exc"
def test_mounted_middleware_does_not_catch_exception(
test_client_factory: Callable[..., TestClient],
) -> None:
# https://github.com/Kludex/starlette/pull/1649#discussion_r960236107
def exc(request: Request) -> Response:
raise HTTPException(status_code=403, detail="auth")
class NamedMiddleware:
def __init__(self, app: ASGIApp, name: str) -> None:
self.app = app
self.name = name
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
async def modified_send(msg: Message) -> None:
if msg["type"] == "http.response.start":
msg["headers"].append((f"X-{self.name}".encode(), b"true"))
await send(msg)
await self.app(scope, receive, modified_send)
app = Starlette(
routes=[
Mount(
"/mount",
routes=[
Route("/err", exc),
Route("/home", homepage),
],
middleware=[Middleware(NamedMiddleware, name="Mounted")],
),
Route("/err", exc),
Route("/home", homepage),
],
middleware=[Middleware(NamedMiddleware, name="Outer")],
)
client = test_client_factory(app)
resp = client.get("/home")
assert resp.status_code == 200, resp.content
assert "X-Outer" in resp.headers
resp = client.get("/err")
assert resp.status_code == 403, resp.content
assert "X-Outer" in resp.headers
resp = client.get("/mount/home")
assert resp.status_code == 200, resp.content
assert "X-Mounted" in resp.headers
resp = client.get("/mount/err")
assert resp.status_code == 403, resp.content
assert "X-Mounted" in resp.headers
def test_websocket_route_middleware(
test_client_factory: TestClientFactory,
) -> None:
async def websocket_endpoint(session: WebSocket) -> None:
await session.accept()
await session.send_text("Hello, world!")
await session.close()
class WebsocketMiddleware:
def __init__(self, app: ASGIApp) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
async def modified_send(msg: Message) -> None:
if msg["type"] == "websocket.accept":
msg["headers"].append((b"X-Test", b"Set by middleware"))
await send(msg)
await self.app(scope, receive, modified_send)
app = Starlette(
routes=[
WebSocketRoute(
"/ws",
endpoint=websocket_endpoint,
middleware=[Middleware(WebsocketMiddleware)],
)
]
)
client = test_client_factory(app)
with client.websocket_connect("/ws") as websocket:
text = websocket.receive_text()
assert text == "Hello, world!"
assert websocket.extra_headers == [(b"X-Test", b"Set by middleware")]
def test_route_repr() -> None:
route = Route("/welcome", endpoint=homepage)
assert repr(route) == "Route(path='/welcome', name='homepage', methods=['GET', 'HEAD'])"
def test_route_repr_without_methods() -> None:
route = Route("/welcome", endpoint=Endpoint, methods=None)
assert repr(route) == "Route(path='/welcome', name='Endpoint', methods=[])"
def test_websocket_route_repr() -> None:
route = WebSocketRoute("/ws", endpoint=websocket_endpoint)
assert repr(route) == "WebSocketRoute(path='/ws', name='websocket_endpoint')"
def test_mount_repr() -> None:
route = Mount(
"/app",
routes=[
Route("/", endpoint=homepage),
],
)
# test for substring because repr(Router) returns unique object ID
assert repr(route).startswith("Mount(path='/app', name='', app=")
def test_mount_named_repr() -> None:
route = Mount(
"/app",
name="app",
routes=[
Route("/", endpoint=homepage),
],
)
# test for substring because repr(Router) returns unique object ID
assert repr(route).startswith("Mount(path='/app', name='app', app=")
def test_host_repr() -> None:
route = Host(
"example.com",
app=Router(
[
Route("/", endpoint=homepage),
]
),
)
# test for substring because repr(Router) returns unique object ID
assert repr(route).startswith("Host(host='example.com', name='', app=")
def test_host_named_repr() -> None:
route = Host(
"example.com",
name="app",
app=Router(
[
Route("/", endpoint=homepage),
]
),
)
# test for substring because repr(Router) returns unique object ID
assert repr(route).startswith("Host(host='example.com', name='app', app=")
def test_decorator_deprecations() -> None:
router = Router()
with pytest.deprecated_call():
router.route("/")(homepage)
with pytest.deprecated_call():
router.websocket_route("/ws")(websocket_endpoint)
with pytest.deprecated_call():
async def startup() -> None: ... # pragma: no cover
router.on_event("startup")(startup)
async def echo_paths(request: Request, name: str) -> JSONResponse:
return JSONResponse(
{
"name": name,
"path": request.scope["path"],
"root_path": request.scope["root_path"],
}
)
async def pure_asgi_echo_paths(scope: Scope, receive: Receive, send: Send, name: str) -> None:
data = {"name": name, "path": scope["path"], "root_path": scope["root_path"]}
content = json.dumps(data).encode("utf-8")
await send(
{
"type": "http.response.start",
"status": 200,
"headers": [(b"content-type", b"application/json")],
}
)
await send({"type": "http.response.body", "body": content})
echo_paths_routes = [
Route(
"/path",
functools.partial(echo_paths, name="path"),
name="path",
methods=["GET"],
),
Route(
"/root-queue/path",
functools.partial(echo_paths, name="queue_path"),
name="queue_path",
methods=["POST"],
),
Mount("/asgipath", app=functools.partial(pure_asgi_echo_paths, name="asgipath")),
Mount(
"/sub",
name="mount",
routes=[
Route(
"/path",
functools.partial(echo_paths, name="subpath"),
name="subpath",
methods=["GET"],
),
],
),
]
def test_paths_with_root_path(test_client_factory: TestClientFactory) -> None:
app = Starlette(routes=echo_paths_routes)
client = test_client_factory(app, base_url="https://www.example.org/", root_path="/root")
response = client.get("/root/path")
assert response.status_code == 200
assert response.json() == {
"name": "path",
"path": "/root/path",
"root_path": "/root",
}
response = client.get("/root/asgipath/")
assert response.status_code == 200
assert response.json() == {
"name": "asgipath",
"path": "/root/asgipath/",
# Things that mount other ASGI apps, like WSGIMiddleware, would not be aware
# of the prefixed path, and would have their own notion of their own paths,
# so they need to be able to rely on the root_path to know the location they
# are mounted on
"root_path": "/root/asgipath",
}
response = client.get("/root/sub/path")
assert response.status_code == 200
assert response.json() == {
"name": "subpath",
"path": "/root/sub/path",
"root_path": "/root/sub",
}
response = client.post("/root/root-queue/path")
assert response.status_code == 200
assert response.json() == {
"name": "queue_path",
"path": "/root/root-queue/path",
"root_path": "/root",
}
| starlette |
python | from __future__ import annotations
import enum
import json
from collections.abc import AsyncIterator, Iterable
from typing import Any, cast
from starlette.requests import HTTPConnection
from starlette.responses import Response
from starlette.types import Message, Receive, Scope, Send
class WebSocketState(enum.Enum):
CONNECTING = 0
CONNECTED = 1
DISCONNECTED = 2
RESPONSE = 3
class WebSocketDisconnect(Exception):
def __init__(self, code: int = 1000, reason: str | None = None) -> None:
self.code = code
self.reason = reason or ""
class WebSocket(HTTPConnection):
def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
super().__init__(scope)
assert scope["type"] == "websocket"
self._receive = receive
self._send = send
self.client_state = WebSocketState.CONNECTING
self.application_state = WebSocketState.CONNECTING
async def receive(self) -> Message:
"""
Receive ASGI websocket messages, ensuring valid state transitions.
"""
if self.client_state == WebSocketState.CONNECTING:
message = await self._receive()
message_type = message["type"]
if message_type != "websocket.connect":
raise RuntimeError(f'Expected ASGI message "websocket.connect", but got {message_type!r}')
self.client_state = WebSocketState.CONNECTED
return message
elif self.client_state == WebSocketState.CONNECTED:
message = await self._receive()
message_type = message["type"]
if message_type not in {"websocket.receive", "websocket.disconnect"}:
raise RuntimeError(
f'Expected ASGI message "websocket.receive" or "websocket.disconnect", but got {message_type!r}'
)
if message_type == "websocket.disconnect":
self.client_state = WebSocketState.DISCONNECTED
return message
else:
raise RuntimeError('Cannot call "receive" once a disconnect message has been received.')
async def send(self, message: Message) -> None:
"""
Send ASGI websocket messages, ensuring valid state transitions.
"""
if self.application_state == WebSocketState.CONNECTING:
message_type = message["type"]
if message_type not in {"websocket.accept", "websocket.close", "websocket.http.response.start"}:
raise RuntimeError(
'Expected ASGI message "websocket.accept", "websocket.close" or "websocket.http.response.start", '
f"but got {message_type!r}"
)
if message_type == "websocket.close":
self.application_state = WebSocketState.DISCONNECTED
elif message_type == "websocket.http.response.start":
self.application_state = WebSocketState.RESPONSE
else:
self.application_state = WebSocketState.CONNECTED
await self._send(message)
elif self.application_state == WebSocketState.CONNECTED:
message_type = message["type"]
if message_type not in {"websocket.send", "websocket.close"}:
raise RuntimeError(
f'Expected ASGI message "websocket.send" or "websocket.close", but got {message_type!r}'
)
if message_type == "websocket.close":
self.application_state = WebSocketState.DISCONNECTED
try:
await self._send(message)
except OSError:
self.application_state = WebSocketState.DISCONNECTED
raise WebSocketDisconnect(code=1006)
elif self.application_state == WebSocketState.RESPONSE:
message_type = message["type"]
if message_type != "websocket.http.response.body":
raise RuntimeError(f'Expected ASGI message "websocket.http.response.body", but got {message_type!r}')
if not message.get("more_body", False):
self.application_state = WebSocketState.DISCONNECTED
await self._send(message)
else:
raise RuntimeError('Cannot call "send" once a close message has been sent.')
async def accept(
self,
subprotocol: str | None = None,
headers: Iterable[tuple[bytes, bytes]] | None = None,
) -> None:
headers = headers or []
if self.client_state == WebSocketState.CONNECTING: # pragma: no branch
# If we haven't yet seen the 'connect' message, then wait for it first.
await self.receive()
await self.send({"type": "websocket.accept", "subprotocol": subprotocol, "headers": headers})
def _raise_on_disconnect(self, message: Message) -> None:
if message["type"] == "websocket.disconnect":
raise WebSocketDisconnect(message["code"], message.get("reason"))
async def receive_text(self) -> str:
if self.application_state != WebSocketState.CONNECTED:
raise RuntimeError('WebSocket is not connected. Need to call "accept" first.')
message = await self.receive()
self._raise_on_disconnect(message)
return cast(str, message["text"])
async def receive_bytes(self) -> bytes:
if self.application_state != WebSocketState.CONNECTED:
raise RuntimeError('WebSocket is not connected. Need to call "accept" first.')
message = await self.receive()
self._raise_on_disconnect(message)
return cast(bytes, message["bytes"])
async def receive_json(self, mode: str = "text") -> Any:
if mode not in {"text", "binary"}:
raise RuntimeError('The "mode" argument should be "text" or "binary".')
if self.application_state != WebSocketState.CONNECTED:
raise RuntimeError('WebSocket is not connected. Need to call "accept" first.')
message = await self.receive()
self._raise_on_disconnect(message)
if mode == "text":
text = message["text"]
else:
text = message["bytes"].decode("utf-8")
return json.loads(text)
async def iter_text(self) -> AsyncIterator[str]:
try:
while True:
yield await self.receive_text()
except WebSocketDisconnect:
pass
async def iter_bytes(self) -> AsyncIterator[bytes]:
try:
while True:
yield await self.receive_bytes()
except WebSocketDisconnect:
pass
async def iter_json(self) -> AsyncIterator[Any]:
try:
while True:
yield await self.receive_json()
except WebSocketDisconnect:
pass
async def send_text(self, data: str) -> None:
await self.send({"type": "websocket.send", "text": data})
async def send_bytes(self, data: bytes) -> None:
await self.send({"type": "websocket.send", "bytes": data})
async def send_json(self, data: Any, mode: str = "text") -> None:
if mode not in {"text", "binary"}:
raise RuntimeError('The "mode" argument should be "text" or "binary".')
text = json.dumps(data, separators=(",", ":"), ensure_ascii=False)
if mode == "text":
await self.send({"type": "websocket.send", "text": text})
else:
await self.send({"type": "websocket.send", "bytes": text.encode("utf-8")})
async def close(self, code: int = 1000, reason: str | None = None) -> None:
await self.send({"type": "websocket.close", "code": code, "reason": reason or ""})
async def send_denial_response(self, response: Response) -> None:
if "websocket.http.response" in self.scope.get("extensions", {}):
await response(self.scope, self.receive, self.send)
else:
raise RuntimeError("The server doesn't support the Websocket Denial Response extension.")
class WebSocketClose:
def __init__(self, code: int = 1000, reason: str | None = None) -> None:
self.code = code
self.reason = reason or ""
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
await send({"type": "websocket.close", "code": self.code, "reason": self.reason})
| import sys
from collections.abc import MutableMapping
from typing import Any
import anyio
import pytest
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from starlette import status
from starlette.responses import Response
from starlette.testclient import WebSocketDenialResponse
from starlette.types import Message, Receive, Scope, Send
from starlette.websockets import WebSocket, WebSocketDisconnect, WebSocketState
from tests.types import TestClientFactory
def test_websocket_url(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.accept()
await websocket.send_json({"url": str(websocket.url)})
await websocket.close()
client = test_client_factory(app)
with client.websocket_connect("/123?a=abc") as websocket:
data = websocket.receive_json()
assert data == {"url": "ws://testserver/123?a=abc"}
def test_websocket_binary_json(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.accept()
message = await websocket.receive_json(mode="binary")
await websocket.send_json(message, mode="binary")
await websocket.close()
client = test_client_factory(app)
with client.websocket_connect("/123?a=abc") as websocket:
websocket.send_json({"test": "data"}, mode="binary")
data = websocket.receive_json(mode="binary")
assert data == {"test": "data"}
def test_websocket_ensure_unicode_on_send_json(
test_client_factory: TestClientFactory,
) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.accept()
message = await websocket.receive_json(mode="text")
await websocket.send_json(message, mode="text")
await websocket.close()
client = test_client_factory(app)
with client.websocket_connect("/123?a=abc") as websocket:
websocket.send_json({"test": "数据"}, mode="text")
data = websocket.receive_text()
assert data == '{"test":"数据"}'
def test_websocket_query_params(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
query_params = dict(websocket.query_params)
await websocket.accept()
await websocket.send_json({"params": query_params})
await websocket.close()
client = test_client_factory(app)
with client.websocket_connect("/?a=abc&b=456") as websocket:
data = websocket.receive_json()
assert data == {"params": {"a": "abc", "b": "456"}}
@pytest.mark.skipif(
any(module in sys.modules for module in ("brotli", "brotlicffi")),
reason='urllib3 includes "br" to the "accept-encoding" headers.',
)
def test_websocket_headers(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
headers = dict(websocket.headers)
await websocket.accept()
await websocket.send_json({"headers": headers})
await websocket.close()
client = test_client_factory(app)
with client.websocket_connect("/") as websocket:
expected_headers = {
"accept": "*/*",
"accept-encoding": "gzip, deflate",
"connection": "upgrade",
"host": "testserver",
"user-agent": "testclient",
"sec-websocket-key": "testserver==",
"sec-websocket-version": "13",
}
data = websocket.receive_json()
assert data == {"headers": expected_headers}
def test_websocket_port(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.accept()
await websocket.send_json({"port": websocket.url.port})
await websocket.close()
client = test_client_factory(app)
with client.websocket_connect("ws://example.com:123/123?a=abc") as websocket:
data = websocket.receive_json()
assert data == {"port": 123}
def test_websocket_send_and_receive_text(
test_client_factory: TestClientFactory,
) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.accept()
data = await websocket.receive_text()
await websocket.send_text("Message was: " + data)
await websocket.close()
client = test_client_factory(app)
with client.websocket_connect("/") as websocket:
websocket.send_text("Hello, world!")
data = websocket.receive_text()
assert data == "Message was: Hello, world!"
def test_websocket_send_and_receive_bytes(
test_client_factory: TestClientFactory,
) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.accept()
data = await websocket.receive_bytes()
await websocket.send_bytes(b"Message was: " + data)
await websocket.close()
client = test_client_factory(app)
with client.websocket_connect("/") as websocket:
websocket.send_bytes(b"Hello, world!")
data = websocket.receive_bytes()
assert data == b"Message was: Hello, world!"
def test_websocket_send_and_receive_json(
test_client_factory: TestClientFactory,
) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.accept()
data = await websocket.receive_json()
await websocket.send_json({"message": data})
await websocket.close()
client = test_client_factory(app)
with client.websocket_connect("/") as websocket:
websocket.send_json({"hello": "world"})
data = websocket.receive_json()
assert data == {"message": {"hello": "world"}}
def test_websocket_iter_text(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.accept()
async for data in websocket.iter_text():
await websocket.send_text("Message was: " + data)
client = test_client_factory(app)
with client.websocket_connect("/") as websocket:
websocket.send_text("Hello, world!")
data = websocket.receive_text()
assert data == "Message was: Hello, world!"
def test_websocket_iter_bytes(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.accept()
async for data in websocket.iter_bytes():
await websocket.send_bytes(b"Message was: " + data)
client = test_client_factory(app)
with client.websocket_connect("/") as websocket:
websocket.send_bytes(b"Hello, world!")
data = websocket.receive_bytes()
assert data == b"Message was: Hello, world!"
def test_websocket_iter_json(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.accept()
async for data in websocket.iter_json():
await websocket.send_json({"message": data})
client = test_client_factory(app)
with client.websocket_connect("/") as websocket:
websocket.send_json({"hello": "world"})
data = websocket.receive_json()
assert data == {"message": {"hello": "world"}}
def test_websocket_concurrency_pattern(test_client_factory: TestClientFactory) -> None:
stream_send: ObjectSendStream[MutableMapping[str, Any]]
stream_receive: ObjectReceiveStream[MutableMapping[str, Any]]
stream_send, stream_receive = anyio.create_memory_object_stream()
async def reader(websocket: WebSocket) -> None:
async with stream_send:
async for data in websocket.iter_json():
await stream_send.send(data)
async def writer(websocket: WebSocket) -> None:
async with stream_receive:
async for message in stream_receive:
await websocket.send_json(message)
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.accept()
async with anyio.create_task_group() as task_group:
task_group.start_soon(reader, websocket)
await writer(websocket)
await websocket.close()
client = test_client_factory(app)
with client.websocket_connect("/") as websocket:
websocket.send_json({"hello": "world"})
data = websocket.receive_json()
assert data == {"hello": "world"}
def test_client_close(test_client_factory: TestClientFactory) -> None:
close_code = None
close_reason = None
async def app(scope: Scope, receive: Receive, send: Send) -> None:
nonlocal close_code, close_reason
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.accept()
try:
await websocket.receive_text()
except WebSocketDisconnect as exc:
close_code = exc.code
close_reason = exc.reason
client = test_client_factory(app)
with client.websocket_connect("/") as websocket:
websocket.close(code=status.WS_1001_GOING_AWAY, reason="Going Away")
assert close_code == status.WS_1001_GOING_AWAY
assert close_reason == "Going Away"
@pytest.mark.anyio
async def test_client_disconnect_on_send() -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.accept()
await websocket.send_text("Hello, world!")
async def receive() -> Message:
return {"type": "websocket.connect"}
async def send(message: Message) -> None:
if message["type"] == "websocket.accept":
return
# Simulate the exception the server would send to the application when the client disconnects.
raise OSError
with pytest.raises(WebSocketDisconnect) as ctx:
await app({"type": "websocket", "path": "/"}, receive, send)
assert ctx.value.code == status.WS_1006_ABNORMAL_CLOSURE
def test_application_close(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.accept()
await websocket.close(status.WS_1001_GOING_AWAY)
client = test_client_factory(app)
with client.websocket_connect("/") as websocket:
with pytest.raises(WebSocketDisconnect) as exc:
websocket.receive_text()
assert exc.value.code == status.WS_1001_GOING_AWAY
def test_rejected_connection(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
msg = await websocket.receive()
assert msg == {"type": "websocket.connect"}
await websocket.close(status.WS_1001_GOING_AWAY)
client = test_client_factory(app)
with pytest.raises(WebSocketDisconnect) as exc:
with client.websocket_connect("/"):
pass # pragma: no cover
assert exc.value.code == status.WS_1001_GOING_AWAY
def test_send_denial_response(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
msg = await websocket.receive()
assert msg == {"type": "websocket.connect"}
response = Response(status_code=404, content="foo")
await websocket.send_denial_response(response)
client = test_client_factory(app)
with pytest.raises(WebSocketDenialResponse) as exc:
with client.websocket_connect("/"):
pass # pragma: no cover
assert exc.value.status_code == 404
assert exc.value.content == b"foo"
def test_send_response_multi(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
msg = await websocket.receive()
assert msg == {"type": "websocket.connect"}
await websocket.send(
{
"type": "websocket.http.response.start",
"status": 404,
"headers": [(b"content-type", b"text/plain"), (b"foo", b"bar")],
}
)
await websocket.send({"type": "websocket.http.response.body", "body": b"hard", "more_body": True})
await websocket.send({"type": "websocket.http.response.body", "body": b"body"})
client = test_client_factory(app)
with pytest.raises(WebSocketDenialResponse) as exc:
with client.websocket_connect("/"):
pass # pragma: no cover
assert exc.value.status_code == 404
assert exc.value.content == b"hardbody"
assert exc.value.headers["foo"] == "bar"
def test_send_response_unsupported(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
del scope["extensions"]["websocket.http.response"]
websocket = WebSocket(scope, receive=receive, send=send)
msg = await websocket.receive()
assert msg == {"type": "websocket.connect"}
response = Response(status_code=404, content="foo")
with pytest.raises(
RuntimeError,
match="The server doesn't support the Websocket Denial Response extension.",
):
await websocket.send_denial_response(response)
await websocket.close()
client = test_client_factory(app)
with pytest.raises(WebSocketDisconnect) as exc:
with client.websocket_connect("/"):
pass # pragma: no cover
assert exc.value.code == status.WS_1000_NORMAL_CLOSURE
def test_send_response_duplicate_start(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
msg = await websocket.receive()
assert msg == {"type": "websocket.connect"}
response = Response(status_code=404, content="foo")
await websocket.send(
{
"type": "websocket.http.response.start",
"status": response.status_code,
"headers": response.raw_headers,
}
)
await websocket.send(
{
"type": "websocket.http.response.start",
"status": response.status_code,
"headers": response.raw_headers,
}
)
client = test_client_factory(app)
with pytest.raises(
RuntimeError,
match=("Expected ASGI message \"websocket.http.response.body\", but got 'websocket.http.response.start'"),
):
with client.websocket_connect("/"):
pass # pragma: no cover
def test_subprotocol(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
assert websocket["subprotocols"] == ["soap", "wamp"]
await websocket.accept(subprotocol="wamp")
await websocket.close()
client = test_client_factory(app)
with client.websocket_connect("/", subprotocols=["soap", "wamp"]) as websocket:
assert websocket.accepted_subprotocol == "wamp"
def test_additional_headers(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.accept(headers=[(b"additional", b"header")])
await websocket.close()
client = test_client_factory(app)
with client.websocket_connect("/") as websocket:
assert websocket.extra_headers == [(b"additional", b"header")]
def test_no_additional_headers(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.accept()
await websocket.close()
client = test_client_factory(app)
with client.websocket_connect("/") as websocket:
assert websocket.extra_headers == []
def test_websocket_exception(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
assert False
client = test_client_factory(app)
with pytest.raises(AssertionError):
with client.websocket_connect("/123?a=abc"):
pass # pragma: no cover
def test_duplicate_close(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.accept()
await websocket.close()
await websocket.close()
client = test_client_factory(app)
with pytest.raises(RuntimeError):
with client.websocket_connect("/"):
pass # pragma: no cover
def test_duplicate_disconnect(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.accept()
message = await websocket.receive()
assert message["type"] == "websocket.disconnect"
message = await websocket.receive()
client = test_client_factory(app)
with pytest.raises(RuntimeError):
with client.websocket_connect("/") as websocket:
websocket.close()
def test_websocket_scope_interface() -> None:
"""
A WebSocket can be instantiated with a scope, and presents a `Mapping`
interface.
"""
async def mock_receive() -> Message: # type: ignore
... # pragma: no cover
async def mock_send(message: Message) -> None: ... # pragma: no cover
websocket = WebSocket({"type": "websocket", "path": "/abc/", "headers": []}, receive=mock_receive, send=mock_send)
assert websocket["type"] == "websocket"
assert dict(websocket) == {"type": "websocket", "path": "/abc/", "headers": []}
assert len(websocket) == 3
# check __eq__ and __hash__
assert websocket != WebSocket(
{"type": "websocket", "path": "/abc/", "headers": []},
receive=mock_receive,
send=mock_send,
)
assert websocket == websocket
assert websocket in {websocket}
assert {websocket} == {websocket}
def test_websocket_close_reason(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.accept()
await websocket.close(code=status.WS_1001_GOING_AWAY, reason="Going Away")
client = test_client_factory(app)
with client.websocket_connect("/") as websocket:
with pytest.raises(WebSocketDisconnect) as exc:
websocket.receive_text()
assert exc.value.code == status.WS_1001_GOING_AWAY
assert exc.value.reason == "Going Away"
def test_send_json_invalid_mode(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.accept()
await websocket.send_json({}, mode="invalid")
client = test_client_factory(app)
with pytest.raises(RuntimeError):
with client.websocket_connect("/"):
pass # pragma: no cover
def test_receive_json_invalid_mode(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.accept()
await websocket.receive_json(mode="invalid")
client = test_client_factory(app)
with pytest.raises(RuntimeError):
with client.websocket_connect("/"):
pass # pragma: no cover
def test_receive_text_before_accept(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.receive_text()
client = test_client_factory(app)
with pytest.raises(RuntimeError):
with client.websocket_connect("/"):
pass # pragma: no cover
def test_receive_bytes_before_accept(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.receive_bytes()
client = test_client_factory(app)
with pytest.raises(RuntimeError):
with client.websocket_connect("/"):
pass # pragma: no cover
def test_receive_json_before_accept(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.receive_json()
client = test_client_factory(app)
with pytest.raises(RuntimeError):
with client.websocket_connect("/"):
pass # pragma: no cover
def test_send_before_accept(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.send({"type": "websocket.send"})
client = test_client_factory(app)
with pytest.raises(RuntimeError):
with client.websocket_connect("/"):
pass # pragma: no cover
def test_send_wrong_message_type(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.send({"type": "websocket.accept"})
await websocket.send({"type": "websocket.accept"})
client = test_client_factory(app)
with pytest.raises(RuntimeError):
with client.websocket_connect("/"):
pass # pragma: no cover
def test_receive_before_accept(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.accept()
websocket.client_state = WebSocketState.CONNECTING
await websocket.receive()
client = test_client_factory(app)
with pytest.raises(RuntimeError):
with client.websocket_connect("/") as websocket:
websocket.send({"type": "websocket.send"})
def test_receive_wrong_message_type(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.accept()
await websocket.receive()
client = test_client_factory(app)
with pytest.raises(RuntimeError):
with client.websocket_connect("/") as websocket:
websocket.send({"type": "websocket.connect"})
| starlette |
python | from __future__ import annotations
from collections.abc import Callable, Sequence
from typing import Any, ParamSpec
from starlette._utils import is_async_callable
from starlette.concurrency import run_in_threadpool
P = ParamSpec("P")
class BackgroundTask:
def __init__(self, func: Callable[P, Any], *args: P.args, **kwargs: P.kwargs) -> None:
self.func = func
self.args = args
self.kwargs = kwargs
self.is_async = is_async_callable(func)
async def __call__(self) -> None:
if self.is_async:
await self.func(*self.args, **self.kwargs)
else:
await run_in_threadpool(self.func, *self.args, **self.kwargs)
class BackgroundTasks(BackgroundTask):
def __init__(self, tasks: Sequence[BackgroundTask] | None = None):
self.tasks = list(tasks) if tasks else []
def add_task(self, func: Callable[P, Any], *args: P.args, **kwargs: P.kwargs) -> None:
task = BackgroundTask(func, *args, **kwargs)
self.tasks.append(task)
async def __call__(self) -> None:
for task in self.tasks:
await task()
| import pytest
from starlette.background import BackgroundTask, BackgroundTasks
from starlette.responses import Response
from starlette.types import Receive, Scope, Send
from tests.types import TestClientFactory
def test_async_task(test_client_factory: TestClientFactory) -> None:
TASK_COMPLETE = False
async def async_task() -> None:
nonlocal TASK_COMPLETE
TASK_COMPLETE = True
task = BackgroundTask(async_task)
async def app(scope: Scope, receive: Receive, send: Send) -> None:
response = Response("task initiated", media_type="text/plain", background=task)
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/")
assert response.text == "task initiated"
assert TASK_COMPLETE
def test_sync_task(test_client_factory: TestClientFactory) -> None:
TASK_COMPLETE = False
def sync_task() -> None:
nonlocal TASK_COMPLETE
TASK_COMPLETE = True
task = BackgroundTask(sync_task)
async def app(scope: Scope, receive: Receive, send: Send) -> None:
response = Response("task initiated", media_type="text/plain", background=task)
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/")
assert response.text == "task initiated"
assert TASK_COMPLETE
def test_multiple_tasks(test_client_factory: TestClientFactory) -> None:
TASK_COUNTER = 0
def increment(amount: int) -> None:
nonlocal TASK_COUNTER
TASK_COUNTER += amount
async def app(scope: Scope, receive: Receive, send: Send) -> None:
tasks = BackgroundTasks()
tasks.add_task(increment, amount=1)
tasks.add_task(increment, amount=2)
tasks.add_task(increment, amount=3)
response = Response("tasks initiated", media_type="text/plain", background=tasks)
await response(scope, receive, send)
client = test_client_factory(app)
response = client.get("/")
assert response.text == "tasks initiated"
assert TASK_COUNTER == 1 + 2 + 3
def test_multi_tasks_failure_avoids_next_execution(
test_client_factory: TestClientFactory,
) -> None:
TASK_COUNTER = 0
def increment() -> None:
nonlocal TASK_COUNTER
TASK_COUNTER += 1
if TASK_COUNTER == 1: # pragma: no branch
raise Exception("task failed")
async def app(scope: Scope, receive: Receive, send: Send) -> None:
tasks = BackgroundTasks()
tasks.add_task(increment)
tasks.add_task(increment)
response = Response("tasks initiated", media_type="text/plain", background=tasks)
await response(scope, receive, send)
client = test_client_factory(app)
with pytest.raises(Exception):
client.get("/")
assert TASK_COUNTER == 1
| starlette |
python | from __future__ import annotations
from collections.abc import ItemsView, Iterable, Iterator, KeysView, Mapping, MutableMapping, Sequence, ValuesView
from shlex import shlex
from typing import (
Any,
BinaryIO,
NamedTuple,
TypeVar,
cast,
)
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from starlette.concurrency import run_in_threadpool
from starlette.types import Scope
class Address(NamedTuple):
host: str
port: int
_KeyType = TypeVar("_KeyType")
# Mapping keys are invariant but their values are covariant since
# you can only read them
# that is, you can't do `Mapping[str, Animal]()["fido"] = Dog()`
_CovariantValueType = TypeVar("_CovariantValueType", covariant=True)
class URL:
def __init__(
self,
url: str = "",
scope: Scope | None = None,
**components: Any,
) -> None:
if scope is not None:
assert not url, 'Cannot set both "url" and "scope".'
assert not components, 'Cannot set both "scope" and "**components".'
scheme = scope.get("scheme", "http")
server = scope.get("server", None)
path = scope["path"]
query_string = scope.get("query_string", b"")
host_header = None
for key, value in scope["headers"]:
if key == b"host":
host_header = value.decode("latin-1")
break
if host_header is not None:
url = f"{scheme}://{host_header}{path}"
elif server is None:
url = path
else:
host, port = server
default_port = {"http": 80, "https": 443, "ws": 80, "wss": 443}[scheme]
if port == default_port:
url = f"{scheme}://{host}{path}"
else:
url = f"{scheme}://{host}:{port}{path}"
if query_string:
url += "?" + query_string.decode()
elif components:
assert not url, 'Cannot set both "url" and "**components".'
url = URL("").replace(**components).components.geturl()
self._url = url
@property
def components(self) -> SplitResult:
if not hasattr(self, "_components"):
self._components = urlsplit(self._url)
return self._components
@property
def scheme(self) -> str:
return self.components.scheme
@property
def netloc(self) -> str:
return self.components.netloc
@property
def path(self) -> str:
return self.components.path
@property
def query(self) -> str:
return self.components.query
@property
def fragment(self) -> str:
return self.components.fragment
@property
def username(self) -> None | str:
return self.components.username
@property
def password(self) -> None | str:
return self.components.password
@property
def hostname(self) -> None | str:
return self.components.hostname
@property
def port(self) -> int | None:
return self.components.port
@property
def is_secure(self) -> bool:
return self.scheme in ("https", "wss")
def replace(self, **kwargs: Any) -> URL:
if "username" in kwargs or "password" in kwargs or "hostname" in kwargs or "port" in kwargs:
hostname = kwargs.pop("hostname", None)
port = kwargs.pop("port", self.port)
username = kwargs.pop("username", self.username)
password = kwargs.pop("password", self.password)
if hostname is None:
netloc = self.netloc
_, _, hostname = netloc.rpartition("@")
if hostname[-1] != "]":
hostname = hostname.rsplit(":", 1)[0]
netloc = hostname
if port is not None:
netloc += f":{port}"
if username is not None:
userpass = username
if password is not None:
userpass += f":{password}"
netloc = f"{userpass}@{netloc}"
kwargs["netloc"] = netloc
components = self.components._replace(**kwargs)
return self.__class__(components.geturl())
def include_query_params(self, **kwargs: Any) -> URL:
params = MultiDict(parse_qsl(self.query, keep_blank_values=True))
params.update({str(key): str(value) for key, value in kwargs.items()})
query = urlencode(params.multi_items())
return self.replace(query=query)
def replace_query_params(self, **kwargs: Any) -> URL:
query = urlencode([(str(key), str(value)) for key, value in kwargs.items()])
return self.replace(query=query)
def remove_query_params(self, keys: str | Sequence[str]) -> URL:
if isinstance(keys, str):
keys = [keys]
params = MultiDict(parse_qsl(self.query, keep_blank_values=True))
for key in keys:
params.pop(key, None)
query = urlencode(params.multi_items())
return self.replace(query=query)
def __eq__(self, other: Any) -> bool:
return str(self) == str(other)
def __str__(self) -> str:
return self._url
def __repr__(self) -> str:
url = str(self)
if self.password:
url = str(self.replace(password="********"))
return f"{self.__class__.__name__}({repr(url)})"
class URLPath(str):
"""
A URL path string that may also hold an associated protocol and/or host.
Used by the routing to return `url_path_for` matches.
"""
def __new__(cls, path: str, protocol: str = "", host: str = "") -> URLPath:
assert protocol in ("http", "websocket", "")
return str.__new__(cls, path)
def __init__(self, path: str, protocol: str = "", host: str = "") -> None:
self.protocol = protocol
self.host = host
def make_absolute_url(self, base_url: str | URL) -> URL:
if isinstance(base_url, str):
base_url = URL(base_url)
if self.protocol:
scheme = {
"http": {True: "https", False: "http"},
"websocket": {True: "wss", False: "ws"},
}[self.protocol][base_url.is_secure]
else:
scheme = base_url.scheme
netloc = self.host or base_url.netloc
path = base_url.path.rstrip("/") + str(self)
return URL(scheme=scheme, netloc=netloc, path=path)
class Secret:
"""
Holds a string value that should not be revealed in tracebacks etc.
You should cast the value to `str` at the point it is required.
"""
def __init__(self, value: str):
self._value = value
def __repr__(self) -> str:
class_name = self.__class__.__name__
return f"{class_name}('**********')"
def __str__(self) -> str:
return self._value
def __bool__(self) -> bool:
return bool(self._value)
class CommaSeparatedStrings(Sequence[str]):
def __init__(self, value: str | Sequence[str]):
if isinstance(value, str):
splitter = shlex(value, posix=True)
splitter.whitespace = ","
splitter.whitespace_split = True
self._items = [item.strip() for item in splitter]
else:
self._items = list(value)
def __len__(self) -> int:
return len(self._items)
def __getitem__(self, index: int | slice) -> Any:
return self._items[index]
def __iter__(self) -> Iterator[str]:
return iter(self._items)
def __repr__(self) -> str:
class_name = self.__class__.__name__
items = [item for item in self]
return f"{class_name}({items!r})"
def __str__(self) -> str:
return ", ".join(repr(item) for item in self)
class ImmutableMultiDict(Mapping[_KeyType, _CovariantValueType]):
_dict: dict[_KeyType, _CovariantValueType]
def __init__(
self,
*args: ImmutableMultiDict[_KeyType, _CovariantValueType]
| Mapping[_KeyType, _CovariantValueType]
| Iterable[tuple[_KeyType, _CovariantValueType]],
**kwargs: Any,
) -> None:
assert len(args) < 2, "Too many arguments."
value: Any = args[0] if args else []
if kwargs:
value = ImmutableMultiDict(value).multi_items() + ImmutableMultiDict(kwargs).multi_items()
if not value:
_items: list[tuple[Any, Any]] = []
elif hasattr(value, "multi_items"):
value = cast(ImmutableMultiDict[_KeyType, _CovariantValueType], value)
_items = list(value.multi_items())
elif hasattr(value, "items"):
value = cast(Mapping[_KeyType, _CovariantValueType], value)
_items = list(value.items())
else:
value = cast("list[tuple[Any, Any]]", value)
_items = list(value)
self._dict = {k: v for k, v in _items}
self._list = _items
def getlist(self, key: Any) -> list[_CovariantValueType]:
return [item_value for item_key, item_value in self._list if item_key == key]
def keys(self) -> KeysView[_KeyType]:
return self._dict.keys()
def values(self) -> ValuesView[_CovariantValueType]:
return self._dict.values()
def items(self) -> ItemsView[_KeyType, _CovariantValueType]:
return self._dict.items()
def multi_items(self) -> list[tuple[_KeyType, _CovariantValueType]]:
return list(self._list)
def __getitem__(self, key: _KeyType) -> _CovariantValueType:
return self._dict[key]
def __contains__(self, key: Any) -> bool:
return key in self._dict
def __iter__(self) -> Iterator[_KeyType]:
return iter(self.keys())
def __len__(self) -> int:
return len(self._dict)
def __eq__(self, other: Any) -> bool:
if not isinstance(other, self.__class__):
return False
return sorted(self._list) == sorted(other._list)
def __repr__(self) -> str:
class_name = self.__class__.__name__
items = self.multi_items()
return f"{class_name}({items!r})"
class MultiDict(ImmutableMultiDict[Any, Any]):
def __setitem__(self, key: Any, value: Any) -> None:
self.setlist(key, [value])
def __delitem__(self, key: Any) -> None:
self._list = [(k, v) for k, v in self._list if k != key]
del self._dict[key]
def pop(self, key: Any, default: Any = None) -> Any:
self._list = [(k, v) for k, v in self._list if k != key]
return self._dict.pop(key, default)
def popitem(self) -> tuple[Any, Any]:
key, value = self._dict.popitem()
self._list = [(k, v) for k, v in self._list if k != key]
return key, value
def poplist(self, key: Any) -> list[Any]:
values = [v for k, v in self._list if k == key]
self.pop(key)
return values
def clear(self) -> None:
self._dict.clear()
self._list.clear()
def setdefault(self, key: Any, default: Any = None) -> Any:
if key not in self:
self._dict[key] = default
self._list.append((key, default))
return self[key]
def setlist(self, key: Any, values: list[Any]) -> None:
if not values:
self.pop(key, None)
else:
existing_items = [(k, v) for (k, v) in self._list if k != key]
self._list = existing_items + [(key, value) for value in values]
self._dict[key] = values[-1]
def append(self, key: Any, value: Any) -> None:
self._list.append((key, value))
self._dict[key] = value
def update(
self,
*args: MultiDict | Mapping[Any, Any] | list[tuple[Any, Any]],
**kwargs: Any,
) -> None:
value = MultiDict(*args, **kwargs)
existing_items = [(k, v) for (k, v) in self._list if k not in value.keys()]
self._list = existing_items + value.multi_items()
self._dict.update(value)
class QueryParams(ImmutableMultiDict[str, str]):
"""
An immutable multidict.
"""
def __init__(
self,
*args: ImmutableMultiDict[Any, Any] | Mapping[Any, Any] | list[tuple[Any, Any]] | str | bytes,
**kwargs: Any,
) -> None:
assert len(args) < 2, "Too many arguments."
value = args[0] if args else []
if isinstance(value, str):
super().__init__(parse_qsl(value, keep_blank_values=True), **kwargs)
elif isinstance(value, bytes):
super().__init__(parse_qsl(value.decode("latin-1"), keep_blank_values=True), **kwargs)
else:
super().__init__(*args, **kwargs) # type: ignore[arg-type]
self._list = [(str(k), str(v)) for k, v in self._list]
self._dict = {str(k): str(v) for k, v in self._dict.items()}
def __str__(self) -> str:
return urlencode(self._list)
def __repr__(self) -> str:
class_name = self.__class__.__name__
query_string = str(self)
return f"{class_name}({query_string!r})"
class UploadFile:
"""
An uploaded file included as part of the request data.
"""
def __init__(
self,
file: BinaryIO,
*,
size: int | None = None,
filename: str | None = None,
headers: Headers | None = None,
) -> None:
self.filename = filename
self.file = file
self.size = size
self.headers = headers or Headers()
# Capture max size from SpooledTemporaryFile if one is provided. This slightly speeds up future checks.
# Note 0 means unlimited mirroring SpooledTemporaryFile's __init__
self._max_mem_size = getattr(self.file, "_max_size", 0)
@property
def content_type(self) -> str | None:
return self.headers.get("content-type", None)
@property
def _in_memory(self) -> bool:
# check for SpooledTemporaryFile._rolled
rolled_to_disk = getattr(self.file, "_rolled", True)
return not rolled_to_disk
def _will_roll(self, size_to_add: int) -> bool:
# If we're not in_memory then we will always roll
if not self._in_memory:
return True
# Check for SpooledTemporaryFile._max_size
future_size = self.file.tell() + size_to_add
return bool(future_size > self._max_mem_size) if self._max_mem_size else False
async def write(self, data: bytes) -> None:
new_data_len = len(data)
if self.size is not None:
self.size += new_data_len
if self._will_roll(new_data_len):
await run_in_threadpool(self.file.write, data)
else:
self.file.write(data)
async def read(self, size: int = -1) -> bytes:
if self._in_memory:
return self.file.read(size)
return await run_in_threadpool(self.file.read, size)
async def seek(self, offset: int) -> None:
if self._in_memory:
self.file.seek(offset)
else:
await run_in_threadpool(self.file.seek, offset)
async def close(self) -> None:
if self._in_memory:
self.file.close()
else:
await run_in_threadpool(self.file.close)
def __repr__(self) -> str:
return f"{self.__class__.__name__}(filename={self.filename!r}, size={self.size!r}, headers={self.headers!r})"
class FormData(ImmutableMultiDict[str, UploadFile | str]):
"""
An immutable multidict, containing both file uploads and text input.
"""
def __init__(
self,
*args: FormData | Mapping[str, str | UploadFile] | list[tuple[str, str | UploadFile]],
**kwargs: str | UploadFile,
) -> None:
super().__init__(*args, **kwargs)
async def close(self) -> None:
for key, value in self.multi_items():
if isinstance(value, UploadFile):
await value.close()
class Headers(Mapping[str, str]):
"""
An immutable, case-insensitive multidict.
"""
def __init__(
self,
headers: Mapping[str, str] | None = None,
raw: list[tuple[bytes, bytes]] | None = None,
scope: MutableMapping[str, Any] | None = None,
) -> None:
self._list: list[tuple[bytes, bytes]] = []
if headers is not None:
assert raw is None, 'Cannot set both "headers" and "raw".'
assert scope is None, 'Cannot set both "headers" and "scope".'
self._list = [(key.lower().encode("latin-1"), value.encode("latin-1")) for key, value in headers.items()]
elif raw is not None:
assert scope is None, 'Cannot set both "raw" and "scope".'
self._list = raw
elif scope is not None:
# scope["headers"] isn't necessarily a list
# it might be a tuple or other iterable
self._list = scope["headers"] = list(scope["headers"])
@property
def raw(self) -> list[tuple[bytes, bytes]]:
return list(self._list)
def keys(self) -> list[str]: # type: ignore[override]
return [key.decode("latin-1") for key, value in self._list]
def values(self) -> list[str]: # type: ignore[override]
return [value.decode("latin-1") for key, value in self._list]
def items(self) -> list[tuple[str, str]]: # type: ignore[override]
return [(key.decode("latin-1"), value.decode("latin-1")) for key, value in self._list]
def getlist(self, key: str) -> list[str]:
get_header_key = key.lower().encode("latin-1")
return [item_value.decode("latin-1") for item_key, item_value in self._list if item_key == get_header_key]
def mutablecopy(self) -> MutableHeaders:
return MutableHeaders(raw=self._list[:])
def __getitem__(self, key: str) -> str:
get_header_key = key.lower().encode("latin-1")
for header_key, header_value in self._list:
if header_key == get_header_key:
return header_value.decode("latin-1")
raise KeyError(key)
def __contains__(self, key: Any) -> bool:
get_header_key = key.lower().encode("latin-1")
for header_key, header_value in self._list:
if header_key == get_header_key:
return True
return False
def __iter__(self) -> Iterator[Any]:
return iter(self.keys())
def __len__(self) -> int:
return len(self._list)
def __eq__(self, other: Any) -> bool:
if not isinstance(other, Headers):
return False
return sorted(self._list) == sorted(other._list)
def __repr__(self) -> str:
class_name = self.__class__.__name__
as_dict = dict(self.items())
if len(as_dict) == len(self):
return f"{class_name}({as_dict!r})"
return f"{class_name}(raw={self.raw!r})"
class MutableHeaders(Headers):
def __setitem__(self, key: str, value: str) -> None:
"""
Set the header `key` to `value`, removing any duplicate entries.
Retains insertion order.
"""
set_key = key.lower().encode("latin-1")
set_value = value.encode("latin-1")
found_indexes: list[int] = []
for idx, (item_key, item_value) in enumerate(self._list):
if item_key == set_key:
found_indexes.append(idx)
for idx in reversed(found_indexes[1:]):
del self._list[idx]
if found_indexes:
idx = found_indexes[0]
self._list[idx] = (set_key, set_value)
else:
self._list.append((set_key, set_value))
def __delitem__(self, key: str) -> None:
"""
Remove the header `key`.
"""
del_key = key.lower().encode("latin-1")
pop_indexes: list[int] = []
for idx, (item_key, item_value) in enumerate(self._list):
if item_key == del_key:
pop_indexes.append(idx)
for idx in reversed(pop_indexes):
del self._list[idx]
def __ior__(self, other: Mapping[str, str]) -> MutableHeaders:
if not isinstance(other, Mapping):
raise TypeError(f"Expected a mapping but got {other.__class__.__name__}")
self.update(other)
return self
def __or__(self, other: Mapping[str, str]) -> MutableHeaders:
if not isinstance(other, Mapping):
raise TypeError(f"Expected a mapping but got {other.__class__.__name__}")
new = self.mutablecopy()
new.update(other)
return new
@property
def raw(self) -> list[tuple[bytes, bytes]]:
return self._list
def setdefault(self, key: str, value: str) -> str:
"""
If the header `key` does not exist, then set it to `value`.
Returns the header value.
"""
set_key = key.lower().encode("latin-1")
set_value = value.encode("latin-1")
for idx, (item_key, item_value) in enumerate(self._list):
if item_key == set_key:
return item_value.decode("latin-1")
self._list.append((set_key, set_value))
return value
def update(self, other: Mapping[str, str]) -> None:
for key, val in other.items():
self[key] = val
def append(self, key: str, value: str) -> None:
"""
Append a header, preserving any duplicate entries.
"""
append_key = key.lower().encode("latin-1")
append_value = value.encode("latin-1")
self._list.append((append_key, append_value))
def add_vary_header(self, vary: str) -> None:
existing = self.get("vary")
if existing is not None:
vary = ", ".join([existing, vary])
self["vary"] = vary
class State:
"""
An object that can be used to store arbitrary state.
Used for `request.state` and `app.state`.
"""
_state: dict[str, Any]
def __init__(self, state: dict[str, Any] | None = None):
if state is None:
state = {}
super().__setattr__("_state", state)
def __setattr__(self, key: Any, value: Any) -> None:
self._state[key] = value
def __getattr__(self, key: Any) -> Any:
try:
return self._state[key]
except KeyError:
message = "'{}' object has no attribute '{}'"
raise AttributeError(message.format(self.__class__.__name__, key))
def __delattr__(self, key: Any) -> None:
del self._state[key]
| import io
from tempfile import SpooledTemporaryFile
from typing import BinaryIO
import pytest
from starlette.datastructures import (
URL,
CommaSeparatedStrings,
FormData,
Headers,
MultiDict,
MutableHeaders,
QueryParams,
UploadFile,
)
def test_url() -> None:
u = URL("https://example.org:123/path/to/somewhere?abc=123#anchor")
assert u.scheme == "https"
assert u.hostname == "example.org"
assert u.port == 123
assert u.netloc == "example.org:123"
assert u.username is None
assert u.password is None
assert u.path == "/path/to/somewhere"
assert u.query == "abc=123"
assert u.fragment == "anchor"
new = u.replace(scheme="http")
assert new == "http://example.org:123/path/to/somewhere?abc=123#anchor"
assert new.scheme == "http"
new = u.replace(port=None)
assert new == "https://example.org/path/to/somewhere?abc=123#anchor"
assert new.port is None
new = u.replace(hostname="example.com")
assert new == "https://example.com:123/path/to/somewhere?abc=123#anchor"
assert new.hostname == "example.com"
ipv6_url = URL("https://[fe::2]:12345")
new = ipv6_url.replace(port=8080)
assert new == "https://[fe::2]:8080"
new = ipv6_url.replace(username="username", password="password")
assert new == "https://username:password@[fe::2]:12345"
assert new.netloc == "username:password@[fe::2]:12345"
ipv6_url = URL("https://[fe::2]")
new = ipv6_url.replace(port=123)
assert new == "https://[fe::2]:123"
url = URL("http://u:p@host/")
assert url.replace(hostname="bar") == URL("http://u:p@bar/")
url = URL("http://u:p@host:80")
assert url.replace(port=88) == URL("http://u:p@host:88")
url = URL("http://host:80")
assert url.replace(username="u") == URL("http://u@host:80")
def test_url_query_params() -> None:
u = URL("https://example.org/path/?page=3")
assert u.query == "page=3"
u = u.include_query_params(page=4)
assert str(u) == "https://example.org/path/?page=4"
u = u.include_query_params(search="testing")
assert str(u) == "https://example.org/path/?page=4&search=testing"
u = u.replace_query_params(order="name")
assert str(u) == "https://example.org/path/?order=name"
u = u.remove_query_params("order")
assert str(u) == "https://example.org/path/"
u = u.include_query_params(page=4, search="testing")
assert str(u) == "https://example.org/path/?page=4&search=testing"
u = u.remove_query_params(["page", "search"])
assert str(u) == "https://example.org/path/"
def test_hidden_password() -> None:
u = URL("https://example.org/path/to/somewhere")
assert repr(u) == "URL('https://example.org/path/to/somewhere')"
u = URL("https://username@example.org/path/to/somewhere")
assert repr(u) == "URL('https://username@example.org/path/to/somewhere')"
u = URL("https://username:password@example.org/path/to/somewhere")
assert repr(u) == "URL('https://username:********@example.org/path/to/somewhere')"
def test_csv() -> None:
csv = CommaSeparatedStrings('"localhost", "127.0.0.1", 0.0.0.0')
assert list(csv) == ["localhost", "127.0.0.1", "0.0.0.0"]
assert repr(csv) == "CommaSeparatedStrings(['localhost', '127.0.0.1', '0.0.0.0'])"
assert str(csv) == "'localhost', '127.0.0.1', '0.0.0.0'"
assert csv[0] == "localhost"
assert len(csv) == 3
csv = CommaSeparatedStrings("'localhost', '127.0.0.1', 0.0.0.0")
assert list(csv) == ["localhost", "127.0.0.1", "0.0.0.0"]
assert repr(csv) == "CommaSeparatedStrings(['localhost', '127.0.0.1', '0.0.0.0'])"
assert str(csv) == "'localhost', '127.0.0.1', '0.0.0.0'"
csv = CommaSeparatedStrings("localhost, 127.0.0.1, 0.0.0.0")
assert list(csv) == ["localhost", "127.0.0.1", "0.0.0.0"]
assert repr(csv) == "CommaSeparatedStrings(['localhost', '127.0.0.1', '0.0.0.0'])"
assert str(csv) == "'localhost', '127.0.0.1', '0.0.0.0'"
csv = CommaSeparatedStrings(["localhost", "127.0.0.1", "0.0.0.0"])
assert list(csv) == ["localhost", "127.0.0.1", "0.0.0.0"]
assert repr(csv) == "CommaSeparatedStrings(['localhost', '127.0.0.1', '0.0.0.0'])"
assert str(csv) == "'localhost', '127.0.0.1', '0.0.0.0'"
def test_url_from_scope() -> None:
u = URL(scope={"path": "/path/to/somewhere", "query_string": b"abc=123", "headers": []})
assert u == "/path/to/somewhere?abc=123"
assert repr(u) == "URL('/path/to/somewhere?abc=123')"
u = URL(
scope={
"scheme": "https",
"server": ("example.org", 123),
"path": "/path/to/somewhere",
"query_string": b"abc=123",
"headers": [],
}
)
assert u == "https://example.org:123/path/to/somewhere?abc=123"
assert repr(u) == "URL('https://example.org:123/path/to/somewhere?abc=123')"
u = URL(
scope={
"scheme": "https",
"server": ("example.org", 443),
"path": "/path/to/somewhere",
"query_string": b"abc=123",
"headers": [],
}
)
assert u == "https://example.org/path/to/somewhere?abc=123"
assert repr(u) == "URL('https://example.org/path/to/somewhere?abc=123')"
u = URL(
scope={
"scheme": "http",
"path": "/some/path",
"query_string": b"query=string",
"headers": [
(b"content-type", b"text/html"),
(b"host", b"example.com:8000"),
(b"accept", b"text/html"),
],
}
)
assert u == "http://example.com:8000/some/path?query=string"
assert repr(u) == "URL('http://example.com:8000/some/path?query=string')"
def test_headers() -> None:
h = Headers(raw=[(b"a", b"123"), (b"a", b"456"), (b"b", b"789")])
assert "a" in h
assert "A" in h
assert "b" in h
assert "B" in h
assert "c" not in h
assert h["a"] == "123"
assert h.get("a") == "123"
assert h.get("nope", default=None) is None
assert h.getlist("a") == ["123", "456"]
assert h.keys() == ["a", "a", "b"]
assert h.values() == ["123", "456", "789"]
assert h.items() == [("a", "123"), ("a", "456"), ("b", "789")]
assert list(h) == ["a", "a", "b"]
assert dict(h) == {"a": "123", "b": "789"}
assert repr(h) == "Headers(raw=[(b'a', b'123'), (b'a', b'456'), (b'b', b'789')])"
assert h == Headers(raw=[(b"a", b"123"), (b"b", b"789"), (b"a", b"456")])
assert h != [(b"a", b"123"), (b"A", b"456"), (b"b", b"789")]
h = Headers({"a": "123", "b": "789"})
assert h["A"] == "123"
assert h["B"] == "789"
assert h.raw == [(b"a", b"123"), (b"b", b"789")]
assert repr(h) == "Headers({'a': '123', 'b': '789'})"
def test_mutable_headers() -> None:
h = MutableHeaders()
assert dict(h) == {}
h["a"] = "1"
assert dict(h) == {"a": "1"}
h["a"] = "2"
assert dict(h) == {"a": "2"}
h.setdefault("a", "3")
assert dict(h) == {"a": "2"}
h.setdefault("b", "4")
assert dict(h) == {"a": "2", "b": "4"}
del h["a"]
assert dict(h) == {"b": "4"}
assert h.raw == [(b"b", b"4")]
def test_mutable_headers_merge() -> None:
h = MutableHeaders()
h = h | MutableHeaders({"a": "1"})
assert isinstance(h, MutableHeaders)
assert dict(h) == {"a": "1"}
assert h.items() == [("a", "1")]
assert h.raw == [(b"a", b"1")]
def test_mutable_headers_merge_dict() -> None:
h = MutableHeaders()
h = h | {"a": "1"}
assert isinstance(h, MutableHeaders)
assert dict(h) == {"a": "1"}
assert h.items() == [("a", "1")]
assert h.raw == [(b"a", b"1")]
def test_mutable_headers_update() -> None:
h = MutableHeaders()
h |= MutableHeaders({"a": "1"})
assert isinstance(h, MutableHeaders)
assert dict(h) == {"a": "1"}
assert h.items() == [("a", "1")]
assert h.raw == [(b"a", b"1")]
def test_mutable_headers_update_dict() -> None:
h = MutableHeaders()
h |= {"a": "1"}
assert isinstance(h, MutableHeaders)
assert dict(h) == {"a": "1"}
assert h.items() == [("a", "1")]
assert h.raw == [(b"a", b"1")]
def test_mutable_headers_merge_not_mapping() -> None:
h = MutableHeaders()
with pytest.raises(TypeError):
h |= {"not_mapping"} # type: ignore[arg-type]
with pytest.raises(TypeError):
h | {"not_mapping"} # type: ignore[operator]
def test_headers_mutablecopy() -> None:
h = Headers(raw=[(b"a", b"123"), (b"a", b"456"), (b"b", b"789")])
c = h.mutablecopy()
assert c.items() == [("a", "123"), ("a", "456"), ("b", "789")]
c["a"] = "abc"
assert c.items() == [("a", "abc"), ("b", "789")]
def test_mutable_headers_from_scope() -> None:
# "headers" in scope must not necessarily be a list
h = MutableHeaders(scope={"headers": ((b"a", b"1"),)})
assert dict(h) == {"a": "1"}
h.update({"b": "2"})
assert dict(h) == {"a": "1", "b": "2"}
assert list(h.items()) == [("a", "1"), ("b", "2")]
assert list(h.raw) == [(b"a", b"1"), (b"b", b"2")]
def test_url_blank_params() -> None:
q = QueryParams("a=123&abc&def&b=456")
assert "a" in q
assert "abc" in q
assert "def" in q
assert "b" in q
val = q.get("abc")
assert val is not None
assert len(val) == 0
assert len(q["a"]) == 3
assert list(q.keys()) == ["a", "abc", "def", "b"]
def test_queryparams() -> None:
q = QueryParams("a=123&a=456&b=789")
assert "a" in q
assert "A" not in q
assert "c" not in q
assert q["a"] == "456"
assert q.get("a") == "456"
assert q.get("nope", default=None) is None
assert q.getlist("a") == ["123", "456"]
assert list(q.keys()) == ["a", "b"]
assert list(q.values()) == ["456", "789"]
assert list(q.items()) == [("a", "456"), ("b", "789")]
assert len(q) == 2
assert list(q) == ["a", "b"]
assert dict(q) == {"a": "456", "b": "789"}
assert str(q) == "a=123&a=456&b=789"
assert repr(q) == "QueryParams('a=123&a=456&b=789')"
assert QueryParams({"a": "123", "b": "456"}) == QueryParams([("a", "123"), ("b", "456")])
assert QueryParams({"a": "123", "b": "456"}) == QueryParams("a=123&b=456")
assert QueryParams({"a": "123", "b": "456"}) == QueryParams({"b": "456", "a": "123"})
assert QueryParams() == QueryParams({})
assert QueryParams([("a", "123"), ("a", "456")]) == QueryParams("a=123&a=456")
assert QueryParams({"a": "123", "b": "456"}) != "invalid"
q = QueryParams([("a", "123"), ("a", "456")])
assert QueryParams(q) == q
@pytest.mark.anyio
async def test_upload_file_file_input() -> None:
"""Test passing file/stream into the UploadFile constructor"""
stream = io.BytesIO(b"data")
file = UploadFile(filename="file", file=stream, size=4)
assert await file.read() == b"data"
assert file.size == 4
await file.write(b" and more data!")
assert await file.read() == b""
assert file.size == 19
await file.seek(0)
assert await file.read() == b"data and more data!"
@pytest.mark.anyio
async def test_upload_file_without_size() -> None:
"""Test passing file/stream into the UploadFile constructor without size"""
stream = io.BytesIO(b"data")
file = UploadFile(filename="file", file=stream)
assert await file.read() == b"data"
assert file.size is None
await file.write(b" and more data!")
assert await file.read() == b""
assert file.size is None
await file.seek(0)
assert await file.read() == b"data and more data!"
@pytest.mark.anyio
@pytest.mark.parametrize("max_size", [1, 1024], ids=["rolled", "unrolled"])
async def test_uploadfile_rolling(max_size: int) -> None:
"""Test that we can r/w to a SpooledTemporaryFile
managed by UploadFile before and after it rolls to disk
"""
stream: BinaryIO = SpooledTemporaryFile( # type: ignore[assignment]
max_size=max_size
)
file = UploadFile(filename="file", file=stream, size=0)
assert await file.read() == b""
assert file.size == 0
await file.write(b"data")
assert await file.read() == b""
assert file.size == 4
await file.seek(0)
assert await file.read() == b"data"
await file.write(b" more")
assert await file.read() == b""
assert file.size == 9
await file.seek(0)
assert await file.read() == b"data more"
assert file.size == 9
await file.close()
def test_formdata() -> None:
stream = io.BytesIO(b"data")
upload = UploadFile(filename="file", file=stream, size=4)
form = FormData([("a", "123"), ("a", "456"), ("b", upload)])
assert "a" in form
assert "A" not in form
assert "c" not in form
assert form["a"] == "456"
assert form.get("a") == "456"
assert form.get("nope", default=None) is None
assert form.getlist("a") == ["123", "456"]
assert list(form.keys()) == ["a", "b"]
assert list(form.values()) == ["456", upload]
assert list(form.items()) == [("a", "456"), ("b", upload)]
assert len(form) == 2
assert list(form) == ["a", "b"]
assert dict(form) == {"a": "456", "b": upload}
assert repr(form) == "FormData([('a', '123'), ('a', '456'), ('b', " + repr(upload) + ")])"
assert FormData(form) == form
assert FormData({"a": "123", "b": "789"}) == FormData([("a", "123"), ("b", "789")])
assert FormData({"a": "123", "b": "789"}) != {"a": "123", "b": "789"}
@pytest.mark.anyio
async def test_upload_file_repr() -> None:
stream = io.BytesIO(b"data")
file = UploadFile(filename="file", file=stream, size=4)
assert repr(file) == "UploadFile(filename='file', size=4, headers=Headers({}))"
@pytest.mark.anyio
async def test_upload_file_repr_headers() -> None:
stream = io.BytesIO(b"data")
file = UploadFile(filename="file", file=stream, headers=Headers({"foo": "bar"}))
assert repr(file) == "UploadFile(filename='file', size=None, headers=Headers({'foo': 'bar'}))"
def test_multidict() -> None:
q = MultiDict([("a", "123"), ("a", "456"), ("b", "789")])
assert "a" in q
assert "A" not in q
assert "c" not in q
assert q["a"] == "456"
assert q.get("a") == "456"
assert q.get("nope", default=None) is None
assert q.getlist("a") == ["123", "456"]
assert list(q.keys()) == ["a", "b"]
assert list(q.values()) == ["456", "789"]
assert list(q.items()) == [("a", "456"), ("b", "789")]
assert len(q) == 2
assert list(q) == ["a", "b"]
assert dict(q) == {"a": "456", "b": "789"}
assert str(q) == "MultiDict([('a', '123'), ('a', '456'), ('b', '789')])"
assert repr(q) == "MultiDict([('a', '123'), ('a', '456'), ('b', '789')])"
assert MultiDict({"a": "123", "b": "456"}) == MultiDict([("a", "123"), ("b", "456")])
assert MultiDict({"a": "123", "b": "456"}) == MultiDict({"b": "456", "a": "123"})
assert MultiDict() == MultiDict({})
assert MultiDict({"a": "123", "b": "456"}) != "invalid"
q = MultiDict([("a", "123"), ("a", "456")])
assert MultiDict(q) == q
q = MultiDict([("a", "123"), ("a", "456")])
q["a"] = "789"
assert q["a"] == "789"
assert q.get("a") == "789"
assert q.getlist("a") == ["789"]
q = MultiDict([("a", "123"), ("a", "456")])
del q["a"]
assert q.get("a") is None
assert repr(q) == "MultiDict([])"
q = MultiDict([("a", "123"), ("a", "456"), ("b", "789")])
assert q.pop("a") == "456"
assert q.get("a", None) is None
assert repr(q) == "MultiDict([('b', '789')])"
q = MultiDict([("a", "123"), ("a", "456"), ("b", "789")])
item = q.popitem()
assert q.get(item[0]) is None
q = MultiDict([("a", "123"), ("a", "456"), ("b", "789")])
assert q.poplist("a") == ["123", "456"]
assert q.get("a") is None
assert repr(q) == "MultiDict([('b', '789')])"
q = MultiDict([("a", "123"), ("a", "456"), ("b", "789")])
q.clear()
assert q.get("a") is None
assert repr(q) == "MultiDict([])"
q = MultiDict([("a", "123")])
q.setlist("a", ["456", "789"])
assert q.getlist("a") == ["456", "789"]
q.setlist("b", [])
assert "b" not in q
q = MultiDict([("a", "123")])
assert q.setdefault("a", "456") == "123"
assert q.getlist("a") == ["123"]
assert q.setdefault("b", "456") == "456"
assert q.getlist("b") == ["456"]
assert repr(q) == "MultiDict([('a', '123'), ('b', '456')])"
q = MultiDict([("a", "123")])
q.append("a", "456")
assert q.getlist("a") == ["123", "456"]
assert repr(q) == "MultiDict([('a', '123'), ('a', '456')])"
q = MultiDict([("a", "123"), ("b", "456")])
q.update({"a": "789"})
assert q.getlist("a") == ["789"]
assert q == MultiDict([("a", "789"), ("b", "456")])
q = MultiDict([("a", "123"), ("b", "456")])
q.update(q)
assert repr(q) == "MultiDict([('a', '123'), ('b', '456')])"
q = MultiDict([("a", "123"), ("a", "456")])
q.update([("a", "123")])
assert q.getlist("a") == ["123"]
q.update([("a", "456")], a="789", b="123")
assert q == MultiDict([("a", "456"), ("a", "789"), ("b", "123")])
| starlette |
python | from __future__ import annotations
import errno
import importlib.util
import os
import stat
from email.utils import parsedate
from typing import Union
import anyio
import anyio.to_thread
from starlette._utils import get_route_path
from starlette.datastructures import URL, Headers
from starlette.exceptions import HTTPException
from starlette.responses import FileResponse, RedirectResponse, Response
from starlette.types import Receive, Scope, Send
PathLike = Union[str, "os.PathLike[str]"]
class NotModifiedResponse(Response):
NOT_MODIFIED_HEADERS = (
"cache-control",
"content-location",
"date",
"etag",
"expires",
"vary",
)
def __init__(self, headers: Headers):
super().__init__(
status_code=304,
headers={name: value for name, value in headers.items() if name in self.NOT_MODIFIED_HEADERS},
)
class StaticFiles:
def __init__(
self,
*,
directory: PathLike | None = None,
packages: list[str | tuple[str, str]] | None = None,
html: bool = False,
check_dir: bool = True,
follow_symlink: bool = False,
) -> None:
self.directory = directory
self.packages = packages
self.all_directories = self.get_directories(directory, packages)
self.html = html
self.config_checked = False
self.follow_symlink = follow_symlink
if check_dir and directory is not None and not os.path.isdir(directory):
raise RuntimeError(f"Directory '{directory}' does not exist")
def get_directories(
self,
directory: PathLike | None = None,
packages: list[str | tuple[str, str]] | None = None,
) -> list[PathLike]:
"""
Given `directory` and `packages` arguments, return a list of all the
directories that should be used for serving static files from.
"""
directories = []
if directory is not None:
directories.append(directory)
for package in packages or []:
if isinstance(package, tuple):
package, statics_dir = package
else:
statics_dir = "statics"
spec = importlib.util.find_spec(package)
assert spec is not None, f"Package {package!r} could not be found."
assert spec.origin is not None, f"Package {package!r} could not be found."
package_directory = os.path.normpath(os.path.join(spec.origin, "..", statics_dir))
assert os.path.isdir(package_directory), (
f"Directory '{statics_dir!r}' in package {package!r} could not be found."
)
directories.append(package_directory)
return directories
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
"""
The ASGI entry point.
"""
assert scope["type"] == "http"
if not self.config_checked:
await self.check_config()
self.config_checked = True
path = self.get_path(scope)
response = await self.get_response(path, scope)
await response(scope, receive, send)
def get_path(self, scope: Scope) -> str:
"""
Given the ASGI scope, return the `path` string to serve up,
with OS specific path separators, and any '..', '.' components removed.
"""
route_path = get_route_path(scope)
return os.path.normpath(os.path.join(*route_path.split("/")))
async def get_response(self, path: str, scope: Scope) -> Response:
"""
Returns an HTTP response, given the incoming path, method and request headers.
"""
if scope["method"] not in ("GET", "HEAD"):
raise HTTPException(status_code=405)
try:
full_path, stat_result = await anyio.to_thread.run_sync(self.lookup_path, path)
except PermissionError:
raise HTTPException(status_code=401)
except OSError as exc:
# Filename is too long, so it can't be a valid static file.
if exc.errno == errno.ENAMETOOLONG:
raise HTTPException(status_code=404)
raise exc
if stat_result and stat.S_ISREG(stat_result.st_mode):
# We have a static file to serve.
return self.file_response(full_path, stat_result, scope)
elif stat_result and stat.S_ISDIR(stat_result.st_mode) and self.html:
# We're in HTML mode, and have got a directory URL.
# Check if we have 'index.html' file to serve.
index_path = os.path.join(path, "index.html")
full_path, stat_result = await anyio.to_thread.run_sync(self.lookup_path, index_path)
if stat_result is not None and stat.S_ISREG(stat_result.st_mode):
if not scope["path"].endswith("/"):
# Directory URLs should redirect to always end in "/".
url = URL(scope=scope)
url = url.replace(path=url.path + "/")
return RedirectResponse(url=url)
return self.file_response(full_path, stat_result, scope)
if self.html:
# Check for '404.html' if we're in HTML mode.
full_path, stat_result = await anyio.to_thread.run_sync(self.lookup_path, "404.html")
if stat_result and stat.S_ISREG(stat_result.st_mode):
return FileResponse(full_path, stat_result=stat_result, status_code=404)
raise HTTPException(status_code=404)
def lookup_path(self, path: str) -> tuple[str, os.stat_result | None]:
for directory in self.all_directories:
joined_path = os.path.join(directory, path)
if self.follow_symlink:
full_path = os.path.abspath(joined_path)
directory = os.path.abspath(directory)
else:
full_path = os.path.realpath(joined_path)
directory = os.path.realpath(directory)
if os.path.commonpath([full_path, directory]) != str(directory):
# Don't allow misbehaving clients to break out of the static files directory.
continue
try:
return full_path, os.stat(full_path)
except (FileNotFoundError, NotADirectoryError):
continue
return "", None
def file_response(
self,
full_path: PathLike,
stat_result: os.stat_result,
scope: Scope,
status_code: int = 200,
) -> Response:
request_headers = Headers(scope=scope)
response = FileResponse(full_path, status_code=status_code, stat_result=stat_result)
if self.is_not_modified(response.headers, request_headers):
return NotModifiedResponse(response.headers)
return response
async def check_config(self) -> None:
"""
Perform a one-off configuration check that StaticFiles is actually
pointed at a directory, so that we can raise loud errors rather than
just returning 404 responses.
"""
if self.directory is None:
return
try:
stat_result = await anyio.to_thread.run_sync(os.stat, self.directory)
except FileNotFoundError:
raise RuntimeError(f"StaticFiles directory '{self.directory}' does not exist.")
if not (stat.S_ISDIR(stat_result.st_mode) or stat.S_ISLNK(stat_result.st_mode)):
raise RuntimeError(f"StaticFiles path '{self.directory}' is not a directory.")
def is_not_modified(self, response_headers: Headers, request_headers: Headers) -> bool:
"""
Given the request and response headers, return `True` if an HTTP
"Not Modified" response could be returned instead.
"""
if if_none_match := request_headers.get("if-none-match"):
# The "etag" header is added by FileResponse, so it's always present.
etag = response_headers["etag"]
return etag in [tag.strip(" W/") for tag in if_none_match.split(",")]
try:
if_modified_since = parsedate(request_headers["if-modified-since"])
last_modified = parsedate(response_headers["last-modified"])
if if_modified_since is not None and last_modified is not None and if_modified_since >= last_modified:
return True
except KeyError:
pass
return False
| import os
import stat
import tempfile
import time
from pathlib import Path
from typing import Any
import anyio
import pytest
from starlette.applications import Starlette
from starlette.exceptions import HTTPException
from starlette.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import Mount
from starlette.staticfiles import StaticFiles
from tests.types import TestClientFactory
def test_staticfiles(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
path = os.path.join(tmpdir, "example.txt")
with open(path, "w") as file:
file.write("<file content>")
app = StaticFiles(directory=tmpdir)
client = test_client_factory(app)
response = client.get("/example.txt")
assert response.status_code == 200
assert response.text == "<file content>"
def test_staticfiles_with_pathlib(tmp_path: Path, test_client_factory: TestClientFactory) -> None:
path = tmp_path / "example.txt"
with open(path, "w") as file:
file.write("<file content>")
app = StaticFiles(directory=tmp_path)
client = test_client_factory(app)
response = client.get("/example.txt")
assert response.status_code == 200
assert response.text == "<file content>"
def test_staticfiles_head_with_middleware(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
"""
see https://github.com/Kludex/starlette/pull/935
"""
path = os.path.join(tmpdir, "example.txt")
with open(path, "w") as file:
file.write("x" * 100)
async def does_nothing_middleware(request: Request, call_next: RequestResponseEndpoint) -> Response:
response = await call_next(request)
return response
routes = [Mount("/static", app=StaticFiles(directory=tmpdir), name="static")]
middleware = [Middleware(BaseHTTPMiddleware, dispatch=does_nothing_middleware)]
app = Starlette(routes=routes, middleware=middleware)
client = test_client_factory(app)
response = client.head("/static/example.txt")
assert response.status_code == 200
assert response.headers.get("content-length") == "100"
def test_staticfiles_with_package(test_client_factory: TestClientFactory) -> None:
app = StaticFiles(packages=["tests"])
client = test_client_factory(app)
response = client.get("/example.txt")
assert response.status_code == 200
assert response.text == "123\n"
app = StaticFiles(packages=[("tests", "statics")])
client = test_client_factory(app)
response = client.get("/example.txt")
assert response.status_code == 200
assert response.text == "123\n"
def test_staticfiles_post(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
path = os.path.join(tmpdir, "example.txt")
with open(path, "w") as file:
file.write("<file content>")
routes = [Mount("/", app=StaticFiles(directory=tmpdir), name="static")]
app = Starlette(routes=routes)
client = test_client_factory(app)
response = client.post("/example.txt")
assert response.status_code == 405
assert response.text == "Method Not Allowed"
def test_staticfiles_with_directory_returns_404(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
path = os.path.join(tmpdir, "example.txt")
with open(path, "w") as file:
file.write("<file content>")
routes = [Mount("/", app=StaticFiles(directory=tmpdir), name="static")]
app = Starlette(routes=routes)
client = test_client_factory(app)
response = client.get("/")
assert response.status_code == 404
assert response.text == "Not Found"
def test_staticfiles_with_missing_file_returns_404(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
path = os.path.join(tmpdir, "example.txt")
with open(path, "w") as file:
file.write("<file content>")
routes = [Mount("/", app=StaticFiles(directory=tmpdir), name="static")]
app = Starlette(routes=routes)
client = test_client_factory(app)
response = client.get("/404.txt")
assert response.status_code == 404
assert response.text == "Not Found"
def test_staticfiles_instantiated_with_missing_directory(tmpdir: Path) -> None:
with pytest.raises(RuntimeError) as exc_info:
path = os.path.join(tmpdir, "no_such_directory")
StaticFiles(directory=path)
assert "does not exist" in str(exc_info.value)
def test_staticfiles_configured_with_missing_directory(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
path = os.path.join(tmpdir, "no_such_directory")
app = StaticFiles(directory=path, check_dir=False)
client = test_client_factory(app)
with pytest.raises(RuntimeError) as exc_info:
client.get("/example.txt")
assert "does not exist" in str(exc_info.value)
def test_staticfiles_configured_with_file_instead_of_directory(
tmpdir: Path, test_client_factory: TestClientFactory
) -> None:
path = os.path.join(tmpdir, "example.txt")
with open(path, "w") as file:
file.write("<file content>")
app = StaticFiles(directory=path, check_dir=False)
client = test_client_factory(app)
with pytest.raises(RuntimeError) as exc_info:
client.get("/example.txt")
assert "is not a directory" in str(exc_info.value)
def test_staticfiles_config_check_occurs_only_once(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
app = StaticFiles(directory=tmpdir)
client = test_client_factory(app)
assert not app.config_checked
with pytest.raises(HTTPException):
client.get("/")
assert app.config_checked
with pytest.raises(HTTPException):
client.get("/")
def test_staticfiles_prevents_breaking_out_of_directory(tmpdir: Path) -> None:
directory = os.path.join(tmpdir, "foo")
os.mkdir(directory)
path = os.path.join(tmpdir, "example.txt")
with open(path, "w") as file:
file.write("outside root dir")
app = StaticFiles(directory=directory)
# We can't test this with 'httpx', so we test the app directly here.
path = app.get_path({"path": "/../example.txt"})
scope = {"method": "GET"}
with pytest.raises(HTTPException) as exc_info:
anyio.run(app.get_response, path, scope)
assert exc_info.value.status_code == 404
assert exc_info.value.detail == "Not Found"
def test_staticfiles_never_read_file_for_head_method(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
path = os.path.join(tmpdir, "example.txt")
with open(path, "w") as file:
file.write("<file content>")
app = StaticFiles(directory=tmpdir)
client = test_client_factory(app)
response = client.head("/example.txt")
assert response.status_code == 200
assert response.content == b""
assert response.headers["content-length"] == "14"
def test_staticfiles_304_with_etag_match(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
path = os.path.join(tmpdir, "example.txt")
with open(path, "w") as file:
file.write("<file content>")
app = StaticFiles(directory=tmpdir)
client = test_client_factory(app)
first_resp = client.get("/example.txt")
assert first_resp.status_code == 200
last_etag = first_resp.headers["etag"]
second_resp = client.get("/example.txt", headers={"if-none-match": last_etag})
assert second_resp.status_code == 304
assert second_resp.content == b""
second_resp = client.get("/example.txt", headers={"if-none-match": f'W/{last_etag}, "123"'})
assert second_resp.status_code == 304
assert second_resp.content == b""
def test_staticfiles_200_with_etag_mismatch(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
path = os.path.join(tmpdir, "example.txt")
with open(path, "w") as file:
file.write("<file content>")
app = StaticFiles(directory=tmpdir)
client = test_client_factory(app)
first_resp = client.get("/example.txt")
assert first_resp.status_code == 200
assert first_resp.headers["etag"] != '"123"'
second_resp = client.get("/example.txt", headers={"if-none-match": '"123"'})
assert second_resp.status_code == 200
assert second_resp.content == b"<file content>"
def test_staticfiles_200_with_etag_mismatch_and_timestamp_match(
tmpdir: Path, test_client_factory: TestClientFactory
) -> None:
path = tmpdir / "example.txt"
path.write_text("<file content>", encoding="utf-8")
app = StaticFiles(directory=tmpdir)
client = test_client_factory(app)
first_resp = client.get("/example.txt")
assert first_resp.status_code == 200
assert first_resp.headers["etag"] != '"123"'
last_modified = first_resp.headers["last-modified"]
# If `if-none-match` is present, `if-modified-since` is ignored.
second_resp = client.get("/example.txt", headers={"if-none-match": '"123"', "if-modified-since": last_modified})
assert second_resp.status_code == 200
assert second_resp.content == b"<file content>"
def test_staticfiles_304_with_last_modified_compare_last_req(
tmpdir: Path, test_client_factory: TestClientFactory
) -> None:
path = os.path.join(tmpdir, "example.txt")
file_last_modified_time = time.mktime(time.strptime("2013-10-10 23:40:00", "%Y-%m-%d %H:%M:%S"))
with open(path, "w") as file:
file.write("<file content>")
os.utime(path, (file_last_modified_time, file_last_modified_time))
app = StaticFiles(directory=tmpdir)
client = test_client_factory(app)
# last modified less than last request, 304
response = client.get("/example.txt", headers={"If-Modified-Since": "Thu, 11 Oct 2013 15:30:19 GMT"})
assert response.status_code == 304
assert response.content == b""
# last modified greater than last request, 200 with content
response = client.get("/example.txt", headers={"If-Modified-Since": "Thu, 20 Feb 2012 15:30:19 GMT"})
assert response.status_code == 200
assert response.content == b"<file content>"
def test_staticfiles_html_normal(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
path = os.path.join(tmpdir, "404.html")
with open(path, "w") as file:
file.write("<h1>Custom not found page</h1>")
path = os.path.join(tmpdir, "dir")
os.mkdir(path)
path = os.path.join(path, "index.html")
with open(path, "w") as file:
file.write("<h1>Hello</h1>")
app = StaticFiles(directory=tmpdir, html=True)
client = test_client_factory(app)
response = client.get("/dir/")
assert response.url == "http://testserver/dir/"
assert response.status_code == 200
assert response.text == "<h1>Hello</h1>"
response = client.get("/dir")
assert response.url == "http://testserver/dir/"
assert response.status_code == 200
assert response.text == "<h1>Hello</h1>"
response = client.get("/dir/index.html")
assert response.url == "http://testserver/dir/index.html"
assert response.status_code == 200
assert response.text == "<h1>Hello</h1>"
response = client.get("/missing")
assert response.status_code == 404
assert response.text == "<h1>Custom not found page</h1>"
def test_staticfiles_html_without_index(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
path = os.path.join(tmpdir, "404.html")
with open(path, "w") as file:
file.write("<h1>Custom not found page</h1>")
path = os.path.join(tmpdir, "dir")
os.mkdir(path)
app = StaticFiles(directory=tmpdir, html=True)
client = test_client_factory(app)
response = client.get("/dir/")
assert response.url == "http://testserver/dir/"
assert response.status_code == 404
assert response.text == "<h1>Custom not found page</h1>"
response = client.get("/dir")
assert response.url == "http://testserver/dir"
assert response.status_code == 404
assert response.text == "<h1>Custom not found page</h1>"
response = client.get("/missing")
assert response.status_code == 404
assert response.text == "<h1>Custom not found page</h1>"
def test_staticfiles_html_without_404(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
path = os.path.join(tmpdir, "dir")
os.mkdir(path)
path = os.path.join(path, "index.html")
with open(path, "w") as file:
file.write("<h1>Hello</h1>")
app = StaticFiles(directory=tmpdir, html=True)
client = test_client_factory(app)
response = client.get("/dir/")
assert response.url == "http://testserver/dir/"
assert response.status_code == 200
assert response.text == "<h1>Hello</h1>"
response = client.get("/dir")
assert response.url == "http://testserver/dir/"
assert response.status_code == 200
assert response.text == "<h1>Hello</h1>"
with pytest.raises(HTTPException) as exc_info:
response = client.get("/missing")
assert exc_info.value.status_code == 404
def test_staticfiles_html_only_files(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
path = os.path.join(tmpdir, "hello.html")
with open(path, "w") as file:
file.write("<h1>Hello</h1>")
app = StaticFiles(directory=tmpdir, html=True)
client = test_client_factory(app)
with pytest.raises(HTTPException) as exc_info:
response = client.get("/")
assert exc_info.value.status_code == 404
response = client.get("/hello.html")
assert response.status_code == 200
assert response.text == "<h1>Hello</h1>"
def test_staticfiles_cache_invalidation_for_deleted_file_html_mode(
tmpdir: Path, test_client_factory: TestClientFactory
) -> None:
path_404 = os.path.join(tmpdir, "404.html")
with open(path_404, "w") as file:
file.write("<p>404 file</p>")
path_some = os.path.join(tmpdir, "some.html")
with open(path_some, "w") as file:
file.write("<p>some file</p>")
common_modified_time = time.mktime(time.strptime("2013-10-10 23:40:00", "%Y-%m-%d %H:%M:%S"))
os.utime(path_404, (common_modified_time, common_modified_time))
os.utime(path_some, (common_modified_time, common_modified_time))
app = StaticFiles(directory=tmpdir, html=True)
client = test_client_factory(app)
resp_exists = client.get("/some.html")
assert resp_exists.status_code == 200
assert resp_exists.text == "<p>some file</p>"
resp_cached = client.get(
"/some.html",
headers={"If-Modified-Since": resp_exists.headers["last-modified"]},
)
assert resp_cached.status_code == 304
os.remove(path_some)
resp_deleted = client.get(
"/some.html",
headers={"If-Modified-Since": resp_exists.headers["last-modified"]},
)
assert resp_deleted.status_code == 404
assert resp_deleted.text == "<p>404 file</p>"
def test_staticfiles_with_invalid_dir_permissions_returns_401(
tmp_path: Path, test_client_factory: TestClientFactory
) -> None:
(tmp_path / "example.txt").write_bytes(b"<file content>")
original_mode = tmp_path.stat().st_mode
tmp_path.chmod(stat.S_IRWXO)
try:
routes = [
Mount(
"/",
app=StaticFiles(directory=os.fsdecode(tmp_path)),
name="static",
)
]
app = Starlette(routes=routes)
client = test_client_factory(app)
response = client.get("/example.txt")
assert response.status_code == 401
assert response.text == "Unauthorized"
finally:
tmp_path.chmod(original_mode)
def test_staticfiles_with_missing_dir_returns_404(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
path = os.path.join(tmpdir, "example.txt")
with open(path, "w") as file:
file.write("<file content>")
routes = [Mount("/", app=StaticFiles(directory=tmpdir), name="static")]
app = Starlette(routes=routes)
client = test_client_factory(app)
response = client.get("/foo/example.txt")
assert response.status_code == 404
assert response.text == "Not Found"
def test_staticfiles_access_file_as_dir_returns_404(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
path = os.path.join(tmpdir, "example.txt")
with open(path, "w") as file:
file.write("<file content>")
routes = [Mount("/", app=StaticFiles(directory=tmpdir), name="static")]
app = Starlette(routes=routes)
client = test_client_factory(app)
response = client.get("/example.txt/foo")
assert response.status_code == 404
assert response.text == "Not Found"
def test_staticfiles_filename_too_long(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
routes = [Mount("/", app=StaticFiles(directory=tmpdir), name="static")]
app = Starlette(routes=routes)
client = test_client_factory(app)
path_max_size = os.pathconf("/", "PC_PATH_MAX")
response = client.get(f"/{'a' * path_max_size}.txt")
assert response.status_code == 404
assert response.text == "Not Found"
def test_staticfiles_unhandled_os_error_returns_500(
tmpdir: Path,
test_client_factory: TestClientFactory,
monkeypatch: pytest.MonkeyPatch,
) -> None:
def mock_timeout(*args: Any, **kwargs: Any) -> None:
raise TimeoutError
path = os.path.join(tmpdir, "example.txt")
with open(path, "w") as file:
file.write("<file content>")
routes = [Mount("/", app=StaticFiles(directory=tmpdir), name="static")]
app = Starlette(routes=routes)
client = test_client_factory(app, raise_server_exceptions=False)
monkeypatch.setattr("starlette.staticfiles.StaticFiles.lookup_path", mock_timeout)
response = client.get("/example.txt")
assert response.status_code == 500
assert response.text == "Internal Server Error"
def test_staticfiles_follows_symlinks(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
statics_path = os.path.join(tmpdir, "statics")
os.mkdir(statics_path)
source_path = tempfile.mkdtemp()
source_file_path = os.path.join(source_path, "page.html")
with open(source_file_path, "w") as file:
file.write("<h1>Hello</h1>")
statics_file_path = os.path.join(statics_path, "index.html")
os.symlink(source_file_path, statics_file_path)
app = StaticFiles(directory=statics_path, follow_symlink=True)
client = test_client_factory(app)
response = client.get("/index.html")
assert response.url == "http://testserver/index.html"
assert response.status_code == 200
assert response.text == "<h1>Hello</h1>"
def test_staticfiles_follows_symlink_directories(tmpdir: Path, test_client_factory: TestClientFactory) -> None:
statics_path = os.path.join(tmpdir, "statics")
statics_html_path = os.path.join(statics_path, "html")
os.mkdir(statics_path)
source_path = tempfile.mkdtemp()
source_file_path = os.path.join(source_path, "page.html")
with open(source_file_path, "w") as file:
file.write("<h1>Hello</h1>")
os.symlink(source_path, statics_html_path)
app = StaticFiles(directory=statics_path, follow_symlink=True)
client = test_client_factory(app)
response = client.get("/html/page.html")
assert response.url == "http://testserver/html/page.html"
assert response.status_code == 200
assert response.text == "<h1>Hello</h1>"
def test_staticfiles_disallows_path_traversal_with_symlinks(tmpdir: Path) -> None:
statics_path = os.path.join(tmpdir, "statics")
root_source_path = tempfile.mkdtemp()
source_path = os.path.join(root_source_path, "statics")
os.mkdir(source_path)
source_file_path = os.path.join(root_source_path, "index.html")
with open(source_file_path, "w") as file:
file.write("<h1>Hello</h1>")
os.symlink(source_path, statics_path)
app = StaticFiles(directory=statics_path, follow_symlink=True)
# We can't test this with 'httpx', so we test the app directly here.
path = app.get_path({"path": "/../index.html"})
scope = {"method": "GET"}
with pytest.raises(HTTPException) as exc_info:
anyio.run(app.get_response, path, scope)
assert exc_info.value.status_code == 404
assert exc_info.value.detail == "Not Found"
def test_staticfiles_avoids_path_traversal(tmp_path: Path) -> None:
statics_path = tmp_path / "static"
statics_disallow_path = tmp_path / "static_disallow"
statics_path.mkdir()
statics_disallow_path.mkdir()
static_index_file = statics_path / "index.html"
statics_disallow_path_index_file = statics_disallow_path / "index.html"
static_file = tmp_path / "static1.txt"
static_index_file.write_text("<h1>Hello</h1>")
statics_disallow_path_index_file.write_text("<h1>Private</h1>")
static_file.write_text("Private")
app = StaticFiles(directory=statics_path)
# We can't test this with 'httpx', so we test the app directly here.
path = app.get_path({"path": "/../static1.txt"})
with pytest.raises(HTTPException) as exc_info:
anyio.run(app.get_response, path, {"method": "GET"})
assert exc_info.value.status_code == 404
assert exc_info.value.detail == "Not Found"
path = app.get_path({"path": "/../static_disallow/index.html"})
with pytest.raises(HTTPException) as exc_info:
anyio.run(app.get_response, path, {"method": "GET"})
assert exc_info.value.status_code == 404
assert exc_info.value.detail == "Not Found"
def test_staticfiles_self_symlinks(tmp_path: Path, test_client_factory: TestClientFactory) -> None:
statics_path = tmp_path / "statics"
statics_path.mkdir()
source_file_path = statics_path / "index.html"
source_file_path.write_text("<h1>Hello</h1>", encoding="utf-8")
statics_symlink_path = tmp_path / "statics_symlink"
statics_symlink_path.symlink_to(statics_path)
app = StaticFiles(directory=statics_symlink_path, follow_symlink=True)
client = test_client_factory(app)
response = client.get("/index.html")
assert response.url == "http://testserver/index.html"
assert response.status_code == 200
assert response.text == "<h1>Hello</h1>"
def test_staticfiles_relative_directory_symlinks(test_client_factory: TestClientFactory) -> None:
app = StaticFiles(directory="tests/statics", follow_symlink=True)
client = test_client_factory(app)
response = client.get("/example.txt")
assert response.status_code == 200
assert response.text == "123\n"
| starlette |
python | from __future__ import annotations
import functools
import re
from collections.abc import Sequence
from starlette.datastructures import Headers, MutableHeaders
from starlette.responses import PlainTextResponse, Response
from starlette.types import ASGIApp, Message, Receive, Scope, Send
ALL_METHODS = ("DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT")
SAFELISTED_HEADERS = {"Accept", "Accept-Language", "Content-Language", "Content-Type"}
class CORSMiddleware:
def __init__(
self,
app: ASGIApp,
allow_origins: Sequence[str] = (),
allow_methods: Sequence[str] = ("GET",),
allow_headers: Sequence[str] = (),
allow_credentials: bool = False,
allow_origin_regex: str | None = None,
allow_private_network: bool = False,
expose_headers: Sequence[str] = (),
max_age: int = 600,
) -> None:
if "*" in allow_methods:
allow_methods = ALL_METHODS
compiled_allow_origin_regex = None
if allow_origin_regex is not None:
compiled_allow_origin_regex = re.compile(allow_origin_regex)
allow_all_origins = "*" in allow_origins
allow_all_headers = "*" in allow_headers
preflight_explicit_allow_origin = not allow_all_origins or allow_credentials
simple_headers: dict[str, str] = {}
if allow_all_origins:
simple_headers["Access-Control-Allow-Origin"] = "*"
if allow_credentials:
simple_headers["Access-Control-Allow-Credentials"] = "true"
if expose_headers:
simple_headers["Access-Control-Expose-Headers"] = ", ".join(expose_headers)
preflight_headers: dict[str, str] = {}
if preflight_explicit_allow_origin:
# The origin value will be set in preflight_response() if it is allowed.
preflight_headers["Vary"] = "Origin"
else:
preflight_headers["Access-Control-Allow-Origin"] = "*"
preflight_headers.update(
{
"Access-Control-Allow-Methods": ", ".join(allow_methods),
"Access-Control-Max-Age": str(max_age),
}
)
allow_headers = sorted(SAFELISTED_HEADERS | set(allow_headers))
if allow_headers and not allow_all_headers:
preflight_headers["Access-Control-Allow-Headers"] = ", ".join(allow_headers)
if allow_credentials:
preflight_headers["Access-Control-Allow-Credentials"] = "true"
self.app = app
self.allow_origins = allow_origins
self.allow_methods = allow_methods
self.allow_headers = [h.lower() for h in allow_headers]
self.allow_all_origins = allow_all_origins
self.allow_all_headers = allow_all_headers
self.preflight_explicit_allow_origin = preflight_explicit_allow_origin
self.allow_origin_regex = compiled_allow_origin_regex
self.allow_private_network = allow_private_network
self.simple_headers = simple_headers
self.preflight_headers = preflight_headers
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http": # pragma: no cover
await self.app(scope, receive, send)
return
method = scope["method"]
headers = Headers(scope=scope)
origin = headers.get("origin")
if origin is None:
await self.app(scope, receive, send)
return
if method == "OPTIONS" and "access-control-request-method" in headers:
response = self.preflight_response(request_headers=headers)
await response(scope, receive, send)
return
await self.simple_response(scope, receive, send, request_headers=headers)
def is_allowed_origin(self, origin: str) -> bool:
if self.allow_all_origins:
return True
if self.allow_origin_regex is not None and self.allow_origin_regex.fullmatch(origin):
return True
return origin in self.allow_origins
def preflight_response(self, request_headers: Headers) -> Response:
requested_origin = request_headers["origin"]
requested_method = request_headers["access-control-request-method"]
requested_headers = request_headers.get("access-control-request-headers")
requested_private_network = request_headers.get("access-control-request-private-network")
headers = dict(self.preflight_headers)
failures: list[str] = []
if self.is_allowed_origin(origin=requested_origin):
if self.preflight_explicit_allow_origin:
# The "else" case is already accounted for in self.preflight_headers
# and the value would be "*".
headers["Access-Control-Allow-Origin"] = requested_origin
else:
failures.append("origin")
if requested_method not in self.allow_methods:
failures.append("method")
# If we allow all headers, then we have to mirror back any requested
# headers in the response.
if self.allow_all_headers and requested_headers is not None:
headers["Access-Control-Allow-Headers"] = requested_headers
elif requested_headers is not None:
for header in [h.lower() for h in requested_headers.split(",")]:
if header.strip() not in self.allow_headers:
failures.append("headers")
break
if requested_private_network is not None:
if self.allow_private_network:
headers["Access-Control-Allow-Private-Network"] = "true"
else:
failures.append("private-network")
# We don't strictly need to use 400 responses here, since its up to
# the browser to enforce the CORS policy, but its more informative
# if we do.
if failures:
failure_text = "Disallowed CORS " + ", ".join(failures)
return PlainTextResponse(failure_text, status_code=400, headers=headers)
return PlainTextResponse("OK", status_code=200, headers=headers)
async def simple_response(self, scope: Scope, receive: Receive, send: Send, request_headers: Headers) -> None:
send = functools.partial(self.send, send=send, request_headers=request_headers)
await self.app(scope, receive, send)
async def send(self, message: Message, send: Send, request_headers: Headers) -> None:
if message["type"] != "http.response.start":
await send(message)
return
message.setdefault("headers", [])
headers = MutableHeaders(scope=message)
headers.update(self.simple_headers)
origin = request_headers["Origin"]
has_cookie = "cookie" in request_headers
# If request includes any cookie headers, then we must respond
# with the specific origin instead of '*'.
if self.allow_all_origins and has_cookie:
self.allow_explicit_origin(headers, origin)
# If we only allow specific origins, then we have to mirror back
# the Origin header in the response.
elif not self.allow_all_origins and self.is_allowed_origin(origin=origin):
self.allow_explicit_origin(headers, origin)
await send(message)
@staticmethod
def allow_explicit_origin(headers: MutableHeaders, origin: str) -> None:
headers["Access-Control-Allow-Origin"] = origin
headers.add_vary_header("Origin")
| from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
from starlette.requests import Request
from starlette.responses import PlainTextResponse
from starlette.routing import Route
from tests.types import TestClientFactory
def test_cors_allow_all(
test_client_factory: TestClientFactory,
) -> None:
def homepage(request: Request) -> PlainTextResponse:
return PlainTextResponse("Homepage", status_code=200)
app = Starlette(
routes=[Route("/", endpoint=homepage)],
middleware=[
Middleware(
CORSMiddleware,
allow_origins=["*"],
allow_headers=["*"],
allow_methods=["*"],
expose_headers=["X-Status"],
allow_credentials=True,
)
],
)
client = test_client_factory(app)
# Test pre-flight response
headers = {
"Origin": "https://example.org",
"Access-Control-Request-Method": "GET",
"Access-Control-Request-Headers": "X-Example",
}
response = client.options("/", headers=headers)
assert response.status_code == 200
assert response.text == "OK"
assert response.headers["access-control-allow-origin"] == "https://example.org"
assert response.headers["access-control-allow-headers"] == "X-Example"
assert response.headers["access-control-allow-credentials"] == "true"
assert response.headers["vary"] == "Origin"
# Test standard response
headers = {"Origin": "https://example.org"}
response = client.get("/", headers=headers)
assert response.status_code == 200
assert response.text == "Homepage"
assert response.headers["access-control-allow-origin"] == "*"
assert response.headers["access-control-expose-headers"] == "X-Status"
assert response.headers["access-control-allow-credentials"] == "true"
# Test standard credentialed response
headers = {"Origin": "https://example.org", "Cookie": "star_cookie=sugar"}
response = client.get("/", headers=headers)
assert response.status_code == 200
assert response.text == "Homepage"
assert response.headers["access-control-allow-origin"] == "https://example.org"
assert response.headers["access-control-expose-headers"] == "X-Status"
assert response.headers["access-control-allow-credentials"] == "true"
# Test non-CORS response
response = client.get("/")
assert response.status_code == 200
assert response.text == "Homepage"
assert "access-control-allow-origin" not in response.headers
def test_cors_allow_all_except_credentials(
test_client_factory: TestClientFactory,
) -> None:
def homepage(request: Request) -> PlainTextResponse:
return PlainTextResponse("Homepage", status_code=200)
app = Starlette(
routes=[Route("/", endpoint=homepage)],
middleware=[
Middleware(
CORSMiddleware,
allow_origins=["*"],
allow_headers=["*"],
allow_methods=["*"],
expose_headers=["X-Status"],
)
],
)
client = test_client_factory(app)
# Test pre-flight response
headers = {
"Origin": "https://example.org",
"Access-Control-Request-Method": "GET",
"Access-Control-Request-Headers": "X-Example",
}
response = client.options("/", headers=headers)
assert response.status_code == 200
assert response.text == "OK"
assert response.headers["access-control-allow-origin"] == "*"
assert response.headers["access-control-allow-headers"] == "X-Example"
assert "access-control-allow-credentials" not in response.headers
assert "vary" not in response.headers
# Test standard response
headers = {"Origin": "https://example.org"}
response = client.get("/", headers=headers)
assert response.status_code == 200
assert response.text == "Homepage"
assert response.headers["access-control-allow-origin"] == "*"
assert response.headers["access-control-expose-headers"] == "X-Status"
assert "access-control-allow-credentials" not in response.headers
# Test non-CORS response
response = client.get("/")
assert response.status_code == 200
assert response.text == "Homepage"
assert "access-control-allow-origin" not in response.headers
def test_cors_allow_specific_origin(
test_client_factory: TestClientFactory,
) -> None:
def homepage(request: Request) -> PlainTextResponse:
return PlainTextResponse("Homepage", status_code=200)
app = Starlette(
routes=[Route("/", endpoint=homepage)],
middleware=[
Middleware(
CORSMiddleware,
allow_origins=["https://example.org"],
allow_headers=["X-Example", "Content-Type"],
)
],
)
client = test_client_factory(app)
# Test pre-flight response
headers = {
"Origin": "https://example.org",
"Access-Control-Request-Method": "GET",
"Access-Control-Request-Headers": "X-Example, Content-Type",
}
response = client.options("/", headers=headers)
assert response.status_code == 200
assert response.text == "OK"
assert response.headers["access-control-allow-origin"] == "https://example.org"
assert response.headers["access-control-allow-headers"] == (
"Accept, Accept-Language, Content-Language, Content-Type, X-Example"
)
assert "access-control-allow-credentials" not in response.headers
# Test standard response
headers = {"Origin": "https://example.org"}
response = client.get("/", headers=headers)
assert response.status_code == 200
assert response.text == "Homepage"
assert response.headers["access-control-allow-origin"] == "https://example.org"
assert "access-control-allow-credentials" not in response.headers
# Test non-CORS response
response = client.get("/")
assert response.status_code == 200
assert response.text == "Homepage"
assert "access-control-allow-origin" not in response.headers
def test_cors_disallowed_preflight(
test_client_factory: TestClientFactory,
) -> None:
def homepage(request: Request) -> None:
pass # pragma: no cover
app = Starlette(
routes=[Route("/", endpoint=homepage)],
middleware=[
Middleware(
CORSMiddleware,
allow_origins=["https://example.org"],
allow_headers=["X-Example"],
)
],
)
client = test_client_factory(app)
# Test pre-flight response
headers = {
"Origin": "https://another.org",
"Access-Control-Request-Method": "POST",
"Access-Control-Request-Headers": "X-Nope",
}
response = client.options("/", headers=headers)
assert response.status_code == 400
assert response.text == "Disallowed CORS origin, method, headers"
assert "access-control-allow-origin" not in response.headers
# Bug specific test, https://github.com/Kludex/starlette/pull/1199
# Test preflight response text with multiple disallowed headers
headers = {
"Origin": "https://example.org",
"Access-Control-Request-Method": "GET",
"Access-Control-Request-Headers": "X-Nope-1, X-Nope-2",
}
response = client.options("/", headers=headers)
assert response.text == "Disallowed CORS headers"
def test_preflight_allows_request_origin_if_origins_wildcard_and_credentials_allowed(
test_client_factory: TestClientFactory,
) -> None:
def homepage(request: Request) -> None:
return # pragma: no cover
app = Starlette(
routes=[Route("/", endpoint=homepage)],
middleware=[
Middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["POST"],
allow_credentials=True,
)
],
)
client = test_client_factory(app)
# Test pre-flight response
headers = {
"Origin": "https://example.org",
"Access-Control-Request-Method": "POST",
}
response = client.options(
"/",
headers=headers,
)
assert response.status_code == 200
assert response.headers["access-control-allow-origin"] == "https://example.org"
assert response.headers["access-control-allow-credentials"] == "true"
assert response.headers["vary"] == "Origin"
def test_cors_preflight_allow_all_methods(
test_client_factory: TestClientFactory,
) -> None:
def homepage(request: Request) -> None:
pass # pragma: no cover
app = Starlette(
routes=[Route("/", endpoint=homepage)],
middleware=[Middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"])],
)
client = test_client_factory(app)
headers = {
"Origin": "https://example.org",
"Access-Control-Request-Method": "POST",
}
for method in ("DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"):
response = client.options("/", headers=headers)
assert response.status_code == 200
assert method in response.headers["access-control-allow-methods"]
def test_cors_allow_all_methods(
test_client_factory: TestClientFactory,
) -> None:
def homepage(request: Request) -> PlainTextResponse:
return PlainTextResponse("Homepage", status_code=200)
app = Starlette(
routes=[
Route(
"/",
endpoint=homepage,
methods=["delete", "get", "head", "options", "patch", "post", "put"],
)
],
middleware=[Middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"])],
)
client = test_client_factory(app)
headers = {"Origin": "https://example.org"}
for method in ("patch", "post", "put"):
response = getattr(client, method)("/", headers=headers, json={})
assert response.status_code == 200
for method in ("delete", "get", "head", "options"):
response = getattr(client, method)("/", headers=headers)
assert response.status_code == 200
def test_cors_allow_origin_regex(
test_client_factory: TestClientFactory,
) -> None:
def homepage(request: Request) -> PlainTextResponse:
return PlainTextResponse("Homepage", status_code=200)
app = Starlette(
routes=[Route("/", endpoint=homepage)],
middleware=[
Middleware(
CORSMiddleware,
allow_headers=["X-Example", "Content-Type"],
allow_origin_regex="https://.*",
allow_credentials=True,
)
],
)
client = test_client_factory(app)
# Test standard response
headers = {"Origin": "https://example.org"}
response = client.get("/", headers=headers)
assert response.status_code == 200
assert response.text == "Homepage"
assert response.headers["access-control-allow-origin"] == "https://example.org"
assert response.headers["access-control-allow-credentials"] == "true"
# Test standard credentialed response
headers = {"Origin": "https://example.org", "Cookie": "star_cookie=sugar"}
response = client.get("/", headers=headers)
assert response.status_code == 200
assert response.text == "Homepage"
assert response.headers["access-control-allow-origin"] == "https://example.org"
assert response.headers["access-control-allow-credentials"] == "true"
# Test disallowed standard response
# Note that enforcement is a browser concern. The disallowed-ness is reflected
# in the lack of an "access-control-allow-origin" header in the response.
headers = {"Origin": "http://example.org"}
response = client.get("/", headers=headers)
assert response.status_code == 200
assert response.text == "Homepage"
assert "access-control-allow-origin" not in response.headers
# Test pre-flight response
headers = {
"Origin": "https://another.com",
"Access-Control-Request-Method": "GET",
"Access-Control-Request-Headers": "X-Example, content-type",
}
response = client.options("/", headers=headers)
assert response.status_code == 200
assert response.text == "OK"
assert response.headers["access-control-allow-origin"] == "https://another.com"
assert response.headers["access-control-allow-headers"] == (
"Accept, Accept-Language, Content-Language, Content-Type, X-Example"
)
assert response.headers["access-control-allow-credentials"] == "true"
# Test disallowed pre-flight response
headers = {
"Origin": "http://another.com",
"Access-Control-Request-Method": "GET",
"Access-Control-Request-Headers": "X-Example",
}
response = client.options("/", headers=headers)
assert response.status_code == 400
assert response.text == "Disallowed CORS origin"
assert "access-control-allow-origin" not in response.headers
def test_cors_allow_origin_regex_fullmatch(
test_client_factory: TestClientFactory,
) -> None:
def homepage(request: Request) -> PlainTextResponse:
return PlainTextResponse("Homepage", status_code=200)
app = Starlette(
routes=[Route("/", endpoint=homepage)],
middleware=[
Middleware(
CORSMiddleware,
allow_headers=["X-Example", "Content-Type"],
allow_origin_regex=r"https://.*\.example.org",
)
],
)
client = test_client_factory(app)
# Test standard response
headers = {"Origin": "https://subdomain.example.org"}
response = client.get("/", headers=headers)
assert response.status_code == 200
assert response.text == "Homepage"
assert response.headers["access-control-allow-origin"] == "https://subdomain.example.org"
assert "access-control-allow-credentials" not in response.headers
# Test disallowed standard response
headers = {"Origin": "https://subdomain.example.org.hacker.com"}
response = client.get("/", headers=headers)
assert response.status_code == 200
assert response.text == "Homepage"
assert "access-control-allow-origin" not in response.headers
def test_cors_credentialed_requests_return_specific_origin(
test_client_factory: TestClientFactory,
) -> None:
def homepage(request: Request) -> PlainTextResponse:
return PlainTextResponse("Homepage", status_code=200)
app = Starlette(
routes=[Route("/", endpoint=homepage)],
middleware=[Middleware(CORSMiddleware, allow_origins=["*"])],
)
client = test_client_factory(app)
# Test credentialed request
headers = {"Origin": "https://example.org", "Cookie": "star_cookie=sugar"}
response = client.get("/", headers=headers)
assert response.status_code == 200
assert response.text == "Homepage"
assert response.headers["access-control-allow-origin"] == "https://example.org"
assert "access-control-allow-credentials" not in response.headers
def test_cors_vary_header_defaults_to_origin(
test_client_factory: TestClientFactory,
) -> None:
def homepage(request: Request) -> PlainTextResponse:
return PlainTextResponse("Homepage", status_code=200)
app = Starlette(
routes=[Route("/", endpoint=homepage)],
middleware=[Middleware(CORSMiddleware, allow_origins=["https://example.org"])],
)
headers = {"Origin": "https://example.org"}
client = test_client_factory(app)
response = client.get("/", headers=headers)
assert response.status_code == 200
assert response.headers["vary"] == "Origin"
def test_cors_vary_header_is_not_set_for_non_credentialed_request(
test_client_factory: TestClientFactory,
) -> None:
def homepage(request: Request) -> PlainTextResponse:
return PlainTextResponse("Homepage", status_code=200, headers={"Vary": "Accept-Encoding"})
app = Starlette(
routes=[Route("/", endpoint=homepage)],
middleware=[Middleware(CORSMiddleware, allow_origins=["*"])],
)
client = test_client_factory(app)
response = client.get("/", headers={"Origin": "https://someplace.org"})
assert response.status_code == 200
assert response.headers["vary"] == "Accept-Encoding"
def test_cors_vary_header_is_properly_set_for_credentialed_request(
test_client_factory: TestClientFactory,
) -> None:
def homepage(request: Request) -> PlainTextResponse:
return PlainTextResponse("Homepage", status_code=200, headers={"Vary": "Accept-Encoding"})
app = Starlette(
routes=[Route("/", endpoint=homepage)],
middleware=[Middleware(CORSMiddleware, allow_origins=["*"])],
)
client = test_client_factory(app)
response = client.get("/", headers={"Cookie": "foo=bar", "Origin": "https://someplace.org"})
assert response.status_code == 200
assert response.headers["vary"] == "Accept-Encoding, Origin"
def test_cors_vary_header_is_properly_set_when_allow_origins_is_not_wildcard(
test_client_factory: TestClientFactory,
) -> None:
def homepage(request: Request) -> PlainTextResponse:
return PlainTextResponse("Homepage", status_code=200, headers={"Vary": "Accept-Encoding"})
app = Starlette(
routes=[
Route("/", endpoint=homepage),
],
middleware=[Middleware(CORSMiddleware, allow_origins=["https://example.org"])],
)
client = test_client_factory(app)
response = client.get("/", headers={"Origin": "https://example.org"})
assert response.status_code == 200
assert response.headers["vary"] == "Accept-Encoding, Origin"
def test_cors_allowed_origin_does_not_leak_between_credentialed_requests(
test_client_factory: TestClientFactory,
) -> None:
def homepage(request: Request) -> PlainTextResponse:
return PlainTextResponse("Homepage", status_code=200)
app = Starlette(
routes=[
Route("/", endpoint=homepage),
],
middleware=[
Middleware(
CORSMiddleware,
allow_origins=["*"],
allow_headers=["*"],
allow_methods=["*"],
)
],
)
client = test_client_factory(app)
response = client.get("/", headers={"Origin": "https://someplace.org"})
assert response.headers["access-control-allow-origin"] == "*"
assert "access-control-allow-credentials" not in response.headers
response = client.get("/", headers={"Cookie": "foo=bar", "Origin": "https://someplace.org"})
assert response.headers["access-control-allow-origin"] == "https://someplace.org"
assert "access-control-allow-credentials" not in response.headers
response = client.get("/", headers={"Origin": "https://someplace.org"})
assert response.headers["access-control-allow-origin"] == "*"
assert "access-control-allow-credentials" not in response.headers
def test_cors_private_network_access_allowed(test_client_factory: TestClientFactory) -> None:
def homepage(request: Request) -> PlainTextResponse:
return PlainTextResponse("Homepage", status_code=200)
app = Starlette(
routes=[Route("/", endpoint=homepage)],
middleware=[
Middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_private_network=True,
)
],
)
client = test_client_factory(app)
headers_without_pna = {"Origin": "https://example.org", "Access-Control-Request-Method": "GET"}
headers_with_pna = {**headers_without_pna, "Access-Control-Request-Private-Network": "true"}
# Test preflight with Private Network Access request
response = client.options("/", headers=headers_with_pna)
assert response.status_code == 200
assert response.text == "OK"
assert response.headers["access-control-allow-private-network"] == "true"
# Test preflight without Private Network Access request
response = client.options("/", headers=headers_without_pna)
assert response.status_code == 200
assert response.text == "OK"
assert "access-control-allow-private-network" not in response.headers
# The access-control-allow-private-network header is not set for non-preflight requests
response = client.get("/", headers=headers_with_pna)
assert response.status_code == 200
assert response.text == "Homepage"
assert "access-control-allow-private-network" not in response.headers
assert "access-control-allow-origin" in response.headers
def test_cors_private_network_access_disallowed(test_client_factory: TestClientFactory) -> None:
def homepage(request: Request) -> None: ... # pragma: no cover
app = Starlette(
routes=[Route("/", endpoint=homepage)],
middleware=[
Middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_private_network=False,
)
],
)
client = test_client_factory(app)
# Test preflight with Private Network Access request when not allowed
headers_without_pna = {"Origin": "https://example.org", "Access-Control-Request-Method": "GET"}
headers_with_pna = {**headers_without_pna, "Access-Control-Request-Private-Network": "true"}
response = client.options("/", headers=headers_without_pna)
assert response.status_code == 200
assert response.text == "OK"
assert "access-control-allow-private-network" not in response.headers
# If the request includes a Private Network Access header, but the middleware is configured to disallow it, the
# request should be denied with a 400 response.
response = client.options("/", headers=headers_with_pna)
assert response.status_code == 400
assert response.text == "Disallowed CORS private-network"
assert "access-control-allow-private-network" not in response.headers
| starlette |
python | from __future__ import annotations
import html
import inspect
import sys
import traceback
from starlette._utils import is_async_callable
from starlette.concurrency import run_in_threadpool
from starlette.requests import Request
from starlette.responses import HTMLResponse, PlainTextResponse, Response
from starlette.types import ASGIApp, ExceptionHandler, Message, Receive, Scope, Send
STYLES = """
p {
color: #211c1c;
}
.traceback-container {
border: 1px solid #038BB8;
}
.traceback-title {
background-color: #038BB8;
color: lemonchiffon;
padding: 12px;
font-size: 20px;
margin-top: 0px;
}
.frame-line {
padding-left: 10px;
font-family: monospace;
}
.frame-filename {
font-family: monospace;
}
.center-line {
background-color: #038BB8;
color: #f9f6e1;
padding: 5px 0px 5px 5px;
}
.lineno {
margin-right: 5px;
}
.frame-title {
font-weight: unset;
padding: 10px 10px 10px 10px;
background-color: #E4F4FD;
margin-right: 10px;
color: #191f21;
font-size: 17px;
border: 1px solid #c7dce8;
}
.collapse-btn {
float: right;
padding: 0px 5px 1px 5px;
border: solid 1px #96aebb;
cursor: pointer;
}
.collapsed {
display: none;
}
.source-code {
font-family: courier;
font-size: small;
padding-bottom: 10px;
}
"""
JS = """
<script type="text/javascript">
function collapse(element){
const frameId = element.getAttribute("data-frame-id");
const frame = document.getElementById(frameId);
if (frame.classList.contains("collapsed")){
element.innerHTML = "‒";
frame.classList.remove("collapsed");
} else {
element.innerHTML = "+";
frame.classList.add("collapsed");
}
}
</script>
"""
TEMPLATE = """
<html>
<head>
<style type='text/css'>
{styles}
</style>
<title>Starlette Debugger</title>
</head>
<body>
<h1>500 Server Error</h1>
<h2>{error}</h2>
<div class="traceback-container">
<p class="traceback-title">Traceback</p>
<div>{exc_html}</div>
</div>
{js}
</body>
</html>
"""
FRAME_TEMPLATE = """
<div>
<p class="frame-title">File <span class="frame-filename">{frame_filename}</span>,
line <i>{frame_lineno}</i>,
in <b>{frame_name}</b>
<span class="collapse-btn" data-frame-id="{frame_filename}-{frame_lineno}" onclick="collapse(this)">{collapse_button}</span>
</p>
<div id="{frame_filename}-{frame_lineno}" class="source-code {collapsed}">{code_context}</div>
</div>
""" # noqa: E501
LINE = """
<p><span class="frame-line">
<span class="lineno">{lineno}.</span> {line}</span></p>
"""
CENTER_LINE = """
<p class="center-line"><span class="frame-line center-line">
<span class="lineno">{lineno}.</span> {line}</span></p>
"""
class ServerErrorMiddleware:
"""
Handles returning 500 responses when a server error occurs.
If 'debug' is set, then traceback responses will be returned,
otherwise the designated 'handler' will be called.
This middleware class should generally be used to wrap *everything*
else up, so that unhandled exceptions anywhere in the stack
always result in an appropriate 500 response.
"""
def __init__(
self,
app: ASGIApp,
handler: ExceptionHandler | None = None,
debug: bool = False,
) -> None:
self.app = app
self.handler = handler
self.debug = debug
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
response_started = False
async def _send(message: Message) -> None:
nonlocal response_started, send
if message["type"] == "http.response.start":
response_started = True
await send(message)
try:
await self.app(scope, receive, _send)
except Exception as exc:
request = Request(scope)
if self.debug:
# In debug mode, return traceback responses.
response = self.debug_response(request, exc)
elif self.handler is None:
# Use our default 500 error handler.
response = self.error_response(request, exc)
else:
# Use an installed 500 error handler.
if is_async_callable(self.handler):
response = await self.handler(request, exc)
else:
response = await run_in_threadpool(self.handler, request, exc)
if not response_started:
await response(scope, receive, send)
# We always continue to raise the exception.
# This allows servers to log the error, or allows test clients
# to optionally raise the error within the test case.
raise exc
def format_line(self, index: int, line: str, frame_lineno: int, frame_index: int) -> str:
values = {
# HTML escape - line could contain < or >
"line": html.escape(line).replace(" ", " "),
"lineno": (frame_lineno - frame_index) + index,
}
if index != frame_index:
return LINE.format(**values)
return CENTER_LINE.format(**values)
def generate_frame_html(self, frame: inspect.FrameInfo, is_collapsed: bool) -> str:
code_context = "".join(
self.format_line(
index,
line,
frame.lineno,
frame.index, # type: ignore[arg-type]
)
for index, line in enumerate(frame.code_context or [])
)
values = {
# HTML escape - filename could contain < or >, especially if it's a virtual
# file e.g. <stdin> in the REPL
"frame_filename": html.escape(frame.filename),
"frame_lineno": frame.lineno,
# HTML escape - if you try very hard it's possible to name a function with <
# or >
"frame_name": html.escape(frame.function),
"code_context": code_context,
"collapsed": "collapsed" if is_collapsed else "",
"collapse_button": "+" if is_collapsed else "‒",
}
return FRAME_TEMPLATE.format(**values)
def generate_html(self, exc: Exception, limit: int = 7) -> str:
traceback_obj = traceback.TracebackException.from_exception(exc, capture_locals=True)
exc_html = ""
is_collapsed = False
exc_traceback = exc.__traceback__
if exc_traceback is not None:
frames = inspect.getinnerframes(exc_traceback, limit)
for frame in reversed(frames):
exc_html += self.generate_frame_html(frame, is_collapsed)
is_collapsed = True
if sys.version_info >= (3, 13): # pragma: no cover
exc_type_str = traceback_obj.exc_type_str
else: # pragma: no cover
exc_type_str = traceback_obj.exc_type.__name__
# escape error class and text
error = f"{html.escape(exc_type_str)}: {html.escape(str(traceback_obj))}"
return TEMPLATE.format(styles=STYLES, js=JS, error=error, exc_html=exc_html)
def generate_plain_text(self, exc: Exception) -> str:
return "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))
def debug_response(self, request: Request, exc: Exception) -> Response:
accept = request.headers.get("accept", "")
if "text/html" in accept:
content = self.generate_html(exc)
return HTMLResponse(content, status_code=500)
content = self.generate_plain_text(exc)
return PlainTextResponse(content, status_code=500)
def error_response(self, request: Request, exc: Exception) -> Response:
return PlainTextResponse("Internal Server Error", status_code=500)
| from typing import Any
import pytest
from starlette.applications import Starlette
from starlette.background import BackgroundTask
from starlette.middleware.errors import ServerErrorMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
from starlette.routing import Route
from starlette.types import Receive, Scope, Send
from tests.types import TestClientFactory
def test_handler(
test_client_factory: TestClientFactory,
) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
raise RuntimeError("Something went wrong")
def error_500(request: Request, exc: Exception) -> JSONResponse:
return JSONResponse({"detail": "Server Error"}, status_code=500)
app = ServerErrorMiddleware(app, handler=error_500)
client = test_client_factory(app, raise_server_exceptions=False)
response = client.get("/")
assert response.status_code == 500
assert response.json() == {"detail": "Server Error"}
def test_debug_text(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
raise RuntimeError("Something went wrong")
app = ServerErrorMiddleware(app, debug=True)
client = test_client_factory(app, raise_server_exceptions=False)
response = client.get("/")
assert response.status_code == 500
assert response.headers["content-type"].startswith("text/plain")
assert "RuntimeError: Something went wrong" in response.text
def test_debug_html(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
raise RuntimeError("Something went wrong")
app = ServerErrorMiddleware(app, debug=True)
client = test_client_factory(app, raise_server_exceptions=False)
response = client.get("/", headers={"Accept": "text/html, */*"})
assert response.status_code == 500
assert response.headers["content-type"].startswith("text/html")
assert "RuntimeError" in response.text
def test_debug_after_response_sent(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
response = Response(b"", status_code=204)
await response(scope, receive, send)
raise RuntimeError("Something went wrong")
app = ServerErrorMiddleware(app, debug=True)
client = test_client_factory(app)
with pytest.raises(RuntimeError):
client.get("/")
def test_debug_not_http(test_client_factory: TestClientFactory) -> None:
"""
DebugMiddleware should just pass through any non-http messages as-is.
"""
async def app(scope: Scope, receive: Receive, send: Send) -> None:
raise RuntimeError("Something went wrong")
app = ServerErrorMiddleware(app)
with pytest.raises(RuntimeError):
client = test_client_factory(app)
with client.websocket_connect("/"):
pass # pragma: no cover
def test_background_task(test_client_factory: TestClientFactory) -> None:
accessed_error_handler = False
def error_handler(request: Request, exc: Exception) -> Any:
nonlocal accessed_error_handler
accessed_error_handler = True
def raise_exception() -> None:
raise Exception("Something went wrong")
async def endpoint(request: Request) -> Response:
task = BackgroundTask(raise_exception)
return Response(status_code=204, background=task)
app = Starlette(
routes=[Route("/", endpoint=endpoint)],
exception_handlers={Exception: error_handler},
)
client = test_client_factory(app, raise_server_exceptions=False)
response = client.get("/")
assert response.status_code == 204
assert accessed_error_handler
| starlette |
python | from __future__ import annotations
from collections.abc import AsyncGenerator, AsyncIterable, Awaitable, Callable, Mapping, MutableMapping
from typing import Any, TypeVar
import anyio
from starlette._utils import collapse_excgroups
from starlette.requests import ClientDisconnect, Request
from starlette.responses import Response
from starlette.types import ASGIApp, Message, Receive, Scope, Send
RequestResponseEndpoint = Callable[[Request], Awaitable[Response]]
DispatchFunction = Callable[[Request, RequestResponseEndpoint], Awaitable[Response]]
BodyStreamGenerator = AsyncGenerator[bytes | MutableMapping[str, Any], None]
AsyncContentStream = AsyncIterable[str | bytes | memoryview | MutableMapping[str, Any]]
T = TypeVar("T")
class _CachedRequest(Request):
"""
If the user calls Request.body() from their dispatch function
we cache the entire request body in memory and pass that to downstream middlewares,
but if they call Request.stream() then all we do is send an
empty body so that downstream things don't hang forever.
"""
def __init__(self, scope: Scope, receive: Receive):
super().__init__(scope, receive)
self._wrapped_rcv_disconnected = False
self._wrapped_rcv_consumed = False
self._wrapped_rc_stream = self.stream()
async def wrapped_receive(self) -> Message:
# wrapped_rcv state 1: disconnected
if self._wrapped_rcv_disconnected:
# we've already sent a disconnect to the downstream app
# we don't need to wait to get another one
# (although most ASGI servers will just keep sending it)
return {"type": "http.disconnect"}
# wrapped_rcv state 1: consumed but not yet disconnected
if self._wrapped_rcv_consumed:
# since the downstream app has consumed us all that is left
# is to send it a disconnect
if self._is_disconnected:
# the middleware has already seen the disconnect
# since we know the client is disconnected no need to wait
# for the message
self._wrapped_rcv_disconnected = True
return {"type": "http.disconnect"}
# we don't know yet if the client is disconnected or not
# so we'll wait until we get that message
msg = await self.receive()
if msg["type"] != "http.disconnect": # pragma: no cover
# at this point a disconnect is all that we should be receiving
# if we get something else, things went wrong somewhere
raise RuntimeError(f"Unexpected message received: {msg['type']}")
self._wrapped_rcv_disconnected = True
return msg
# wrapped_rcv state 3: not yet consumed
if getattr(self, "_body", None) is not None:
# body() was called, we return it even if the client disconnected
self._wrapped_rcv_consumed = True
return {
"type": "http.request",
"body": self._body,
"more_body": False,
}
elif self._stream_consumed:
# stream() was called to completion
# return an empty body so that downstream apps don't hang
# waiting for a disconnect
self._wrapped_rcv_consumed = True
return {
"type": "http.request",
"body": b"",
"more_body": False,
}
else:
# body() was never called and stream() wasn't consumed
try:
stream = self.stream()
chunk = await stream.__anext__()
self._wrapped_rcv_consumed = self._stream_consumed
return {
"type": "http.request",
"body": chunk,
"more_body": not self._stream_consumed,
}
except ClientDisconnect:
self._wrapped_rcv_disconnected = True
return {"type": "http.disconnect"}
class BaseHTTPMiddleware:
def __init__(self, app: ASGIApp, dispatch: DispatchFunction | None = None) -> None:
self.app = app
self.dispatch_func = self.dispatch if dispatch is None else dispatch
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
request = _CachedRequest(scope, receive)
wrapped_receive = request.wrapped_receive
response_sent = anyio.Event()
app_exc: Exception | None = None
exception_already_raised = False
async def call_next(request: Request) -> Response:
async def receive_or_disconnect() -> Message:
if response_sent.is_set():
return {"type": "http.disconnect"}
async with anyio.create_task_group() as task_group:
async def wrap(func: Callable[[], Awaitable[T]]) -> T:
result = await func()
task_group.cancel_scope.cancel()
return result
task_group.start_soon(wrap, response_sent.wait)
message = await wrap(wrapped_receive)
if response_sent.is_set():
return {"type": "http.disconnect"}
return message
async def send_no_error(message: Message) -> None:
try:
await send_stream.send(message)
except anyio.BrokenResourceError:
# recv_stream has been closed, i.e. response_sent has been set.
return
async def coro() -> None:
nonlocal app_exc
with send_stream:
try:
await self.app(scope, receive_or_disconnect, send_no_error)
except Exception as exc:
app_exc = exc
task_group.start_soon(coro)
try:
message = await recv_stream.receive()
info = message.get("info", None)
if message["type"] == "http.response.debug" and info is not None:
message = await recv_stream.receive()
except anyio.EndOfStream:
if app_exc is not None:
nonlocal exception_already_raised
exception_already_raised = True
# Prevent `anyio.EndOfStream` from polluting app exception context.
# If both cause and context are None then the context is suppressed
# and `anyio.EndOfStream` is not present in the exception traceback.
# If exception cause is not None then it is propagated with
# reraising here.
# If exception has no cause but has context set then the context is
# propagated as a cause with the reraise. This is necessary in order
# to prevent `anyio.EndOfStream` from polluting the exception
# context.
raise app_exc from app_exc.__cause__ or app_exc.__context__
raise RuntimeError("No response returned.")
assert message["type"] == "http.response.start"
async def body_stream() -> BodyStreamGenerator:
async for message in recv_stream:
if message["type"] == "http.response.pathsend":
yield message
break
assert message["type"] == "http.response.body", f"Unexpected message: {message}"
body = message.get("body", b"")
if body:
yield body
if not message.get("more_body", False):
break
response = _StreamingResponse(status_code=message["status"], content=body_stream(), info=info)
response.raw_headers = message["headers"]
return response
streams: anyio.create_memory_object_stream[Message] = anyio.create_memory_object_stream()
send_stream, recv_stream = streams
with recv_stream, send_stream, collapse_excgroups():
async with anyio.create_task_group() as task_group:
response = await self.dispatch_func(request, call_next)
await response(scope, wrapped_receive, send)
response_sent.set()
recv_stream.close()
if app_exc is not None and not exception_already_raised:
raise app_exc
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
raise NotImplementedError() # pragma: no cover
class _StreamingResponse(Response):
def __init__(
self,
content: AsyncContentStream,
status_code: int = 200,
headers: Mapping[str, str] | None = None,
media_type: str | None = None,
info: Mapping[str, Any] | None = None,
) -> None:
self.info = info
self.body_iterator = content
self.status_code = status_code
self.media_type = media_type
self.init_headers(headers)
self.background = None
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if self.info is not None:
await send({"type": "http.response.debug", "info": self.info})
await send(
{
"type": "http.response.start",
"status": self.status_code,
"headers": self.raw_headers,
}
)
should_close_body = True
async for chunk in self.body_iterator:
if isinstance(chunk, dict):
# We got an ASGI message which is not response body (eg: pathsend)
should_close_body = False
await send(chunk)
continue
await send({"type": "http.response.body", "body": chunk, "more_body": True})
if should_close_body:
await send({"type": "http.response.body", "body": b"", "more_body": False})
if self.background:
await self.background()
| from __future__ import annotations
import contextvars
from collections.abc import AsyncGenerator, AsyncIterator, Generator
from contextlib import AsyncExitStack
from pathlib import Path
from typing import Any
import anyio
import pytest
from anyio.abc import TaskStatus
from starlette.applications import Starlette
from starlette.background import BackgroundTask
from starlette.middleware import Middleware, _MiddlewareFactory
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.requests import ClientDisconnect, Request
from starlette.responses import FileResponse, PlainTextResponse, Response, StreamingResponse
from starlette.routing import Route, WebSocketRoute
from starlette.testclient import TestClient
from starlette.types import ASGIApp, Message, Receive, Scope, Send
from starlette.websockets import WebSocket
from tests.types import TestClientFactory
class CustomMiddleware(BaseHTTPMiddleware):
async def dispatch(
self,
request: Request,
call_next: RequestResponseEndpoint,
) -> Response:
response = await call_next(request)
response.headers["Custom-Header"] = "Example"
return response
def homepage(request: Request) -> PlainTextResponse:
return PlainTextResponse("Homepage")
def exc(request: Request) -> None:
raise Exception("Exc")
def exc_stream(request: Request) -> StreamingResponse:
return StreamingResponse(_generate_faulty_stream())
def _generate_faulty_stream() -> Generator[bytes, None, None]:
yield b"Ok"
raise Exception("Faulty Stream")
class NoResponse:
def __init__(
self,
scope: Scope,
receive: Receive,
send: Send,
):
pass
def __await__(self) -> Generator[Any, None, None]:
return self.dispatch().__await__()
async def dispatch(self) -> None:
pass
async def websocket_endpoint(session: WebSocket) -> None:
await session.accept()
await session.send_text("Hello, world!")
await session.close()
app = Starlette(
routes=[
Route("/", endpoint=homepage),
Route("/exc", endpoint=exc),
Route("/exc-stream", endpoint=exc_stream),
Route("/no-response", endpoint=NoResponse),
WebSocketRoute("/ws", endpoint=websocket_endpoint),
],
middleware=[Middleware(CustomMiddleware)],
)
def test_custom_middleware(test_client_factory: TestClientFactory) -> None:
client = test_client_factory(app)
response = client.get("/")
assert response.headers["Custom-Header"] == "Example"
with pytest.raises(Exception) as ctx:
response = client.get("/exc")
assert str(ctx.value) == "Exc"
with pytest.raises(Exception) as ctx:
response = client.get("/exc-stream")
assert str(ctx.value) == "Faulty Stream"
with pytest.raises(RuntimeError):
response = client.get("/no-response")
with client.websocket_connect("/ws") as session:
text = session.receive_text()
assert text == "Hello, world!"
def test_state_data_across_multiple_middlewares(
test_client_factory: TestClientFactory,
) -> None:
expected_value1 = "foo"
expected_value2 = "bar"
class aMiddleware(BaseHTTPMiddleware):
async def dispatch(
self,
request: Request,
call_next: RequestResponseEndpoint,
) -> Response:
request.state.foo = expected_value1
response = await call_next(request)
return response
class bMiddleware(BaseHTTPMiddleware):
async def dispatch(
self,
request: Request,
call_next: RequestResponseEndpoint,
) -> Response:
request.state.bar = expected_value2
response = await call_next(request)
response.headers["X-State-Foo"] = request.state.foo
return response
class cMiddleware(BaseHTTPMiddleware):
async def dispatch(
self,
request: Request,
call_next: RequestResponseEndpoint,
) -> Response:
response = await call_next(request)
response.headers["X-State-Bar"] = request.state.bar
return response
def homepage(request: Request) -> PlainTextResponse:
return PlainTextResponse("OK")
app = Starlette(
routes=[Route("/", homepage)],
middleware=[
Middleware(aMiddleware),
Middleware(bMiddleware),
Middleware(cMiddleware),
],
)
client = test_client_factory(app)
response = client.get("/")
assert response.text == "OK"
assert response.headers["X-State-Foo"] == expected_value1
assert response.headers["X-State-Bar"] == expected_value2
def test_app_middleware_argument(test_client_factory: TestClientFactory) -> None:
def homepage(request: Request) -> PlainTextResponse:
return PlainTextResponse("Homepage")
app = Starlette(routes=[Route("/", homepage)], middleware=[Middleware(CustomMiddleware)])
client = test_client_factory(app)
response = client.get("/")
assert response.headers["Custom-Header"] == "Example"
def test_fully_evaluated_response(test_client_factory: TestClientFactory) -> None:
# Test for https://github.com/Kludex/starlette/issues/1022
class CustomMiddleware(BaseHTTPMiddleware):
async def dispatch(
self,
request: Request,
call_next: RequestResponseEndpoint,
) -> PlainTextResponse:
await call_next(request)
return PlainTextResponse("Custom")
app = Starlette(middleware=[Middleware(CustomMiddleware)])
client = test_client_factory(app)
response = client.get("/does_not_exist")
assert response.text == "Custom"
ctxvar: contextvars.ContextVar[str] = contextvars.ContextVar("ctxvar")
class CustomMiddlewareWithoutBaseHTTPMiddleware:
def __init__(self, app: ASGIApp) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
ctxvar.set("set by middleware")
await self.app(scope, receive, send)
assert ctxvar.get() == "set by endpoint"
class CustomMiddlewareUsingBaseHTTPMiddleware(BaseHTTPMiddleware):
async def dispatch(
self,
request: Request,
call_next: RequestResponseEndpoint,
) -> Response:
ctxvar.set("set by middleware")
resp = await call_next(request)
assert ctxvar.get() == "set by endpoint"
return resp # pragma: no cover
@pytest.mark.parametrize(
"middleware_cls",
[
CustomMiddlewareWithoutBaseHTTPMiddleware,
pytest.param(
CustomMiddlewareUsingBaseHTTPMiddleware,
marks=pytest.mark.xfail(
reason=(
"BaseHTTPMiddleware creates a TaskGroup which copies the context"
"and erases any changes to it made within the TaskGroup"
),
raises=AssertionError,
),
),
],
)
def test_contextvars(
test_client_factory: TestClientFactory,
middleware_cls: _MiddlewareFactory[Any],
) -> None:
# this has to be an async endpoint because Starlette calls run_in_threadpool
# on sync endpoints which has it's own set of peculiarities w.r.t propagating
# contextvars (it propagates them forwards but not backwards)
async def homepage(request: Request) -> PlainTextResponse:
assert ctxvar.get() == "set by middleware"
ctxvar.set("set by endpoint")
return PlainTextResponse("Homepage")
app = Starlette(middleware=[Middleware(middleware_cls)], routes=[Route("/", homepage)])
client = test_client_factory(app)
response = client.get("/")
assert response.status_code == 200, response.content
@pytest.mark.anyio
async def test_run_background_tasks_even_if_client_disconnects() -> None:
# test for https://github.com/Kludex/starlette/issues/1438
response_complete = anyio.Event()
background_task_run = anyio.Event()
async def sleep_and_set() -> None:
# small delay to give BaseHTTPMiddleware a chance to cancel us
# this is required to make the test fail prior to fixing the issue
# so do not be surprised if you remove it and the test still passes
await anyio.sleep(0.1)
background_task_run.set()
async def endpoint_with_background_task(_: Request) -> PlainTextResponse:
return PlainTextResponse(background=BackgroundTask(sleep_and_set))
async def passthrough(
request: Request,
call_next: RequestResponseEndpoint,
) -> Response:
return await call_next(request)
app = Starlette(
middleware=[Middleware(BaseHTTPMiddleware, dispatch=passthrough)],
routes=[Route("/", endpoint_with_background_task)],
)
scope = {
"type": "http",
"version": "3",
"method": "GET",
"path": "/",
}
async def receive() -> Message:
raise NotImplementedError("Should not be called!")
async def send(message: Message) -> None:
if message["type"] == "http.response.body":
if not message.get("more_body", False): # pragma: no branch
response_complete.set()
await app(scope, receive, send)
assert background_task_run.is_set()
def test_run_background_tasks_raise_exceptions(test_client_factory: TestClientFactory) -> None:
# test for https://github.com/Kludex/starlette/issues/2625
async def sleep_and_set() -> None:
await anyio.sleep(0.1)
raise ValueError("TEST")
async def endpoint_with_background_task(_: Request) -> PlainTextResponse:
return PlainTextResponse(background=BackgroundTask(sleep_and_set))
async def passthrough(request: Request, call_next: RequestResponseEndpoint) -> Response:
return await call_next(request)
app = Starlette(
middleware=[Middleware(BaseHTTPMiddleware, dispatch=passthrough)],
routes=[Route("/", endpoint_with_background_task)],
)
client = test_client_factory(app)
with pytest.raises(ValueError, match="TEST"):
client.get("/")
def test_exception_can_be_caught(test_client_factory: TestClientFactory) -> None:
async def error_endpoint(_: Request) -> None:
raise ValueError("TEST")
async def catches_error(request: Request, call_next: RequestResponseEndpoint) -> Response:
try:
return await call_next(request)
except ValueError as exc:
return PlainTextResponse(content=str(exc), status_code=400)
app = Starlette(
middleware=[Middleware(BaseHTTPMiddleware, dispatch=catches_error)],
routes=[Route("/", error_endpoint)],
)
client = test_client_factory(app)
response = client.get("/")
assert response.status_code == 400
assert response.text == "TEST"
@pytest.mark.anyio
async def test_do_not_block_on_background_tasks() -> None:
response_complete = anyio.Event()
events: list[str | Message] = []
async def sleep_and_set() -> None:
events.append("Background task started")
await anyio.sleep(0.1)
events.append("Background task finished")
async def endpoint_with_background_task(_: Request) -> PlainTextResponse:
return PlainTextResponse(content="Hello", background=BackgroundTask(sleep_and_set))
async def passthrough(request: Request, call_next: RequestResponseEndpoint) -> Response:
return await call_next(request)
app = Starlette(
middleware=[Middleware(BaseHTTPMiddleware, dispatch=passthrough)],
routes=[Route("/", endpoint_with_background_task)],
)
scope = {
"type": "http",
"version": "3",
"method": "GET",
"path": "/",
}
async def receive() -> Message:
raise NotImplementedError("Should not be called!")
async def send(message: Message) -> None:
if message["type"] == "http.response.body":
events.append(message)
if not message.get("more_body", False):
response_complete.set()
async with anyio.create_task_group() as tg:
tg.start_soon(app, scope, receive, send)
tg.start_soon(app, scope, receive, send)
# Without the fix, the background tasks would start and finish before the
# last http.response.body is sent.
assert events == [
{"body": b"Hello", "more_body": True, "type": "http.response.body"},
{"body": b"", "more_body": False, "type": "http.response.body"},
{"body": b"Hello", "more_body": True, "type": "http.response.body"},
{"body": b"", "more_body": False, "type": "http.response.body"},
"Background task started",
"Background task started",
"Background task finished",
"Background task finished",
]
@pytest.mark.anyio
async def test_run_context_manager_exit_even_if_client_disconnects() -> None:
# test for https://github.com/Kludex/starlette/issues/1678#issuecomment-1172916042
response_complete = anyio.Event()
context_manager_exited = anyio.Event()
async def sleep_and_set() -> None:
# small delay to give BaseHTTPMiddleware a chance to cancel us
# this is required to make the test fail prior to fixing the issue
# so do not be surprised if you remove it and the test still passes
await anyio.sleep(0.1)
context_manager_exited.set()
class ContextManagerMiddleware:
def __init__(self, app: ASGIApp):
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
async with AsyncExitStack() as stack:
stack.push_async_callback(sleep_and_set)
await self.app(scope, receive, send)
async def simple_endpoint(_: Request) -> PlainTextResponse:
return PlainTextResponse(background=BackgroundTask(sleep_and_set))
async def passthrough(
request: Request,
call_next: RequestResponseEndpoint,
) -> Response:
return await call_next(request)
app = Starlette(
middleware=[
Middleware(BaseHTTPMiddleware, dispatch=passthrough),
Middleware(ContextManagerMiddleware),
],
routes=[Route("/", simple_endpoint)],
)
scope = {
"type": "http",
"version": "3",
"method": "GET",
"path": "/",
}
async def receive() -> Message:
raise NotImplementedError("Should not be called!")
async def send(message: Message) -> None:
if message["type"] == "http.response.body":
if not message.get("more_body", False): # pragma: no branch
response_complete.set()
await app(scope, receive, send)
assert context_manager_exited.is_set()
def test_app_receives_http_disconnect_while_sending_if_discarded(
test_client_factory: TestClientFactory,
) -> None:
class DiscardingMiddleware(BaseHTTPMiddleware):
async def dispatch(
self,
request: Request,
call_next: Any,
) -> PlainTextResponse:
# As a matter of ordering, this test targets the case where the downstream
# app response is discarded while it is sending a response body.
# We need to wait for the downstream app to begin sending a response body
# before sending the middleware response that will overwrite the downstream
# response.
downstream_app_response = await call_next(request)
body_generator = downstream_app_response.body_iterator
try:
await body_generator.__anext__()
finally:
await body_generator.aclose()
return PlainTextResponse("Custom")
async def downstream_app(
scope: Scope,
receive: Receive,
send: Send,
) -> None:
await send(
{
"type": "http.response.start",
"status": 200,
"headers": [
(b"content-type", b"text/plain"),
],
}
)
async with anyio.create_task_group() as task_group:
async def cancel_on_disconnect(
*,
task_status: TaskStatus[None] = anyio.TASK_STATUS_IGNORED,
) -> None:
task_status.started()
while True:
message = await receive()
if message["type"] == "http.disconnect": # pragma: no branch
task_group.cancel_scope.cancel()
break
# Using start instead of start_soon to ensure that
# cancel_on_disconnect is scheduled by the event loop
# before we start returning the body
await task_group.start(cancel_on_disconnect)
# A timeout is set for 0.1 second in order to ensure that
# we never deadlock the test run in an infinite loop
with anyio.move_on_after(0.1):
while True:
await send(
{
"type": "http.response.body",
"body": b"chunk ",
"more_body": True,
}
)
pytest.fail("http.disconnect should have been received and canceled the scope") # pragma: no cover
app = DiscardingMiddleware(downstream_app)
client = test_client_factory(app)
response = client.get("/does_not_exist")
assert response.text == "Custom"
def test_app_receives_http_disconnect_after_sending_if_discarded(
test_client_factory: TestClientFactory,
) -> None:
class DiscardingMiddleware(BaseHTTPMiddleware):
async def dispatch(
self,
request: Request,
call_next: RequestResponseEndpoint,
) -> PlainTextResponse:
await call_next(request)
return PlainTextResponse("Custom")
async def downstream_app(
scope: Scope,
receive: Receive,
send: Send,
) -> None:
await send(
{
"type": "http.response.start",
"status": 200,
"headers": [
(b"content-type", b"text/plain"),
],
}
)
await send(
{
"type": "http.response.body",
"body": b"first chunk, ",
"more_body": True,
}
)
await send(
{
"type": "http.response.body",
"body": b"second chunk",
"more_body": True,
}
)
message = await receive()
assert message["type"] == "http.disconnect"
app = DiscardingMiddleware(downstream_app)
client = test_client_factory(app)
response = client.get("/does_not_exist")
assert response.text == "Custom"
def test_read_request_stream_in_app_after_middleware_calls_stream(
test_client_factory: TestClientFactory,
) -> None:
async def homepage(request: Request) -> PlainTextResponse:
expected = [b""]
async for chunk in request.stream():
assert chunk == expected.pop(0)
assert expected == []
return PlainTextResponse("Homepage")
class ConsumingMiddleware(BaseHTTPMiddleware):
async def dispatch(
self,
request: Request,
call_next: RequestResponseEndpoint,
) -> Response:
expected = [b"a", b""]
async for chunk in request.stream():
assert chunk == expected.pop(0)
assert expected == []
return await call_next(request)
app = Starlette(
routes=[Route("/", homepage, methods=["POST"])],
middleware=[Middleware(ConsumingMiddleware)],
)
client: TestClient = test_client_factory(app)
response = client.post("/", content=b"a")
assert response.status_code == 200
def test_read_request_stream_in_app_after_middleware_calls_body(
test_client_factory: TestClientFactory,
) -> None:
async def homepage(request: Request) -> PlainTextResponse:
expected = [b"a", b""]
async for chunk in request.stream():
assert chunk == expected.pop(0)
assert expected == []
return PlainTextResponse("Homepage")
class ConsumingMiddleware(BaseHTTPMiddleware):
async def dispatch(
self,
request: Request,
call_next: RequestResponseEndpoint,
) -> Response:
assert await request.body() == b"a"
return await call_next(request)
app = Starlette(
routes=[Route("/", homepage, methods=["POST"])],
middleware=[Middleware(ConsumingMiddleware)],
)
client: TestClient = test_client_factory(app)
response = client.post("/", content=b"a")
assert response.status_code == 200
def test_read_request_body_in_app_after_middleware_calls_stream(
test_client_factory: TestClientFactory,
) -> None:
async def homepage(request: Request) -> PlainTextResponse:
assert await request.body() == b""
return PlainTextResponse("Homepage")
class ConsumingMiddleware(BaseHTTPMiddleware):
async def dispatch(
self,
request: Request,
call_next: RequestResponseEndpoint,
) -> Response:
expected = [b"a", b""]
async for chunk in request.stream():
assert chunk == expected.pop(0)
assert expected == []
return await call_next(request)
app = Starlette(
routes=[Route("/", homepage, methods=["POST"])],
middleware=[Middleware(ConsumingMiddleware)],
)
client: TestClient = test_client_factory(app)
response = client.post("/", content=b"a")
assert response.status_code == 200
def test_read_request_body_in_app_after_middleware_calls_body(
test_client_factory: TestClientFactory,
) -> None:
async def homepage(request: Request) -> PlainTextResponse:
assert await request.body() == b"a"
return PlainTextResponse("Homepage")
class ConsumingMiddleware(BaseHTTPMiddleware):
async def dispatch(
self,
request: Request,
call_next: RequestResponseEndpoint,
) -> Response:
assert await request.body() == b"a"
return await call_next(request)
app = Starlette(
routes=[Route("/", homepage, methods=["POST"])],
middleware=[Middleware(ConsumingMiddleware)],
)
client: TestClient = test_client_factory(app)
response = client.post("/", content=b"a")
assert response.status_code == 200
def test_read_request_stream_in_dispatch_after_app_calls_stream(
test_client_factory: TestClientFactory,
) -> None:
async def homepage(request: Request) -> PlainTextResponse:
expected = [b"a", b""]
async for chunk in request.stream():
assert chunk == expected.pop(0)
assert expected == []
return PlainTextResponse("Homepage")
class ConsumingMiddleware(BaseHTTPMiddleware):
async def dispatch(
self,
request: Request,
call_next: RequestResponseEndpoint,
) -> Response:
resp = await call_next(request)
with pytest.raises(RuntimeError, match="Stream consumed"):
async for _ in request.stream():
raise AssertionError("should not be called") # pragma: no cover
return resp
app = Starlette(
routes=[Route("/", homepage, methods=["POST"])],
middleware=[Middleware(ConsumingMiddleware)],
)
client: TestClient = test_client_factory(app)
response = client.post("/", content=b"a")
assert response.status_code == 200
def test_read_request_stream_in_dispatch_after_app_calls_body(
test_client_factory: TestClientFactory,
) -> None:
async def homepage(request: Request) -> PlainTextResponse:
assert await request.body() == b"a"
return PlainTextResponse("Homepage")
class ConsumingMiddleware(BaseHTTPMiddleware):
async def dispatch(
self,
request: Request,
call_next: RequestResponseEndpoint,
) -> Response:
resp = await call_next(request)
with pytest.raises(RuntimeError, match="Stream consumed"):
async for _ in request.stream():
raise AssertionError("should not be called") # pragma: no cover
return resp
app = Starlette(
routes=[Route("/", homepage, methods=["POST"])],
middleware=[Middleware(ConsumingMiddleware)],
)
client: TestClient = test_client_factory(app)
response = client.post("/", content=b"a")
assert response.status_code == 200
@pytest.mark.anyio
async def test_read_request_stream_in_dispatch_wrapping_app_calls_body() -> None:
async def endpoint(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
async for chunk in request.stream(): # pragma: no branch
assert chunk == b"2"
break
await Response()(scope, receive, send)
class ConsumingMiddleware(BaseHTTPMiddleware):
async def dispatch(
self,
request: Request,
call_next: RequestResponseEndpoint,
) -> Response:
expected = b"1"
response: Response | None = None
async for chunk in request.stream(): # pragma: no branch
assert chunk == expected
if expected == b"1":
response = await call_next(request)
expected = b"3"
else:
break
assert response is not None
return response
async def rcv() -> AsyncGenerator[Message, None]:
yield {"type": "http.request", "body": b"1", "more_body": True}
yield {"type": "http.request", "body": b"2", "more_body": True}
yield {"type": "http.request", "body": b"3"}
raise AssertionError( # pragma: no cover
"Should not be called, no need to poll for disconnect"
)
sent: list[Message] = []
async def send(msg: Message) -> None:
sent.append(msg)
app: ASGIApp = endpoint
app = ConsumingMiddleware(app)
rcv_stream = rcv()
await app({"type": "http"}, rcv_stream.__anext__, send)
assert sent == [
{
"type": "http.response.start",
"status": 200,
"headers": [(b"content-length", b"0")],
},
{"type": "http.response.body", "body": b"", "more_body": False},
]
await rcv_stream.aclose()
def test_read_request_stream_in_dispatch_after_app_calls_body_with_middleware_calling_body_before_call_next(
test_client_factory: TestClientFactory,
) -> None:
async def homepage(request: Request) -> PlainTextResponse:
assert await request.body() == b"a"
return PlainTextResponse("Homepage")
class ConsumingMiddleware(BaseHTTPMiddleware):
async def dispatch(
self,
request: Request,
call_next: RequestResponseEndpoint,
) -> Response:
assert await request.body() == b"a" # this buffers the request body in memory
resp = await call_next(request)
async for chunk in request.stream():
if chunk:
assert chunk == b"a"
return resp
app = Starlette(
routes=[Route("/", homepage, methods=["POST"])],
middleware=[Middleware(ConsumingMiddleware)],
)
client: TestClient = test_client_factory(app)
response = client.post("/", content=b"a")
assert response.status_code == 200
def test_read_request_body_in_dispatch_after_app_calls_body_with_middleware_calling_body_before_call_next(
test_client_factory: TestClientFactory,
) -> None:
async def homepage(request: Request) -> PlainTextResponse:
assert await request.body() == b"a"
return PlainTextResponse("Homepage")
class ConsumingMiddleware(BaseHTTPMiddleware):
async def dispatch(
self,
request: Request,
call_next: RequestResponseEndpoint,
) -> Response:
assert await request.body() == b"a" # this buffers the request body in memory
resp = await call_next(request)
assert await request.body() == b"a" # no problem here
return resp
app = Starlette(
routes=[Route("/", homepage, methods=["POST"])],
middleware=[Middleware(ConsumingMiddleware)],
)
client: TestClient = test_client_factory(app)
response = client.post("/", content=b"a")
assert response.status_code == 200
@pytest.mark.anyio
async def test_read_request_disconnected_client() -> None:
"""If we receive a disconnect message when the downstream ASGI
app calls receive() the Request instance passed into the dispatch function
should get marked as disconnected.
The downstream ASGI app should not get a ClientDisconnect raised,
instead if should just receive the disconnect message.
"""
async def endpoint(scope: Scope, receive: Receive, send: Send) -> None:
msg = await receive()
assert msg["type"] == "http.disconnect"
await Response()(scope, receive, send)
class ConsumingMiddleware(BaseHTTPMiddleware):
async def dispatch(
self,
request: Request,
call_next: RequestResponseEndpoint,
) -> Response:
response = await call_next(request)
disconnected = await request.is_disconnected()
assert disconnected is True
return response
scope = {"type": "http", "method": "POST", "path": "/"}
async def receive() -> AsyncGenerator[Message, None]:
yield {"type": "http.disconnect"}
raise AssertionError("Should not be called, would hang") # pragma: no cover
async def send(msg: Message) -> None:
if msg["type"] == "http.response.start":
assert msg["status"] == 200
app: ASGIApp = ConsumingMiddleware(endpoint)
rcv = receive()
await app(scope, rcv.__anext__, send)
await rcv.aclose()
@pytest.mark.anyio
async def test_read_request_disconnected_after_consuming_steam() -> None:
async def endpoint(scope: Scope, receive: Receive, send: Send) -> None:
msg = await receive()
assert msg.pop("more_body", False) is False
assert msg == {"type": "http.request", "body": b"hi"}
msg = await receive()
assert msg == {"type": "http.disconnect"}
await Response()(scope, receive, send)
class ConsumingMiddleware(BaseHTTPMiddleware):
async def dispatch(
self,
request: Request,
call_next: RequestResponseEndpoint,
) -> Response:
await request.body()
disconnected = await request.is_disconnected()
assert disconnected is True
response = await call_next(request)
return response
scope = {"type": "http", "method": "POST", "path": "/"}
async def receive() -> AsyncGenerator[Message, None]:
yield {"type": "http.request", "body": b"hi"}
yield {"type": "http.disconnect"}
raise AssertionError("Should not be called, would hang") # pragma: no cover
async def send(msg: Message) -> None:
if msg["type"] == "http.response.start":
assert msg["status"] == 200
app: ASGIApp = ConsumingMiddleware(endpoint)
rcv = receive()
await app(scope, rcv.__anext__, send)
await rcv.aclose()
def test_downstream_middleware_modifies_receive(
test_client_factory: TestClientFactory,
) -> None:
"""If a downstream middleware modifies receive() the final ASGI app
should see the modified version.
"""
async def endpoint(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
body = await request.body()
assert body == b"foo foo "
await Response()(scope, receive, send)
class ConsumingMiddleware(BaseHTTPMiddleware):
async def dispatch(
self,
request: Request,
call_next: RequestResponseEndpoint,
) -> Response:
body = await request.body()
assert body == b"foo "
return await call_next(request)
def modifying_middleware(app: ASGIApp) -> ASGIApp:
async def wrapped_app(scope: Scope, receive: Receive, send: Send) -> None:
async def wrapped_receive() -> Message:
msg = await receive()
if msg["type"] == "http.request": # pragma: no branch
msg["body"] = msg["body"] * 2
return msg
await app(scope, wrapped_receive, send)
return wrapped_app
client = test_client_factory(ConsumingMiddleware(modifying_middleware(endpoint)))
resp = client.post("/", content=b"foo ")
assert resp.status_code == 200
def test_pr_1519_comment_1236166180_example() -> None:
"""
https://github.com/Kludex/starlette/pull/1519#issuecomment-1236166180
"""
bodies: list[bytes] = []
class LogRequestBodySize(BaseHTTPMiddleware):
async def dispatch(
self,
request: Request,
call_next: RequestResponseEndpoint,
) -> Response:
print(len(await request.body()))
return await call_next(request)
def replace_body_middleware(app: ASGIApp) -> ASGIApp:
async def wrapped_app(scope: Scope, receive: Receive, send: Send) -> None:
async def wrapped_rcv() -> Message:
msg = await receive()
msg["body"] += b"-foo"
return msg
await app(scope, wrapped_rcv, send)
return wrapped_app
async def endpoint(request: Request) -> Response:
body = await request.body()
bodies.append(body)
return Response()
app: ASGIApp = Starlette(routes=[Route("/", endpoint, methods=["POST"])])
app = replace_body_middleware(app)
app = LogRequestBodySize(app)
client = TestClient(app)
resp = client.post("/", content=b"Hello, World!")
resp.raise_for_status()
assert bodies == [b"Hello, World!-foo"]
@pytest.mark.anyio
async def test_multiple_middlewares_stacked_client_disconnected() -> None:
"""
Tests for:
- https://github.com/Kludex/starlette/issues/2516
- https://github.com/Kludex/starlette/pull/2687
"""
ordered_events: list[str] = []
unordered_events: list[str] = []
class MyMiddleware(BaseHTTPMiddleware):
def __init__(self, app: ASGIApp, version: int) -> None:
self.version = version
super().__init__(app)
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
ordered_events.append(f"{self.version}:STARTED")
res = await call_next(request)
ordered_events.append(f"{self.version}:COMPLETED")
def background() -> None:
unordered_events.append(f"{self.version}:BACKGROUND")
assert res.background is None
res.background = BackgroundTask(background)
return res
async def sleepy(request: Request) -> Response:
try:
await request.body()
except ClientDisconnect:
pass
else: # pragma: no cover
raise AssertionError("Should have raised ClientDisconnect")
return Response(b"")
app = Starlette(
routes=[Route("/", sleepy)],
middleware=[Middleware(MyMiddleware, version=_ + 1) for _ in range(10)],
)
scope = {
"type": "http",
"version": "3",
"method": "GET",
"path": "/",
}
async def receive() -> AsyncIterator[Message]:
yield {"type": "http.disconnect"}
sent: list[Message] = []
async def send(message: Message) -> None:
sent.append(message)
await app(scope, receive().__anext__, send)
assert ordered_events == [
"1:STARTED",
"2:STARTED",
"3:STARTED",
"4:STARTED",
"5:STARTED",
"6:STARTED",
"7:STARTED",
"8:STARTED",
"9:STARTED",
"10:STARTED",
"10:COMPLETED",
"9:COMPLETED",
"8:COMPLETED",
"7:COMPLETED",
"6:COMPLETED",
"5:COMPLETED",
"4:COMPLETED",
"3:COMPLETED",
"2:COMPLETED",
"1:COMPLETED",
]
assert sorted(unordered_events) == sorted(
[
"1:BACKGROUND",
"2:BACKGROUND",
"3:BACKGROUND",
"4:BACKGROUND",
"5:BACKGROUND",
"6:BACKGROUND",
"7:BACKGROUND",
"8:BACKGROUND",
"9:BACKGROUND",
"10:BACKGROUND",
]
)
assert sent == [
{
"type": "http.response.start",
"status": 200,
"headers": [(b"content-length", b"0")],
},
{"type": "http.response.body", "body": b"", "more_body": False},
]
@pytest.mark.anyio
@pytest.mark.parametrize("send_body", [True, False])
async def test_poll_for_disconnect_repeated(send_body: bool) -> None:
async def app_poll_disconnect(scope: Scope, receive: Receive, send: Send) -> None:
for _ in range(2):
msg = await receive()
while msg["type"] == "http.request":
msg = await receive()
assert msg["type"] == "http.disconnect"
await Response(b"good!")(scope, receive, send)
class MyMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
return await call_next(request)
app = MyMiddleware(app_poll_disconnect)
scope = {
"type": "http",
"version": "3",
"method": "GET",
"path": "/",
}
async def receive() -> AsyncIterator[Message]:
# the key here is that we only ever send 1 htt.disconnect message
if send_body:
yield {"type": "http.request", "body": b"hello", "more_body": True}
yield {"type": "http.request", "body": b"", "more_body": False}
yield {"type": "http.disconnect"}
raise AssertionError("Should not be called, would hang") # pragma: no cover
sent: list[Message] = []
async def send(message: Message) -> None:
sent.append(message)
await app(scope, receive().__anext__, send)
assert sent == [
{
"type": "http.response.start",
"status": 200,
"headers": [(b"content-length", b"5")],
},
{"type": "http.response.body", "body": b"good!", "more_body": True},
{"type": "http.response.body", "body": b"", "more_body": False},
]
@pytest.mark.anyio
async def test_asgi_pathsend_events(tmpdir: Path) -> None:
path = tmpdir / "example.txt"
with path.open("w") as file:
file.write("<file content>")
response_complete = anyio.Event()
events: list[Message] = []
async def endpoint_with_pathsend(_: Request) -> FileResponse:
return FileResponse(path)
async def passthrough(request: Request, call_next: RequestResponseEndpoint) -> Response:
return await call_next(request)
app = Starlette(
middleware=[Middleware(BaseHTTPMiddleware, dispatch=passthrough)],
routes=[Route("/", endpoint_with_pathsend)],
)
scope = {
"type": "http",
"version": "3",
"method": "GET",
"path": "/",
"headers": [],
"extensions": {"http.response.pathsend": {}},
}
async def receive() -> Message:
raise NotImplementedError("Should not be called!") # pragma: no cover
async def send(message: Message) -> None:
events.append(message)
if message["type"] == "http.response.pathsend":
response_complete.set()
await app(scope, receive, send)
assert len(events) == 2
assert events[0]["type"] == "http.response.start"
assert events[1]["type"] == "http.response.pathsend"
def test_error_context_propagation(test_client_factory: TestClientFactory) -> None:
class PassthroughMiddleware(BaseHTTPMiddleware):
async def dispatch(
self,
request: Request,
call_next: RequestResponseEndpoint,
) -> Response:
return await call_next(request)
def exception_without_context(request: Request) -> None:
raise Exception("Exception")
def exception_with_context(request: Request) -> None:
try:
raise Exception("Inner exception")
except Exception:
raise Exception("Outer exception")
def exception_with_cause(request: Request) -> None:
try:
raise Exception("Inner exception")
except Exception as e:
raise Exception("Outer exception") from e
app = Starlette(
routes=[
Route("/exception-without-context", endpoint=exception_without_context),
Route("/exception-with-context", endpoint=exception_with_context),
Route("/exception-with-cause", endpoint=exception_with_cause),
],
middleware=[Middleware(PassthroughMiddleware)],
)
client = test_client_factory(app)
# For exceptions without context the context is filled with the `anyio.EndOfStream`
# but it is suppressed therefore not propagated to traceback.
with pytest.raises(Exception) as ctx:
client.get("/exception-without-context")
assert str(ctx.value) == "Exception"
assert ctx.value.__cause__ is None
assert ctx.value.__context__ is not None
assert ctx.value.__suppress_context__ is True
# For exceptions with context the context is propagated as a cause to avoid
# `anyio.EndOfStream` error from overwriting it.
with pytest.raises(Exception) as ctx:
client.get("/exception-with-context")
assert str(ctx.value) == "Outer exception"
assert ctx.value.__cause__ is not None
assert str(ctx.value.__cause__) == "Inner exception"
# For exceptions with cause check that it gets correctly propagated.
with pytest.raises(Exception) as ctx:
client.get("/exception-with-cause")
assert str(ctx.value) == "Outer exception"
assert ctx.value.__cause__ is not None
assert str(ctx.value.__cause__) == "Inner exception"
| starlette |
python | import gzip
import io
from typing import NoReturn
from starlette.datastructures import Headers, MutableHeaders
from starlette.types import ASGIApp, Message, Receive, Scope, Send
DEFAULT_EXCLUDED_CONTENT_TYPES = ("text/event-stream",)
class GZipMiddleware:
def __init__(self, app: ASGIApp, minimum_size: int = 500, compresslevel: int = 9) -> None:
self.app = app
self.minimum_size = minimum_size
self.compresslevel = compresslevel
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http": # pragma: no cover
await self.app(scope, receive, send)
return
headers = Headers(scope=scope)
responder: ASGIApp
if "gzip" in headers.get("Accept-Encoding", ""):
responder = GZipResponder(self.app, self.minimum_size, compresslevel=self.compresslevel)
else:
responder = IdentityResponder(self.app, self.minimum_size)
await responder(scope, receive, send)
class IdentityResponder:
content_encoding: str
def __init__(self, app: ASGIApp, minimum_size: int) -> None:
self.app = app
self.minimum_size = minimum_size
self.send: Send = unattached_send
self.initial_message: Message = {}
self.started = False
self.content_encoding_set = False
self.content_type_is_excluded = False
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
self.send = send
await self.app(scope, receive, self.send_with_compression)
async def send_with_compression(self, message: Message) -> None:
message_type = message["type"]
if message_type == "http.response.start":
# Don't send the initial message until we've determined how to
# modify the outgoing headers correctly.
self.initial_message = message
headers = Headers(raw=self.initial_message["headers"])
self.content_encoding_set = "content-encoding" in headers
self.content_type_is_excluded = headers.get("content-type", "").startswith(DEFAULT_EXCLUDED_CONTENT_TYPES)
elif message_type == "http.response.body" and (self.content_encoding_set or self.content_type_is_excluded):
if not self.started:
self.started = True
await self.send(self.initial_message)
await self.send(message)
elif message_type == "http.response.body" and not self.started:
self.started = True
body = message.get("body", b"")
more_body = message.get("more_body", False)
if len(body) < self.minimum_size and not more_body:
# Don't apply compression to small outgoing responses.
await self.send(self.initial_message)
await self.send(message)
elif not more_body:
# Standard response.
body = self.apply_compression(body, more_body=False)
headers = MutableHeaders(raw=self.initial_message["headers"])
headers.add_vary_header("Accept-Encoding")
if body != message["body"]:
headers["Content-Encoding"] = self.content_encoding
headers["Content-Length"] = str(len(body))
message["body"] = body
await self.send(self.initial_message)
await self.send(message)
else:
# Initial body in streaming response.
body = self.apply_compression(body, more_body=True)
headers = MutableHeaders(raw=self.initial_message["headers"])
headers.add_vary_header("Accept-Encoding")
if body != message["body"]:
headers["Content-Encoding"] = self.content_encoding
del headers["Content-Length"]
message["body"] = body
await self.send(self.initial_message)
await self.send(message)
elif message_type == "http.response.body":
# Remaining body in streaming response.
body = message.get("body", b"")
more_body = message.get("more_body", False)
message["body"] = self.apply_compression(body, more_body=more_body)
await self.send(message)
elif message_type == "http.response.pathsend": # pragma: no branch
# Don't apply GZip to pathsend responses
await self.send(self.initial_message)
await self.send(message)
def apply_compression(self, body: bytes, *, more_body: bool) -> bytes:
"""Apply compression on the response body.
If more_body is False, any compression file should be closed. If it
isn't, it won't be closed automatically until all background tasks
complete.
"""
return body
class GZipResponder(IdentityResponder):
content_encoding = "gzip"
def __init__(self, app: ASGIApp, minimum_size: int, compresslevel: int = 9) -> None:
super().__init__(app, minimum_size)
self.gzip_buffer = io.BytesIO()
self.gzip_file = gzip.GzipFile(mode="wb", fileobj=self.gzip_buffer, compresslevel=compresslevel)
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
with self.gzip_buffer, self.gzip_file:
await super().__call__(scope, receive, send)
def apply_compression(self, body: bytes, *, more_body: bool) -> bytes:
self.gzip_file.write(body)
if not more_body:
self.gzip_file.close()
body = self.gzip_buffer.getvalue()
self.gzip_buffer.seek(0)
self.gzip_buffer.truncate()
return body
async def unattached_send(message: Message) -> NoReturn:
raise RuntimeError("send awaitable not set") # pragma: no cover
| from __future__ import annotations
from pathlib import Path
import pytest
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.gzip import GZipMiddleware
from starlette.requests import Request
from starlette.responses import ContentStream, FileResponse, PlainTextResponse, StreamingResponse
from starlette.routing import Route
from starlette.types import Message
from tests.types import TestClientFactory
def test_gzip_responses(test_client_factory: TestClientFactory) -> None:
def homepage(request: Request) -> PlainTextResponse:
return PlainTextResponse("x" * 4000, status_code=200)
app = Starlette(
routes=[Route("/", endpoint=homepage)],
middleware=[Middleware(GZipMiddleware)],
)
client = test_client_factory(app)
response = client.get("/", headers={"accept-encoding": "gzip"})
assert response.status_code == 200
assert response.text == "x" * 4000
assert response.headers["Content-Encoding"] == "gzip"
assert response.headers["Vary"] == "Accept-Encoding"
assert int(response.headers["Content-Length"]) < 4000
def test_gzip_not_in_accept_encoding(test_client_factory: TestClientFactory) -> None:
def homepage(request: Request) -> PlainTextResponse:
return PlainTextResponse("x" * 4000, status_code=200)
app = Starlette(
routes=[Route("/", endpoint=homepage)],
middleware=[Middleware(GZipMiddleware)],
)
client = test_client_factory(app)
response = client.get("/", headers={"accept-encoding": "identity"})
assert response.status_code == 200
assert response.text == "x" * 4000
assert "Content-Encoding" not in response.headers
assert response.headers["Vary"] == "Accept-Encoding"
assert int(response.headers["Content-Length"]) == 4000
def test_gzip_ignored_for_small_responses(
test_client_factory: TestClientFactory,
) -> None:
def homepage(request: Request) -> PlainTextResponse:
return PlainTextResponse("OK", status_code=200)
app = Starlette(
routes=[Route("/", endpoint=homepage)],
middleware=[Middleware(GZipMiddleware)],
)
client = test_client_factory(app)
response = client.get("/", headers={"accept-encoding": "gzip"})
assert response.status_code == 200
assert response.text == "OK"
assert "Content-Encoding" not in response.headers
assert "Vary" not in response.headers
assert int(response.headers["Content-Length"]) == 2
def test_gzip_streaming_response(test_client_factory: TestClientFactory) -> None:
def homepage(request: Request) -> StreamingResponse:
async def generator(bytes: bytes, count: int) -> ContentStream:
for index in range(count):
yield bytes
streaming = generator(bytes=b"x" * 400, count=10)
return StreamingResponse(streaming, status_code=200)
app = Starlette(
routes=[Route("/", endpoint=homepage)],
middleware=[Middleware(GZipMiddleware)],
)
client = test_client_factory(app)
response = client.get("/", headers={"accept-encoding": "gzip"})
assert response.status_code == 200
assert response.text == "x" * 4000
assert response.headers["Content-Encoding"] == "gzip"
assert response.headers["Vary"] == "Accept-Encoding"
assert "Content-Length" not in response.headers
def test_gzip_streaming_response_identity(test_client_factory: TestClientFactory) -> None:
def homepage(request: Request) -> StreamingResponse:
async def generator(bytes: bytes, count: int) -> ContentStream:
for index in range(count):
yield bytes
streaming = generator(bytes=b"x" * 400, count=10)
return StreamingResponse(streaming, status_code=200)
app = Starlette(
routes=[Route("/", endpoint=homepage)],
middleware=[Middleware(GZipMiddleware)],
)
client = test_client_factory(app)
response = client.get("/", headers={"accept-encoding": "identity"})
assert response.status_code == 200
assert response.text == "x" * 4000
assert "Content-Encoding" not in response.headers
assert response.headers["Vary"] == "Accept-Encoding"
assert "Content-Length" not in response.headers
def test_gzip_ignored_for_responses_with_encoding_set(
test_client_factory: TestClientFactory,
) -> None:
def homepage(request: Request) -> StreamingResponse:
async def generator(bytes: bytes, count: int) -> ContentStream:
for index in range(count):
yield bytes
streaming = generator(bytes=b"x" * 400, count=10)
return StreamingResponse(streaming, status_code=200, headers={"Content-Encoding": "text"})
app = Starlette(
routes=[Route("/", endpoint=homepage)],
middleware=[Middleware(GZipMiddleware)],
)
client = test_client_factory(app)
response = client.get("/", headers={"accept-encoding": "gzip, text"})
assert response.status_code == 200
assert response.text == "x" * 4000
assert response.headers["Content-Encoding"] == "text"
assert "Vary" not in response.headers
assert "Content-Length" not in response.headers
def test_gzip_ignored_on_server_sent_events(test_client_factory: TestClientFactory) -> None:
def homepage(request: Request) -> StreamingResponse:
async def generator(bytes: bytes, count: int) -> ContentStream:
for _ in range(count):
yield bytes
streaming = generator(bytes=b"x" * 400, count=10)
return StreamingResponse(streaming, status_code=200, media_type="text/event-stream")
app = Starlette(
routes=[Route("/", endpoint=homepage)],
middleware=[Middleware(GZipMiddleware)],
)
client = test_client_factory(app)
response = client.get("/", headers={"accept-encoding": "gzip"})
assert response.status_code == 200
assert response.text == "x" * 4000
assert "Content-Encoding" not in response.headers
assert "Content-Length" not in response.headers
@pytest.mark.anyio
async def test_gzip_ignored_for_pathsend_responses(tmpdir: Path) -> None:
path = tmpdir / "example.txt"
with path.open("w") as file:
file.write("<file content>")
events: list[Message] = []
async def endpoint_with_pathsend(request: Request) -> FileResponse:
_ = await request.body()
return FileResponse(path)
app = Starlette(
routes=[Route("/", endpoint=endpoint_with_pathsend)],
middleware=[Middleware(GZipMiddleware)],
)
scope = {
"type": "http",
"version": "3",
"method": "GET",
"path": "/",
"headers": [(b"accept-encoding", b"gzip, text")],
"extensions": {"http.response.pathsend": {}},
}
async def receive() -> Message:
return {"type": "http.request", "body": b"", "more_body": False}
async def send(message: Message) -> None:
events.append(message)
await app(scope, receive, send)
assert len(events) == 2
assert events[0]["type"] == "http.response.start"
assert events[1]["type"] == "http.response.pathsend"
| starlette |
python | from __future__ import annotations
import io
import math
import sys
import warnings
from collections.abc import Callable, MutableMapping
from typing import Any
import anyio
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from starlette.types import Receive, Scope, Send
warnings.warn(
"starlette.middleware.wsgi is deprecated and will be removed in a future release. "
"Please refer to https://github.com/abersheeran/a2wsgi as a replacement.",
DeprecationWarning,
)
def build_environ(scope: Scope, body: bytes) -> dict[str, Any]:
"""
Builds a scope and request body into a WSGI environ object.
"""
script_name = scope.get("root_path", "").encode("utf8").decode("latin1")
path_info = scope["path"].encode("utf8").decode("latin1")
if path_info.startswith(script_name):
path_info = path_info[len(script_name) :]
environ = {
"REQUEST_METHOD": scope["method"],
"SCRIPT_NAME": script_name,
"PATH_INFO": path_info,
"QUERY_STRING": scope["query_string"].decode("ascii"),
"SERVER_PROTOCOL": f"HTTP/{scope['http_version']}",
"wsgi.version": (1, 0),
"wsgi.url_scheme": scope.get("scheme", "http"),
"wsgi.input": io.BytesIO(body),
"wsgi.errors": sys.stdout,
"wsgi.multithread": True,
"wsgi.multiprocess": True,
"wsgi.run_once": False,
}
# Get server name and port - required in WSGI, not in ASGI
server = scope.get("server") or ("localhost", 80)
environ["SERVER_NAME"] = server[0]
environ["SERVER_PORT"] = server[1]
# Get client IP address
if scope.get("client"):
environ["REMOTE_ADDR"] = scope["client"][0]
# Go through headers and make them into environ entries
for name, value in scope.get("headers", []):
name = name.decode("latin1")
if name == "content-length":
corrected_name = "CONTENT_LENGTH"
elif name == "content-type":
corrected_name = "CONTENT_TYPE"
else:
corrected_name = f"HTTP_{name}".upper().replace("-", "_")
# HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in
# case
value = value.decode("latin1")
if corrected_name in environ:
value = environ[corrected_name] + "," + value
environ[corrected_name] = value
return environ
class WSGIMiddleware:
def __init__(self, app: Callable[..., Any]) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
assert scope["type"] == "http"
responder = WSGIResponder(self.app, scope)
await responder(receive, send)
class WSGIResponder:
stream_send: ObjectSendStream[MutableMapping[str, Any]]
stream_receive: ObjectReceiveStream[MutableMapping[str, Any]]
def __init__(self, app: Callable[..., Any], scope: Scope) -> None:
self.app = app
self.scope = scope
self.status = None
self.response_headers = None
self.stream_send, self.stream_receive = anyio.create_memory_object_stream(math.inf)
self.response_started = False
self.exc_info: Any = None
async def __call__(self, receive: Receive, send: Send) -> None:
body = b""
more_body = True
while more_body:
message = await receive()
body += message.get("body", b"")
more_body = message.get("more_body", False)
environ = build_environ(self.scope, body)
async with anyio.create_task_group() as task_group:
task_group.start_soon(self.sender, send)
async with self.stream_send:
await anyio.to_thread.run_sync(self.wsgi, environ, self.start_response)
if self.exc_info is not None:
raise self.exc_info[0].with_traceback(self.exc_info[1], self.exc_info[2])
async def sender(self, send: Send) -> None:
async with self.stream_receive:
async for message in self.stream_receive:
await send(message)
def start_response(
self,
status: str,
response_headers: list[tuple[str, str]],
exc_info: Any = None,
) -> None:
self.exc_info = exc_info
if not self.response_started: # pragma: no branch
self.response_started = True
status_code_string, _ = status.split(" ", 1)
status_code = int(status_code_string)
headers = [
(name.strip().encode("ascii").lower(), value.strip().encode("ascii"))
for name, value in response_headers
]
anyio.from_thread.run(
self.stream_send.send,
{
"type": "http.response.start",
"status": status_code,
"headers": headers,
},
)
def wsgi(
self,
environ: dict[str, Any],
start_response: Callable[..., Any],
) -> None:
for chunk in self.app(environ, start_response):
anyio.from_thread.run(
self.stream_send.send,
{"type": "http.response.body", "body": chunk, "more_body": True},
)
anyio.from_thread.run(self.stream_send.send, {"type": "http.response.body", "body": b""})
| import sys
from collections.abc import Callable, Iterable
from typing import Any
import pytest
from starlette._utils import collapse_excgroups
from starlette.middleware.wsgi import WSGIMiddleware, build_environ
from tests.types import TestClientFactory
WSGIResponse = Iterable[bytes]
StartResponse = Callable[..., Any]
Environment = dict[str, Any]
def hello_world(
environ: Environment,
start_response: StartResponse,
) -> WSGIResponse:
status = "200 OK"
output = b"Hello World!\n"
headers = [
("Content-Type", "text/plain; charset=utf-8"),
("Content-Length", str(len(output))),
]
start_response(status, headers)
return [output]
def echo_body(
environ: Environment,
start_response: StartResponse,
) -> WSGIResponse:
status = "200 OK"
output = environ["wsgi.input"].read()
headers = [
("Content-Type", "text/plain; charset=utf-8"),
("Content-Length", str(len(output))),
]
start_response(status, headers)
return [output]
def raise_exception(
environ: Environment,
start_response: StartResponse,
) -> WSGIResponse:
raise RuntimeError("Something went wrong")
def return_exc_info(
environ: Environment,
start_response: StartResponse,
) -> WSGIResponse:
try:
raise RuntimeError("Something went wrong")
except RuntimeError:
status = "500 Internal Server Error"
output = b"Internal Server Error"
headers = [
("Content-Type", "text/plain; charset=utf-8"),
("Content-Length", str(len(output))),
]
start_response(status, headers, exc_info=sys.exc_info())
return [output]
def test_wsgi_get(test_client_factory: TestClientFactory) -> None:
app = WSGIMiddleware(hello_world)
client = test_client_factory(app)
response = client.get("/")
assert response.status_code == 200
assert response.text == "Hello World!\n"
def test_wsgi_post(test_client_factory: TestClientFactory) -> None:
app = WSGIMiddleware(echo_body)
client = test_client_factory(app)
response = client.post("/", json={"example": 123})
assert response.status_code == 200
assert response.text == '{"example":123}'
def test_wsgi_exception(test_client_factory: TestClientFactory) -> None:
# Note that we're testing the WSGI app directly here.
# The HTTP protocol implementations would catch this error and return 500.
app = WSGIMiddleware(raise_exception)
client = test_client_factory(app)
with pytest.raises(RuntimeError), collapse_excgroups():
client.get("/")
def test_wsgi_exc_info(test_client_factory: TestClientFactory) -> None:
# Note that we're testing the WSGI app directly here.
# The HTTP protocol implementations would catch this error and return 500.
app = WSGIMiddleware(return_exc_info)
client = test_client_factory(app)
with pytest.raises(RuntimeError):
response = client.get("/")
app = WSGIMiddleware(return_exc_info)
client = test_client_factory(app, raise_server_exceptions=False)
response = client.get("/")
assert response.status_code == 500
assert response.text == "Internal Server Error"
def test_build_environ() -> None:
scope = {
"type": "http",
"http_version": "1.1",
"method": "GET",
"scheme": "https",
"path": "/sub/",
"root_path": "/sub",
"query_string": b"a=123&b=456",
"headers": [
(b"host", b"www.example.org"),
(b"content-type", b"application/json"),
(b"content-length", b"18"),
(b"accept", b"application/json"),
(b"accept", b"text/plain"),
],
"client": ("134.56.78.4", 1453),
"server": ("www.example.org", 443),
}
body = b'{"example":"body"}'
environ = build_environ(scope, body)
stream = environ.pop("wsgi.input")
assert stream.read() == b'{"example":"body"}'
assert environ == {
"CONTENT_LENGTH": "18",
"CONTENT_TYPE": "application/json",
"HTTP_ACCEPT": "application/json,text/plain",
"HTTP_HOST": "www.example.org",
"PATH_INFO": "/",
"QUERY_STRING": "a=123&b=456",
"REMOTE_ADDR": "134.56.78.4",
"REQUEST_METHOD": "GET",
"SCRIPT_NAME": "/sub",
"SERVER_NAME": "www.example.org",
"SERVER_PORT": 443,
"SERVER_PROTOCOL": "HTTP/1.1",
"wsgi.errors": sys.stdout,
"wsgi.multiprocess": True,
"wsgi.multithread": True,
"wsgi.run_once": False,
"wsgi.url_scheme": "https",
"wsgi.version": (1, 0),
}
def test_build_environ_encoding() -> None:
scope = {
"type": "http",
"http_version": "1.1",
"method": "GET",
"path": "/小星",
"root_path": "/中国",
"query_string": b"a=123&b=456",
"headers": [],
}
environ = build_environ(scope, b"")
assert environ["SCRIPT_NAME"] == "/中国".encode().decode("latin-1")
assert environ["PATH_INFO"] == "/小星".encode().decode("latin-1")
| starlette |
python | from __future__ import annotations
import typing
from contextlib import contextmanager
from ._client import Client
from ._config import DEFAULT_TIMEOUT_CONFIG
from ._models import Response
from ._types import (
AuthTypes,
CookieTypes,
HeaderTypes,
ProxyTypes,
QueryParamTypes,
RequestContent,
RequestData,
RequestFiles,
TimeoutTypes,
)
from ._urls import URL
if typing.TYPE_CHECKING:
import ssl # pragma: no cover
__all__ = [
"delete",
"get",
"head",
"options",
"patch",
"post",
"put",
"request",
"stream",
]
def request(
method: str,
url: URL | str,
*,
params: QueryParamTypes | None = None,
content: RequestContent | None = None,
data: RequestData | None = None,
files: RequestFiles | None = None,
json: typing.Any | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | None = None,
proxy: ProxyTypes | None = None,
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
follow_redirects: bool = False,
verify: ssl.SSLContext | str | bool = True,
trust_env: bool = True,
) -> Response:
"""
Sends an HTTP request.
**Parameters:**
* **method** - HTTP method for the new `Request` object: `GET`, `OPTIONS`,
`HEAD`, `POST`, `PUT`, `PATCH`, or `DELETE`.
* **url** - URL for the new `Request` object.
* **params** - *(optional)* Query parameters to include in the URL, as a
string, dictionary, or sequence of two-tuples.
* **content** - *(optional)* Binary content to include in the body of the
request, as bytes or a byte iterator.
* **data** - *(optional)* Form data to include in the body of the request,
as a dictionary.
* **files** - *(optional)* A dictionary of upload files to include in the
body of the request.
* **json** - *(optional)* A JSON serializable object to include in the body
of the request.
* **headers** - *(optional)* Dictionary of HTTP headers to include in the
request.
* **cookies** - *(optional)* Dictionary of Cookie items to include in the
request.
* **auth** - *(optional)* An authentication class to use when sending the
request.
* **proxy** - *(optional)* A proxy URL where all the traffic should be routed.
* **timeout** - *(optional)* The timeout configuration to use when sending
the request.
* **follow_redirects** - *(optional)* Enables or disables HTTP redirects.
* **verify** - *(optional)* Either `True` to use an SSL context with the
default CA bundle, `False` to disable verification, or an instance of
`ssl.SSLContext` to use a custom context.
* **trust_env** - *(optional)* Enables or disables usage of environment
variables for configuration.
**Returns:** `Response`
Usage:
```
>>> import httpx
>>> response = httpx.request('GET', 'https://httpbin.org/get')
>>> response
<Response [200 OK]>
```
"""
with Client(
cookies=cookies,
proxy=proxy,
verify=verify,
timeout=timeout,
trust_env=trust_env,
) as client:
return client.request(
method=method,
url=url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
auth=auth,
follow_redirects=follow_redirects,
)
@contextmanager
def stream(
method: str,
url: URL | str,
*,
params: QueryParamTypes | None = None,
content: RequestContent | None = None,
data: RequestData | None = None,
files: RequestFiles | None = None,
json: typing.Any | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | None = None,
proxy: ProxyTypes | None = None,
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
follow_redirects: bool = False,
verify: ssl.SSLContext | str | bool = True,
trust_env: bool = True,
) -> typing.Iterator[Response]:
"""
Alternative to `httpx.request()` that streams the response body
instead of loading it into memory at once.
**Parameters**: See `httpx.request`.
See also: [Streaming Responses][0]
[0]: /quickstart#streaming-responses
"""
with Client(
cookies=cookies,
proxy=proxy,
verify=verify,
timeout=timeout,
trust_env=trust_env,
) as client:
with client.stream(
method=method,
url=url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
auth=auth,
follow_redirects=follow_redirects,
) as response:
yield response
def get(
url: URL | str,
*,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | None = None,
proxy: ProxyTypes | None = None,
follow_redirects: bool = False,
verify: ssl.SSLContext | str | bool = True,
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
trust_env: bool = True,
) -> Response:
"""
Sends a `GET` request.
**Parameters**: See `httpx.request`.
Note that the `data`, `files`, `json` and `content` parameters are not available
on this function, as `GET` requests should not include a request body.
"""
return request(
"GET",
url,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
proxy=proxy,
follow_redirects=follow_redirects,
verify=verify,
timeout=timeout,
trust_env=trust_env,
)
def options(
url: URL | str,
*,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | None = None,
proxy: ProxyTypes | None = None,
follow_redirects: bool = False,
verify: ssl.SSLContext | str | bool = True,
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
trust_env: bool = True,
) -> Response:
"""
Sends an `OPTIONS` request.
**Parameters**: See `httpx.request`.
Note that the `data`, `files`, `json` and `content` parameters are not available
on this function, as `OPTIONS` requests should not include a request body.
"""
return request(
"OPTIONS",
url,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
proxy=proxy,
follow_redirects=follow_redirects,
verify=verify,
timeout=timeout,
trust_env=trust_env,
)
def head(
url: URL | str,
*,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | None = None,
proxy: ProxyTypes | None = None,
follow_redirects: bool = False,
verify: ssl.SSLContext | str | bool = True,
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
trust_env: bool = True,
) -> Response:
"""
Sends a `HEAD` request.
**Parameters**: See `httpx.request`.
Note that the `data`, `files`, `json` and `content` parameters are not available
on this function, as `HEAD` requests should not include a request body.
"""
return request(
"HEAD",
url,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
proxy=proxy,
follow_redirects=follow_redirects,
verify=verify,
timeout=timeout,
trust_env=trust_env,
)
def post(
url: URL | str,
*,
content: RequestContent | None = None,
data: RequestData | None = None,
files: RequestFiles | None = None,
json: typing.Any | None = None,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | None = None,
proxy: ProxyTypes | None = None,
follow_redirects: bool = False,
verify: ssl.SSLContext | str | bool = True,
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
trust_env: bool = True,
) -> Response:
"""
Sends a `POST` request.
**Parameters**: See `httpx.request`.
"""
return request(
"POST",
url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
proxy=proxy,
follow_redirects=follow_redirects,
verify=verify,
timeout=timeout,
trust_env=trust_env,
)
def put(
url: URL | str,
*,
content: RequestContent | None = None,
data: RequestData | None = None,
files: RequestFiles | None = None,
json: typing.Any | None = None,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | None = None,
proxy: ProxyTypes | None = None,
follow_redirects: bool = False,
verify: ssl.SSLContext | str | bool = True,
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
trust_env: bool = True,
) -> Response:
"""
Sends a `PUT` request.
**Parameters**: See `httpx.request`.
"""
return request(
"PUT",
url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
proxy=proxy,
follow_redirects=follow_redirects,
verify=verify,
timeout=timeout,
trust_env=trust_env,
)
def patch(
url: URL | str,
*,
content: RequestContent | None = None,
data: RequestData | None = None,
files: RequestFiles | None = None,
json: typing.Any | None = None,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | None = None,
proxy: ProxyTypes | None = None,
follow_redirects: bool = False,
verify: ssl.SSLContext | str | bool = True,
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
trust_env: bool = True,
) -> Response:
"""
Sends a `PATCH` request.
**Parameters**: See `httpx.request`.
"""
return request(
"PATCH",
url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
proxy=proxy,
follow_redirects=follow_redirects,
verify=verify,
timeout=timeout,
trust_env=trust_env,
)
def delete(
url: URL | str,
*,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | None = None,
proxy: ProxyTypes | None = None,
follow_redirects: bool = False,
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
verify: ssl.SSLContext | str | bool = True,
trust_env: bool = True,
) -> Response:
"""
Sends a `DELETE` request.
**Parameters**: See `httpx.request`.
Note that the `data`, `files`, `json` and `content` parameters are not available
on this function, as `DELETE` requests should not include a request body.
"""
return request(
"DELETE",
url,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
proxy=proxy,
follow_redirects=follow_redirects,
verify=verify,
timeout=timeout,
trust_env=trust_env,
)
| import typing
import pytest
import httpx
def test_get(server):
response = httpx.get(server.url)
assert response.status_code == 200
assert response.reason_phrase == "OK"
assert response.text == "Hello, world!"
assert response.http_version == "HTTP/1.1"
def test_post(server):
response = httpx.post(server.url, content=b"Hello, world!")
assert response.status_code == 200
assert response.reason_phrase == "OK"
def test_post_byte_iterator(server):
def data() -> typing.Iterator[bytes]:
yield b"Hello"
yield b", "
yield b"world!"
response = httpx.post(server.url, content=data())
assert response.status_code == 200
assert response.reason_phrase == "OK"
def test_post_byte_stream(server):
class Data(httpx.SyncByteStream):
def __iter__(self):
yield b"Hello"
yield b", "
yield b"world!"
response = httpx.post(server.url, content=Data())
assert response.status_code == 200
assert response.reason_phrase == "OK"
def test_options(server):
response = httpx.options(server.url)
assert response.status_code == 200
assert response.reason_phrase == "OK"
def test_head(server):
response = httpx.head(server.url)
assert response.status_code == 200
assert response.reason_phrase == "OK"
def test_put(server):
response = httpx.put(server.url, content=b"Hello, world!")
assert response.status_code == 200
assert response.reason_phrase == "OK"
def test_patch(server):
response = httpx.patch(server.url, content=b"Hello, world!")
assert response.status_code == 200
assert response.reason_phrase == "OK"
def test_delete(server):
response = httpx.delete(server.url)
assert response.status_code == 200
assert response.reason_phrase == "OK"
def test_stream(server):
with httpx.stream("GET", server.url) as response:
response.read()
assert response.status_code == 200
assert response.reason_phrase == "OK"
assert response.text == "Hello, world!"
assert response.http_version == "HTTP/1.1"
def test_get_invalid_url():
with pytest.raises(httpx.UnsupportedProtocol):
httpx.get("invalid://example.org")
# check that httpcore isn't imported until we do a request
def test_httpcore_lazy_loading(server):
import sys
# unload our module if it is already loaded
if "httpx" in sys.modules:
del sys.modules["httpx"]
del sys.modules["httpcore"]
import httpx
assert "httpcore" not in sys.modules
_response = httpx.get(server.url)
assert "httpcore" in sys.modules
| httpx |
python | from __future__ import annotations
import ipaddress
import os
import re
import typing
from urllib.request import getproxies
from ._types import PrimitiveData
if typing.TYPE_CHECKING: # pragma: no cover
from ._urls import URL
def primitive_value_to_str(value: PrimitiveData) -> str:
"""
Coerce a primitive data type into a string value.
Note that we prefer JSON-style 'true'/'false' for boolean values here.
"""
if value is True:
return "true"
elif value is False:
return "false"
elif value is None:
return ""
return str(value)
def get_environment_proxies() -> dict[str, str | None]:
"""Gets proxy information from the environment"""
# urllib.request.getproxies() falls back on System
# Registry and Config for proxies on Windows and macOS.
# We don't want to propagate non-HTTP proxies into
# our configuration such as 'TRAVIS_APT_PROXY'.
proxy_info = getproxies()
mounts: dict[str, str | None] = {}
for scheme in ("http", "https", "all"):
if proxy_info.get(scheme):
hostname = proxy_info[scheme]
mounts[f"{scheme}://"] = (
hostname if "://" in hostname else f"http://{hostname}"
)
no_proxy_hosts = [host.strip() for host in proxy_info.get("no", "").split(",")]
for hostname in no_proxy_hosts:
# See https://curl.haxx.se/libcurl/c/CURLOPT_NOPROXY.html for details
# on how names in `NO_PROXY` are handled.
if hostname == "*":
# If NO_PROXY=* is used or if "*" occurs as any one of the comma
# separated hostnames, then we should just bypass any information
# from HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, and always ignore
# proxies.
return {}
elif hostname:
# NO_PROXY=.google.com is marked as "all://*.google.com,
# which disables "www.google.com" but not "google.com"
# NO_PROXY=google.com is marked as "all://*google.com,
# which disables "www.google.com" and "google.com".
# (But not "wwwgoogle.com")
# NO_PROXY can include domains, IPv6, IPv4 addresses and "localhost"
# NO_PROXY=example.com,::1,localhost,192.168.0.0/16
if "://" in hostname:
mounts[hostname] = None
elif is_ipv4_hostname(hostname):
mounts[f"all://{hostname}"] = None
elif is_ipv6_hostname(hostname):
mounts[f"all://[{hostname}]"] = None
elif hostname.lower() == "localhost":
mounts[f"all://{hostname}"] = None
else:
mounts[f"all://*{hostname}"] = None
return mounts
def to_bytes(value: str | bytes, encoding: str = "utf-8") -> bytes:
return value.encode(encoding) if isinstance(value, str) else value
def to_str(value: str | bytes, encoding: str = "utf-8") -> str:
return value if isinstance(value, str) else value.decode(encoding)
def to_bytes_or_str(value: str, match_type_of: typing.AnyStr) -> typing.AnyStr:
return value if isinstance(match_type_of, str) else value.encode()
def unquote(value: str) -> str:
return value[1:-1] if value[0] == value[-1] == '"' else value
def peek_filelike_length(stream: typing.Any) -> int | None:
"""
Given a file-like stream object, return its length in number of bytes
without reading it into memory.
"""
try:
# Is it an actual file?
fd = stream.fileno()
# Yup, seems to be an actual file.
length = os.fstat(fd).st_size
except (AttributeError, OSError):
# No... Maybe it's something that supports random access, like `io.BytesIO`?
try:
# Assuming so, go to end of stream to figure out its length,
# then put it back in place.
offset = stream.tell()
length = stream.seek(0, os.SEEK_END)
stream.seek(offset)
except (AttributeError, OSError):
# Not even that? Sorry, we're doomed...
return None
return length
class URLPattern:
"""
A utility class currently used for making lookups against proxy keys...
# Wildcard matching...
>>> pattern = URLPattern("all://")
>>> pattern.matches(httpx.URL("http://example.com"))
True
# Witch scheme matching...
>>> pattern = URLPattern("https://")
>>> pattern.matches(httpx.URL("https://example.com"))
True
>>> pattern.matches(httpx.URL("http://example.com"))
False
# With domain matching...
>>> pattern = URLPattern("https://example.com")
>>> pattern.matches(httpx.URL("https://example.com"))
True
>>> pattern.matches(httpx.URL("http://example.com"))
False
>>> pattern.matches(httpx.URL("https://other.com"))
False
# Wildcard scheme, with domain matching...
>>> pattern = URLPattern("all://example.com")
>>> pattern.matches(httpx.URL("https://example.com"))
True
>>> pattern.matches(httpx.URL("http://example.com"))
True
>>> pattern.matches(httpx.URL("https://other.com"))
False
# With port matching...
>>> pattern = URLPattern("https://example.com:1234")
>>> pattern.matches(httpx.URL("https://example.com:1234"))
True
>>> pattern.matches(httpx.URL("https://example.com"))
False
"""
def __init__(self, pattern: str) -> None:
from ._urls import URL
if pattern and ":" not in pattern:
raise ValueError(
f"Proxy keys should use proper URL forms rather "
f"than plain scheme strings. "
f'Instead of "{pattern}", use "{pattern}://"'
)
url = URL(pattern)
self.pattern = pattern
self.scheme = "" if url.scheme == "all" else url.scheme
self.host = "" if url.host == "*" else url.host
self.port = url.port
if not url.host or url.host == "*":
self.host_regex: typing.Pattern[str] | None = None
elif url.host.startswith("*."):
# *.example.com should match "www.example.com", but not "example.com"
domain = re.escape(url.host[2:])
self.host_regex = re.compile(f"^.+\\.{domain}$")
elif url.host.startswith("*"):
# *example.com should match "www.example.com" and "example.com"
domain = re.escape(url.host[1:])
self.host_regex = re.compile(f"^(.+\\.)?{domain}$")
else:
# example.com should match "example.com" but not "www.example.com"
domain = re.escape(url.host)
self.host_regex = re.compile(f"^{domain}$")
def matches(self, other: URL) -> bool:
if self.scheme and self.scheme != other.scheme:
return False
if (
self.host
and self.host_regex is not None
and not self.host_regex.match(other.host)
):
return False
if self.port is not None and self.port != other.port:
return False
return True
@property
def priority(self) -> tuple[int, int, int]:
"""
The priority allows URLPattern instances to be sortable, so that
we can match from most specific to least specific.
"""
# URLs with a port should take priority over URLs without a port.
port_priority = 0 if self.port is not None else 1
# Longer hostnames should match first.
host_priority = -len(self.host)
# Longer schemes should match first.
scheme_priority = -len(self.scheme)
return (port_priority, host_priority, scheme_priority)
def __hash__(self) -> int:
return hash(self.pattern)
def __lt__(self, other: URLPattern) -> bool:
return self.priority < other.priority
def __eq__(self, other: typing.Any) -> bool:
return isinstance(other, URLPattern) and self.pattern == other.pattern
def is_ipv4_hostname(hostname: str) -> bool:
try:
ipaddress.IPv4Address(hostname.split("/")[0])
except Exception:
return False
return True
def is_ipv6_hostname(hostname: str) -> bool:
try:
ipaddress.IPv6Address(hostname.split("/")[0])
except Exception:
return False
return True
| import json
import logging
import os
import random
import pytest
import httpx
from httpx._utils import URLPattern, get_environment_proxies
@pytest.mark.parametrize(
"encoding",
(
"utf-32",
"utf-8-sig",
"utf-16",
"utf-8",
"utf-16-be",
"utf-16-le",
"utf-32-be",
"utf-32-le",
),
)
def test_encoded(encoding):
content = '{"abc": 123}'.encode(encoding)
response = httpx.Response(200, content=content)
assert response.json() == {"abc": 123}
def test_bad_utf_like_encoding():
content = b"\x00\x00\x00\x00"
response = httpx.Response(200, content=content)
with pytest.raises(json.decoder.JSONDecodeError):
response.json()
@pytest.mark.parametrize(
("encoding", "expected"),
(
("utf-16-be", "utf-16"),
("utf-16-le", "utf-16"),
("utf-32-be", "utf-32"),
("utf-32-le", "utf-32"),
),
)
def test_guess_by_bom(encoding, expected):
content = '\ufeff{"abc": 123}'.encode(encoding)
response = httpx.Response(200, content=content)
assert response.json() == {"abc": 123}
def test_logging_request(server, caplog):
caplog.set_level(logging.INFO)
with httpx.Client() as client:
response = client.get(server.url)
assert response.status_code == 200
assert caplog.record_tuples == [
(
"httpx",
logging.INFO,
'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"',
)
]
def test_logging_redirect_chain(server, caplog):
caplog.set_level(logging.INFO)
with httpx.Client(follow_redirects=True) as client:
response = client.get(server.url.copy_with(path="/redirect_301"))
assert response.status_code == 200
assert caplog.record_tuples == [
(
"httpx",
logging.INFO,
"HTTP Request: GET http://127.0.0.1:8000/redirect_301"
' "HTTP/1.1 301 Moved Permanently"',
),
(
"httpx",
logging.INFO,
'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"',
),
]
@pytest.mark.parametrize(
["environment", "proxies"],
[
({}, {}),
({"HTTP_PROXY": "http://127.0.0.1"}, {"http://": "http://127.0.0.1"}),
(
{"https_proxy": "http://127.0.0.1", "HTTP_PROXY": "https://127.0.0.1"},
{"https://": "http://127.0.0.1", "http://": "https://127.0.0.1"},
),
({"all_proxy": "http://127.0.0.1"}, {"all://": "http://127.0.0.1"}),
({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}),
({"no_proxy": "127.0.0.1"}, {"all://127.0.0.1": None}),
({"no_proxy": "192.168.0.0/16"}, {"all://192.168.0.0/16": None}),
({"no_proxy": "::1"}, {"all://[::1]": None}),
({"no_proxy": "localhost"}, {"all://localhost": None}),
({"no_proxy": "github.com"}, {"all://*github.com": None}),
({"no_proxy": ".github.com"}, {"all://*.github.com": None}),
({"no_proxy": "http://github.com"}, {"http://github.com": None}),
],
)
def test_get_environment_proxies(environment, proxies):
os.environ.update(environment)
assert get_environment_proxies() == proxies
@pytest.mark.parametrize(
["pattern", "url", "expected"],
[
("http://example.com", "http://example.com", True),
("http://example.com", "https://example.com", False),
("http://example.com", "http://other.com", False),
("http://example.com:123", "http://example.com:123", True),
("http://example.com:123", "http://example.com:456", False),
("http://example.com:123", "http://example.com", False),
("all://example.com", "http://example.com", True),
("all://example.com", "https://example.com", True),
("http://", "http://example.com", True),
("http://", "https://example.com", False),
("all://", "https://example.com:123", True),
("", "https://example.com:123", True),
],
)
def test_url_matches(pattern, url, expected):
pattern = URLPattern(pattern)
assert pattern.matches(httpx.URL(url)) == expected
def test_pattern_priority():
matchers = [
URLPattern("all://"),
URLPattern("http://"),
URLPattern("http://example.com"),
URLPattern("http://example.com:123"),
]
random.shuffle(matchers)
assert sorted(matchers) == [
URLPattern("http://example.com:123"),
URLPattern("http://example.com"),
URLPattern("http://"),
URLPattern("all://"),
]
| httpx |
python | from __future__ import annotations
import hashlib
import os
import re
import time
import typing
from base64 import b64encode
from urllib.request import parse_http_list
from ._exceptions import ProtocolError
from ._models import Cookies, Request, Response
from ._utils import to_bytes, to_str, unquote
if typing.TYPE_CHECKING: # pragma: no cover
from hashlib import _Hash
__all__ = ["Auth", "BasicAuth", "DigestAuth", "NetRCAuth"]
class Auth:
"""
Base class for all authentication schemes.
To implement a custom authentication scheme, subclass `Auth` and override
the `.auth_flow()` method.
If the authentication scheme does I/O such as disk access or network calls, or uses
synchronization primitives such as locks, you should override `.sync_auth_flow()`
and/or `.async_auth_flow()` instead of `.auth_flow()` to provide specialized
implementations that will be used by `Client` and `AsyncClient` respectively.
"""
requires_request_body = False
requires_response_body = False
def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
"""
Execute the authentication flow.
To dispatch a request, `yield` it:
```
yield request
```
The client will `.send()` the response back into the flow generator. You can
access it like so:
```
response = yield request
```
A `return` (or reaching the end of the generator) will result in the
client returning the last response obtained from the server.
You can dispatch as many requests as is necessary.
"""
yield request
def sync_auth_flow(
self, request: Request
) -> typing.Generator[Request, Response, None]:
"""
Execute the authentication flow synchronously.
By default, this defers to `.auth_flow()`. You should override this method
when the authentication scheme does I/O and/or uses concurrency primitives.
"""
if self.requires_request_body:
request.read()
flow = self.auth_flow(request)
request = next(flow)
while True:
response = yield request
if self.requires_response_body:
response.read()
try:
request = flow.send(response)
except StopIteration:
break
async def async_auth_flow(
self, request: Request
) -> typing.AsyncGenerator[Request, Response]:
"""
Execute the authentication flow asynchronously.
By default, this defers to `.auth_flow()`. You should override this method
when the authentication scheme does I/O and/or uses concurrency primitives.
"""
if self.requires_request_body:
await request.aread()
flow = self.auth_flow(request)
request = next(flow)
while True:
response = yield request
if self.requires_response_body:
await response.aread()
try:
request = flow.send(response)
except StopIteration:
break
class FunctionAuth(Auth):
"""
Allows the 'auth' argument to be passed as a simple callable function,
that takes the request, and returns a new, modified request.
"""
def __init__(self, func: typing.Callable[[Request], Request]) -> None:
self._func = func
def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
yield self._func(request)
class BasicAuth(Auth):
"""
Allows the 'auth' argument to be passed as a (username, password) pair,
and uses HTTP Basic authentication.
"""
def __init__(self, username: str | bytes, password: str | bytes) -> None:
self._auth_header = self._build_auth_header(username, password)
def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
request.headers["Authorization"] = self._auth_header
yield request
def _build_auth_header(self, username: str | bytes, password: str | bytes) -> str:
userpass = b":".join((to_bytes(username), to_bytes(password)))
token = b64encode(userpass).decode()
return f"Basic {token}"
class NetRCAuth(Auth):
"""
Use a 'netrc' file to lookup basic auth credentials based on the url host.
"""
def __init__(self, file: str | None = None) -> None:
# Lazily import 'netrc'.
# There's no need for us to load this module unless 'NetRCAuth' is being used.
import netrc
self._netrc_info = netrc.netrc(file)
def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
auth_info = self._netrc_info.authenticators(request.url.host)
if auth_info is None or not auth_info[2]:
# The netrc file did not have authentication credentials for this host.
yield request
else:
# Build a basic auth header with credentials from the netrc file.
request.headers["Authorization"] = self._build_auth_header(
username=auth_info[0], password=auth_info[2]
)
yield request
def _build_auth_header(self, username: str | bytes, password: str | bytes) -> str:
userpass = b":".join((to_bytes(username), to_bytes(password)))
token = b64encode(userpass).decode()
return f"Basic {token}"
class DigestAuth(Auth):
_ALGORITHM_TO_HASH_FUNCTION: dict[str, typing.Callable[[bytes], _Hash]] = {
"MD5": hashlib.md5,
"MD5-SESS": hashlib.md5,
"SHA": hashlib.sha1,
"SHA-SESS": hashlib.sha1,
"SHA-256": hashlib.sha256,
"SHA-256-SESS": hashlib.sha256,
"SHA-512": hashlib.sha512,
"SHA-512-SESS": hashlib.sha512,
}
def __init__(self, username: str | bytes, password: str | bytes) -> None:
self._username = to_bytes(username)
self._password = to_bytes(password)
self._last_challenge: _DigestAuthChallenge | None = None
self._nonce_count = 1
def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
if self._last_challenge:
request.headers["Authorization"] = self._build_auth_header(
request, self._last_challenge
)
response = yield request
if response.status_code != 401 or "www-authenticate" not in response.headers:
# If the response is not a 401 then we don't
# need to build an authenticated request.
return
for auth_header in response.headers.get_list("www-authenticate"):
if auth_header.lower().startswith("digest "):
break
else:
# If the response does not include a 'WWW-Authenticate: Digest ...'
# header, then we don't need to build an authenticated request.
return
self._last_challenge = self._parse_challenge(request, response, auth_header)
self._nonce_count = 1
request.headers["Authorization"] = self._build_auth_header(
request, self._last_challenge
)
if response.cookies:
Cookies(response.cookies).set_cookie_header(request=request)
yield request
def _parse_challenge(
self, request: Request, response: Response, auth_header: str
) -> _DigestAuthChallenge:
"""
Returns a challenge from a Digest WWW-Authenticate header.
These take the form of:
`Digest realm="realm@host.com",qop="auth,auth-int",nonce="abc",opaque="xyz"`
"""
scheme, _, fields = auth_header.partition(" ")
# This method should only ever have been called with a Digest auth header.
assert scheme.lower() == "digest"
header_dict: dict[str, str] = {}
for field in parse_http_list(fields):
key, value = field.strip().split("=", 1)
header_dict[key] = unquote(value)
try:
realm = header_dict["realm"].encode()
nonce = header_dict["nonce"].encode()
algorithm = header_dict.get("algorithm", "MD5")
opaque = header_dict["opaque"].encode() if "opaque" in header_dict else None
qop = header_dict["qop"].encode() if "qop" in header_dict else None
return _DigestAuthChallenge(
realm=realm, nonce=nonce, algorithm=algorithm, opaque=opaque, qop=qop
)
except KeyError as exc:
message = "Malformed Digest WWW-Authenticate header"
raise ProtocolError(message, request=request) from exc
def _build_auth_header(
self, request: Request, challenge: _DigestAuthChallenge
) -> str:
hash_func = self._ALGORITHM_TO_HASH_FUNCTION[challenge.algorithm.upper()]
def digest(data: bytes) -> bytes:
return hash_func(data).hexdigest().encode()
A1 = b":".join((self._username, challenge.realm, self._password))
path = request.url.raw_path
A2 = b":".join((request.method.encode(), path))
# TODO: implement auth-int
HA2 = digest(A2)
nc_value = b"%08x" % self._nonce_count
cnonce = self._get_client_nonce(self._nonce_count, challenge.nonce)
self._nonce_count += 1
HA1 = digest(A1)
if challenge.algorithm.lower().endswith("-sess"):
HA1 = digest(b":".join((HA1, challenge.nonce, cnonce)))
qop = self._resolve_qop(challenge.qop, request=request)
if qop is None:
# Following RFC 2069
digest_data = [HA1, challenge.nonce, HA2]
else:
# Following RFC 2617/7616
digest_data = [HA1, challenge.nonce, nc_value, cnonce, qop, HA2]
format_args = {
"username": self._username,
"realm": challenge.realm,
"nonce": challenge.nonce,
"uri": path,
"response": digest(b":".join(digest_data)),
"algorithm": challenge.algorithm.encode(),
}
if challenge.opaque:
format_args["opaque"] = challenge.opaque
if qop:
format_args["qop"] = b"auth"
format_args["nc"] = nc_value
format_args["cnonce"] = cnonce
return "Digest " + self._get_header_value(format_args)
def _get_client_nonce(self, nonce_count: int, nonce: bytes) -> bytes:
s = str(nonce_count).encode()
s += nonce
s += time.ctime().encode()
s += os.urandom(8)
return hashlib.sha1(s).hexdigest()[:16].encode()
def _get_header_value(self, header_fields: dict[str, bytes]) -> str:
NON_QUOTED_FIELDS = ("algorithm", "qop", "nc")
QUOTED_TEMPLATE = '{}="{}"'
NON_QUOTED_TEMPLATE = "{}={}"
header_value = ""
for i, (field, value) in enumerate(header_fields.items()):
if i > 0:
header_value += ", "
template = (
QUOTED_TEMPLATE
if field not in NON_QUOTED_FIELDS
else NON_QUOTED_TEMPLATE
)
header_value += template.format(field, to_str(value))
return header_value
def _resolve_qop(self, qop: bytes | None, request: Request) -> bytes | None:
if qop is None:
return None
qops = re.split(b", ?", qop)
if b"auth" in qops:
return b"auth"
if qops == [b"auth-int"]:
raise NotImplementedError("Digest auth-int support is not yet implemented")
message = f'Unexpected qop value "{qop!r}" in digest auth'
raise ProtocolError(message, request=request)
class _DigestAuthChallenge(typing.NamedTuple):
realm: bytes
nonce: bytes
algorithm: str
opaque: bytes | None
qop: bytes | None
| """
Unit tests for auth classes.
Integration tests also exist in tests/client/test_auth.py
"""
from urllib.request import parse_keqv_list
import pytest
import httpx
def test_basic_auth():
auth = httpx.BasicAuth(username="user", password="pass")
request = httpx.Request("GET", "https://www.example.com")
# The initial request should include a basic auth header.
flow = auth.sync_auth_flow(request)
request = next(flow)
assert request.headers["Authorization"].startswith("Basic")
# No other requests are made.
response = httpx.Response(content=b"Hello, world!", status_code=200)
with pytest.raises(StopIteration):
flow.send(response)
def test_digest_auth_with_200():
auth = httpx.DigestAuth(username="user", password="pass")
request = httpx.Request("GET", "https://www.example.com")
# The initial request should not include an auth header.
flow = auth.sync_auth_flow(request)
request = next(flow)
assert "Authorization" not in request.headers
# If a 200 response is returned, then no other requests are made.
response = httpx.Response(content=b"Hello, world!", status_code=200)
with pytest.raises(StopIteration):
flow.send(response)
def test_digest_auth_with_401():
auth = httpx.DigestAuth(username="user", password="pass")
request = httpx.Request("GET", "https://www.example.com")
# The initial request should not include an auth header.
flow = auth.sync_auth_flow(request)
request = next(flow)
assert "Authorization" not in request.headers
# If a 401 response is returned, then a digest auth request is made.
headers = {
"WWW-Authenticate": 'Digest realm="...", qop="auth", nonce="...", opaque="..."'
}
response = httpx.Response(
content=b"Auth required", status_code=401, headers=headers, request=request
)
request = flow.send(response)
assert request.headers["Authorization"].startswith("Digest")
# No other requests are made.
response = httpx.Response(content=b"Hello, world!", status_code=200)
with pytest.raises(StopIteration):
flow.send(response)
def test_digest_auth_with_401_nonce_counting():
auth = httpx.DigestAuth(username="user", password="pass")
request = httpx.Request("GET", "https://www.example.com")
# The initial request should not include an auth header.
flow = auth.sync_auth_flow(request)
request = next(flow)
assert "Authorization" not in request.headers
# If a 401 response is returned, then a digest auth request is made.
headers = {
"WWW-Authenticate": 'Digest realm="...", qop="auth", nonce="...", opaque="..."'
}
response = httpx.Response(
content=b"Auth required", status_code=401, headers=headers, request=request
)
first_request = flow.send(response)
assert first_request.headers["Authorization"].startswith("Digest")
# Each subsequent request contains the digest header by default...
request = httpx.Request("GET", "https://www.example.com")
flow = auth.sync_auth_flow(request)
second_request = next(flow)
assert second_request.headers["Authorization"].startswith("Digest")
# ... and the client nonce count (nc) is increased
first_nc = parse_keqv_list(first_request.headers["Authorization"].split(", "))["nc"]
second_nc = parse_keqv_list(second_request.headers["Authorization"].split(", "))[
"nc"
]
assert int(first_nc, 16) + 1 == int(second_nc, 16)
# No other requests are made.
response = httpx.Response(content=b"Hello, world!", status_code=200)
with pytest.raises(StopIteration):
flow.send(response)
def set_cookies(request: httpx.Request) -> httpx.Response:
headers = {
"Set-Cookie": "session=.session_value...",
"WWW-Authenticate": 'Digest realm="...", qop="auth", nonce="...", opaque="..."',
}
if request.url.path == "/auth":
return httpx.Response(
content=b"Auth required", status_code=401, headers=headers
)
else:
raise NotImplementedError() # pragma: no cover
def test_digest_auth_setting_cookie_in_request():
url = "https://www.example.com/auth"
client = httpx.Client(transport=httpx.MockTransport(set_cookies))
request = client.build_request("GET", url)
auth = httpx.DigestAuth(username="user", password="pass")
flow = auth.sync_auth_flow(request)
request = next(flow)
assert "Authorization" not in request.headers
response = client.get(url)
assert len(response.cookies) > 0
assert response.cookies["session"] == ".session_value..."
request = flow.send(response)
assert request.headers["Authorization"].startswith("Digest")
assert request.headers["Cookie"] == "session=.session_value..."
# No other requests are made.
response = httpx.Response(
content=b"Hello, world!", status_code=200, request=request
)
with pytest.raises(StopIteration):
flow.send(response)
def test_digest_auth_rfc_2069():
# Example from https://datatracker.ietf.org/doc/html/rfc2069#section-2.4
# with corrected response from https://www.rfc-editor.org/errata/eid749
auth = httpx.DigestAuth(username="Mufasa", password="CircleOfLife")
request = httpx.Request("GET", "https://www.example.com/dir/index.html")
# The initial request should not include an auth header.
flow = auth.sync_auth_flow(request)
request = next(flow)
assert "Authorization" not in request.headers
# If a 401 response is returned, then a digest auth request is made.
headers = {
"WWW-Authenticate": (
'Digest realm="testrealm@host.com", '
'nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", '
'opaque="5ccc069c403ebaf9f0171e9517f40e41"'
)
}
response = httpx.Response(
content=b"Auth required", status_code=401, headers=headers, request=request
)
request = flow.send(response)
assert request.headers["Authorization"].startswith("Digest")
assert 'username="Mufasa"' in request.headers["Authorization"]
assert 'realm="testrealm@host.com"' in request.headers["Authorization"]
assert (
'nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093"' in request.headers["Authorization"]
)
assert 'uri="/dir/index.html"' in request.headers["Authorization"]
assert (
'opaque="5ccc069c403ebaf9f0171e9517f40e41"' in request.headers["Authorization"]
)
assert (
'response="1949323746fe6a43ef61f9606e7febea"'
in request.headers["Authorization"]
)
# No other requests are made.
response = httpx.Response(content=b"Hello, world!", status_code=200)
with pytest.raises(StopIteration):
flow.send(response)
def test_digest_auth_rfc_7616_md5(monkeypatch):
# Example from https://datatracker.ietf.org/doc/html/rfc7616#section-3.9.1
def mock_get_client_nonce(nonce_count: int, nonce: bytes) -> bytes:
return "f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ".encode()
auth = httpx.DigestAuth(username="Mufasa", password="Circle of Life")
monkeypatch.setattr(auth, "_get_client_nonce", mock_get_client_nonce)
request = httpx.Request("GET", "https://www.example.com/dir/index.html")
# The initial request should not include an auth header.
flow = auth.sync_auth_flow(request)
request = next(flow)
assert "Authorization" not in request.headers
# If a 401 response is returned, then a digest auth request is made.
headers = {
"WWW-Authenticate": (
'Digest realm="http-auth@example.org", '
'qop="auth, auth-int", '
"algorithm=MD5, "
'nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", '
'opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS"'
)
}
response = httpx.Response(
content=b"Auth required", status_code=401, headers=headers, request=request
)
request = flow.send(response)
assert request.headers["Authorization"].startswith("Digest")
assert 'username="Mufasa"' in request.headers["Authorization"]
assert 'realm="http-auth@example.org"' in request.headers["Authorization"]
assert 'uri="/dir/index.html"' in request.headers["Authorization"]
assert "algorithm=MD5" in request.headers["Authorization"]
assert (
'nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v"'
in request.headers["Authorization"]
)
assert "nc=00000001" in request.headers["Authorization"]
assert (
'cnonce="f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ"'
in request.headers["Authorization"]
)
assert "qop=auth" in request.headers["Authorization"]
assert (
'opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS"'
in request.headers["Authorization"]
)
assert (
'response="8ca523f5e9506fed4657c9700eebdbec"'
in request.headers["Authorization"]
)
# No other requests are made.
response = httpx.Response(content=b"Hello, world!", status_code=200)
with pytest.raises(StopIteration):
flow.send(response)
def test_digest_auth_rfc_7616_sha_256(monkeypatch):
# Example from https://datatracker.ietf.org/doc/html/rfc7616#section-3.9.1
def mock_get_client_nonce(nonce_count: int, nonce: bytes) -> bytes:
return "f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ".encode()
auth = httpx.DigestAuth(username="Mufasa", password="Circle of Life")
monkeypatch.setattr(auth, "_get_client_nonce", mock_get_client_nonce)
request = httpx.Request("GET", "https://www.example.com/dir/index.html")
# The initial request should not include an auth header.
flow = auth.sync_auth_flow(request)
request = next(flow)
assert "Authorization" not in request.headers
# If a 401 response is returned, then a digest auth request is made.
headers = {
"WWW-Authenticate": (
'Digest realm="http-auth@example.org", '
'qop="auth, auth-int", '
"algorithm=SHA-256, "
'nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", '
'opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS"'
)
}
response = httpx.Response(
content=b"Auth required", status_code=401, headers=headers, request=request
)
request = flow.send(response)
assert request.headers["Authorization"].startswith("Digest")
assert 'username="Mufasa"' in request.headers["Authorization"]
assert 'realm="http-auth@example.org"' in request.headers["Authorization"]
assert 'uri="/dir/index.html"' in request.headers["Authorization"]
assert "algorithm=SHA-256" in request.headers["Authorization"]
assert (
'nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v"'
in request.headers["Authorization"]
)
assert "nc=00000001" in request.headers["Authorization"]
assert (
'cnonce="f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ"'
in request.headers["Authorization"]
)
assert "qop=auth" in request.headers["Authorization"]
assert (
'opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS"'
in request.headers["Authorization"]
)
assert (
'response="753927fa0e85d155564e2e272a28d1802ca10daf4496794697cf8db5856cb6c1"'
in request.headers["Authorization"]
)
# No other requests are made.
response = httpx.Response(content=b"Hello, world!", status_code=200)
with pytest.raises(StopIteration):
flow.send(response)
| httpx |
python | from __future__ import annotations
import os
import typing
from ._models import Headers
from ._types import CertTypes, HeaderTypes, TimeoutTypes
from ._urls import URL
if typing.TYPE_CHECKING:
import ssl # pragma: no cover
__all__ = ["Limits", "Proxy", "Timeout", "create_ssl_context"]
class UnsetType:
pass # pragma: no cover
UNSET = UnsetType()
def create_ssl_context(
verify: ssl.SSLContext | str | bool = True,
cert: CertTypes | None = None,
trust_env: bool = True,
) -> ssl.SSLContext:
import ssl
import warnings
import certifi
if verify is True:
if trust_env and os.environ.get("SSL_CERT_FILE"): # pragma: nocover
ctx = ssl.create_default_context(cafile=os.environ["SSL_CERT_FILE"])
elif trust_env and os.environ.get("SSL_CERT_DIR"): # pragma: nocover
ctx = ssl.create_default_context(capath=os.environ["SSL_CERT_DIR"])
else:
# Default case...
ctx = ssl.create_default_context(cafile=certifi.where())
elif verify is False:
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
elif isinstance(verify, str): # pragma: nocover
message = (
"`verify=<str>` is deprecated. "
"Use `verify=ssl.create_default_context(cafile=...)` "
"or `verify=ssl.create_default_context(capath=...)` instead."
)
warnings.warn(message, DeprecationWarning)
if os.path.isdir(verify):
return ssl.create_default_context(capath=verify)
return ssl.create_default_context(cafile=verify)
else:
ctx = verify
if cert: # pragma: nocover
message = (
"`cert=...` is deprecated. Use `verify=<ssl_context>` instead,"
"with `.load_cert_chain()` to configure the certificate chain."
)
warnings.warn(message, DeprecationWarning)
if isinstance(cert, str):
ctx.load_cert_chain(cert)
else:
ctx.load_cert_chain(*cert)
return ctx
class Timeout:
"""
Timeout configuration.
**Usage**:
Timeout(None) # No timeouts.
Timeout(5.0) # 5s timeout on all operations.
Timeout(None, connect=5.0) # 5s timeout on connect, no other timeouts.
Timeout(5.0, connect=10.0) # 10s timeout on connect. 5s timeout elsewhere.
Timeout(5.0, pool=None) # No timeout on acquiring connection from pool.
# 5s timeout elsewhere.
"""
def __init__(
self,
timeout: TimeoutTypes | UnsetType = UNSET,
*,
connect: None | float | UnsetType = UNSET,
read: None | float | UnsetType = UNSET,
write: None | float | UnsetType = UNSET,
pool: None | float | UnsetType = UNSET,
) -> None:
if isinstance(timeout, Timeout):
# Passed as a single explicit Timeout.
assert connect is UNSET
assert read is UNSET
assert write is UNSET
assert pool is UNSET
self.connect = timeout.connect # type: typing.Optional[float]
self.read = timeout.read # type: typing.Optional[float]
self.write = timeout.write # type: typing.Optional[float]
self.pool = timeout.pool # type: typing.Optional[float]
elif isinstance(timeout, tuple):
# Passed as a tuple.
self.connect = timeout[0]
self.read = timeout[1]
self.write = None if len(timeout) < 3 else timeout[2]
self.pool = None if len(timeout) < 4 else timeout[3]
elif not (
isinstance(connect, UnsetType)
or isinstance(read, UnsetType)
or isinstance(write, UnsetType)
or isinstance(pool, UnsetType)
):
self.connect = connect
self.read = read
self.write = write
self.pool = pool
else:
if isinstance(timeout, UnsetType):
raise ValueError(
"httpx.Timeout must either include a default, or set all "
"four parameters explicitly."
)
self.connect = timeout if isinstance(connect, UnsetType) else connect
self.read = timeout if isinstance(read, UnsetType) else read
self.write = timeout if isinstance(write, UnsetType) else write
self.pool = timeout if isinstance(pool, UnsetType) else pool
def as_dict(self) -> dict[str, float | None]:
return {
"connect": self.connect,
"read": self.read,
"write": self.write,
"pool": self.pool,
}
def __eq__(self, other: typing.Any) -> bool:
return (
isinstance(other, self.__class__)
and self.connect == other.connect
and self.read == other.read
and self.write == other.write
and self.pool == other.pool
)
def __repr__(self) -> str:
class_name = self.__class__.__name__
if len({self.connect, self.read, self.write, self.pool}) == 1:
return f"{class_name}(timeout={self.connect})"
return (
f"{class_name}(connect={self.connect}, "
f"read={self.read}, write={self.write}, pool={self.pool})"
)
class Limits:
"""
Configuration for limits to various client behaviors.
**Parameters:**
* **max_connections** - The maximum number of concurrent connections that may be
established.
* **max_keepalive_connections** - Allow the connection pool to maintain
keep-alive connections below this point. Should be less than or equal
to `max_connections`.
* **keepalive_expiry** - Time limit on idle keep-alive connections in seconds.
"""
def __init__(
self,
*,
max_connections: int | None = None,
max_keepalive_connections: int | None = None,
keepalive_expiry: float | None = 5.0,
) -> None:
self.max_connections = max_connections
self.max_keepalive_connections = max_keepalive_connections
self.keepalive_expiry = keepalive_expiry
def __eq__(self, other: typing.Any) -> bool:
return (
isinstance(other, self.__class__)
and self.max_connections == other.max_connections
and self.max_keepalive_connections == other.max_keepalive_connections
and self.keepalive_expiry == other.keepalive_expiry
)
def __repr__(self) -> str:
class_name = self.__class__.__name__
return (
f"{class_name}(max_connections={self.max_connections}, "
f"max_keepalive_connections={self.max_keepalive_connections}, "
f"keepalive_expiry={self.keepalive_expiry})"
)
class Proxy:
def __init__(
self,
url: URL | str,
*,
ssl_context: ssl.SSLContext | None = None,
auth: tuple[str, str] | None = None,
headers: HeaderTypes | None = None,
) -> None:
url = URL(url)
headers = Headers(headers)
if url.scheme not in ("http", "https", "socks5", "socks5h"):
raise ValueError(f"Unknown scheme for proxy URL {url!r}")
if url.username or url.password:
# Remove any auth credentials from the URL.
auth = (url.username, url.password)
url = url.copy_with(username=None, password=None)
self.url = url
self.auth = auth
self.headers = headers
self.ssl_context = ssl_context
@property
def raw_auth(self) -> tuple[bytes, bytes] | None:
# The proxy authentication as raw bytes.
return (
None
if self.auth is None
else (self.auth[0].encode("utf-8"), self.auth[1].encode("utf-8"))
)
def __repr__(self) -> str:
# The authentication is represented with the password component masked.
auth = (self.auth[0], "********") if self.auth else None
# Build a nice concise representation.
url_str = f"{str(self.url)!r}"
auth_str = f", auth={auth!r}" if auth else ""
headers_str = f", headers={dict(self.headers)!r}" if self.headers else ""
return f"Proxy({url_str}{auth_str}{headers_str})"
DEFAULT_TIMEOUT_CONFIG = Timeout(timeout=5.0)
DEFAULT_LIMITS = Limits(max_connections=100, max_keepalive_connections=20)
DEFAULT_MAX_REDIRECTS = 20
| import ssl
import typing
from pathlib import Path
import certifi
import pytest
import httpx
def test_load_ssl_config():
context = httpx.create_ssl_context()
assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED
assert context.check_hostname is True
def test_load_ssl_config_verify_non_existing_file():
with pytest.raises(IOError):
context = httpx.create_ssl_context()
context.load_verify_locations(cafile="/path/to/nowhere")
def test_load_ssl_with_keylog(monkeypatch: typing.Any) -> None:
monkeypatch.setenv("SSLKEYLOGFILE", "test")
context = httpx.create_ssl_context()
assert context.keylog_filename == "test"
def test_load_ssl_config_verify_existing_file():
context = httpx.create_ssl_context()
context.load_verify_locations(capath=certifi.where())
assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED
assert context.check_hostname is True
def test_load_ssl_config_verify_directory():
context = httpx.create_ssl_context()
context.load_verify_locations(capath=Path(certifi.where()).parent)
assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED
assert context.check_hostname is True
def test_load_ssl_config_cert_and_key(cert_pem_file, cert_private_key_file):
context = httpx.create_ssl_context()
context.load_cert_chain(cert_pem_file, cert_private_key_file)
assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED
assert context.check_hostname is True
@pytest.mark.parametrize("password", [b"password", "password"])
def test_load_ssl_config_cert_and_encrypted_key(
cert_pem_file, cert_encrypted_private_key_file, password
):
context = httpx.create_ssl_context()
context.load_cert_chain(cert_pem_file, cert_encrypted_private_key_file, password)
assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED
assert context.check_hostname is True
def test_load_ssl_config_cert_and_key_invalid_password(
cert_pem_file, cert_encrypted_private_key_file
):
with pytest.raises(ssl.SSLError):
context = httpx.create_ssl_context()
context.load_cert_chain(
cert_pem_file, cert_encrypted_private_key_file, "password1"
)
def test_load_ssl_config_cert_without_key_raises(cert_pem_file):
with pytest.raises(ssl.SSLError):
context = httpx.create_ssl_context()
context.load_cert_chain(cert_pem_file)
def test_load_ssl_config_no_verify():
context = httpx.create_ssl_context(verify=False)
assert context.verify_mode == ssl.VerifyMode.CERT_NONE
assert context.check_hostname is False
def test_SSLContext_with_get_request(server, cert_pem_file):
context = httpx.create_ssl_context()
context.load_verify_locations(cert_pem_file)
response = httpx.get(server.url, verify=context)
assert response.status_code == 200
def test_limits_repr():
limits = httpx.Limits(max_connections=100)
expected = (
"Limits(max_connections=100, max_keepalive_connections=None,"
" keepalive_expiry=5.0)"
)
assert repr(limits) == expected
def test_limits_eq():
limits = httpx.Limits(max_connections=100)
assert limits == httpx.Limits(max_connections=100)
def test_timeout_eq():
timeout = httpx.Timeout(timeout=5.0)
assert timeout == httpx.Timeout(timeout=5.0)
def test_timeout_all_parameters_set():
timeout = httpx.Timeout(connect=5.0, read=5.0, write=5.0, pool=5.0)
assert timeout == httpx.Timeout(timeout=5.0)
def test_timeout_from_nothing():
timeout = httpx.Timeout(None)
assert timeout.connect is None
assert timeout.read is None
assert timeout.write is None
assert timeout.pool is None
def test_timeout_from_none():
timeout = httpx.Timeout(timeout=None)
assert timeout == httpx.Timeout(None)
def test_timeout_from_one_none_value():
timeout = httpx.Timeout(None, read=None)
assert timeout == httpx.Timeout(None)
def test_timeout_from_one_value():
timeout = httpx.Timeout(None, read=5.0)
assert timeout == httpx.Timeout(timeout=(None, 5.0, None, None))
def test_timeout_from_one_value_and_default():
timeout = httpx.Timeout(5.0, pool=60.0)
assert timeout == httpx.Timeout(timeout=(5.0, 5.0, 5.0, 60.0))
def test_timeout_missing_default():
with pytest.raises(ValueError):
httpx.Timeout(pool=60.0)
def test_timeout_from_tuple():
timeout = httpx.Timeout(timeout=(5.0, 5.0, 5.0, 5.0))
assert timeout == httpx.Timeout(timeout=5.0)
def test_timeout_from_config_instance():
timeout = httpx.Timeout(timeout=5.0)
assert httpx.Timeout(timeout) == httpx.Timeout(timeout=5.0)
def test_timeout_repr():
timeout = httpx.Timeout(timeout=5.0)
assert repr(timeout) == "Timeout(timeout=5.0)"
timeout = httpx.Timeout(None, read=5.0)
assert repr(timeout) == "Timeout(connect=None, read=5.0, write=None, pool=None)"
def test_proxy_from_url():
proxy = httpx.Proxy("https://example.com")
assert str(proxy.url) == "https://example.com"
assert proxy.auth is None
assert proxy.headers == {}
assert repr(proxy) == "Proxy('https://example.com')"
def test_proxy_with_auth_from_url():
proxy = httpx.Proxy("https://username:password@example.com")
assert str(proxy.url) == "https://example.com"
assert proxy.auth == ("username", "password")
assert proxy.headers == {}
assert repr(proxy) == "Proxy('https://example.com', auth=('username', '********'))"
def test_invalid_proxy_scheme():
with pytest.raises(ValueError):
httpx.Proxy("invalid://example.com")
| httpx |
python | from __future__ import annotations
import io
import mimetypes
import os
import re
import typing
from pathlib import Path
from ._types import (
AsyncByteStream,
FileContent,
FileTypes,
RequestData,
RequestFiles,
SyncByteStream,
)
from ._utils import (
peek_filelike_length,
primitive_value_to_str,
to_bytes,
)
_HTML5_FORM_ENCODING_REPLACEMENTS = {'"': "%22", "\\": "\\\\"}
_HTML5_FORM_ENCODING_REPLACEMENTS.update(
{chr(c): "%{:02X}".format(c) for c in range(0x1F + 1) if c != 0x1B}
)
_HTML5_FORM_ENCODING_RE = re.compile(
r"|".join([re.escape(c) for c in _HTML5_FORM_ENCODING_REPLACEMENTS.keys()])
)
def _format_form_param(name: str, value: str) -> bytes:
"""
Encode a name/value pair within a multipart form.
"""
def replacer(match: typing.Match[str]) -> str:
return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)]
value = _HTML5_FORM_ENCODING_RE.sub(replacer, value)
return f'{name}="{value}"'.encode()
def _guess_content_type(filename: str | None) -> str | None:
"""
Guesses the mimetype based on a filename. Defaults to `application/octet-stream`.
Returns `None` if `filename` is `None` or empty.
"""
if filename:
return mimetypes.guess_type(filename)[0] or "application/octet-stream"
return None
def get_multipart_boundary_from_content_type(
content_type: bytes | None,
) -> bytes | None:
if not content_type or not content_type.startswith(b"multipart/form-data"):
return None
# parse boundary according to
# https://www.rfc-editor.org/rfc/rfc2046#section-5.1.1
if b";" in content_type:
for section in content_type.split(b";"):
if section.strip().lower().startswith(b"boundary="):
return section.strip()[len(b"boundary=") :].strip(b'"')
return None
class DataField:
"""
A single form field item, within a multipart form field.
"""
def __init__(self, name: str, value: str | bytes | int | float | None) -> None:
if not isinstance(name, str):
raise TypeError(
f"Invalid type for name. Expected str, got {type(name)}: {name!r}"
)
if value is not None and not isinstance(value, (str, bytes, int, float)):
raise TypeError(
"Invalid type for value. Expected primitive type,"
f" got {type(value)}: {value!r}"
)
self.name = name
self.value: str | bytes = (
value if isinstance(value, bytes) else primitive_value_to_str(value)
)
def render_headers(self) -> bytes:
if not hasattr(self, "_headers"):
name = _format_form_param("name", self.name)
self._headers = b"".join(
[b"Content-Disposition: form-data; ", name, b"\r\n\r\n"]
)
return self._headers
def render_data(self) -> bytes:
if not hasattr(self, "_data"):
self._data = to_bytes(self.value)
return self._data
def get_length(self) -> int:
headers = self.render_headers()
data = self.render_data()
return len(headers) + len(data)
def render(self) -> typing.Iterator[bytes]:
yield self.render_headers()
yield self.render_data()
class FileField:
"""
A single file field item, within a multipart form field.
"""
CHUNK_SIZE = 64 * 1024
def __init__(self, name: str, value: FileTypes) -> None:
self.name = name
fileobj: FileContent
headers: dict[str, str] = {}
content_type: str | None = None
# This large tuple based API largely mirror's requests' API
# It would be good to think of better APIs for this that we could
# include in httpx 2.0 since variable length tuples(especially of 4 elements)
# are quite unwieldly
if isinstance(value, tuple):
if len(value) == 2:
# neither the 3rd parameter (content_type) nor the 4th (headers)
# was included
filename, fileobj = value
elif len(value) == 3:
filename, fileobj, content_type = value
else:
# all 4 parameters included
filename, fileobj, content_type, headers = value # type: ignore
else:
filename = Path(str(getattr(value, "name", "upload"))).name
fileobj = value
if content_type is None:
content_type = _guess_content_type(filename)
has_content_type_header = any("content-type" in key.lower() for key in headers)
if content_type is not None and not has_content_type_header:
# note that unlike requests, we ignore the content_type provided in the 3rd
# tuple element if it is also included in the headers requests does
# the opposite (it overwrites the headerwith the 3rd tuple element)
headers["Content-Type"] = content_type
if isinstance(fileobj, io.StringIO):
raise TypeError(
"Multipart file uploads require 'io.BytesIO', not 'io.StringIO'."
)
if isinstance(fileobj, io.TextIOBase):
raise TypeError(
"Multipart file uploads must be opened in binary mode, not text mode."
)
self.filename = filename
self.file = fileobj
self.headers = headers
def get_length(self) -> int | None:
headers = self.render_headers()
if isinstance(self.file, (str, bytes)):
return len(headers) + len(to_bytes(self.file))
file_length = peek_filelike_length(self.file)
# If we can't determine the filesize without reading it into memory,
# then return `None` here, to indicate an unknown file length.
if file_length is None:
return None
return len(headers) + file_length
def render_headers(self) -> bytes:
if not hasattr(self, "_headers"):
parts = [
b"Content-Disposition: form-data; ",
_format_form_param("name", self.name),
]
if self.filename:
filename = _format_form_param("filename", self.filename)
parts.extend([b"; ", filename])
for header_name, header_value in self.headers.items():
key, val = f"\r\n{header_name}: ".encode(), header_value.encode()
parts.extend([key, val])
parts.append(b"\r\n\r\n")
self._headers = b"".join(parts)
return self._headers
def render_data(self) -> typing.Iterator[bytes]:
if isinstance(self.file, (str, bytes)):
yield to_bytes(self.file)
return
if hasattr(self.file, "seek"):
try:
self.file.seek(0)
except io.UnsupportedOperation:
pass
chunk = self.file.read(self.CHUNK_SIZE)
while chunk:
yield to_bytes(chunk)
chunk = self.file.read(self.CHUNK_SIZE)
def render(self) -> typing.Iterator[bytes]:
yield self.render_headers()
yield from self.render_data()
class MultipartStream(SyncByteStream, AsyncByteStream):
"""
Request content as streaming multipart encoded form data.
"""
def __init__(
self,
data: RequestData,
files: RequestFiles,
boundary: bytes | None = None,
) -> None:
if boundary is None:
boundary = os.urandom(16).hex().encode("ascii")
self.boundary = boundary
self.content_type = "multipart/form-data; boundary=%s" % boundary.decode(
"ascii"
)
self.fields = list(self._iter_fields(data, files))
def _iter_fields(
self, data: RequestData, files: RequestFiles
) -> typing.Iterator[FileField | DataField]:
for name, value in data.items():
if isinstance(value, (tuple, list)):
for item in value:
yield DataField(name=name, value=item)
else:
yield DataField(name=name, value=value)
file_items = files.items() if isinstance(files, typing.Mapping) else files
for name, value in file_items:
yield FileField(name=name, value=value)
def iter_chunks(self) -> typing.Iterator[bytes]:
for field in self.fields:
yield b"--%s\r\n" % self.boundary
yield from field.render()
yield b"\r\n"
yield b"--%s--\r\n" % self.boundary
def get_content_length(self) -> int | None:
"""
Return the length of the multipart encoded content, or `None` if
any of the files have a length that cannot be determined upfront.
"""
boundary_length = len(self.boundary)
length = 0
for field in self.fields:
field_length = field.get_length()
if field_length is None:
return None
length += 2 + boundary_length + 2 # b"--{boundary}\r\n"
length += field_length
length += 2 # b"\r\n"
length += 2 + boundary_length + 4 # b"--{boundary}--\r\n"
return length
# Content stream interface.
def get_headers(self) -> dict[str, str]:
content_length = self.get_content_length()
content_type = self.content_type
if content_length is None:
return {"Transfer-Encoding": "chunked", "Content-Type": content_type}
return {"Content-Length": str(content_length), "Content-Type": content_type}
def __iter__(self) -> typing.Iterator[bytes]:
for chunk in self.iter_chunks():
yield chunk
async def __aiter__(self) -> typing.AsyncIterator[bytes]:
for chunk in self.iter_chunks():
yield chunk
| from __future__ import annotations
import io
import tempfile
import typing
import pytest
import httpx
def echo_request_content(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, content=request.content)
@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))
def test_multipart(value, output):
client = httpx.Client(transport=httpx.MockTransport(echo_request_content))
# Test with a single-value 'data' argument, and a plain file 'files' argument.
data = {"text": value}
files = {"file": io.BytesIO(b"<file content>")}
response = client.post("http://127.0.0.1:8000/", data=data, files=files)
boundary = response.request.headers["Content-Type"].split("boundary=")[-1]
boundary_bytes = boundary.encode("ascii")
assert response.status_code == 200
assert response.content == b"".join(
[
b"--" + boundary_bytes + b"\r\n",
b'Content-Disposition: form-data; name="text"\r\n',
b"\r\n",
b"abc\r\n",
b"--" + boundary_bytes + b"\r\n",
b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',
b"Content-Type: application/octet-stream\r\n",
b"\r\n",
b"<file content>\r\n",
b"--" + boundary_bytes + b"--\r\n",
]
)
@pytest.mark.parametrize(
"header",
[
"multipart/form-data; boundary=+++; charset=utf-8",
"multipart/form-data; charset=utf-8; boundary=+++",
"multipart/form-data; boundary=+++",
"multipart/form-data; boundary=+++ ;",
'multipart/form-data; boundary="+++"; charset=utf-8',
'multipart/form-data; charset=utf-8; boundary="+++"',
'multipart/form-data; boundary="+++"',
'multipart/form-data; boundary="+++" ;',
],
)
def test_multipart_explicit_boundary(header: str) -> None:
client = httpx.Client(transport=httpx.MockTransport(echo_request_content))
files = {"file": io.BytesIO(b"<file content>")}
headers = {"content-type": header}
response = client.post("http://127.0.0.1:8000/", files=files, headers=headers)
boundary_bytes = b"+++"
assert response.status_code == 200
assert response.request.headers["Content-Type"] == header
assert response.content == b"".join(
[
b"--" + boundary_bytes + b"\r\n",
b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',
b"Content-Type: application/octet-stream\r\n",
b"\r\n",
b"<file content>\r\n",
b"--" + boundary_bytes + b"--\r\n",
]
)
@pytest.mark.parametrize(
"header",
[
"multipart/form-data; charset=utf-8",
"multipart/form-data; charset=utf-8; ",
],
)
def test_multipart_header_without_boundary(header: str) -> None:
client = httpx.Client(transport=httpx.MockTransport(echo_request_content))
files = {"file": io.BytesIO(b"<file content>")}
headers = {"content-type": header}
response = client.post("http://127.0.0.1:8000/", files=files, headers=headers)
assert response.status_code == 200
assert response.request.headers["Content-Type"] == header
@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))
def test_multipart_invalid_key(key):
client = httpx.Client(transport=httpx.MockTransport(echo_request_content))
data = {key: "abc"}
files = {"file": io.BytesIO(b"<file content>")}
with pytest.raises(TypeError) as e:
client.post(
"http://127.0.0.1:8000/",
data=data,
files=files,
)
assert "Invalid type for name" in str(e.value)
assert repr(key) in str(e.value)
@pytest.mark.parametrize(("value"), (object(), {"key": "value"}))
def test_multipart_invalid_value(value):
client = httpx.Client(transport=httpx.MockTransport(echo_request_content))
data = {"text": value}
files = {"file": io.BytesIO(b"<file content>")}
with pytest.raises(TypeError) as e:
client.post("http://127.0.0.1:8000/", data=data, files=files)
assert "Invalid type for value" in str(e.value)
def test_multipart_file_tuple():
client = httpx.Client(transport=httpx.MockTransport(echo_request_content))
# Test with a list of values 'data' argument,
# and a tuple style 'files' argument.
data = {"text": ["abc"]}
files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}
response = client.post("http://127.0.0.1:8000/", data=data, files=files)
boundary = response.request.headers["Content-Type"].split("boundary=")[-1]
boundary_bytes = boundary.encode("ascii")
assert response.status_code == 200
assert response.content == b"".join(
[
b"--" + boundary_bytes + b"\r\n",
b'Content-Disposition: form-data; name="text"\r\n',
b"\r\n",
b"abc\r\n",
b"--" + boundary_bytes + b"\r\n",
b'Content-Disposition: form-data; name="file"; filename="name.txt"\r\n',
b"Content-Type: text/plain\r\n",
b"\r\n",
b"<file content>\r\n",
b"--" + boundary_bytes + b"--\r\n",
]
)
@pytest.mark.parametrize("file_content_type", [None, "text/plain"])
def test_multipart_file_tuple_headers(file_content_type: str | None) -> None:
file_name = "test.txt"
file_content = io.BytesIO(b"<file content>")
file_headers = {"Expires": "0"}
url = "https://www.example.com/"
headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}
files = {"file": (file_name, file_content, file_content_type, file_headers)}
request = httpx.Request("POST", url, headers=headers, files=files)
request.read()
assert request.headers == {
"Host": "www.example.com",
"Content-Type": "multipart/form-data; boundary=BOUNDARY",
"Content-Length": str(len(request.content)),
}
assert request.content == (
f'--BOUNDARY\r\nContent-Disposition: form-data; name="file"; '
f'filename="{file_name}"\r\nExpires: 0\r\nContent-Type: '
f"text/plain\r\n\r\n<file content>\r\n--BOUNDARY--\r\n"
"".encode("ascii")
)
def test_multipart_headers_include_content_type() -> None:
"""
Content-Type from 4th tuple parameter (headers) should
override the 3rd parameter (content_type)
"""
file_name = "test.txt"
file_content = io.BytesIO(b"<file content>")
file_content_type = "text/plain"
file_headers = {"Content-Type": "image/png"}
url = "https://www.example.com/"
headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}
files = {"file": (file_name, file_content, file_content_type, file_headers)}
request = httpx.Request("POST", url, headers=headers, files=files)
request.read()
assert request.headers == {
"Host": "www.example.com",
"Content-Type": "multipart/form-data; boundary=BOUNDARY",
"Content-Length": str(len(request.content)),
}
assert request.content == (
f'--BOUNDARY\r\nContent-Disposition: form-data; name="file"; '
f'filename="{file_name}"\r\nContent-Type: '
f"image/png\r\n\r\n<file content>\r\n--BOUNDARY--\r\n"
"".encode("ascii")
)
def test_multipart_encode(tmp_path: typing.Any) -> None:
path = str(tmp_path / "name.txt")
with open(path, "wb") as f:
f.write(b"<file content>")
url = "https://www.example.com/"
headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}
data = {
"a": "1",
"b": b"C",
"c": ["11", "22", "33"],
"d": "",
"e": True,
"f": "",
}
with open(path, "rb") as input_file:
files = {"file": ("name.txt", input_file)}
request = httpx.Request("POST", url, headers=headers, data=data, files=files)
request.read()
assert request.headers == {
"Host": "www.example.com",
"Content-Type": "multipart/form-data; boundary=BOUNDARY",
"Content-Length": str(len(request.content)),
}
assert request.content == (
'--BOUNDARY\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'
'--BOUNDARY\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'
'--BOUNDARY\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'
'--BOUNDARY\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'
'--BOUNDARY\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'
'--BOUNDARY\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'
'--BOUNDARY\r\nContent-Disposition: form-data; name="e"\r\n\r\ntrue\r\n'
'--BOUNDARY\r\nContent-Disposition: form-data; name="f"\r\n\r\n\r\n'
'--BOUNDARY\r\nContent-Disposition: form-data; name="file";'
' filename="name.txt"\r\n'
"Content-Type: text/plain\r\n\r\n<file content>\r\n"
"--BOUNDARY--\r\n"
"".encode("ascii")
)
def test_multipart_encode_unicode_file_contents() -> None:
url = "https://www.example.com/"
headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}
files = {"file": ("name.txt", b"<bytes content>")}
request = httpx.Request("POST", url, headers=headers, files=files)
request.read()
assert request.headers == {
"Host": "www.example.com",
"Content-Type": "multipart/form-data; boundary=BOUNDARY",
"Content-Length": str(len(request.content)),
}
assert request.content == (
b'--BOUNDARY\r\nContent-Disposition: form-data; name="file";'
b' filename="name.txt"\r\n'
b"Content-Type: text/plain\r\n\r\n<bytes content>\r\n"
b"--BOUNDARY--\r\n"
)
def test_multipart_encode_files_allows_filenames_as_none() -> None:
url = "https://www.example.com/"
headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}
files = {"file": (None, io.BytesIO(b"<file content>"))}
request = httpx.Request("POST", url, headers=headers, data={}, files=files)
request.read()
assert request.headers == {
"Host": "www.example.com",
"Content-Type": "multipart/form-data; boundary=BOUNDARY",
"Content-Length": str(len(request.content)),
}
assert request.content == (
'--BOUNDARY\r\nContent-Disposition: form-data; name="file"\r\n\r\n'
"<file content>\r\n--BOUNDARY--\r\n"
"".encode("ascii")
)
@pytest.mark.parametrize(
"file_name,expected_content_type",
[
("example.json", "application/json"),
("example.txt", "text/plain"),
("no-extension", "application/octet-stream"),
],
)
def test_multipart_encode_files_guesses_correct_content_type(
file_name: str, expected_content_type: str
) -> None:
url = "https://www.example.com/"
headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}
files = {"file": (file_name, io.BytesIO(b"<file content>"))}
request = httpx.Request("POST", url, headers=headers, data={}, files=files)
request.read()
assert request.headers == {
"Host": "www.example.com",
"Content-Type": "multipart/form-data; boundary=BOUNDARY",
"Content-Length": str(len(request.content)),
}
assert request.content == (
f'--BOUNDARY\r\nContent-Disposition: form-data; name="file"; '
f'filename="{file_name}"\r\nContent-Type: '
f"{expected_content_type}\r\n\r\n<file content>\r\n--BOUNDARY--\r\n"
"".encode("ascii")
)
def test_multipart_encode_files_allows_bytes_content() -> None:
url = "https://www.example.com/"
headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}
files = {"file": ("test.txt", b"<bytes content>", "text/plain")}
request = httpx.Request("POST", url, headers=headers, data={}, files=files)
request.read()
assert request.headers == {
"Host": "www.example.com",
"Content-Type": "multipart/form-data; boundary=BOUNDARY",
"Content-Length": str(len(request.content)),
}
assert request.content == (
'--BOUNDARY\r\nContent-Disposition: form-data; name="file"; '
'filename="test.txt"\r\n'
"Content-Type: text/plain\r\n\r\n<bytes content>\r\n"
"--BOUNDARY--\r\n"
"".encode("ascii")
)
def test_multipart_encode_files_allows_str_content() -> None:
url = "https://www.example.com/"
headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}
files = {"file": ("test.txt", "<str content>", "text/plain")}
request = httpx.Request("POST", url, headers=headers, data={}, files=files)
request.read()
assert request.headers == {
"Host": "www.example.com",
"Content-Type": "multipart/form-data; boundary=BOUNDARY",
"Content-Length": str(len(request.content)),
}
assert request.content == (
'--BOUNDARY\r\nContent-Disposition: form-data; name="file"; '
'filename="test.txt"\r\n'
"Content-Type: text/plain\r\n\r\n<str content>\r\n"
"--BOUNDARY--\r\n"
"".encode("ascii")
)
def test_multipart_encode_files_raises_exception_with_StringIO_content() -> None:
url = "https://www.example.com"
files = {"file": ("test.txt", io.StringIO("content"), "text/plain")}
with pytest.raises(TypeError):
httpx.Request("POST", url, data={}, files=files) # type: ignore
def test_multipart_encode_files_raises_exception_with_text_mode_file() -> None:
url = "https://www.example.com"
with tempfile.TemporaryFile(mode="w") as upload:
files = {"file": ("test.txt", upload, "text/plain")}
with pytest.raises(TypeError):
httpx.Request("POST", url, data={}, files=files) # type: ignore
def test_multipart_encode_non_seekable_filelike() -> None:
"""
Test that special readable but non-seekable filelike objects are supported.
In this case uploads with use 'Transfer-Encoding: chunked', instead of
a 'Content-Length' header.
"""
class IteratorIO(io.IOBase):
def __init__(self, iterator: typing.Iterator[bytes]) -> None:
self._iterator = iterator
def read(self, *args: typing.Any) -> bytes:
return b"".join(self._iterator)
def data() -> typing.Iterator[bytes]:
yield b"Hello"
yield b"World"
url = "https://www.example.com/"
headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}
fileobj: typing.Any = IteratorIO(data())
files = {"file": fileobj}
request = httpx.Request("POST", url, headers=headers, files=files)
request.read()
assert request.headers == {
"Host": "www.example.com",
"Content-Type": "multipart/form-data; boundary=BOUNDARY",
"Transfer-Encoding": "chunked",
}
assert request.content == (
b"--BOUNDARY\r\n"
b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'
b"Content-Type: application/octet-stream\r\n"
b"\r\n"
b"HelloWorld\r\n"
b"--BOUNDARY--\r\n"
)
def test_multipart_rewinds_files():
with tempfile.TemporaryFile() as upload:
upload.write(b"Hello, world!")
transport = httpx.MockTransport(echo_request_content)
client = httpx.Client(transport=transport)
files = {"file": upload}
response = client.post("http://127.0.0.1:8000/", files=files)
assert response.status_code == 200
assert b"\r\nHello, world!\r\n" in response.content
# POSTing the same file instance a second time should have the same content.
files = {"file": upload}
response = client.post("http://127.0.0.1:8000/", files=files)
assert response.status_code == 200
assert b"\r\nHello, world!\r\n" in response.content
class TestHeaderParamHTML5Formatting:
def test_unicode(self):
filename = "n\u00e4me"
expected = b'filename="n\xc3\xa4me"'
files = {"upload": (filename, b"<file content>")}
request = httpx.Request("GET", "https://www.example.com", files=files)
assert expected in request.read()
def test_ascii(self):
filename = "name"
expected = b'filename="name"'
files = {"upload": (filename, b"<file content>")}
request = httpx.Request("GET", "https://www.example.com", files=files)
assert expected in request.read()
def test_unicode_escape(self):
filename = "hello\\world\u0022"
expected = b'filename="hello\\\\world%22"'
files = {"upload": (filename, b"<file content>")}
request = httpx.Request("GET", "https://www.example.com", files=files)
assert expected in request.read()
def test_unicode_with_control_character(self):
filename = "hello\x1a\x1b\x1c"
expected = b'filename="hello%1A\x1b%1C"'
files = {"upload": (filename, b"<file content>")}
request = httpx.Request("GET", "https://www.example.com", files=files)
assert expected in request.read()
| httpx |
python | """
Our exception hierarchy:
* HTTPError
x RequestError
+ TransportError
- TimeoutException
· ConnectTimeout
· ReadTimeout
· WriteTimeout
· PoolTimeout
- NetworkError
· ConnectError
· ReadError
· WriteError
· CloseError
- ProtocolError
· LocalProtocolError
· RemoteProtocolError
- ProxyError
- UnsupportedProtocol
+ DecodingError
+ TooManyRedirects
x HTTPStatusError
* InvalidURL
* CookieConflict
* StreamError
x StreamConsumed
x StreamClosed
x ResponseNotRead
x RequestNotRead
"""
from __future__ import annotations
import contextlib
import typing
if typing.TYPE_CHECKING:
from ._models import Request, Response # pragma: no cover
__all__ = [
"CloseError",
"ConnectError",
"ConnectTimeout",
"CookieConflict",
"DecodingError",
"HTTPError",
"HTTPStatusError",
"InvalidURL",
"LocalProtocolError",
"NetworkError",
"PoolTimeout",
"ProtocolError",
"ProxyError",
"ReadError",
"ReadTimeout",
"RemoteProtocolError",
"RequestError",
"RequestNotRead",
"ResponseNotRead",
"StreamClosed",
"StreamConsumed",
"StreamError",
"TimeoutException",
"TooManyRedirects",
"TransportError",
"UnsupportedProtocol",
"WriteError",
"WriteTimeout",
]
class HTTPError(Exception):
"""
Base class for `RequestError` and `HTTPStatusError`.
Useful for `try...except` blocks when issuing a request,
and then calling `.raise_for_status()`.
For example:
```
try:
response = httpx.get("https://www.example.com")
response.raise_for_status()
except httpx.HTTPError as exc:
print(f"HTTP Exception for {exc.request.url} - {exc}")
```
"""
def __init__(self, message: str) -> None:
super().__init__(message)
self._request: Request | None = None
@property
def request(self) -> Request:
if self._request is None:
raise RuntimeError("The .request property has not been set.")
return self._request
@request.setter
def request(self, request: Request) -> None:
self._request = request
class RequestError(HTTPError):
"""
Base class for all exceptions that may occur when issuing a `.request()`.
"""
def __init__(self, message: str, *, request: Request | None = None) -> None:
super().__init__(message)
# At the point an exception is raised we won't typically have a request
# instance to associate it with.
#
# The 'request_context' context manager is used within the Client and
# Response methods in order to ensure that any raised exceptions
# have a `.request` property set on them.
self._request = request
class TransportError(RequestError):
"""
Base class for all exceptions that occur at the level of the Transport API.
"""
# Timeout exceptions...
class TimeoutException(TransportError):
"""
The base class for timeout errors.
An operation has timed out.
"""
class ConnectTimeout(TimeoutException):
"""
Timed out while connecting to the host.
"""
class ReadTimeout(TimeoutException):
"""
Timed out while receiving data from the host.
"""
class WriteTimeout(TimeoutException):
"""
Timed out while sending data to the host.
"""
class PoolTimeout(TimeoutException):
"""
Timed out waiting to acquire a connection from the pool.
"""
# Core networking exceptions...
class NetworkError(TransportError):
"""
The base class for network-related errors.
An error occurred while interacting with the network.
"""
class ReadError(NetworkError):
"""
Failed to receive data from the network.
"""
class WriteError(NetworkError):
"""
Failed to send data through the network.
"""
class ConnectError(NetworkError):
"""
Failed to establish a connection.
"""
class CloseError(NetworkError):
"""
Failed to close a connection.
"""
# Other transport exceptions...
class ProxyError(TransportError):
"""
An error occurred while establishing a proxy connection.
"""
class UnsupportedProtocol(TransportError):
"""
Attempted to make a request to an unsupported protocol.
For example issuing a request to `ftp://www.example.com`.
"""
class ProtocolError(TransportError):
"""
The protocol was violated.
"""
class LocalProtocolError(ProtocolError):
"""
A protocol was violated by the client.
For example if the user instantiated a `Request` instance explicitly,
failed to include the mandatory `Host:` header, and then issued it directly
using `client.send()`.
"""
class RemoteProtocolError(ProtocolError):
"""
The protocol was violated by the server.
For example, returning malformed HTTP.
"""
# Other request exceptions...
class DecodingError(RequestError):
"""
Decoding of the response failed, due to a malformed encoding.
"""
class TooManyRedirects(RequestError):
"""
Too many redirects.
"""
# Client errors
class HTTPStatusError(HTTPError):
"""
The response had an error HTTP status of 4xx or 5xx.
May be raised when calling `response.raise_for_status()`
"""
def __init__(self, message: str, *, request: Request, response: Response) -> None:
super().__init__(message)
self.request = request
self.response = response
class InvalidURL(Exception):
"""
URL is improperly formed or cannot be parsed.
"""
def __init__(self, message: str) -> None:
super().__init__(message)
class CookieConflict(Exception):
"""
Attempted to lookup a cookie by name, but multiple cookies existed.
Can occur when calling `response.cookies.get(...)`.
"""
def __init__(self, message: str) -> None:
super().__init__(message)
# Stream exceptions...
# These may occur as the result of a programming error, by accessing
# the request/response stream in an invalid manner.
class StreamError(RuntimeError):
"""
The base class for stream exceptions.
The developer made an error in accessing the request stream in
an invalid way.
"""
def __init__(self, message: str) -> None:
super().__init__(message)
class StreamConsumed(StreamError):
"""
Attempted to read or stream content, but the content has already
been streamed.
"""
def __init__(self) -> None:
message = (
"Attempted to read or stream some content, but the content has "
"already been streamed. For requests, this could be due to passing "
"a generator as request content, and then receiving a redirect "
"response or a secondary request as part of an authentication flow."
"For responses, this could be due to attempting to stream the response "
"content more than once."
)
super().__init__(message)
class StreamClosed(StreamError):
"""
Attempted to read or stream response content, but the request has been
closed.
"""
def __init__(self) -> None:
message = "Attempted to read or stream content, but the stream has been closed."
super().__init__(message)
class ResponseNotRead(StreamError):
"""
Attempted to access streaming response content, without having called `read()`.
"""
def __init__(self) -> None:
message = (
"Attempted to access streaming response content,"
" without having called `read()`."
)
super().__init__(message)
class RequestNotRead(StreamError):
"""
Attempted to access streaming request content, without having called `read()`.
"""
def __init__(self) -> None:
message = (
"Attempted to access streaming request content,"
" without having called `read()`."
)
super().__init__(message)
@contextlib.contextmanager
def request_context(
request: Request | None = None,
) -> typing.Iterator[None]:
"""
A context manager that can be used to attach the given request context
to any `RequestError` exceptions that are raised within the block.
"""
try:
yield
except RequestError as exc:
if request is not None:
exc.request = request
raise exc
| from __future__ import annotations
import typing
import httpcore
import pytest
import httpx
if typing.TYPE_CHECKING: # pragma: no cover
from conftest import TestServer
def test_httpcore_all_exceptions_mapped() -> None:
"""
All exception classes exposed by HTTPCore are properly mapped to an HTTPX-specific
exception class.
"""
expected_mapped_httpcore_exceptions = {
value.__name__
for _, value in vars(httpcore).items()
if isinstance(value, type)
and issubclass(value, Exception)
and value is not httpcore.ConnectionNotAvailable
}
httpx_exceptions = {
value.__name__
for _, value in vars(httpx).items()
if isinstance(value, type) and issubclass(value, Exception)
}
unmapped_exceptions = expected_mapped_httpcore_exceptions - httpx_exceptions
if unmapped_exceptions: # pragma: no cover
pytest.fail(f"Unmapped httpcore exceptions: {unmapped_exceptions}")
def test_httpcore_exception_mapping(server: TestServer) -> None:
"""
HTTPCore exception mapping works as expected.
"""
impossible_port = 123456
with pytest.raises(httpx.ConnectError):
httpx.get(server.url.copy_with(port=impossible_port))
with pytest.raises(httpx.ReadTimeout):
httpx.get(
server.url.copy_with(path="/slow_response"),
timeout=httpx.Timeout(5, read=0.01),
)
def test_request_attribute() -> None:
# Exception without request attribute
exc = httpx.ReadTimeout("Read operation timed out")
with pytest.raises(RuntimeError):
exc.request # noqa: B018
# Exception with request attribute
request = httpx.Request("GET", "https://www.example.com")
exc = httpx.ReadTimeout("Read operation timed out", request=request)
assert exc.request == request
| httpx |
python | from __future__ import annotations
import inspect
import warnings
from json import dumps as json_dumps
from typing import (
Any,
AsyncIterable,
AsyncIterator,
Iterable,
Iterator,
Mapping,
)
from urllib.parse import urlencode
from ._exceptions import StreamClosed, StreamConsumed
from ._multipart import MultipartStream
from ._types import (
AsyncByteStream,
RequestContent,
RequestData,
RequestFiles,
ResponseContent,
SyncByteStream,
)
from ._utils import peek_filelike_length, primitive_value_to_str
__all__ = ["ByteStream"]
class ByteStream(AsyncByteStream, SyncByteStream):
def __init__(self, stream: bytes) -> None:
self._stream = stream
def __iter__(self) -> Iterator[bytes]:
yield self._stream
async def __aiter__(self) -> AsyncIterator[bytes]:
yield self._stream
class IteratorByteStream(SyncByteStream):
CHUNK_SIZE = 65_536
def __init__(self, stream: Iterable[bytes]) -> None:
self._stream = stream
self._is_stream_consumed = False
self._is_generator = inspect.isgenerator(stream)
def __iter__(self) -> Iterator[bytes]:
if self._is_stream_consumed and self._is_generator:
raise StreamConsumed()
self._is_stream_consumed = True
if hasattr(self._stream, "read"):
# File-like interfaces should use 'read' directly.
chunk = self._stream.read(self.CHUNK_SIZE)
while chunk:
yield chunk
chunk = self._stream.read(self.CHUNK_SIZE)
else:
# Otherwise iterate.
for part in self._stream:
yield part
class AsyncIteratorByteStream(AsyncByteStream):
CHUNK_SIZE = 65_536
def __init__(self, stream: AsyncIterable[bytes]) -> None:
self._stream = stream
self._is_stream_consumed = False
self._is_generator = inspect.isasyncgen(stream)
async def __aiter__(self) -> AsyncIterator[bytes]:
if self._is_stream_consumed and self._is_generator:
raise StreamConsumed()
self._is_stream_consumed = True
if hasattr(self._stream, "aread"):
# File-like interfaces should use 'aread' directly.
chunk = await self._stream.aread(self.CHUNK_SIZE)
while chunk:
yield chunk
chunk = await self._stream.aread(self.CHUNK_SIZE)
else:
# Otherwise iterate.
async for part in self._stream:
yield part
class UnattachedStream(AsyncByteStream, SyncByteStream):
"""
If a request or response is serialized using pickle, then it is no longer
attached to a stream for I/O purposes. Any stream operations should result
in `httpx.StreamClosed`.
"""
def __iter__(self) -> Iterator[bytes]:
raise StreamClosed()
async def __aiter__(self) -> AsyncIterator[bytes]:
raise StreamClosed()
yield b"" # pragma: no cover
def encode_content(
content: str | bytes | Iterable[bytes] | AsyncIterable[bytes],
) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]:
if isinstance(content, (bytes, str)):
body = content.encode("utf-8") if isinstance(content, str) else content
content_length = len(body)
headers = {"Content-Length": str(content_length)} if body else {}
return headers, ByteStream(body)
elif isinstance(content, Iterable) and not isinstance(content, dict):
# `not isinstance(content, dict)` is a bit oddly specific, but it
# catches a case that's easy for users to make in error, and would
# otherwise pass through here, like any other bytes-iterable,
# because `dict` happens to be iterable. See issue #2491.
content_length_or_none = peek_filelike_length(content)
if content_length_or_none is None:
headers = {"Transfer-Encoding": "chunked"}
else:
headers = {"Content-Length": str(content_length_or_none)}
return headers, IteratorByteStream(content) # type: ignore
elif isinstance(content, AsyncIterable):
headers = {"Transfer-Encoding": "chunked"}
return headers, AsyncIteratorByteStream(content)
raise TypeError(f"Unexpected type for 'content', {type(content)!r}")
def encode_urlencoded_data(
data: RequestData,
) -> tuple[dict[str, str], ByteStream]:
plain_data = []
for key, value in data.items():
if isinstance(value, (list, tuple)):
plain_data.extend([(key, primitive_value_to_str(item)) for item in value])
else:
plain_data.append((key, primitive_value_to_str(value)))
body = urlencode(plain_data, doseq=True).encode("utf-8")
content_length = str(len(body))
content_type = "application/x-www-form-urlencoded"
headers = {"Content-Length": content_length, "Content-Type": content_type}
return headers, ByteStream(body)
def encode_multipart_data(
data: RequestData, files: RequestFiles, boundary: bytes | None
) -> tuple[dict[str, str], MultipartStream]:
multipart = MultipartStream(data=data, files=files, boundary=boundary)
headers = multipart.get_headers()
return headers, multipart
def encode_text(text: str) -> tuple[dict[str, str], ByteStream]:
body = text.encode("utf-8")
content_length = str(len(body))
content_type = "text/plain; charset=utf-8"
headers = {"Content-Length": content_length, "Content-Type": content_type}
return headers, ByteStream(body)
def encode_html(html: str) -> tuple[dict[str, str], ByteStream]:
body = html.encode("utf-8")
content_length = str(len(body))
content_type = "text/html; charset=utf-8"
headers = {"Content-Length": content_length, "Content-Type": content_type}
return headers, ByteStream(body)
def encode_json(json: Any) -> tuple[dict[str, str], ByteStream]:
body = json_dumps(
json, ensure_ascii=False, separators=(",", ":"), allow_nan=False
).encode("utf-8")
content_length = str(len(body))
content_type = "application/json"
headers = {"Content-Length": content_length, "Content-Type": content_type}
return headers, ByteStream(body)
def encode_request(
content: RequestContent | None = None,
data: RequestData | None = None,
files: RequestFiles | None = None,
json: Any | None = None,
boundary: bytes | None = None,
) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]:
"""
Handles encoding the given `content`, `data`, `files`, and `json`,
returning a two-tuple of (<headers>, <stream>).
"""
if data is not None and not isinstance(data, Mapping):
# We prefer to separate `content=<bytes|str|byte iterator|bytes aiterator>`
# for raw request content, and `data=<form data>` for url encoded or
# multipart form content.
#
# However for compat with requests, we *do* still support
# `data=<bytes...>` usages. We deal with that case here, treating it
# as if `content=<...>` had been supplied instead.
message = "Use 'content=<...>' to upload raw bytes/text content."
warnings.warn(message, DeprecationWarning, stacklevel=2)
return encode_content(data)
if content is not None:
return encode_content(content)
elif files:
return encode_multipart_data(data or {}, files, boundary)
elif data:
return encode_urlencoded_data(data)
elif json is not None:
return encode_json(json)
return {}, ByteStream(b"")
def encode_response(
content: ResponseContent | None = None,
text: str | None = None,
html: str | None = None,
json: Any | None = None,
) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]:
"""
Handles encoding the given `content`, returning a two-tuple of
(<headers>, <stream>).
"""
if content is not None:
return encode_content(content)
elif text is not None:
return encode_text(text)
elif html is not None:
return encode_html(html)
elif json is not None:
return encode_json(json)
return {}, ByteStream(b"")
| import io
import typing
import pytest
import httpx
method = "POST"
url = "https://www.example.com"
@pytest.mark.anyio
async def test_empty_content():
request = httpx.Request(method, url)
assert isinstance(request.stream, httpx.SyncByteStream)
assert isinstance(request.stream, httpx.AsyncByteStream)
sync_content = b"".join(list(request.stream))
async_content = b"".join([part async for part in request.stream])
assert request.headers == {"Host": "www.example.com", "Content-Length": "0"}
assert sync_content == b""
assert async_content == b""
@pytest.mark.anyio
async def test_bytes_content():
request = httpx.Request(method, url, content=b"Hello, world!")
assert isinstance(request.stream, typing.Iterable)
assert isinstance(request.stream, typing.AsyncIterable)
sync_content = b"".join(list(request.stream))
async_content = b"".join([part async for part in request.stream])
assert request.headers == {"Host": "www.example.com", "Content-Length": "13"}
assert sync_content == b"Hello, world!"
assert async_content == b"Hello, world!"
# Support 'data' for compat with requests.
with pytest.warns(DeprecationWarning):
request = httpx.Request(method, url, data=b"Hello, world!") # type: ignore
assert isinstance(request.stream, typing.Iterable)
assert isinstance(request.stream, typing.AsyncIterable)
sync_content = b"".join(list(request.stream))
async_content = b"".join([part async for part in request.stream])
assert request.headers == {"Host": "www.example.com", "Content-Length": "13"}
assert sync_content == b"Hello, world!"
assert async_content == b"Hello, world!"
@pytest.mark.anyio
async def test_bytesio_content():
request = httpx.Request(method, url, content=io.BytesIO(b"Hello, world!"))
assert isinstance(request.stream, typing.Iterable)
assert not isinstance(request.stream, typing.AsyncIterable)
content = b"".join(list(request.stream))
assert request.headers == {"Host": "www.example.com", "Content-Length": "13"}
assert content == b"Hello, world!"
@pytest.mark.anyio
async def test_async_bytesio_content():
class AsyncBytesIO:
def __init__(self, content: bytes) -> None:
self._idx = 0
self._content = content
async def aread(self, chunk_size: int) -> bytes:
chunk = self._content[self._idx : self._idx + chunk_size]
self._idx = self._idx + chunk_size
return chunk
async def __aiter__(self):
yield self._content # pragma: no cover
request = httpx.Request(method, url, content=AsyncBytesIO(b"Hello, world!"))
assert not isinstance(request.stream, typing.Iterable)
assert isinstance(request.stream, typing.AsyncIterable)
content = b"".join([part async for part in request.stream])
assert request.headers == {
"Host": "www.example.com",
"Transfer-Encoding": "chunked",
}
assert content == b"Hello, world!"
@pytest.mark.anyio
async def test_iterator_content():
def hello_world() -> typing.Iterator[bytes]:
yield b"Hello, "
yield b"world!"
request = httpx.Request(method, url, content=hello_world())
assert isinstance(request.stream, typing.Iterable)
assert not isinstance(request.stream, typing.AsyncIterable)
content = b"".join(list(request.stream))
assert request.headers == {
"Host": "www.example.com",
"Transfer-Encoding": "chunked",
}
assert content == b"Hello, world!"
with pytest.raises(httpx.StreamConsumed):
list(request.stream)
# Support 'data' for compat with requests.
with pytest.warns(DeprecationWarning):
request = httpx.Request(method, url, data=hello_world()) # type: ignore
assert isinstance(request.stream, typing.Iterable)
assert not isinstance(request.stream, typing.AsyncIterable)
content = b"".join(list(request.stream))
assert request.headers == {
"Host": "www.example.com",
"Transfer-Encoding": "chunked",
}
assert content == b"Hello, world!"
@pytest.mark.anyio
async def test_aiterator_content():
async def hello_world() -> typing.AsyncIterator[bytes]:
yield b"Hello, "
yield b"world!"
request = httpx.Request(method, url, content=hello_world())
assert not isinstance(request.stream, typing.Iterable)
assert isinstance(request.stream, typing.AsyncIterable)
content = b"".join([part async for part in request.stream])
assert request.headers == {
"Host": "www.example.com",
"Transfer-Encoding": "chunked",
}
assert content == b"Hello, world!"
with pytest.raises(httpx.StreamConsumed):
[part async for part in request.stream]
# Support 'data' for compat with requests.
with pytest.warns(DeprecationWarning):
request = httpx.Request(method, url, data=hello_world()) # type: ignore
assert not isinstance(request.stream, typing.Iterable)
assert isinstance(request.stream, typing.AsyncIterable)
content = b"".join([part async for part in request.stream])
assert request.headers == {
"Host": "www.example.com",
"Transfer-Encoding": "chunked",
}
assert content == b"Hello, world!"
@pytest.mark.anyio
async def test_json_content():
request = httpx.Request(method, url, json={"Hello": "world!"})
assert isinstance(request.stream, typing.Iterable)
assert isinstance(request.stream, typing.AsyncIterable)
sync_content = b"".join(list(request.stream))
async_content = b"".join([part async for part in request.stream])
assert request.headers == {
"Host": "www.example.com",
"Content-Length": "18",
"Content-Type": "application/json",
}
assert sync_content == b'{"Hello":"world!"}'
assert async_content == b'{"Hello":"world!"}'
@pytest.mark.anyio
async def test_urlencoded_content():
request = httpx.Request(method, url, data={"Hello": "world!"})
assert isinstance(request.stream, typing.Iterable)
assert isinstance(request.stream, typing.AsyncIterable)
sync_content = b"".join(list(request.stream))
async_content = b"".join([part async for part in request.stream])
assert request.headers == {
"Host": "www.example.com",
"Content-Length": "14",
"Content-Type": "application/x-www-form-urlencoded",
}
assert sync_content == b"Hello=world%21"
assert async_content == b"Hello=world%21"
@pytest.mark.anyio
async def test_urlencoded_boolean():
request = httpx.Request(method, url, data={"example": True})
assert isinstance(request.stream, typing.Iterable)
assert isinstance(request.stream, typing.AsyncIterable)
sync_content = b"".join(list(request.stream))
async_content = b"".join([part async for part in request.stream])
assert request.headers == {
"Host": "www.example.com",
"Content-Length": "12",
"Content-Type": "application/x-www-form-urlencoded",
}
assert sync_content == b"example=true"
assert async_content == b"example=true"
@pytest.mark.anyio
async def test_urlencoded_none():
request = httpx.Request(method, url, data={"example": None})
assert isinstance(request.stream, typing.Iterable)
assert isinstance(request.stream, typing.AsyncIterable)
sync_content = b"".join(list(request.stream))
async_content = b"".join([part async for part in request.stream])
assert request.headers == {
"Host": "www.example.com",
"Content-Length": "8",
"Content-Type": "application/x-www-form-urlencoded",
}
assert sync_content == b"example="
assert async_content == b"example="
@pytest.mark.anyio
async def test_urlencoded_list():
request = httpx.Request(method, url, data={"example": ["a", 1, True]})
assert isinstance(request.stream, typing.Iterable)
assert isinstance(request.stream, typing.AsyncIterable)
sync_content = b"".join(list(request.stream))
async_content = b"".join([part async for part in request.stream])
assert request.headers == {
"Host": "www.example.com",
"Content-Length": "32",
"Content-Type": "application/x-www-form-urlencoded",
}
assert sync_content == b"example=a&example=1&example=true"
assert async_content == b"example=a&example=1&example=true"
@pytest.mark.anyio
async def test_multipart_files_content():
files = {"file": io.BytesIO(b"<file content>")}
headers = {"Content-Type": "multipart/form-data; boundary=+++"}
request = httpx.Request(
method,
url,
files=files,
headers=headers,
)
assert isinstance(request.stream, typing.Iterable)
assert isinstance(request.stream, typing.AsyncIterable)
sync_content = b"".join(list(request.stream))
async_content = b"".join([part async for part in request.stream])
assert request.headers == {
"Host": "www.example.com",
"Content-Length": "138",
"Content-Type": "multipart/form-data; boundary=+++",
}
assert sync_content == b"".join(
[
b"--+++\r\n",
b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',
b"Content-Type: application/octet-stream\r\n",
b"\r\n",
b"<file content>\r\n",
b"--+++--\r\n",
]
)
assert async_content == b"".join(
[
b"--+++\r\n",
b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',
b"Content-Type: application/octet-stream\r\n",
b"\r\n",
b"<file content>\r\n",
b"--+++--\r\n",
]
)
@pytest.mark.anyio
async def test_multipart_data_and_files_content():
data = {"message": "Hello, world!"}
files = {"file": io.BytesIO(b"<file content>")}
headers = {"Content-Type": "multipart/form-data; boundary=+++"}
request = httpx.Request(method, url, data=data, files=files, headers=headers)
assert isinstance(request.stream, typing.Iterable)
assert isinstance(request.stream, typing.AsyncIterable)
sync_content = b"".join(list(request.stream))
async_content = b"".join([part async for part in request.stream])
assert request.headers == {
"Host": "www.example.com",
"Content-Length": "210",
"Content-Type": "multipart/form-data; boundary=+++",
}
assert sync_content == b"".join(
[
b"--+++\r\n",
b'Content-Disposition: form-data; name="message"\r\n',
b"\r\n",
b"Hello, world!\r\n",
b"--+++\r\n",
b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',
b"Content-Type: application/octet-stream\r\n",
b"\r\n",
b"<file content>\r\n",
b"--+++--\r\n",
]
)
assert async_content == b"".join(
[
b"--+++\r\n",
b'Content-Disposition: form-data; name="message"\r\n',
b"\r\n",
b"Hello, world!\r\n",
b"--+++\r\n",
b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',
b"Content-Type: application/octet-stream\r\n",
b"\r\n",
b"<file content>\r\n",
b"--+++--\r\n",
]
)
@pytest.mark.anyio
async def test_empty_request():
request = httpx.Request(method, url, data={}, files={})
assert isinstance(request.stream, typing.Iterable)
assert isinstance(request.stream, typing.AsyncIterable)
sync_content = b"".join(list(request.stream))
async_content = b"".join([part async for part in request.stream])
assert request.headers == {"Host": "www.example.com", "Content-Length": "0"}
assert sync_content == b""
assert async_content == b""
def test_invalid_argument():
with pytest.raises(TypeError):
httpx.Request(method, url, content=123) # type: ignore
with pytest.raises(TypeError):
httpx.Request(method, url, content={"a": "b"}) # type: ignore
@pytest.mark.anyio
async def test_multipart_multiple_files_single_input_content():
files = [
("file", io.BytesIO(b"<file content 1>")),
("file", io.BytesIO(b"<file content 2>")),
]
headers = {"Content-Type": "multipart/form-data; boundary=+++"}
request = httpx.Request(method, url, files=files, headers=headers)
assert isinstance(request.stream, typing.Iterable)
assert isinstance(request.stream, typing.AsyncIterable)
sync_content = b"".join(list(request.stream))
async_content = b"".join([part async for part in request.stream])
assert request.headers == {
"Host": "www.example.com",
"Content-Length": "271",
"Content-Type": "multipart/form-data; boundary=+++",
}
assert sync_content == b"".join(
[
b"--+++\r\n",
b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',
b"Content-Type: application/octet-stream\r\n",
b"\r\n",
b"<file content 1>\r\n",
b"--+++\r\n",
b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',
b"Content-Type: application/octet-stream\r\n",
b"\r\n",
b"<file content 2>\r\n",
b"--+++--\r\n",
]
)
assert async_content == b"".join(
[
b"--+++\r\n",
b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',
b"Content-Type: application/octet-stream\r\n",
b"\r\n",
b"<file content 1>\r\n",
b"--+++\r\n",
b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',
b"Content-Type: application/octet-stream\r\n",
b"\r\n",
b"<file content 2>\r\n",
b"--+++--\r\n",
]
)
@pytest.mark.anyio
async def test_response_empty_content():
response = httpx.Response(200)
assert isinstance(response.stream, typing.Iterable)
assert isinstance(response.stream, typing.AsyncIterable)
sync_content = b"".join(list(response.stream))
async_content = b"".join([part async for part in response.stream])
assert response.headers == {}
assert sync_content == b""
assert async_content == b""
@pytest.mark.anyio
async def test_response_bytes_content():
response = httpx.Response(200, content=b"Hello, world!")
assert isinstance(response.stream, typing.Iterable)
assert isinstance(response.stream, typing.AsyncIterable)
sync_content = b"".join(list(response.stream))
async_content = b"".join([part async for part in response.stream])
assert response.headers == {"Content-Length": "13"}
assert sync_content == b"Hello, world!"
assert async_content == b"Hello, world!"
@pytest.mark.anyio
async def test_response_iterator_content():
def hello_world() -> typing.Iterator[bytes]:
yield b"Hello, "
yield b"world!"
response = httpx.Response(200, content=hello_world())
assert isinstance(response.stream, typing.Iterable)
assert not isinstance(response.stream, typing.AsyncIterable)
content = b"".join(list(response.stream))
assert response.headers == {"Transfer-Encoding": "chunked"}
assert content == b"Hello, world!"
with pytest.raises(httpx.StreamConsumed):
list(response.stream)
@pytest.mark.anyio
async def test_response_aiterator_content():
async def hello_world() -> typing.AsyncIterator[bytes]:
yield b"Hello, "
yield b"world!"
response = httpx.Response(200, content=hello_world())
assert not isinstance(response.stream, typing.Iterable)
assert isinstance(response.stream, typing.AsyncIterable)
content = b"".join([part async for part in response.stream])
assert response.headers == {"Transfer-Encoding": "chunked"}
assert content == b"Hello, world!"
with pytest.raises(httpx.StreamConsumed):
[part async for part in response.stream]
def test_response_invalid_argument():
with pytest.raises(TypeError):
httpx.Response(200, content=123) # type: ignore
def test_ensure_ascii_false_with_french_characters():
data = {"greeting": "Bonjour, ça va ?"}
response = httpx.Response(200, json=data)
assert "ça va" in response.text, (
"ensure_ascii=False should preserve French accented characters"
)
assert response.headers["Content-Type"] == "application/json"
def test_separators_for_compact_json():
data = {"clé": "valeur", "liste": [1, 2, 3]}
response = httpx.Response(200, json=data)
assert response.text == '{"clé":"valeur","liste":[1,2,3]}', (
"separators=(',', ':') should produce a compact representation"
)
assert response.headers["Content-Type"] == "application/json"
def test_allow_nan_false():
data_with_nan = {"nombre": float("nan")}
data_with_inf = {"nombre": float("inf")}
with pytest.raises(
ValueError, match="Out of range float values are not JSON compliant"
):
httpx.Response(200, json=data_with_nan)
with pytest.raises(
ValueError, match="Out of range float values are not JSON compliant"
):
httpx.Response(200, json=data_with_inf)
| httpx |
python | """
Handlers for Content-Encoding.
See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
"""
from __future__ import annotations
import codecs
import io
import typing
import zlib
from ._exceptions import DecodingError
# Brotli support is optional
try:
# The C bindings in `brotli` are recommended for CPython.
import brotli
except ImportError: # pragma: no cover
try:
# The CFFI bindings in `brotlicffi` are recommended for PyPy
# and other environments.
import brotlicffi as brotli
except ImportError:
brotli = None
# Zstandard support is optional
try:
import zstandard
except ImportError: # pragma: no cover
zstandard = None # type: ignore
class ContentDecoder:
def decode(self, data: bytes) -> bytes:
raise NotImplementedError() # pragma: no cover
def flush(self) -> bytes:
raise NotImplementedError() # pragma: no cover
class IdentityDecoder(ContentDecoder):
"""
Handle unencoded data.
"""
def decode(self, data: bytes) -> bytes:
return data
def flush(self) -> bytes:
return b""
class DeflateDecoder(ContentDecoder):
"""
Handle 'deflate' decoding.
See: https://stackoverflow.com/questions/1838699
"""
def __init__(self) -> None:
self.first_attempt = True
self.decompressor = zlib.decompressobj()
def decode(self, data: bytes) -> bytes:
was_first_attempt = self.first_attempt
self.first_attempt = False
try:
return self.decompressor.decompress(data)
except zlib.error as exc:
if was_first_attempt:
self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS)
return self.decode(data)
raise DecodingError(str(exc)) from exc
def flush(self) -> bytes:
try:
return self.decompressor.flush()
except zlib.error as exc: # pragma: no cover
raise DecodingError(str(exc)) from exc
class GZipDecoder(ContentDecoder):
"""
Handle 'gzip' decoding.
See: https://stackoverflow.com/questions/1838699
"""
def __init__(self) -> None:
self.decompressor = zlib.decompressobj(zlib.MAX_WBITS | 16)
def decode(self, data: bytes) -> bytes:
try:
return self.decompressor.decompress(data)
except zlib.error as exc:
raise DecodingError(str(exc)) from exc
def flush(self) -> bytes:
try:
return self.decompressor.flush()
except zlib.error as exc: # pragma: no cover
raise DecodingError(str(exc)) from exc
class BrotliDecoder(ContentDecoder):
"""
Handle 'brotli' decoding.
Requires `pip install brotlipy`. See: https://brotlipy.readthedocs.io/
or `pip install brotli`. See https://github.com/google/brotli
Supports both 'brotlipy' and 'Brotli' packages since they share an import
name. The top branches are for 'brotlipy' and bottom branches for 'Brotli'
"""
def __init__(self) -> None:
if brotli is None: # pragma: no cover
raise ImportError(
"Using 'BrotliDecoder', but neither of the 'brotlicffi' or 'brotli' "
"packages have been installed. "
"Make sure to install httpx using `pip install httpx[brotli]`."
) from None
self.decompressor = brotli.Decompressor()
self.seen_data = False
self._decompress: typing.Callable[[bytes], bytes]
if hasattr(self.decompressor, "decompress"):
# The 'brotlicffi' package.
self._decompress = self.decompressor.decompress # pragma: no cover
else:
# The 'brotli' package.
self._decompress = self.decompressor.process # pragma: no cover
def decode(self, data: bytes) -> bytes:
if not data:
return b""
self.seen_data = True
try:
return self._decompress(data)
except brotli.error as exc:
raise DecodingError(str(exc)) from exc
def flush(self) -> bytes:
if not self.seen_data:
return b""
try:
if hasattr(self.decompressor, "finish"):
# Only available in the 'brotlicffi' package.
# As the decompressor decompresses eagerly, this
# will never actually emit any data. However, it will potentially throw
# errors if a truncated or damaged data stream has been used.
self.decompressor.finish() # pragma: no cover
return b""
except brotli.error as exc: # pragma: no cover
raise DecodingError(str(exc)) from exc
class ZStandardDecoder(ContentDecoder):
"""
Handle 'zstd' RFC 8878 decoding.
Requires `pip install zstandard`.
Can be installed as a dependency of httpx using `pip install httpx[zstd]`.
"""
# inspired by the ZstdDecoder implementation in urllib3
def __init__(self) -> None:
if zstandard is None: # pragma: no cover
raise ImportError(
"Using 'ZStandardDecoder', ..."
"Make sure to install httpx using `pip install httpx[zstd]`."
) from None
self.decompressor = zstandard.ZstdDecompressor().decompressobj()
self.seen_data = False
def decode(self, data: bytes) -> bytes:
assert zstandard is not None
self.seen_data = True
output = io.BytesIO()
try:
output.write(self.decompressor.decompress(data))
while self.decompressor.eof and self.decompressor.unused_data:
unused_data = self.decompressor.unused_data
self.decompressor = zstandard.ZstdDecompressor().decompressobj()
output.write(self.decompressor.decompress(unused_data))
except zstandard.ZstdError as exc:
raise DecodingError(str(exc)) from exc
return output.getvalue()
def flush(self) -> bytes:
if not self.seen_data:
return b""
ret = self.decompressor.flush() # note: this is a no-op
if not self.decompressor.eof:
raise DecodingError("Zstandard data is incomplete") # pragma: no cover
return bytes(ret)
class MultiDecoder(ContentDecoder):
"""
Handle the case where multiple encodings have been applied.
"""
def __init__(self, children: typing.Sequence[ContentDecoder]) -> None:
"""
'children' should be a sequence of decoders in the order in which
each was applied.
"""
# Note that we reverse the order for decoding.
self.children = list(reversed(children))
def decode(self, data: bytes) -> bytes:
for child in self.children:
data = child.decode(data)
return data
def flush(self) -> bytes:
data = b""
for child in self.children:
data = child.decode(data) + child.flush()
return data
class ByteChunker:
"""
Handles returning byte content in fixed-size chunks.
"""
def __init__(self, chunk_size: int | None = None) -> None:
self._buffer = io.BytesIO()
self._chunk_size = chunk_size
def decode(self, content: bytes) -> list[bytes]:
if self._chunk_size is None:
return [content] if content else []
self._buffer.write(content)
if self._buffer.tell() >= self._chunk_size:
value = self._buffer.getvalue()
chunks = [
value[i : i + self._chunk_size]
for i in range(0, len(value), self._chunk_size)
]
if len(chunks[-1]) == self._chunk_size:
self._buffer.seek(0)
self._buffer.truncate()
return chunks
else:
self._buffer.seek(0)
self._buffer.write(chunks[-1])
self._buffer.truncate()
return chunks[:-1]
else:
return []
def flush(self) -> list[bytes]:
value = self._buffer.getvalue()
self._buffer.seek(0)
self._buffer.truncate()
return [value] if value else []
class TextChunker:
"""
Handles returning text content in fixed-size chunks.
"""
def __init__(self, chunk_size: int | None = None) -> None:
self._buffer = io.StringIO()
self._chunk_size = chunk_size
def decode(self, content: str) -> list[str]:
if self._chunk_size is None:
return [content] if content else []
self._buffer.write(content)
if self._buffer.tell() >= self._chunk_size:
value = self._buffer.getvalue()
chunks = [
value[i : i + self._chunk_size]
for i in range(0, len(value), self._chunk_size)
]
if len(chunks[-1]) == self._chunk_size:
self._buffer.seek(0)
self._buffer.truncate()
return chunks
else:
self._buffer.seek(0)
self._buffer.write(chunks[-1])
self._buffer.truncate()
return chunks[:-1]
else:
return []
def flush(self) -> list[str]:
value = self._buffer.getvalue()
self._buffer.seek(0)
self._buffer.truncate()
return [value] if value else []
class TextDecoder:
"""
Handles incrementally decoding bytes into text
"""
def __init__(self, encoding: str = "utf-8") -> None:
self.decoder = codecs.getincrementaldecoder(encoding)(errors="replace")
def decode(self, data: bytes) -> str:
return self.decoder.decode(data)
def flush(self) -> str:
return self.decoder.decode(b"", True)
class LineDecoder:
"""
Handles incrementally reading lines from text.
Has the same behaviour as the stdllib splitlines,
but handling the input iteratively.
"""
def __init__(self) -> None:
self.buffer: list[str] = []
self.trailing_cr: bool = False
def decode(self, text: str) -> list[str]:
# See https://docs.python.org/3/library/stdtypes.html#str.splitlines
NEWLINE_CHARS = "\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029"
# We always push a trailing `\r` into the next decode iteration.
if self.trailing_cr:
text = "\r" + text
self.trailing_cr = False
if text.endswith("\r"):
self.trailing_cr = True
text = text[:-1]
if not text:
# NOTE: the edge case input of empty text doesn't occur in practice,
# because other httpx internals filter out this value
return [] # pragma: no cover
trailing_newline = text[-1] in NEWLINE_CHARS
lines = text.splitlines()
if len(lines) == 1 and not trailing_newline:
# No new lines, buffer the input and continue.
self.buffer.append(lines[0])
return []
if self.buffer:
# Include any existing buffer in the first portion of the
# splitlines result.
lines = ["".join(self.buffer) + lines[0]] + lines[1:]
self.buffer = []
if not trailing_newline:
# If the last segment of splitlines is not newline terminated,
# then drop it from our output and start a new buffer.
self.buffer = [lines.pop()]
return lines
def flush(self) -> list[str]:
if not self.buffer and not self.trailing_cr:
return []
lines = ["".join(self.buffer)]
self.buffer = []
self.trailing_cr = False
return lines
SUPPORTED_DECODERS = {
"identity": IdentityDecoder,
"gzip": GZipDecoder,
"deflate": DeflateDecoder,
"br": BrotliDecoder,
"zstd": ZStandardDecoder,
}
if brotli is None:
SUPPORTED_DECODERS.pop("br") # pragma: no cover
if zstandard is None:
SUPPORTED_DECODERS.pop("zstd") # pragma: no cover
| from __future__ import annotations
import io
import typing
import zlib
import chardet
import pytest
import zstandard as zstd
import httpx
def test_deflate():
"""
Deflate encoding may use either 'zlib' or 'deflate' in the wild.
https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-22311297
"""
body = b"test 123"
compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)
compressed_body = compressor.compress(body) + compressor.flush()
headers = [(b"Content-Encoding", b"deflate")]
response = httpx.Response(
200,
headers=headers,
content=compressed_body,
)
assert response.content == body
def test_zlib():
"""
Deflate encoding may use either 'zlib' or 'deflate' in the wild.
https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-22311297
"""
body = b"test 123"
compressed_body = zlib.compress(body)
headers = [(b"Content-Encoding", b"deflate")]
response = httpx.Response(
200,
headers=headers,
content=compressed_body,
)
assert response.content == body
def test_gzip():
body = b"test 123"
compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)
compressed_body = compressor.compress(body) + compressor.flush()
headers = [(b"Content-Encoding", b"gzip")]
response = httpx.Response(
200,
headers=headers,
content=compressed_body,
)
assert response.content == body
def test_brotli():
body = b"test 123"
compressed_body = b"\x8b\x03\x80test 123\x03"
headers = [(b"Content-Encoding", b"br")]
response = httpx.Response(
200,
headers=headers,
content=compressed_body,
)
assert response.content == body
def test_zstd():
body = b"test 123"
compressed_body = zstd.compress(body)
headers = [(b"Content-Encoding", b"zstd")]
response = httpx.Response(
200,
headers=headers,
content=compressed_body,
)
assert response.content == body
def test_zstd_decoding_error():
compressed_body = "this_is_not_zstd_compressed_data"
headers = [(b"Content-Encoding", b"zstd")]
with pytest.raises(httpx.DecodingError):
httpx.Response(
200,
headers=headers,
content=compressed_body,
)
def test_zstd_empty():
headers = [(b"Content-Encoding", b"zstd")]
response = httpx.Response(200, headers=headers, content=b"")
assert response.content == b""
def test_zstd_truncated():
body = b"test 123"
compressed_body = zstd.compress(body)
headers = [(b"Content-Encoding", b"zstd")]
with pytest.raises(httpx.DecodingError):
httpx.Response(
200,
headers=headers,
content=compressed_body[1:3],
)
def test_zstd_multiframe():
# test inspired by urllib3 test suite
data = (
# Zstandard frame
zstd.compress(b"foo")
# skippable frame (must be ignored)
+ bytes.fromhex(
"50 2A 4D 18" # Magic_Number (little-endian)
"07 00 00 00" # Frame_Size (little-endian)
"00 00 00 00 00 00 00" # User_Data
)
# Zstandard frame
+ zstd.compress(b"bar")
)
compressed_body = io.BytesIO(data)
headers = [(b"Content-Encoding", b"zstd")]
response = httpx.Response(200, headers=headers, content=compressed_body)
response.read()
assert response.content == b"foobar"
def test_multi():
body = b"test 123"
deflate_compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)
compressed_body = deflate_compressor.compress(body) + deflate_compressor.flush()
gzip_compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)
compressed_body = (
gzip_compressor.compress(compressed_body) + gzip_compressor.flush()
)
headers = [(b"Content-Encoding", b"deflate, gzip")]
response = httpx.Response(
200,
headers=headers,
content=compressed_body,
)
assert response.content == body
def test_multi_with_identity():
body = b"test 123"
compressed_body = b"\x8b\x03\x80test 123\x03"
headers = [(b"Content-Encoding", b"br, identity")]
response = httpx.Response(
200,
headers=headers,
content=compressed_body,
)
assert response.content == body
headers = [(b"Content-Encoding", b"identity, br")]
response = httpx.Response(
200,
headers=headers,
content=compressed_body,
)
assert response.content == body
@pytest.mark.anyio
async def test_streaming():
body = b"test 123"
compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)
async def compress(body: bytes) -> typing.AsyncIterator[bytes]:
yield compressor.compress(body)
yield compressor.flush()
headers = [(b"Content-Encoding", b"gzip")]
response = httpx.Response(
200,
headers=headers,
content=compress(body),
)
assert not hasattr(response, "body")
assert await response.aread() == body
@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br", b"identity"))
def test_empty_content(header_value):
headers = [(b"Content-Encoding", header_value)]
response = httpx.Response(
200,
headers=headers,
content=b"",
)
assert response.content == b""
@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br", b"identity"))
def test_decoders_empty_cases(header_value):
headers = [(b"Content-Encoding", header_value)]
response = httpx.Response(content=b"", status_code=200, headers=headers)
assert response.read() == b""
@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))
def test_decoding_errors(header_value):
headers = [(b"Content-Encoding", header_value)]
compressed_body = b"invalid"
with pytest.raises(httpx.DecodingError):
request = httpx.Request("GET", "https://example.org")
httpx.Response(200, headers=headers, content=compressed_body, request=request)
with pytest.raises(httpx.DecodingError):
httpx.Response(200, headers=headers, content=compressed_body)
@pytest.mark.parametrize(
["data", "encoding"],
[
((b"Hello,", b" world!"), "ascii"),
((b"\xe3\x83", b"\x88\xe3\x83\xa9", b"\xe3", b"\x83\x99\xe3\x83\xab"), "utf-8"),
((b"Euro character: \x88! abcdefghijklmnopqrstuvwxyz", b""), "cp1252"),
((b"Accented: \xd6sterreich abcdefghijklmnopqrstuvwxyz", b""), "iso-8859-1"),
],
)
@pytest.mark.anyio
async def test_text_decoder_with_autodetect(data, encoding):
async def iterator() -> typing.AsyncIterator[bytes]:
nonlocal data
for chunk in data:
yield chunk
def autodetect(content):
return chardet.detect(content).get("encoding")
# Accessing `.text` on a read response.
response = httpx.Response(200, content=iterator(), default_encoding=autodetect)
await response.aread()
assert response.text == (b"".join(data)).decode(encoding)
# Streaming `.aiter_text` iteratively.
# Note that if we streamed the text *without* having read it first, then
# we won't get a `charset_normalizer` guess, and will instead always rely
# on utf-8 if no charset is specified.
text = "".join([part async for part in response.aiter_text()])
assert text == (b"".join(data)).decode(encoding)
@pytest.mark.anyio
async def test_text_decoder_known_encoding():
async def iterator() -> typing.AsyncIterator[bytes]:
yield b"\x83g"
yield b"\x83"
yield b"\x89\x83x\x83\x8b"
response = httpx.Response(
200,
headers=[(b"Content-Type", b"text/html; charset=shift-jis")],
content=iterator(),
)
await response.aread()
assert "".join(response.text) == "トラベル"
def test_text_decoder_empty_cases():
response = httpx.Response(200, content=b"")
assert response.text == ""
response = httpx.Response(200, content=[b""])
response.read()
assert response.text == ""
@pytest.mark.parametrize(
["data", "expected"],
[((b"Hello,", b" world!"), ["Hello,", " world!"])],
)
def test_streaming_text_decoder(
data: typing.Iterable[bytes], expected: list[str]
) -> None:
response = httpx.Response(200, content=iter(data))
assert list(response.iter_text()) == expected
def test_line_decoder_nl():
response = httpx.Response(200, content=[b""])
assert list(response.iter_lines()) == []
response = httpx.Response(200, content=[b"", b"a\n\nb\nc"])
assert list(response.iter_lines()) == ["a", "", "b", "c"]
# Issue #1033
response = httpx.Response(
200, content=[b"", b"12345\n", b"foo ", b"bar ", b"baz\n"]
)
assert list(response.iter_lines()) == ["12345", "foo bar baz"]
def test_line_decoder_cr():
response = httpx.Response(200, content=[b"", b"a\r\rb\rc"])
assert list(response.iter_lines()) == ["a", "", "b", "c"]
response = httpx.Response(200, content=[b"", b"a\r\rb\rc\r"])
assert list(response.iter_lines()) == ["a", "", "b", "c"]
# Issue #1033
response = httpx.Response(
200, content=[b"", b"12345\r", b"foo ", b"bar ", b"baz\r"]
)
assert list(response.iter_lines()) == ["12345", "foo bar baz"]
def test_line_decoder_crnl():
response = httpx.Response(200, content=[b"", b"a\r\n\r\nb\r\nc"])
assert list(response.iter_lines()) == ["a", "", "b", "c"]
response = httpx.Response(200, content=[b"", b"a\r\n\r\nb\r\nc\r\n"])
assert list(response.iter_lines()) == ["a", "", "b", "c"]
response = httpx.Response(200, content=[b"", b"a\r", b"\n\r\nb\r\nc"])
assert list(response.iter_lines()) == ["a", "", "b", "c"]
# Issue #1033
response = httpx.Response(200, content=[b"", b"12345\r\n", b"foo bar baz\r\n"])
assert list(response.iter_lines()) == ["12345", "foo bar baz"]
def test_invalid_content_encoding_header():
headers = [(b"Content-Encoding", b"invalid-header")]
body = b"test 123"
response = httpx.Response(
200,
headers=headers,
content=body,
)
assert response.content == body
| httpx |
python | from __future__ import annotations
import typing
from .._models import Request, Response
from .._types import AsyncByteStream
from .base import AsyncBaseTransport
if typing.TYPE_CHECKING: # pragma: no cover
import asyncio
import trio
Event = typing.Union[asyncio.Event, trio.Event]
_Message = typing.MutableMapping[str, typing.Any]
_Receive = typing.Callable[[], typing.Awaitable[_Message]]
_Send = typing.Callable[
[typing.MutableMapping[str, typing.Any]], typing.Awaitable[None]
]
_ASGIApp = typing.Callable[
[typing.MutableMapping[str, typing.Any], _Receive, _Send], typing.Awaitable[None]
]
__all__ = ["ASGITransport"]
def is_running_trio() -> bool:
try:
# sniffio is a dependency of trio.
# See https://github.com/python-trio/trio/issues/2802
import sniffio
if sniffio.current_async_library() == "trio":
return True
except ImportError: # pragma: nocover
pass
return False
def create_event() -> Event:
if is_running_trio():
import trio
return trio.Event()
import asyncio
return asyncio.Event()
class ASGIResponseStream(AsyncByteStream):
def __init__(self, body: list[bytes]) -> None:
self._body = body
async def __aiter__(self) -> typing.AsyncIterator[bytes]:
yield b"".join(self._body)
class ASGITransport(AsyncBaseTransport):
"""
A custom AsyncTransport that handles sending requests directly to an ASGI app.
```python
transport = httpx.ASGITransport(
app=app,
root_path="/submount",
client=("1.2.3.4", 123)
)
client = httpx.AsyncClient(transport=transport)
```
Arguments:
* `app` - The ASGI application.
* `raise_app_exceptions` - Boolean indicating if exceptions in the application
should be raised. Default to `True`. Can be set to `False` for use cases
such as testing the content of a client 500 response.
* `root_path` - The root path on which the ASGI application should be mounted.
* `client` - A two-tuple indicating the client IP and port of incoming requests.
```
"""
def __init__(
self,
app: _ASGIApp,
raise_app_exceptions: bool = True,
root_path: str = "",
client: tuple[str, int] = ("127.0.0.1", 123),
) -> None:
self.app = app
self.raise_app_exceptions = raise_app_exceptions
self.root_path = root_path
self.client = client
async def handle_async_request(
self,
request: Request,
) -> Response:
assert isinstance(request.stream, AsyncByteStream)
# ASGI scope.
scope = {
"type": "http",
"asgi": {"version": "3.0"},
"http_version": "1.1",
"method": request.method,
"headers": [(k.lower(), v) for (k, v) in request.headers.raw],
"scheme": request.url.scheme,
"path": request.url.path,
"raw_path": request.url.raw_path.split(b"?")[0],
"query_string": request.url.query,
"server": (request.url.host, request.url.port),
"client": self.client,
"root_path": self.root_path,
}
# Request.
request_body_chunks = request.stream.__aiter__()
request_complete = False
# Response.
status_code = None
response_headers = None
body_parts = []
response_started = False
response_complete = create_event()
# ASGI callables.
async def receive() -> dict[str, typing.Any]:
nonlocal request_complete
if request_complete:
await response_complete.wait()
return {"type": "http.disconnect"}
try:
body = await request_body_chunks.__anext__()
except StopAsyncIteration:
request_complete = True
return {"type": "http.request", "body": b"", "more_body": False}
return {"type": "http.request", "body": body, "more_body": True}
async def send(message: typing.MutableMapping[str, typing.Any]) -> None:
nonlocal status_code, response_headers, response_started
if message["type"] == "http.response.start":
assert not response_started
status_code = message["status"]
response_headers = message.get("headers", [])
response_started = True
elif message["type"] == "http.response.body":
assert not response_complete.is_set()
body = message.get("body", b"")
more_body = message.get("more_body", False)
if body and request.method != "HEAD":
body_parts.append(body)
if not more_body:
response_complete.set()
try:
await self.app(scope, receive, send)
except Exception: # noqa: PIE-786
if self.raise_app_exceptions:
raise
response_complete.set()
if status_code is None:
status_code = 500
if response_headers is None:
response_headers = {}
assert response_complete.is_set()
assert status_code is not None
assert response_headers is not None
stream = ASGIResponseStream(body_parts)
return Response(status_code, headers=response_headers, stream=stream)
| import json
import pytest
import httpx
async def hello_world(scope, receive, send):
status = 200
output = b"Hello, World!"
headers = [(b"content-type", "text/plain"), (b"content-length", str(len(output)))]
await send({"type": "http.response.start", "status": status, "headers": headers})
await send({"type": "http.response.body", "body": output})
async def echo_path(scope, receive, send):
status = 200
output = json.dumps({"path": scope["path"]}).encode("utf-8")
headers = [(b"content-type", "text/plain"), (b"content-length", str(len(output)))]
await send({"type": "http.response.start", "status": status, "headers": headers})
await send({"type": "http.response.body", "body": output})
async def echo_raw_path(scope, receive, send):
status = 200
output = json.dumps({"raw_path": scope["raw_path"].decode("ascii")}).encode("utf-8")
headers = [(b"content-type", "text/plain"), (b"content-length", str(len(output)))]
await send({"type": "http.response.start", "status": status, "headers": headers})
await send({"type": "http.response.body", "body": output})
async def echo_body(scope, receive, send):
status = 200
headers = [(b"content-type", "text/plain")]
await send({"type": "http.response.start", "status": status, "headers": headers})
more_body = True
while more_body:
message = await receive()
body = message.get("body", b"")
more_body = message.get("more_body", False)
await send({"type": "http.response.body", "body": body, "more_body": more_body})
async def echo_headers(scope, receive, send):
status = 200
output = json.dumps(
{"headers": [[k.decode(), v.decode()] for k, v in scope["headers"]]}
).encode("utf-8")
headers = [(b"content-type", "text/plain"), (b"content-length", str(len(output)))]
await send({"type": "http.response.start", "status": status, "headers": headers})
await send({"type": "http.response.body", "body": output})
async def raise_exc(scope, receive, send):
raise RuntimeError()
async def raise_exc_after_response(scope, receive, send):
status = 200
output = b"Hello, World!"
headers = [(b"content-type", "text/plain"), (b"content-length", str(len(output)))]
await send({"type": "http.response.start", "status": status, "headers": headers})
await send({"type": "http.response.body", "body": output})
raise RuntimeError()
@pytest.mark.anyio
async def test_asgi_transport():
async with httpx.ASGITransport(app=hello_world) as transport:
request = httpx.Request("GET", "http://www.example.com/")
response = await transport.handle_async_request(request)
await response.aread()
assert response.status_code == 200
assert response.content == b"Hello, World!"
@pytest.mark.anyio
async def test_asgi_transport_no_body():
async with httpx.ASGITransport(app=echo_body) as transport:
request = httpx.Request("GET", "http://www.example.com/")
response = await transport.handle_async_request(request)
await response.aread()
assert response.status_code == 200
assert response.content == b""
@pytest.mark.anyio
async def test_asgi():
transport = httpx.ASGITransport(app=hello_world)
async with httpx.AsyncClient(transport=transport) as client:
response = await client.get("http://www.example.org/")
assert response.status_code == 200
assert response.text == "Hello, World!"
@pytest.mark.anyio
async def test_asgi_urlencoded_path():
transport = httpx.ASGITransport(app=echo_path)
async with httpx.AsyncClient(transport=transport) as client:
url = httpx.URL("http://www.example.org/").copy_with(path="/user@example.org")
response = await client.get(url)
assert response.status_code == 200
assert response.json() == {"path": "/user@example.org"}
@pytest.mark.anyio
async def test_asgi_raw_path():
transport = httpx.ASGITransport(app=echo_raw_path)
async with httpx.AsyncClient(transport=transport) as client:
url = httpx.URL("http://www.example.org/").copy_with(path="/user@example.org")
response = await client.get(url)
assert response.status_code == 200
assert response.json() == {"raw_path": "/user@example.org"}
@pytest.mark.anyio
async def test_asgi_raw_path_should_not_include_querystring_portion():
"""
See https://github.com/encode/httpx/issues/2810
"""
transport = httpx.ASGITransport(app=echo_raw_path)
async with httpx.AsyncClient(transport=transport) as client:
url = httpx.URL("http://www.example.org/path?query")
response = await client.get(url)
assert response.status_code == 200
assert response.json() == {"raw_path": "/path"}
@pytest.mark.anyio
async def test_asgi_upload():
transport = httpx.ASGITransport(app=echo_body)
async with httpx.AsyncClient(transport=transport) as client:
response = await client.post("http://www.example.org/", content=b"example")
assert response.status_code == 200
assert response.text == "example"
@pytest.mark.anyio
async def test_asgi_headers():
transport = httpx.ASGITransport(app=echo_headers)
async with httpx.AsyncClient(transport=transport) as client:
response = await client.get("http://www.example.org/")
assert response.status_code == 200
assert response.json() == {
"headers": [
["host", "www.example.org"],
["accept", "*/*"],
["accept-encoding", "gzip, deflate, br, zstd"],
["connection", "keep-alive"],
["user-agent", f"python-httpx/{httpx.__version__}"],
]
}
@pytest.mark.anyio
async def test_asgi_exc():
transport = httpx.ASGITransport(app=raise_exc)
async with httpx.AsyncClient(transport=transport) as client:
with pytest.raises(RuntimeError):
await client.get("http://www.example.org/")
@pytest.mark.anyio
async def test_asgi_exc_after_response():
transport = httpx.ASGITransport(app=raise_exc_after_response)
async with httpx.AsyncClient(transport=transport) as client:
with pytest.raises(RuntimeError):
await client.get("http://www.example.org/")
@pytest.mark.anyio
async def test_asgi_disconnect_after_response_complete():
disconnect = False
async def read_body(scope, receive, send):
nonlocal disconnect
status = 200
headers = [(b"content-type", "text/plain")]
await send(
{"type": "http.response.start", "status": status, "headers": headers}
)
more_body = True
while more_body:
message = await receive()
more_body = message.get("more_body", False)
await send({"type": "http.response.body", "body": b"", "more_body": False})
# The ASGI spec says of the Disconnect message:
# "Sent to the application when a HTTP connection is closed or if receive is
# called after a response has been sent."
# So if receive() is called again, the disconnect message should be received
message = await receive()
disconnect = message.get("type") == "http.disconnect"
transport = httpx.ASGITransport(app=read_body)
async with httpx.AsyncClient(transport=transport) as client:
response = await client.post("http://www.example.org/", content=b"example")
assert response.status_code == 200
assert disconnect
@pytest.mark.anyio
async def test_asgi_exc_no_raise():
transport = httpx.ASGITransport(app=raise_exc, raise_app_exceptions=False)
async with httpx.AsyncClient(transport=transport) as client:
response = await client.get("http://www.example.org/")
assert response.status_code == 500
| httpx |
python | from __future__ import annotations
import io
import itertools
import sys
import typing
from .._models import Request, Response
from .._types import SyncByteStream
from .base import BaseTransport
if typing.TYPE_CHECKING:
from _typeshed import OptExcInfo # pragma: no cover
from _typeshed.wsgi import WSGIApplication # pragma: no cover
_T = typing.TypeVar("_T")
__all__ = ["WSGITransport"]
def _skip_leading_empty_chunks(body: typing.Iterable[_T]) -> typing.Iterable[_T]:
body = iter(body)
for chunk in body:
if chunk:
return itertools.chain([chunk], body)
return []
class WSGIByteStream(SyncByteStream):
def __init__(self, result: typing.Iterable[bytes]) -> None:
self._close = getattr(result, "close", None)
self._result = _skip_leading_empty_chunks(result)
def __iter__(self) -> typing.Iterator[bytes]:
for part in self._result:
yield part
def close(self) -> None:
if self._close is not None:
self._close()
class WSGITransport(BaseTransport):
"""
A custom transport that handles sending requests directly to an WSGI app.
The simplest way to use this functionality is to use the `app` argument.
```
client = httpx.Client(app=app)
```
Alternatively, you can setup the transport instance explicitly.
This allows you to include any additional configuration arguments specific
to the WSGITransport class:
```
transport = httpx.WSGITransport(
app=app,
script_name="/submount",
remote_addr="1.2.3.4"
)
client = httpx.Client(transport=transport)
```
Arguments:
* `app` - The WSGI application.
* `raise_app_exceptions` - Boolean indicating if exceptions in the application
should be raised. Default to `True`. Can be set to `False` for use cases
such as testing the content of a client 500 response.
* `script_name` - The root path on which the WSGI application should be mounted.
* `remote_addr` - A string indicating the client IP of incoming requests.
```
"""
def __init__(
self,
app: WSGIApplication,
raise_app_exceptions: bool = True,
script_name: str = "",
remote_addr: str = "127.0.0.1",
wsgi_errors: typing.TextIO | None = None,
) -> None:
self.app = app
self.raise_app_exceptions = raise_app_exceptions
self.script_name = script_name
self.remote_addr = remote_addr
self.wsgi_errors = wsgi_errors
def handle_request(self, request: Request) -> Response:
request.read()
wsgi_input = io.BytesIO(request.content)
port = request.url.port or {"http": 80, "https": 443}[request.url.scheme]
environ = {
"wsgi.version": (1, 0),
"wsgi.url_scheme": request.url.scheme,
"wsgi.input": wsgi_input,
"wsgi.errors": self.wsgi_errors or sys.stderr,
"wsgi.multithread": True,
"wsgi.multiprocess": False,
"wsgi.run_once": False,
"REQUEST_METHOD": request.method,
"SCRIPT_NAME": self.script_name,
"PATH_INFO": request.url.path,
"QUERY_STRING": request.url.query.decode("ascii"),
"SERVER_NAME": request.url.host,
"SERVER_PORT": str(port),
"SERVER_PROTOCOL": "HTTP/1.1",
"REMOTE_ADDR": self.remote_addr,
}
for header_key, header_value in request.headers.raw:
key = header_key.decode("ascii").upper().replace("-", "_")
if key not in ("CONTENT_TYPE", "CONTENT_LENGTH"):
key = "HTTP_" + key
environ[key] = header_value.decode("ascii")
seen_status = None
seen_response_headers = None
seen_exc_info = None
def start_response(
status: str,
response_headers: list[tuple[str, str]],
exc_info: OptExcInfo | None = None,
) -> typing.Callable[[bytes], typing.Any]:
nonlocal seen_status, seen_response_headers, seen_exc_info
seen_status = status
seen_response_headers = response_headers
seen_exc_info = exc_info
return lambda _: None
result = self.app(environ, start_response)
stream = WSGIByteStream(result)
assert seen_status is not None
assert seen_response_headers is not None
if seen_exc_info and seen_exc_info[0] and self.raise_app_exceptions:
raise seen_exc_info[1]
status_code = int(seen_status.split()[0])
headers = [
(key.encode("ascii"), value.encode("ascii"))
for key, value in seen_response_headers
]
return Response(status_code, headers=headers, stream=stream)
| from __future__ import annotations
import sys
import typing
import wsgiref.validate
from functools import partial
from io import StringIO
import pytest
import httpx
if typing.TYPE_CHECKING: # pragma: no cover
from _typeshed.wsgi import StartResponse, WSGIApplication, WSGIEnvironment
def application_factory(output: typing.Iterable[bytes]) -> WSGIApplication:
def application(environ, start_response):
status = "200 OK"
response_headers = [
("Content-type", "text/plain"),
]
start_response(status, response_headers)
for item in output:
yield item
return wsgiref.validate.validator(application)
def echo_body(
environ: WSGIEnvironment, start_response: StartResponse
) -> typing.Iterable[bytes]:
status = "200 OK"
output = environ["wsgi.input"].read()
response_headers = [
("Content-type", "text/plain"),
]
start_response(status, response_headers)
return [output]
def echo_body_with_response_stream(
environ: WSGIEnvironment, start_response: StartResponse
) -> typing.Iterable[bytes]:
status = "200 OK"
response_headers = [("Content-Type", "text/plain")]
start_response(status, response_headers)
def output_generator(f: typing.IO[bytes]) -> typing.Iterator[bytes]:
while True:
output = f.read(2)
if not output:
break
yield output
return output_generator(f=environ["wsgi.input"])
def raise_exc(
environ: WSGIEnvironment,
start_response: StartResponse,
exc: type[Exception] = ValueError,
) -> typing.Iterable[bytes]:
status = "500 Server Error"
output = b"Nope!"
response_headers = [
("Content-type", "text/plain"),
]
try:
raise exc()
except exc:
exc_info = sys.exc_info()
start_response(status, response_headers, exc_info)
return [output]
def log_to_wsgi_log_buffer(environ, start_response):
print("test1", file=environ["wsgi.errors"])
environ["wsgi.errors"].write("test2")
return echo_body(environ, start_response)
def test_wsgi():
transport = httpx.WSGITransport(app=application_factory([b"Hello, World!"]))
client = httpx.Client(transport=transport)
response = client.get("http://www.example.org/")
assert response.status_code == 200
assert response.text == "Hello, World!"
def test_wsgi_upload():
transport = httpx.WSGITransport(app=echo_body)
client = httpx.Client(transport=transport)
response = client.post("http://www.example.org/", content=b"example")
assert response.status_code == 200
assert response.text == "example"
def test_wsgi_upload_with_response_stream():
transport = httpx.WSGITransport(app=echo_body_with_response_stream)
client = httpx.Client(transport=transport)
response = client.post("http://www.example.org/", content=b"example")
assert response.status_code == 200
assert response.text == "example"
def test_wsgi_exc():
transport = httpx.WSGITransport(app=raise_exc)
client = httpx.Client(transport=transport)
with pytest.raises(ValueError):
client.get("http://www.example.org/")
def test_wsgi_http_error():
transport = httpx.WSGITransport(app=partial(raise_exc, exc=RuntimeError))
client = httpx.Client(transport=transport)
with pytest.raises(RuntimeError):
client.get("http://www.example.org/")
def test_wsgi_generator():
output = [b"", b"", b"Some content", b" and more content"]
transport = httpx.WSGITransport(app=application_factory(output))
client = httpx.Client(transport=transport)
response = client.get("http://www.example.org/")
assert response.status_code == 200
assert response.text == "Some content and more content"
def test_wsgi_generator_empty():
output = [b"", b"", b"", b""]
transport = httpx.WSGITransport(app=application_factory(output))
client = httpx.Client(transport=transport)
response = client.get("http://www.example.org/")
assert response.status_code == 200
assert response.text == ""
def test_logging():
buffer = StringIO()
transport = httpx.WSGITransport(app=log_to_wsgi_log_buffer, wsgi_errors=buffer)
client = httpx.Client(transport=transport)
response = client.post("http://www.example.org/", content=b"example")
assert response.status_code == 200 # no errors
buffer.seek(0)
assert buffer.read() == "test1\ntest2"
@pytest.mark.parametrize(
"url, expected_server_port",
[
pytest.param("http://www.example.org", "80", id="auto-http"),
pytest.param("https://www.example.org", "443", id="auto-https"),
pytest.param("http://www.example.org:8000", "8000", id="explicit-port"),
],
)
def test_wsgi_server_port(url: str, expected_server_port: str) -> None:
"""
SERVER_PORT is populated correctly from the requested URL.
"""
hello_world_app = application_factory([b"Hello, World!"])
server_port: str | None = None
def app(environ, start_response):
nonlocal server_port
server_port = environ["SERVER_PORT"]
return hello_world_app(environ, start_response)
transport = httpx.WSGITransport(app=app)
client = httpx.Client(transport=transport)
response = client.get(url)
assert response.status_code == 200
assert response.text == "Hello, World!"
assert server_port == expected_server_port
def test_wsgi_server_protocol():
server_protocol = None
def app(environ, start_response):
nonlocal server_protocol
server_protocol = environ["SERVER_PROTOCOL"]
start_response("200 OK", [("Content-Type", "text/plain")])
return [b"success"]
transport = httpx.WSGITransport(app=app)
with httpx.Client(transport=transport, base_url="http://testserver") as client:
response = client.get("/")
assert response.status_code == 200
assert response.text == "success"
assert server_protocol == "HTTP/1.1"
| httpx |
python | """
An implementation of `urlparse` that provides URL validation and normalization
as described by RFC3986.
We rely on this implementation rather than the one in Python's stdlib, because:
* It provides more complete URL validation.
* It properly differentiates between an empty querystring and an absent querystring,
to distinguish URLs with a trailing '?'.
* It handles scheme, hostname, port, and path normalization.
* It supports IDNA hostnames, normalizing them to their encoded form.
* The API supports passing individual components, as well as the complete URL string.
Previously we relied on the excellent `rfc3986` package to handle URL parsing and
validation, but this module provides a simpler alternative, with less indirection
required.
"""
from __future__ import annotations
import ipaddress
import re
import typing
import idna
from ._exceptions import InvalidURL
MAX_URL_LENGTH = 65536
# https://datatracker.ietf.org/doc/html/rfc3986.html#section-2.3
UNRESERVED_CHARACTERS = (
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
)
SUB_DELIMS = "!$&'()*+,;="
PERCENT_ENCODED_REGEX = re.compile("%[A-Fa-f0-9]{2}")
# https://url.spec.whatwg.org/#percent-encoded-bytes
# The fragment percent-encode set is the C0 control percent-encode set
# and U+0020 SPACE, U+0022 ("), U+003C (<), U+003E (>), and U+0060 (`).
FRAG_SAFE = "".join(
[chr(i) for i in range(0x20, 0x7F) if i not in (0x20, 0x22, 0x3C, 0x3E, 0x60)]
)
# The query percent-encode set is the C0 control percent-encode set
# and U+0020 SPACE, U+0022 ("), U+0023 (#), U+003C (<), and U+003E (>).
QUERY_SAFE = "".join(
[chr(i) for i in range(0x20, 0x7F) if i not in (0x20, 0x22, 0x23, 0x3C, 0x3E)]
)
# The path percent-encode set is the query percent-encode set
# and U+003F (?), U+0060 (`), U+007B ({), and U+007D (}).
PATH_SAFE = "".join(
[
chr(i)
for i in range(0x20, 0x7F)
if i not in (0x20, 0x22, 0x23, 0x3C, 0x3E) + (0x3F, 0x60, 0x7B, 0x7D)
]
)
# The userinfo percent-encode set is the path percent-encode set
# and U+002F (/), U+003A (:), U+003B (;), U+003D (=), U+0040 (@),
# U+005B ([) to U+005E (^), inclusive, and U+007C (|).
USERNAME_SAFE = "".join(
[
chr(i)
for i in range(0x20, 0x7F)
if i
not in (0x20, 0x22, 0x23, 0x3C, 0x3E)
+ (0x3F, 0x60, 0x7B, 0x7D)
+ (0x2F, 0x3A, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C)
]
)
PASSWORD_SAFE = "".join(
[
chr(i)
for i in range(0x20, 0x7F)
if i
not in (0x20, 0x22, 0x23, 0x3C, 0x3E)
+ (0x3F, 0x60, 0x7B, 0x7D)
+ (0x2F, 0x3A, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C)
]
)
# Note... The terminology 'userinfo' percent-encode set in the WHATWG document
# is used for the username and password quoting. For the joint userinfo component
# we remove U+003A (:) from the safe set.
USERINFO_SAFE = "".join(
[
chr(i)
for i in range(0x20, 0x7F)
if i
not in (0x20, 0x22, 0x23, 0x3C, 0x3E)
+ (0x3F, 0x60, 0x7B, 0x7D)
+ (0x2F, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C)
]
)
# {scheme}: (optional)
# //{authority} (optional)
# {path}
# ?{query} (optional)
# #{fragment} (optional)
URL_REGEX = re.compile(
(
r"(?:(?P<scheme>{scheme}):)?"
r"(?://(?P<authority>{authority}))?"
r"(?P<path>{path})"
r"(?:\?(?P<query>{query}))?"
r"(?:#(?P<fragment>{fragment}))?"
).format(
scheme="([a-zA-Z][a-zA-Z0-9+.-]*)?",
authority="[^/?#]*",
path="[^?#]*",
query="[^#]*",
fragment=".*",
)
)
# {userinfo}@ (optional)
# {host}
# :{port} (optional)
AUTHORITY_REGEX = re.compile(
(
r"(?:(?P<userinfo>{userinfo})@)?" r"(?P<host>{host})" r":?(?P<port>{port})?"
).format(
userinfo=".*", # Any character sequence.
host="(\\[.*\\]|[^:@]*)", # Either any character sequence excluding ':' or '@',
# or an IPv6 address enclosed within square brackets.
port=".*", # Any character sequence.
)
)
# If we call urlparse with an individual component, then we need to regex
# validate that component individually.
# Note that we're duplicating the same strings as above. Shock! Horror!!
COMPONENT_REGEX = {
"scheme": re.compile("([a-zA-Z][a-zA-Z0-9+.-]*)?"),
"authority": re.compile("[^/?#]*"),
"path": re.compile("[^?#]*"),
"query": re.compile("[^#]*"),
"fragment": re.compile(".*"),
"userinfo": re.compile("[^@]*"),
"host": re.compile("(\\[.*\\]|[^:]*)"),
"port": re.compile(".*"),
}
# We use these simple regexs as a first pass before handing off to
# the stdlib 'ipaddress' module for IP address validation.
IPv4_STYLE_HOSTNAME = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$")
IPv6_STYLE_HOSTNAME = re.compile(r"^\[.*\]$")
class ParseResult(typing.NamedTuple):
scheme: str
userinfo: str
host: str
port: int | None
path: str
query: str | None
fragment: str | None
@property
def authority(self) -> str:
return "".join(
[
f"{self.userinfo}@" if self.userinfo else "",
f"[{self.host}]" if ":" in self.host else self.host,
f":{self.port}" if self.port is not None else "",
]
)
@property
def netloc(self) -> str:
return "".join(
[
f"[{self.host}]" if ":" in self.host else self.host,
f":{self.port}" if self.port is not None else "",
]
)
def copy_with(self, **kwargs: str | None) -> ParseResult:
if not kwargs:
return self
defaults = {
"scheme": self.scheme,
"authority": self.authority,
"path": self.path,
"query": self.query,
"fragment": self.fragment,
}
defaults.update(kwargs)
return urlparse("", **defaults)
def __str__(self) -> str:
authority = self.authority
return "".join(
[
f"{self.scheme}:" if self.scheme else "",
f"//{authority}" if authority else "",
self.path,
f"?{self.query}" if self.query is not None else "",
f"#{self.fragment}" if self.fragment is not None else "",
]
)
def urlparse(url: str = "", **kwargs: str | None) -> ParseResult:
# Initial basic checks on allowable URLs.
# ---------------------------------------
# Hard limit the maximum allowable URL length.
if len(url) > MAX_URL_LENGTH:
raise InvalidURL("URL too long")
# If a URL includes any ASCII control characters including \t, \r, \n,
# then treat it as invalid.
if any(char.isascii() and not char.isprintable() for char in url):
char = next(char for char in url if char.isascii() and not char.isprintable())
idx = url.find(char)
error = (
f"Invalid non-printable ASCII character in URL, {char!r} at position {idx}."
)
raise InvalidURL(error)
# Some keyword arguments require special handling.
# ------------------------------------------------
# Coerce "port" to a string, if it is provided as an integer.
if "port" in kwargs:
port = kwargs["port"]
kwargs["port"] = str(port) if isinstance(port, int) else port
# Replace "netloc" with "host and "port".
if "netloc" in kwargs:
netloc = kwargs.pop("netloc") or ""
kwargs["host"], _, kwargs["port"] = netloc.partition(":")
# Replace "username" and/or "password" with "userinfo".
if "username" in kwargs or "password" in kwargs:
username = quote(kwargs.pop("username", "") or "", safe=USERNAME_SAFE)
password = quote(kwargs.pop("password", "") or "", safe=PASSWORD_SAFE)
kwargs["userinfo"] = f"{username}:{password}" if password else username
# Replace "raw_path" with "path" and "query".
if "raw_path" in kwargs:
raw_path = kwargs.pop("raw_path") or ""
kwargs["path"], seperator, kwargs["query"] = raw_path.partition("?")
if not seperator:
kwargs["query"] = None
# Ensure that IPv6 "host" addresses are always escaped with "[...]".
if "host" in kwargs:
host = kwargs.get("host") or ""
if ":" in host and not (host.startswith("[") and host.endswith("]")):
kwargs["host"] = f"[{host}]"
# If any keyword arguments are provided, ensure they are valid.
# -------------------------------------------------------------
for key, value in kwargs.items():
if value is not None:
if len(value) > MAX_URL_LENGTH:
raise InvalidURL(f"URL component '{key}' too long")
# If a component includes any ASCII control characters including \t, \r, \n,
# then treat it as invalid.
if any(char.isascii() and not char.isprintable() for char in value):
char = next(
char for char in value if char.isascii() and not char.isprintable()
)
idx = value.find(char)
error = (
f"Invalid non-printable ASCII character in URL {key} component, "
f"{char!r} at position {idx}."
)
raise InvalidURL(error)
# Ensure that keyword arguments match as a valid regex.
if not COMPONENT_REGEX[key].fullmatch(value):
raise InvalidURL(f"Invalid URL component '{key}'")
# The URL_REGEX will always match, but may have empty components.
url_match = URL_REGEX.match(url)
assert url_match is not None
url_dict = url_match.groupdict()
# * 'scheme', 'authority', and 'path' may be empty strings.
# * 'query' may be 'None', indicating no trailing "?" portion.
# Any string including the empty string, indicates a trailing "?".
# * 'fragment' may be 'None', indicating no trailing "#" portion.
# Any string including the empty string, indicates a trailing "#".
scheme = kwargs.get("scheme", url_dict["scheme"]) or ""
authority = kwargs.get("authority", url_dict["authority"]) or ""
path = kwargs.get("path", url_dict["path"]) or ""
query = kwargs.get("query", url_dict["query"])
frag = kwargs.get("fragment", url_dict["fragment"])
# The AUTHORITY_REGEX will always match, but may have empty components.
authority_match = AUTHORITY_REGEX.match(authority)
assert authority_match is not None
authority_dict = authority_match.groupdict()
# * 'userinfo' and 'host' may be empty strings.
# * 'port' may be 'None'.
userinfo = kwargs.get("userinfo", authority_dict["userinfo"]) or ""
host = kwargs.get("host", authority_dict["host"]) or ""
port = kwargs.get("port", authority_dict["port"])
# Normalize and validate each component.
# We end up with a parsed representation of the URL,
# with components that are plain ASCII bytestrings.
parsed_scheme: str = scheme.lower()
parsed_userinfo: str = quote(userinfo, safe=USERINFO_SAFE)
parsed_host: str = encode_host(host)
parsed_port: int | None = normalize_port(port, scheme)
has_scheme = parsed_scheme != ""
has_authority = (
parsed_userinfo != "" or parsed_host != "" or parsed_port is not None
)
validate_path(path, has_scheme=has_scheme, has_authority=has_authority)
if has_scheme or has_authority:
path = normalize_path(path)
parsed_path: str = quote(path, safe=PATH_SAFE)
parsed_query: str | None = None if query is None else quote(query, safe=QUERY_SAFE)
parsed_frag: str | None = None if frag is None else quote(frag, safe=FRAG_SAFE)
# The parsed ASCII bytestrings are our canonical form.
# All properties of the URL are derived from these.
return ParseResult(
parsed_scheme,
parsed_userinfo,
parsed_host,
parsed_port,
parsed_path,
parsed_query,
parsed_frag,
)
def encode_host(host: str) -> str:
if not host:
return ""
elif IPv4_STYLE_HOSTNAME.match(host):
# Validate IPv4 hostnames like #.#.#.#
#
# From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2
#
# IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet
try:
ipaddress.IPv4Address(host)
except ipaddress.AddressValueError:
raise InvalidURL(f"Invalid IPv4 address: {host!r}")
return host
elif IPv6_STYLE_HOSTNAME.match(host):
# Validate IPv6 hostnames like [...]
#
# From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2
#
# "A host identified by an Internet Protocol literal address, version 6
# [RFC3513] or later, is distinguished by enclosing the IP literal
# within square brackets ("[" and "]"). This is the only place where
# square bracket characters are allowed in the URI syntax."
try:
ipaddress.IPv6Address(host[1:-1])
except ipaddress.AddressValueError:
raise InvalidURL(f"Invalid IPv6 address: {host!r}")
return host[1:-1]
elif host.isascii():
# Regular ASCII hostnames
#
# From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2
#
# reg-name = *( unreserved / pct-encoded / sub-delims )
WHATWG_SAFE = '"`{}%|\\'
return quote(host.lower(), safe=SUB_DELIMS + WHATWG_SAFE)
# IDNA hostnames
try:
return idna.encode(host.lower()).decode("ascii")
except idna.IDNAError:
raise InvalidURL(f"Invalid IDNA hostname: {host!r}")
def normalize_port(port: str | int | None, scheme: str) -> int | None:
# From https://tools.ietf.org/html/rfc3986#section-3.2.3
#
# "A scheme may define a default port. For example, the "http" scheme
# defines a default port of "80", corresponding to its reserved TCP
# port number. The type of port designated by the port number (e.g.,
# TCP, UDP, SCTP) is defined by the URI scheme. URI producers and
# normalizers should omit the port component and its ":" delimiter if
# port is empty or if its value would be the same as that of the
# scheme's default."
if port is None or port == "":
return None
try:
port_as_int = int(port)
except ValueError:
raise InvalidURL(f"Invalid port: {port!r}")
# See https://url.spec.whatwg.org/#url-miscellaneous
default_port = {"ftp": 21, "http": 80, "https": 443, "ws": 80, "wss": 443}.get(
scheme
)
if port_as_int == default_port:
return None
return port_as_int
def validate_path(path: str, has_scheme: bool, has_authority: bool) -> None:
"""
Path validation rules that depend on if the URL contains
a scheme or authority component.
See https://datatracker.ietf.org/doc/html/rfc3986.html#section-3.3
"""
if has_authority:
# If a URI contains an authority component, then the path component
# must either be empty or begin with a slash ("/") character."
if path and not path.startswith("/"):
raise InvalidURL("For absolute URLs, path must be empty or begin with '/'")
if not has_scheme and not has_authority:
# If a URI does not contain an authority component, then the path cannot begin
# with two slash characters ("//").
if path.startswith("//"):
raise InvalidURL("Relative URLs cannot have a path starting with '//'")
# In addition, a URI reference (Section 4.1) may be a relative-path reference,
# in which case the first path segment cannot contain a colon (":") character.
if path.startswith(":"):
raise InvalidURL("Relative URLs cannot have a path starting with ':'")
def normalize_path(path: str) -> str:
"""
Drop "." and ".." segments from a URL path.
For example:
normalize_path("/path/./to/somewhere/..") == "/path/to"
"""
# Fast return when no '.' characters in the path.
if "." not in path:
return path
components = path.split("/")
# Fast return when no '.' or '..' components in the path.
if "." not in components and ".." not in components:
return path
# https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4
output: list[str] = []
for component in components:
if component == ".":
pass
elif component == "..":
if output and output != [""]:
output.pop()
else:
output.append(component)
return "/".join(output)
def PERCENT(string: str) -> str:
return "".join([f"%{byte:02X}" for byte in string.encode("utf-8")])
def percent_encoded(string: str, safe: str) -> str:
"""
Use percent-encoding to quote a string.
"""
NON_ESCAPED_CHARS = UNRESERVED_CHARACTERS + safe
# Fast path for strings that don't need escaping.
if not string.rstrip(NON_ESCAPED_CHARS):
return string
return "".join(
[char if char in NON_ESCAPED_CHARS else PERCENT(char) for char in string]
)
def quote(string: str, safe: str) -> str:
"""
Use percent-encoding to quote a string, omitting existing '%xx' escape sequences.
See: https://www.rfc-editor.org/rfc/rfc3986#section-2.1
* `string`: The string to be percent-escaped.
* `safe`: A string containing characters that may be treated as safe, and do not
need to be escaped. Unreserved characters are always treated as safe.
See: https://www.rfc-editor.org/rfc/rfc3986#section-2.3
"""
parts = []
current_position = 0
for match in re.finditer(PERCENT_ENCODED_REGEX, string):
start_position, end_position = match.start(), match.end()
matched_text = match.group(0)
# Add any text up to the '%xx' escape sequence.
if start_position != current_position:
leading_text = string[current_position:start_position]
parts.append(percent_encoded(leading_text, safe=safe))
# Add the '%xx' escape sequence.
parts.append(matched_text)
current_position = end_position
# Add any text after the final '%xx' escape sequence.
if current_position != len(string):
trailing_text = string[current_position:]
parts.append(percent_encoded(trailing_text, safe=safe))
return "".join(parts)
| import pytest
import httpx
# Tests for `httpx.URL` instantiation and property accessors.
def test_basic_url():
url = httpx.URL("https://www.example.com/")
assert url.scheme == "https"
assert url.userinfo == b""
assert url.netloc == b"www.example.com"
assert url.host == "www.example.com"
assert url.port is None
assert url.path == "/"
assert url.query == b""
assert url.fragment == ""
assert str(url) == "https://www.example.com/"
assert repr(url) == "URL('https://www.example.com/')"
def test_complete_url():
url = httpx.URL("https://example.org:123/path/to/somewhere?abc=123#anchor")
assert url.scheme == "https"
assert url.host == "example.org"
assert url.port == 123
assert url.path == "/path/to/somewhere"
assert url.query == b"abc=123"
assert url.raw_path == b"/path/to/somewhere?abc=123"
assert url.fragment == "anchor"
assert str(url) == "https://example.org:123/path/to/somewhere?abc=123#anchor"
assert (
repr(url) == "URL('https://example.org:123/path/to/somewhere?abc=123#anchor')"
)
def test_url_with_empty_query():
"""
URLs with and without a trailing `?` but an empty query component
should preserve the information on the raw path.
"""
url = httpx.URL("https://www.example.com/path")
assert url.path == "/path"
assert url.query == b""
assert url.raw_path == b"/path"
url = httpx.URL("https://www.example.com/path?")
assert url.path == "/path"
assert url.query == b""
assert url.raw_path == b"/path?"
def test_url_no_scheme():
url = httpx.URL("://example.com")
assert url.scheme == ""
assert url.host == "example.com"
assert url.path == "/"
def test_url_no_authority():
url = httpx.URL("http://")
assert url.scheme == "http"
assert url.host == ""
assert url.path == "/"
# Tests for percent encoding across path, query, and fragment...
@pytest.mark.parametrize(
"url,raw_path,path,query,fragment",
[
# URL with unescaped chars in path.
(
"https://example.com/!$&'()*+,;= abc ABC 123 :/[]@",
b"/!$&'()*+,;=%20abc%20ABC%20123%20:/[]@",
"/!$&'()*+,;= abc ABC 123 :/[]@",
b"",
"",
),
# URL with escaped chars in path.
(
"https://example.com/!$&'()*+,;=%20abc%20ABC%20123%20:/[]@",
b"/!$&'()*+,;=%20abc%20ABC%20123%20:/[]@",
"/!$&'()*+,;= abc ABC 123 :/[]@",
b"",
"",
),
# URL with mix of unescaped and escaped chars in path.
# WARNING: This has the incorrect behaviour, adding the test as an interim step.
(
"https://example.com/ %61%62%63",
b"/%20%61%62%63",
"/ abc",
b"",
"",
),
# URL with unescaped chars in query.
(
"https://example.com/?!$&'()*+,;= abc ABC 123 :/[]@?",
b"/?!$&'()*+,;=%20abc%20ABC%20123%20:/[]@?",
"/",
b"!$&'()*+,;=%20abc%20ABC%20123%20:/[]@?",
"",
),
# URL with escaped chars in query.
(
"https://example.com/?!$&%27()*+,;=%20abc%20ABC%20123%20:%2F[]@?",
b"/?!$&%27()*+,;=%20abc%20ABC%20123%20:%2F[]@?",
"/",
b"!$&%27()*+,;=%20abc%20ABC%20123%20:%2F[]@?",
"",
),
# URL with mix of unescaped and escaped chars in query.
(
"https://example.com/?%20%97%98%99",
b"/?%20%97%98%99",
"/",
b"%20%97%98%99",
"",
),
# URL encoding characters in fragment.
(
"https://example.com/#!$&'()*+,;= abc ABC 123 :/[]@?#",
b"/",
"/",
b"",
"!$&'()*+,;= abc ABC 123 :/[]@?#",
),
],
)
def test_path_query_fragment(url, raw_path, path, query, fragment):
url = httpx.URL(url)
assert url.raw_path == raw_path
assert url.path == path
assert url.query == query
assert url.fragment == fragment
def test_url_query_encoding():
url = httpx.URL("https://www.example.com/?a=b c&d=e/f")
assert url.raw_path == b"/?a=b%20c&d=e/f"
url = httpx.URL("https://www.example.com/?a=b+c&d=e/f")
assert url.raw_path == b"/?a=b+c&d=e/f"
url = httpx.URL("https://www.example.com/", params={"a": "b c", "d": "e/f"})
assert url.raw_path == b"/?a=b+c&d=e%2Ff"
def test_url_params():
url = httpx.URL("https://example.org:123/path/to/somewhere", params={"a": "123"})
assert str(url) == "https://example.org:123/path/to/somewhere?a=123"
assert url.params == httpx.QueryParams({"a": "123"})
url = httpx.URL(
"https://example.org:123/path/to/somewhere?b=456", params={"a": "123"}
)
assert str(url) == "https://example.org:123/path/to/somewhere?a=123"
assert url.params == httpx.QueryParams({"a": "123"})
# Tests for username and password
@pytest.mark.parametrize(
"url,userinfo,username,password",
[
# username and password in URL.
(
"https://username:password@example.com",
b"username:password",
"username",
"password",
),
# username and password in URL with percent escape sequences.
(
"https://username%40gmail.com:pa%20ssword@example.com",
b"username%40gmail.com:pa%20ssword",
"username@gmail.com",
"pa ssword",
),
(
"https://user%20name:p%40ssword@example.com",
b"user%20name:p%40ssword",
"user name",
"p@ssword",
),
# username and password in URL without percent escape sequences.
(
"https://username@gmail.com:pa ssword@example.com",
b"username%40gmail.com:pa%20ssword",
"username@gmail.com",
"pa ssword",
),
(
"https://user name:p@ssword@example.com",
b"user%20name:p%40ssword",
"user name",
"p@ssword",
),
],
)
def test_url_username_and_password(url, userinfo, username, password):
url = httpx.URL(url)
assert url.userinfo == userinfo
assert url.username == username
assert url.password == password
# Tests for different host types
def test_url_valid_host():
url = httpx.URL("https://example.com/")
assert url.host == "example.com"
def test_url_normalized_host():
url = httpx.URL("https://EXAMPLE.com/")
assert url.host == "example.com"
def test_url_percent_escape_host():
url = httpx.URL("https://exam le.com/")
assert url.host == "exam%20le.com"
def test_url_ipv4_like_host():
"""rare host names used to quality as IPv4"""
url = httpx.URL("https://023b76x43144/")
assert url.host == "023b76x43144"
# Tests for different port types
def test_url_valid_port():
url = httpx.URL("https://example.com:123/")
assert url.port == 123
def test_url_normalized_port():
# If the port matches the scheme default it is normalized to None.
url = httpx.URL("https://example.com:443/")
assert url.port is None
def test_url_invalid_port():
with pytest.raises(httpx.InvalidURL) as exc:
httpx.URL("https://example.com:abc/")
assert str(exc.value) == "Invalid port: 'abc'"
# Tests for path handling
def test_url_normalized_path():
url = httpx.URL("https://example.com/abc/def/../ghi/./jkl")
assert url.path == "/abc/ghi/jkl"
def test_url_escaped_path():
url = httpx.URL("https://example.com/ /🌟/")
assert url.raw_path == b"/%20/%F0%9F%8C%9F/"
def test_url_leading_dot_prefix_on_absolute_url():
url = httpx.URL("https://example.com/../abc")
assert url.path == "/abc"
def test_url_leading_dot_prefix_on_relative_url():
url = httpx.URL("../abc")
assert url.path == "../abc"
# Tests for query parameter percent encoding.
#
# Percent-encoding in `params={}` should match browser form behavior.
def test_param_with_space():
# Params passed as form key-value pairs should be form escaped,
# Including the special case of "+" for space seperators.
url = httpx.URL("http://webservice", params={"u": "with spaces"})
assert str(url) == "http://webservice?u=with+spaces"
def test_param_requires_encoding():
# Params passed as form key-value pairs should be escaped.
url = httpx.URL("http://webservice", params={"u": "%"})
assert str(url) == "http://webservice?u=%25"
def test_param_with_percent_encoded():
# Params passed as form key-value pairs should always be escaped,
# even if they include a valid escape sequence.
# We want to match browser form behaviour here.
url = httpx.URL("http://webservice", params={"u": "with%20spaces"})
assert str(url) == "http://webservice?u=with%2520spaces"
def test_param_with_existing_escape_requires_encoding():
# Params passed as form key-value pairs should always be escaped,
# even if they include a valid escape sequence.
# We want to match browser form behaviour here.
url = httpx.URL("http://webservice", params={"u": "http://example.com?q=foo%2Fa"})
assert str(url) == "http://webservice?u=http%3A%2F%2Fexample.com%3Fq%3Dfoo%252Fa"
# Tests for query parameter percent encoding.
#
# Percent-encoding in `url={}` should match browser URL bar behavior.
def test_query_with_existing_percent_encoding():
# Valid percent encoded sequences should not be double encoded.
url = httpx.URL("http://webservice?u=phrase%20with%20spaces")
assert str(url) == "http://webservice?u=phrase%20with%20spaces"
def test_query_requiring_percent_encoding():
# Characters that require percent encoding should be encoded.
url = httpx.URL("http://webservice?u=phrase with spaces")
assert str(url) == "http://webservice?u=phrase%20with%20spaces"
def test_query_with_mixed_percent_encoding():
# When a mix of encoded and unencoded characters are present,
# characters that require percent encoding should be encoded,
# while existing sequences should not be double encoded.
url = httpx.URL("http://webservice?u=phrase%20with spaces")
assert str(url) == "http://webservice?u=phrase%20with%20spaces"
# Tests for invalid URLs
def test_url_invalid_hostname():
"""
Ensure that invalid URLs raise an `httpx.InvalidURL` exception.
"""
with pytest.raises(httpx.InvalidURL):
httpx.URL("https://😇/")
def test_url_excessively_long_url():
with pytest.raises(httpx.InvalidURL) as exc:
httpx.URL("https://www.example.com/" + "x" * 100_000)
assert str(exc.value) == "URL too long"
def test_url_excessively_long_component():
with pytest.raises(httpx.InvalidURL) as exc:
httpx.URL("https://www.example.com", path="/" + "x" * 100_000)
assert str(exc.value) == "URL component 'path' too long"
def test_url_non_printing_character_in_url():
with pytest.raises(httpx.InvalidURL) as exc:
httpx.URL("https://www.example.com/\n")
assert str(exc.value) == (
"Invalid non-printable ASCII character in URL, '\\n' at position 24."
)
def test_url_non_printing_character_in_component():
with pytest.raises(httpx.InvalidURL) as exc:
httpx.URL("https://www.example.com", path="/\n")
assert str(exc.value) == (
"Invalid non-printable ASCII character in URL path component, "
"'\\n' at position 1."
)
# Test for url components
def test_url_with_components():
url = httpx.URL(scheme="https", host="www.example.com", path="/")
assert url.scheme == "https"
assert url.userinfo == b""
assert url.host == "www.example.com"
assert url.port is None
assert url.path == "/"
assert url.query == b""
assert url.fragment == ""
assert str(url) == "https://www.example.com/"
def test_urlparse_with_invalid_component():
with pytest.raises(TypeError) as exc:
httpx.URL(scheme="https", host="www.example.com", incorrect="/")
assert str(exc.value) == "'incorrect' is an invalid keyword argument for URL()"
def test_urlparse_with_invalid_scheme():
with pytest.raises(httpx.InvalidURL) as exc:
httpx.URL(scheme="~", host="www.example.com", path="/")
assert str(exc.value) == "Invalid URL component 'scheme'"
def test_urlparse_with_invalid_path():
with pytest.raises(httpx.InvalidURL) as exc:
httpx.URL(scheme="https", host="www.example.com", path="abc")
assert str(exc.value) == "For absolute URLs, path must be empty or begin with '/'"
with pytest.raises(httpx.InvalidURL) as exc:
httpx.URL(path="//abc")
assert str(exc.value) == "Relative URLs cannot have a path starting with '//'"
with pytest.raises(httpx.InvalidURL) as exc:
httpx.URL(path=":abc")
assert str(exc.value) == "Relative URLs cannot have a path starting with ':'"
def test_url_with_relative_path():
# This path would be invalid for an absolute URL, but is valid as a relative URL.
url = httpx.URL(path="abc")
assert url.path == "abc"
# Tests for `httpx.URL` python built-in operators.
def test_url_eq_str():
"""
Ensure that `httpx.URL` supports the equality operator.
"""
url = httpx.URL("https://example.org:123/path/to/somewhere?abc=123#anchor")
assert url == "https://example.org:123/path/to/somewhere?abc=123#anchor"
assert str(url) == url
def test_url_set():
"""
Ensure that `httpx.URL` instances can be used in sets.
"""
urls = (
httpx.URL("http://example.org:123/path/to/somewhere"),
httpx.URL("http://example.org:123/path/to/somewhere/else"),
)
url_set = set(urls)
assert all(url in urls for url in url_set)
# Tests for TypeErrors when instantiating `httpx.URL`.
def test_url_invalid_type():
"""
Ensure that invalid types on `httpx.URL()` raise a `TypeError`.
"""
class ExternalURLClass: # representing external URL class
pass
with pytest.raises(TypeError):
httpx.URL(ExternalURLClass()) # type: ignore
def test_url_with_invalid_component():
with pytest.raises(TypeError) as exc:
httpx.URL(scheme="https", host="www.example.com", incorrect="/")
assert str(exc.value) == "'incorrect' is an invalid keyword argument for URL()"
# Tests for `URL.join()`.
def test_url_join():
"""
Some basic URL joining tests.
"""
url = httpx.URL("https://example.org:123/path/to/somewhere")
assert url.join("/somewhere-else") == "https://example.org:123/somewhere-else"
assert (
url.join("somewhere-else") == "https://example.org:123/path/to/somewhere-else"
)
assert (
url.join("../somewhere-else") == "https://example.org:123/path/somewhere-else"
)
assert url.join("../../somewhere-else") == "https://example.org:123/somewhere-else"
def test_relative_url_join():
url = httpx.URL("/path/to/somewhere")
assert url.join("/somewhere-else") == "/somewhere-else"
assert url.join("somewhere-else") == "/path/to/somewhere-else"
assert url.join("../somewhere-else") == "/path/somewhere-else"
assert url.join("../../somewhere-else") == "/somewhere-else"
def test_url_join_rfc3986():
"""
URL joining tests, as-per reference examples in RFC 3986.
https://tools.ietf.org/html/rfc3986#section-5.4
"""
url = httpx.URL("http://example.com/b/c/d;p?q")
assert url.join("g") == "http://example.com/b/c/g"
assert url.join("./g") == "http://example.com/b/c/g"
assert url.join("g/") == "http://example.com/b/c/g/"
assert url.join("/g") == "http://example.com/g"
assert url.join("//g") == "http://g"
assert url.join("?y") == "http://example.com/b/c/d;p?y"
assert url.join("g?y") == "http://example.com/b/c/g?y"
assert url.join("#s") == "http://example.com/b/c/d;p?q#s"
assert url.join("g#s") == "http://example.com/b/c/g#s"
assert url.join("g?y#s") == "http://example.com/b/c/g?y#s"
assert url.join(";x") == "http://example.com/b/c/;x"
assert url.join("g;x") == "http://example.com/b/c/g;x"
assert url.join("g;x?y#s") == "http://example.com/b/c/g;x?y#s"
assert url.join("") == "http://example.com/b/c/d;p?q"
assert url.join(".") == "http://example.com/b/c/"
assert url.join("./") == "http://example.com/b/c/"
assert url.join("..") == "http://example.com/b/"
assert url.join("../") == "http://example.com/b/"
assert url.join("../g") == "http://example.com/b/g"
assert url.join("../..") == "http://example.com/"
assert url.join("../../") == "http://example.com/"
assert url.join("../../g") == "http://example.com/g"
assert url.join("../../../g") == "http://example.com/g"
assert url.join("../../../../g") == "http://example.com/g"
assert url.join("/./g") == "http://example.com/g"
assert url.join("/../g") == "http://example.com/g"
assert url.join("g.") == "http://example.com/b/c/g."
assert url.join(".g") == "http://example.com/b/c/.g"
assert url.join("g..") == "http://example.com/b/c/g.."
assert url.join("..g") == "http://example.com/b/c/..g"
assert url.join("./../g") == "http://example.com/b/g"
assert url.join("./g/.") == "http://example.com/b/c/g/"
assert url.join("g/./h") == "http://example.com/b/c/g/h"
assert url.join("g/../h") == "http://example.com/b/c/h"
assert url.join("g;x=1/./y") == "http://example.com/b/c/g;x=1/y"
assert url.join("g;x=1/../y") == "http://example.com/b/c/y"
assert url.join("g?y/./x") == "http://example.com/b/c/g?y/./x"
assert url.join("g?y/../x") == "http://example.com/b/c/g?y/../x"
assert url.join("g#s/./x") == "http://example.com/b/c/g#s/./x"
assert url.join("g#s/../x") == "http://example.com/b/c/g#s/../x"
def test_resolution_error_1833():
"""
See https://github.com/encode/httpx/issues/1833
"""
url = httpx.URL("https://example.com/?[]")
assert url.join("/") == "https://example.com/"
# Tests for `URL.copy_with()`.
def test_copy_with():
url = httpx.URL("https://www.example.com/")
assert str(url) == "https://www.example.com/"
url = url.copy_with()
assert str(url) == "https://www.example.com/"
url = url.copy_with(scheme="http")
assert str(url) == "http://www.example.com/"
url = url.copy_with(netloc=b"example.com")
assert str(url) == "http://example.com/"
url = url.copy_with(path="/abc")
assert str(url) == "http://example.com/abc"
def test_url_copywith_authority_subcomponents():
copy_with_kwargs = {
"username": "username",
"password": "password",
"port": 444,
"host": "example.net",
}
url = httpx.URL("https://example.org")
new = url.copy_with(**copy_with_kwargs)
assert str(new) == "https://username:password@example.net:444"
def test_url_copywith_netloc():
copy_with_kwargs = {
"netloc": b"example.net:444",
}
url = httpx.URL("https://example.org")
new = url.copy_with(**copy_with_kwargs)
assert str(new) == "https://example.net:444"
def test_url_copywith_userinfo_subcomponents():
copy_with_kwargs = {
"username": "tom@example.org",
"password": "abc123@ %",
}
url = httpx.URL("https://example.org")
new = url.copy_with(**copy_with_kwargs)
assert str(new) == "https://tom%40example.org:abc123%40%20%@example.org"
assert new.username == "tom@example.org"
assert new.password == "abc123@ %"
assert new.userinfo == b"tom%40example.org:abc123%40%20%"
def test_url_copywith_invalid_component():
url = httpx.URL("https://example.org")
with pytest.raises(TypeError):
url.copy_with(pathh="/incorrect-spelling")
with pytest.raises(TypeError):
url.copy_with(userinfo="should be bytes")
def test_url_copywith_urlencoded_path():
url = httpx.URL("https://example.org")
url = url.copy_with(path="/path to somewhere")
assert url.path == "/path to somewhere"
assert url.query == b""
assert url.raw_path == b"/path%20to%20somewhere"
def test_url_copywith_query():
url = httpx.URL("https://example.org")
url = url.copy_with(query=b"a=123")
assert url.path == "/"
assert url.query == b"a=123"
assert url.raw_path == b"/?a=123"
def test_url_copywith_raw_path():
url = httpx.URL("https://example.org")
url = url.copy_with(raw_path=b"/some/path")
assert url.path == "/some/path"
assert url.query == b""
assert url.raw_path == b"/some/path"
url = httpx.URL("https://example.org")
url = url.copy_with(raw_path=b"/some/path?")
assert url.path == "/some/path"
assert url.query == b""
assert url.raw_path == b"/some/path?"
url = httpx.URL("https://example.org")
url = url.copy_with(raw_path=b"/some/path?a=123")
assert url.path == "/some/path"
assert url.query == b"a=123"
assert url.raw_path == b"/some/path?a=123"
def test_url_copywith_security():
"""
Prevent unexpected changes on URL after calling copy_with (CVE-2021-41945)
"""
with pytest.raises(httpx.InvalidURL):
httpx.URL("https://u:p@[invalid!]//evilHost/path?t=w#tw")
url = httpx.URL("https://example.com/path?t=w#tw")
bad = "https://xxxx:xxxx@xxxxxxx/xxxxx/xxx?x=x#xxxxx"
with pytest.raises(httpx.InvalidURL):
url.copy_with(scheme=bad)
# Tests for copy-modifying-parameters methods.
#
# `URL.copy_set_param()`
# `URL.copy_add_param()`
# `URL.copy_remove_param()`
# `URL.copy_merge_params()`
def test_url_set_param_manipulation():
"""
Some basic URL query parameter manipulation.
"""
url = httpx.URL("https://example.org:123/?a=123")
assert url.copy_set_param("a", "456") == "https://example.org:123/?a=456"
def test_url_add_param_manipulation():
"""
Some basic URL query parameter manipulation.
"""
url = httpx.URL("https://example.org:123/?a=123")
assert url.copy_add_param("a", "456") == "https://example.org:123/?a=123&a=456"
def test_url_remove_param_manipulation():
"""
Some basic URL query parameter manipulation.
"""
url = httpx.URL("https://example.org:123/?a=123")
assert url.copy_remove_param("a") == "https://example.org:123/"
def test_url_merge_params_manipulation():
"""
Some basic URL query parameter manipulation.
"""
url = httpx.URL("https://example.org:123/?a=123")
assert url.copy_merge_params({"b": "456"}) == "https://example.org:123/?a=123&b=456"
# Tests for IDNA hostname support.
@pytest.mark.parametrize(
"given,idna,host,raw_host,scheme,port",
[
(
"http://中国.icom.museum:80/",
"http://xn--fiqs8s.icom.museum:80/",
"中国.icom.museum",
b"xn--fiqs8s.icom.museum",
"http",
None,
),
(
"http://Königsgäßchen.de",
"http://xn--knigsgchen-b4a3dun.de",
"königsgäßchen.de",
b"xn--knigsgchen-b4a3dun.de",
"http",
None,
),
(
"https://faß.de",
"https://xn--fa-hia.de",
"faß.de",
b"xn--fa-hia.de",
"https",
None,
),
(
"https://βόλος.com:443",
"https://xn--nxasmm1c.com:443",
"βόλος.com",
b"xn--nxasmm1c.com",
"https",
None,
),
(
"http://ශ්රී.com:444",
"http://xn--10cl1a0b660p.com:444",
"ශ්රී.com",
b"xn--10cl1a0b660p.com",
"http",
444,
),
(
"https://نامهای.com:4433",
"https://xn--mgba3gch31f060k.com:4433",
"نامهای.com",
b"xn--mgba3gch31f060k.com",
"https",
4433,
),
],
ids=[
"http_with_port",
"unicode_tr46_compat",
"https_without_port",
"https_with_port",
"http_with_custom_port",
"https_with_custom_port",
],
)
def test_idna_url(given, idna, host, raw_host, scheme, port):
url = httpx.URL(given)
assert url == httpx.URL(idna)
assert url.host == host
assert url.raw_host == raw_host
assert url.scheme == scheme
assert url.port == port
def test_url_unescaped_idna_host():
url = httpx.URL("https://中国.icom.museum/")
assert url.raw_host == b"xn--fiqs8s.icom.museum"
def test_url_escaped_idna_host():
url = httpx.URL("https://xn--fiqs8s.icom.museum/")
assert url.raw_host == b"xn--fiqs8s.icom.museum"
def test_url_invalid_idna_host():
with pytest.raises(httpx.InvalidURL) as exc:
httpx.URL("https://☃.com/")
assert str(exc.value) == "Invalid IDNA hostname: '☃.com'"
# Tests for IPv4 hostname support.
def test_url_valid_ipv4():
url = httpx.URL("https://1.2.3.4/")
assert url.host == "1.2.3.4"
def test_url_invalid_ipv4():
with pytest.raises(httpx.InvalidURL) as exc:
httpx.URL("https://999.999.999.999/")
assert str(exc.value) == "Invalid IPv4 address: '999.999.999.999'"
# Tests for IPv6 hostname support.
def test_ipv6_url():
url = httpx.URL("http://[::ffff:192.168.0.1]:5678/")
assert url.host == "::ffff:192.168.0.1"
assert url.netloc == b"[::ffff:192.168.0.1]:5678"
def test_url_valid_ipv6():
url = httpx.URL("https://[2001:db8::ff00:42:8329]/")
assert url.host == "2001:db8::ff00:42:8329"
def test_url_invalid_ipv6():
with pytest.raises(httpx.InvalidURL) as exc:
httpx.URL("https://[2001]/")
assert str(exc.value) == "Invalid IPv6 address: '[2001]'"
@pytest.mark.parametrize("host", ["[::ffff:192.168.0.1]", "::ffff:192.168.0.1"])
def test_ipv6_url_from_raw_url(host):
url = httpx.URL(scheme="https", host=host, port=443, path="/")
assert url.host == "::ffff:192.168.0.1"
assert url.netloc == b"[::ffff:192.168.0.1]"
assert str(url) == "https://[::ffff:192.168.0.1]/"
@pytest.mark.parametrize(
"url_str",
[
"http://127.0.0.1:1234",
"http://example.com:1234",
"http://[::ffff:127.0.0.1]:1234",
],
)
@pytest.mark.parametrize("new_host", ["[::ffff:192.168.0.1]", "::ffff:192.168.0.1"])
def test_ipv6_url_copy_with_host(url_str, new_host):
url = httpx.URL(url_str).copy_with(host=new_host)
assert url.host == "::ffff:192.168.0.1"
assert url.netloc == b"[::ffff:192.168.0.1]:1234"
assert str(url) == "http://[::ffff:192.168.0.1]:1234"
| httpx |
python | from __future__ import annotations
import hashlib
import os
import re
import time
import typing
from base64 import b64encode
from urllib.request import parse_http_list
from ._exceptions import ProtocolError
from ._models import Cookies, Request, Response
from ._utils import to_bytes, to_str, unquote
if typing.TYPE_CHECKING: # pragma: no cover
from hashlib import _Hash
__all__ = ["Auth", "BasicAuth", "DigestAuth", "NetRCAuth"]
class Auth:
"""
Base class for all authentication schemes.
To implement a custom authentication scheme, subclass `Auth` and override
the `.auth_flow()` method.
If the authentication scheme does I/O such as disk access or network calls, or uses
synchronization primitives such as locks, you should override `.sync_auth_flow()`
and/or `.async_auth_flow()` instead of `.auth_flow()` to provide specialized
implementations that will be used by `Client` and `AsyncClient` respectively.
"""
requires_request_body = False
requires_response_body = False
def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
"""
Execute the authentication flow.
To dispatch a request, `yield` it:
```
yield request
```
The client will `.send()` the response back into the flow generator. You can
access it like so:
```
response = yield request
```
A `return` (or reaching the end of the generator) will result in the
client returning the last response obtained from the server.
You can dispatch as many requests as is necessary.
"""
yield request
def sync_auth_flow(
self, request: Request
) -> typing.Generator[Request, Response, None]:
"""
Execute the authentication flow synchronously.
By default, this defers to `.auth_flow()`. You should override this method
when the authentication scheme does I/O and/or uses concurrency primitives.
"""
if self.requires_request_body:
request.read()
flow = self.auth_flow(request)
request = next(flow)
while True:
response = yield request
if self.requires_response_body:
response.read()
try:
request = flow.send(response)
except StopIteration:
break
async def async_auth_flow(
self, request: Request
) -> typing.AsyncGenerator[Request, Response]:
"""
Execute the authentication flow asynchronously.
By default, this defers to `.auth_flow()`. You should override this method
when the authentication scheme does I/O and/or uses concurrency primitives.
"""
if self.requires_request_body:
await request.aread()
flow = self.auth_flow(request)
request = next(flow)
while True:
response = yield request
if self.requires_response_body:
await response.aread()
try:
request = flow.send(response)
except StopIteration:
break
class FunctionAuth(Auth):
"""
Allows the 'auth' argument to be passed as a simple callable function,
that takes the request, and returns a new, modified request.
"""
def __init__(self, func: typing.Callable[[Request], Request]) -> None:
self._func = func
def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
yield self._func(request)
class BasicAuth(Auth):
"""
Allows the 'auth' argument to be passed as a (username, password) pair,
and uses HTTP Basic authentication.
"""
def __init__(self, username: str | bytes, password: str | bytes) -> None:
self._auth_header = self._build_auth_header(username, password)
def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
request.headers["Authorization"] = self._auth_header
yield request
def _build_auth_header(self, username: str | bytes, password: str | bytes) -> str:
userpass = b":".join((to_bytes(username), to_bytes(password)))
token = b64encode(userpass).decode()
return f"Basic {token}"
class NetRCAuth(Auth):
"""
Use a 'netrc' file to lookup basic auth credentials based on the url host.
"""
def __init__(self, file: str | None = None) -> None:
# Lazily import 'netrc'.
# There's no need for us to load this module unless 'NetRCAuth' is being used.
import netrc
self._netrc_info = netrc.netrc(file)
def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
auth_info = self._netrc_info.authenticators(request.url.host)
if auth_info is None or not auth_info[2]:
# The netrc file did not have authentication credentials for this host.
yield request
else:
# Build a basic auth header with credentials from the netrc file.
request.headers["Authorization"] = self._build_auth_header(
username=auth_info[0], password=auth_info[2]
)
yield request
def _build_auth_header(self, username: str | bytes, password: str | bytes) -> str:
userpass = b":".join((to_bytes(username), to_bytes(password)))
token = b64encode(userpass).decode()
return f"Basic {token}"
class DigestAuth(Auth):
_ALGORITHM_TO_HASH_FUNCTION: dict[str, typing.Callable[[bytes], _Hash]] = {
"MD5": hashlib.md5,
"MD5-SESS": hashlib.md5,
"SHA": hashlib.sha1,
"SHA-SESS": hashlib.sha1,
"SHA-256": hashlib.sha256,
"SHA-256-SESS": hashlib.sha256,
"SHA-512": hashlib.sha512,
"SHA-512-SESS": hashlib.sha512,
}
def __init__(self, username: str | bytes, password: str | bytes) -> None:
self._username = to_bytes(username)
self._password = to_bytes(password)
self._last_challenge: _DigestAuthChallenge | None = None
self._nonce_count = 1
def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
if self._last_challenge:
request.headers["Authorization"] = self._build_auth_header(
request, self._last_challenge
)
response = yield request
if response.status_code != 401 or "www-authenticate" not in response.headers:
# If the response is not a 401 then we don't
# need to build an authenticated request.
return
for auth_header in response.headers.get_list("www-authenticate"):
if auth_header.lower().startswith("digest "):
break
else:
# If the response does not include a 'WWW-Authenticate: Digest ...'
# header, then we don't need to build an authenticated request.
return
self._last_challenge = self._parse_challenge(request, response, auth_header)
self._nonce_count = 1
request.headers["Authorization"] = self._build_auth_header(
request, self._last_challenge
)
if response.cookies:
Cookies(response.cookies).set_cookie_header(request=request)
yield request
def _parse_challenge(
self, request: Request, response: Response, auth_header: str
) -> _DigestAuthChallenge:
"""
Returns a challenge from a Digest WWW-Authenticate header.
These take the form of:
`Digest realm="realm@host.com",qop="auth,auth-int",nonce="abc",opaque="xyz"`
"""
scheme, _, fields = auth_header.partition(" ")
# This method should only ever have been called with a Digest auth header.
assert scheme.lower() == "digest"
header_dict: dict[str, str] = {}
for field in parse_http_list(fields):
key, value = field.strip().split("=", 1)
header_dict[key] = unquote(value)
try:
realm = header_dict["realm"].encode()
nonce = header_dict["nonce"].encode()
algorithm = header_dict.get("algorithm", "MD5")
opaque = header_dict["opaque"].encode() if "opaque" in header_dict else None
qop = header_dict["qop"].encode() if "qop" in header_dict else None
return _DigestAuthChallenge(
realm=realm, nonce=nonce, algorithm=algorithm, opaque=opaque, qop=qop
)
except KeyError as exc:
message = "Malformed Digest WWW-Authenticate header"
raise ProtocolError(message, request=request) from exc
def _build_auth_header(
self, request: Request, challenge: _DigestAuthChallenge
) -> str:
hash_func = self._ALGORITHM_TO_HASH_FUNCTION[challenge.algorithm.upper()]
def digest(data: bytes) -> bytes:
return hash_func(data).hexdigest().encode()
A1 = b":".join((self._username, challenge.realm, self._password))
path = request.url.raw_path
A2 = b":".join((request.method.encode(), path))
# TODO: implement auth-int
HA2 = digest(A2)
nc_value = b"%08x" % self._nonce_count
cnonce = self._get_client_nonce(self._nonce_count, challenge.nonce)
self._nonce_count += 1
HA1 = digest(A1)
if challenge.algorithm.lower().endswith("-sess"):
HA1 = digest(b":".join((HA1, challenge.nonce, cnonce)))
qop = self._resolve_qop(challenge.qop, request=request)
if qop is None:
# Following RFC 2069
digest_data = [HA1, challenge.nonce, HA2]
else:
# Following RFC 2617/7616
digest_data = [HA1, challenge.nonce, nc_value, cnonce, qop, HA2]
format_args = {
"username": self._username,
"realm": challenge.realm,
"nonce": challenge.nonce,
"uri": path,
"response": digest(b":".join(digest_data)),
"algorithm": challenge.algorithm.encode(),
}
if challenge.opaque:
format_args["opaque"] = challenge.opaque
if qop:
format_args["qop"] = b"auth"
format_args["nc"] = nc_value
format_args["cnonce"] = cnonce
return "Digest " + self._get_header_value(format_args)
def _get_client_nonce(self, nonce_count: int, nonce: bytes) -> bytes:
s = str(nonce_count).encode()
s += nonce
s += time.ctime().encode()
s += os.urandom(8)
return hashlib.sha1(s).hexdigest()[:16].encode()
def _get_header_value(self, header_fields: dict[str, bytes]) -> str:
NON_QUOTED_FIELDS = ("algorithm", "qop", "nc")
QUOTED_TEMPLATE = '{}="{}"'
NON_QUOTED_TEMPLATE = "{}={}"
header_value = ""
for i, (field, value) in enumerate(header_fields.items()):
if i > 0:
header_value += ", "
template = (
QUOTED_TEMPLATE
if field not in NON_QUOTED_FIELDS
else NON_QUOTED_TEMPLATE
)
header_value += template.format(field, to_str(value))
return header_value
def _resolve_qop(self, qop: bytes | None, request: Request) -> bytes | None:
if qop is None:
return None
qops = re.split(b", ?", qop)
if b"auth" in qops:
return b"auth"
if qops == [b"auth-int"]:
raise NotImplementedError("Digest auth-int support is not yet implemented")
message = f'Unexpected qop value "{qop!r}" in digest auth'
raise ProtocolError(message, request=request)
class _DigestAuthChallenge(typing.NamedTuple):
realm: bytes
nonce: bytes
algorithm: str
opaque: bytes | None
qop: bytes | None
| """
Integration tests for authentication.
Unit tests for auth classes also exist in tests/test_auth.py
"""
import hashlib
import netrc
import os
import sys
import threading
import typing
from urllib.request import parse_keqv_list
import anyio
import pytest
import httpx
from ..common import FIXTURES_DIR
class App:
"""
A mock app to test auth credentials.
"""
def __init__(self, auth_header: str = "", status_code: int = 200) -> None:
self.auth_header = auth_header
self.status_code = status_code
def __call__(self, request: httpx.Request) -> httpx.Response:
headers = {"www-authenticate": self.auth_header} if self.auth_header else {}
data = {"auth": request.headers.get("Authorization")}
return httpx.Response(self.status_code, headers=headers, json=data)
class DigestApp:
def __init__(
self,
algorithm: str = "SHA-256",
send_response_after_attempt: int = 1,
qop: str = "auth",
regenerate_nonce: bool = True,
) -> None:
self.algorithm = algorithm
self.send_response_after_attempt = send_response_after_attempt
self.qop = qop
self._regenerate_nonce = regenerate_nonce
self._response_count = 0
def __call__(self, request: httpx.Request) -> httpx.Response:
if self._response_count < self.send_response_after_attempt:
return self.challenge_send(request)
data = {"auth": request.headers.get("Authorization")}
return httpx.Response(200, json=data)
def challenge_send(self, request: httpx.Request) -> httpx.Response:
self._response_count += 1
nonce = (
hashlib.sha256(os.urandom(8)).hexdigest()
if self._regenerate_nonce
else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"
)
challenge_data = {
"nonce": nonce,
"qop": self.qop,
"opaque": (
"ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"
),
"algorithm": self.algorithm,
"stale": "FALSE",
}
challenge_str = ", ".join(
'{}="{}"'.format(key, value)
for key, value in challenge_data.items()
if value
)
headers = {
"www-authenticate": f'Digest realm="httpx@example.org", {challenge_str}',
}
return httpx.Response(401, headers=headers)
class RepeatAuth(httpx.Auth):
"""
A mock authentication scheme that requires clients to send
the request a fixed number of times, and then send a last request containing
an aggregation of nonces that the server sent in 'WWW-Authenticate' headers
of intermediate responses.
"""
requires_request_body = True
def __init__(self, repeat: int) -> None:
self.repeat = repeat
def auth_flow(
self, request: httpx.Request
) -> typing.Generator[httpx.Request, httpx.Response, None]:
nonces = []
for index in range(self.repeat):
request.headers["Authorization"] = f"Repeat {index}"
response = yield request
nonces.append(response.headers["www-authenticate"])
key = ".".join(nonces)
request.headers["Authorization"] = f"Repeat {key}"
yield request
class ResponseBodyAuth(httpx.Auth):
"""
A mock authentication scheme that requires clients to send an 'Authorization'
header, then send back the contents of the response in the 'Authorization'
header.
"""
requires_response_body = True
def __init__(self, token: str) -> None:
self.token = token
def auth_flow(
self, request: httpx.Request
) -> typing.Generator[httpx.Request, httpx.Response, None]:
request.headers["Authorization"] = self.token
response = yield request
data = response.text
request.headers["Authorization"] = data
yield request
class SyncOrAsyncAuth(httpx.Auth):
"""
A mock authentication scheme that uses a different implementation for the
sync and async cases.
"""
def __init__(self) -> None:
self._lock = threading.Lock()
self._async_lock = anyio.Lock()
def sync_auth_flow(
self, request: httpx.Request
) -> typing.Generator[httpx.Request, httpx.Response, None]:
with self._lock:
request.headers["Authorization"] = "sync-auth"
yield request
async def async_auth_flow(
self, request: httpx.Request
) -> typing.AsyncGenerator[httpx.Request, httpx.Response]:
async with self._async_lock:
request.headers["Authorization"] = "async-auth"
yield request
@pytest.mark.anyio
async def test_basic_auth() -> None:
url = "https://example.org/"
auth = ("user", "password123")
app = App()
async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:
response = await client.get(url, auth=auth)
assert response.status_code == 200
assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}
@pytest.mark.anyio
async def test_basic_auth_with_stream() -> None:
"""
See: https://github.com/encode/httpx/pull/1312
"""
url = "https://example.org/"
auth = ("user", "password123")
app = App()
async with httpx.AsyncClient(
transport=httpx.MockTransport(app), auth=auth
) as client:
async with client.stream("GET", url) as response:
await response.aread()
assert response.status_code == 200
assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}
@pytest.mark.anyio
async def test_basic_auth_in_url() -> None:
url = "https://user:password123@example.org/"
app = App()
async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:
response = await client.get(url)
assert response.status_code == 200
assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}
@pytest.mark.anyio
async def test_basic_auth_on_session() -> None:
url = "https://example.org/"
auth = ("user", "password123")
app = App()
async with httpx.AsyncClient(
transport=httpx.MockTransport(app), auth=auth
) as client:
response = await client.get(url)
assert response.status_code == 200
assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}
@pytest.mark.anyio
async def test_custom_auth() -> None:
url = "https://example.org/"
app = App()
def auth(request: httpx.Request) -> httpx.Request:
request.headers["Authorization"] = "Token 123"
return request
async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:
response = await client.get(url, auth=auth)
assert response.status_code == 200
assert response.json() == {"auth": "Token 123"}
def test_netrc_auth_credentials_exist() -> None:
"""
When netrc auth is being used and a request is made to a host that is
in the netrc file, then the relevant credentials should be applied.
"""
netrc_file = str(FIXTURES_DIR / ".netrc")
url = "http://netrcexample.org"
app = App()
auth = httpx.NetRCAuth(netrc_file)
with httpx.Client(transport=httpx.MockTransport(app), auth=auth) as client:
response = client.get(url)
assert response.status_code == 200
assert response.json() == {
"auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"
}
def test_netrc_auth_credentials_do_not_exist() -> None:
"""
When netrc auth is being used and a request is made to a host that is
not in the netrc file, then no credentials should be applied.
"""
netrc_file = str(FIXTURES_DIR / ".netrc")
url = "http://example.org"
app = App()
auth = httpx.NetRCAuth(netrc_file)
with httpx.Client(transport=httpx.MockTransport(app), auth=auth) as client:
response = client.get(url)
assert response.status_code == 200
assert response.json() == {"auth": None}
@pytest.mark.skipif(
sys.version_info >= (3, 11),
reason="netrc files without a password are valid from Python >= 3.11",
)
def test_netrc_auth_nopassword_parse_error() -> None: # pragma: no cover
"""
Python has different netrc parsing behaviours with different versions.
For Python < 3.11 a netrc file with no password is invalid. In this case
we want to allow the parse error to be raised.
"""
netrc_file = str(FIXTURES_DIR / ".netrc-nopassword")
with pytest.raises(netrc.NetrcParseError):
httpx.NetRCAuth(netrc_file)
@pytest.mark.anyio
async def test_auth_disable_per_request() -> None:
url = "https://example.org/"
auth = ("user", "password123")
app = App()
async with httpx.AsyncClient(
transport=httpx.MockTransport(app), auth=auth
) as client:
response = await client.get(url, auth=None)
assert response.status_code == 200
assert response.json() == {"auth": None}
def test_auth_hidden_url() -> None:
url = "http://example-username:example-password@example.org/"
expected = "URL('http://example-username:[secure]@example.org/')"
assert url == httpx.URL(url)
assert expected == repr(httpx.URL(url))
@pytest.mark.anyio
async def test_auth_hidden_header() -> None:
url = "https://example.org/"
auth = ("example-username", "example-password")
app = App()
async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:
response = await client.get(url, auth=auth)
assert "'authorization': '[secure]'" in str(response.request.headers)
@pytest.mark.anyio
async def test_auth_property() -> None:
app = App()
async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:
assert client.auth is None
client.auth = ("user", "password123")
assert isinstance(client.auth, httpx.BasicAuth)
url = "https://example.org/"
response = await client.get(url)
assert response.status_code == 200
assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}
@pytest.mark.anyio
async def test_auth_invalid_type() -> None:
app = App()
with pytest.raises(TypeError):
client = httpx.AsyncClient(
transport=httpx.MockTransport(app),
auth="not a tuple, not a callable", # type: ignore
)
async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:
with pytest.raises(TypeError):
await client.get(auth="not a tuple, not a callable") # type: ignore
with pytest.raises(TypeError):
client.auth = "not a tuple, not a callable" # type: ignore
@pytest.mark.anyio
async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:
url = "https://example.org/"
auth = httpx.DigestAuth(username="user", password="password123")
app = App()
async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:
response = await client.get(url, auth=auth)
assert response.status_code == 200
assert response.json() == {"auth": None}
assert len(response.history) == 0
def test_digest_auth_returns_no_auth_if_alternate_auth_scheme() -> None:
url = "https://example.org/"
auth = httpx.DigestAuth(username="user", password="password123")
auth_header = "Token ..."
app = App(auth_header=auth_header, status_code=401)
client = httpx.Client(transport=httpx.MockTransport(app))
response = client.get(url, auth=auth)
assert response.status_code == 401
assert response.json() == {"auth": None}
assert len(response.history) == 0
@pytest.mark.anyio
async def test_digest_auth_200_response_including_digest_auth_header() -> None:
url = "https://example.org/"
auth = httpx.DigestAuth(username="user", password="password123")
auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'
app = App(auth_header=auth_header, status_code=200)
async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:
response = await client.get(url, auth=auth)
assert response.status_code == 200
assert response.json() == {"auth": None}
assert len(response.history) == 0
@pytest.mark.anyio
async def test_digest_auth_401_response_without_digest_auth_header() -> None:
url = "https://example.org/"
auth = httpx.DigestAuth(username="user", password="password123")
app = App(auth_header="", status_code=401)
async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:
response = await client.get(url, auth=auth)
assert response.status_code == 401
assert response.json() == {"auth": None}
assert len(response.history) == 0
@pytest.mark.parametrize(
"algorithm,expected_hash_length,expected_response_length",
[
("MD5", 64, 32),
("MD5-SESS", 64, 32),
("SHA", 64, 40),
("SHA-SESS", 64, 40),
("SHA-256", 64, 64),
("SHA-256-SESS", 64, 64),
("SHA-512", 64, 128),
("SHA-512-SESS", 64, 128),
],
)
@pytest.mark.anyio
async def test_digest_auth(
algorithm: str, expected_hash_length: int, expected_response_length: int
) -> None:
url = "https://example.org/"
auth = httpx.DigestAuth(username="user", password="password123")
app = DigestApp(algorithm=algorithm)
async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:
response = await client.get(url, auth=auth)
assert response.status_code == 200
assert len(response.history) == 1
authorization = typing.cast(typing.Dict[str, typing.Any], response.json())["auth"]
scheme, _, fields = authorization.partition(" ")
assert scheme == "Digest"
response_fields = [field.strip() for field in fields.split(",")]
digest_data = dict(field.split("=") for field in response_fields)
assert digest_data["username"] == '"user"'
assert digest_data["realm"] == '"httpx@example.org"'
assert "nonce" in digest_data
assert digest_data["uri"] == '"/"'
assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes
assert len(digest_data["opaque"]) == expected_hash_length + 2
assert digest_data["algorithm"] == algorithm
assert digest_data["qop"] == "auth"
assert digest_data["nc"] == "00000001"
assert len(digest_data["cnonce"]) == 16 + 2
@pytest.mark.anyio
async def test_digest_auth_no_specified_qop() -> None:
url = "https://example.org/"
auth = httpx.DigestAuth(username="user", password="password123")
app = DigestApp(qop="")
async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:
response = await client.get(url, auth=auth)
assert response.status_code == 200
assert len(response.history) == 1
authorization = typing.cast(typing.Dict[str, typing.Any], response.json())["auth"]
scheme, _, fields = authorization.partition(" ")
assert scheme == "Digest"
response_fields = [field.strip() for field in fields.split(",")]
digest_data = dict(field.split("=") for field in response_fields)
assert "qop" not in digest_data
assert "nc" not in digest_data
assert "cnonce" not in digest_data
assert digest_data["username"] == '"user"'
assert digest_data["realm"] == '"httpx@example.org"'
assert len(digest_data["nonce"]) == 64 + 2 # extra quotes
assert digest_data["uri"] == '"/"'
assert len(digest_data["response"]) == 64 + 2
assert len(digest_data["opaque"]) == 64 + 2
assert digest_data["algorithm"] == "SHA-256"
@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))
@pytest.mark.anyio
async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:
url = "https://example.org/"
auth = httpx.DigestAuth(username="user", password="password123")
app = DigestApp(qop=qop)
async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:
response = await client.get(url, auth=auth)
assert response.status_code == 200
assert len(response.history) == 1
@pytest.mark.anyio
async def test_digest_auth_qop_auth_int_not_implemented() -> None:
url = "https://example.org/"
auth = httpx.DigestAuth(username="user", password="password123")
app = DigestApp(qop="auth-int")
async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:
with pytest.raises(NotImplementedError):
await client.get(url, auth=auth)
@pytest.mark.anyio
async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:
url = "https://example.org/"
auth = httpx.DigestAuth(username="user", password="password123")
app = DigestApp(qop="not-auth")
async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:
with pytest.raises(httpx.ProtocolError):
await client.get(url, auth=auth)
@pytest.mark.anyio
async def test_digest_auth_incorrect_credentials() -> None:
url = "https://example.org/"
auth = httpx.DigestAuth(username="user", password="password123")
app = DigestApp(send_response_after_attempt=2)
async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:
response = await client.get(url, auth=auth)
assert response.status_code == 401
assert len(response.history) == 1
@pytest.mark.anyio
async def test_digest_auth_reuses_challenge() -> None:
url = "https://example.org/"
auth = httpx.DigestAuth(username="user", password="password123")
app = DigestApp()
async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:
response_1 = await client.get(url, auth=auth)
response_2 = await client.get(url, auth=auth)
assert response_1.status_code == 200
assert response_2.status_code == 200
assert len(response_1.history) == 1
assert len(response_2.history) == 0
@pytest.mark.anyio
async def test_digest_auth_resets_nonce_count_after_401() -> None:
url = "https://example.org/"
auth = httpx.DigestAuth(username="user", password="password123")
app = DigestApp()
async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:
response_1 = await client.get(url, auth=auth)
assert response_1.status_code == 200
assert len(response_1.history) == 1
first_nonce = parse_keqv_list(
response_1.request.headers["Authorization"].split(", ")
)["nonce"]
first_nc = parse_keqv_list(
response_1.request.headers["Authorization"].split(", ")
)["nc"]
# with this we now force a 401 on a subsequent (but initial) request
app.send_response_after_attempt = 2
# we expect the client again to try to authenticate,
# i.e. the history length must be 1
response_2 = await client.get(url, auth=auth)
assert response_2.status_code == 200
assert len(response_2.history) == 1
second_nonce = parse_keqv_list(
response_2.request.headers["Authorization"].split(", ")
)["nonce"]
second_nc = parse_keqv_list(
response_2.request.headers["Authorization"].split(", ")
)["nc"]
assert first_nonce != second_nonce # ensures that the auth challenge was reset
assert (
first_nc == second_nc
) # ensures the nonce count is reset when the authentication failed
@pytest.mark.parametrize(
"auth_header",
[
'Digest realm="httpx@example.org", qop="auth"', # missing fields
'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list
],
)
@pytest.mark.anyio
async def test_async_digest_auth_raises_protocol_error_on_malformed_header(
auth_header: str,
) -> None:
url = "https://example.org/"
auth = httpx.DigestAuth(username="user", password="password123")
app = App(auth_header=auth_header, status_code=401)
async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:
with pytest.raises(httpx.ProtocolError):
await client.get(url, auth=auth)
@pytest.mark.parametrize(
"auth_header",
[
'Digest realm="httpx@example.org", qop="auth"', # missing fields
'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list
],
)
def test_sync_digest_auth_raises_protocol_error_on_malformed_header(
auth_header: str,
) -> None:
url = "https://example.org/"
auth = httpx.DigestAuth(username="user", password="password123")
app = App(auth_header=auth_header, status_code=401)
with httpx.Client(transport=httpx.MockTransport(app)) as client:
with pytest.raises(httpx.ProtocolError):
client.get(url, auth=auth)
@pytest.mark.anyio
async def test_async_auth_history() -> None:
"""
Test that intermediate requests sent as part of an authentication flow
are recorded in the response history.
"""
url = "https://example.org/"
auth = RepeatAuth(repeat=2)
app = App(auth_header="abc")
async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:
response = await client.get(url, auth=auth)
assert response.status_code == 200
assert response.json() == {"auth": "Repeat abc.abc"}
assert len(response.history) == 2
resp1, resp2 = response.history
assert resp1.json() == {"auth": "Repeat 0"}
assert resp2.json() == {"auth": "Repeat 1"}
assert len(resp2.history) == 1
assert resp2.history == [resp1]
assert len(resp1.history) == 0
def test_sync_auth_history() -> None:
"""
Test that intermediate requests sent as part of an authentication flow
are recorded in the response history.
"""
url = "https://example.org/"
auth = RepeatAuth(repeat=2)
app = App(auth_header="abc")
with httpx.Client(transport=httpx.MockTransport(app)) as client:
response = client.get(url, auth=auth)
assert response.status_code == 200
assert response.json() == {"auth": "Repeat abc.abc"}
assert len(response.history) == 2
resp1, resp2 = response.history
assert resp1.json() == {"auth": "Repeat 0"}
assert resp2.json() == {"auth": "Repeat 1"}
assert len(resp2.history) == 1
assert resp2.history == [resp1]
assert len(resp1.history) == 0
class ConsumeBodyTransport(httpx.MockTransport):
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
assert isinstance(request.stream, httpx.AsyncByteStream)
[_ async for _ in request.stream]
return self.handler(request) # type: ignore[return-value]
@pytest.mark.anyio
async def test_digest_auth_unavailable_streaming_body():
url = "https://example.org/"
auth = httpx.DigestAuth(username="user", password="password123")
app = DigestApp()
async def streaming_body() -> typing.AsyncIterator[bytes]:
yield b"Example request body" # pragma: no cover
async with httpx.AsyncClient(transport=ConsumeBodyTransport(app)) as client:
with pytest.raises(httpx.StreamConsumed):
await client.post(url, content=streaming_body(), auth=auth)
@pytest.mark.anyio
async def test_async_auth_reads_response_body() -> None:
"""
Test that we can read the response body in an auth flow if `requires_response_body`
is set.
"""
url = "https://example.org/"
auth = ResponseBodyAuth("xyz")
app = App()
async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:
response = await client.get(url, auth=auth)
assert response.status_code == 200
assert response.json() == {"auth": '{"auth":"xyz"}'}
def test_sync_auth_reads_response_body() -> None:
"""
Test that we can read the response body in an auth flow if `requires_response_body`
is set.
"""
url = "https://example.org/"
auth = ResponseBodyAuth("xyz")
app = App()
with httpx.Client(transport=httpx.MockTransport(app)) as client:
response = client.get(url, auth=auth)
assert response.status_code == 200
assert response.json() == {"auth": '{"auth":"xyz"}'}
@pytest.mark.anyio
async def test_async_auth() -> None:
"""
Test that we can use an auth implementation specific to the async case, to
support cases that require performing I/O or using concurrency primitives (such
as checking a disk-based cache or fetching a token from a remote auth server).
"""
url = "https://example.org/"
auth = SyncOrAsyncAuth()
app = App()
async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:
response = await client.get(url, auth=auth)
assert response.status_code == 200
assert response.json() == {"auth": "async-auth"}
def test_sync_auth() -> None:
"""
Test that we can use an auth implementation specific to the sync case.
"""
url = "https://example.org/"
auth = SyncOrAsyncAuth()
app = App()
with httpx.Client(transport=httpx.MockTransport(app)) as client:
response = client.get(url, auth=auth)
assert response.status_code == 200
assert response.json() == {"auth": "sync-auth"}
| httpx |
python | from __future__ import annotations
import datetime
import enum
import logging
import time
import typing
import warnings
from contextlib import asynccontextmanager, contextmanager
from types import TracebackType
from .__version__ import __version__
from ._auth import Auth, BasicAuth, FunctionAuth
from ._config import (
DEFAULT_LIMITS,
DEFAULT_MAX_REDIRECTS,
DEFAULT_TIMEOUT_CONFIG,
Limits,
Proxy,
Timeout,
)
from ._decoders import SUPPORTED_DECODERS
from ._exceptions import (
InvalidURL,
RemoteProtocolError,
TooManyRedirects,
request_context,
)
from ._models import Cookies, Headers, Request, Response
from ._status_codes import codes
from ._transports.base import AsyncBaseTransport, BaseTransport
from ._transports.default import AsyncHTTPTransport, HTTPTransport
from ._types import (
AsyncByteStream,
AuthTypes,
CertTypes,
CookieTypes,
HeaderTypes,
ProxyTypes,
QueryParamTypes,
RequestContent,
RequestData,
RequestExtensions,
RequestFiles,
SyncByteStream,
TimeoutTypes,
)
from ._urls import URL, QueryParams
from ._utils import URLPattern, get_environment_proxies
if typing.TYPE_CHECKING:
import ssl # pragma: no cover
__all__ = ["USE_CLIENT_DEFAULT", "AsyncClient", "Client"]
# The type annotation for @classmethod and context managers here follows PEP 484
# https://www.python.org/dev/peps/pep-0484/#annotating-instance-and-class-methods
T = typing.TypeVar("T", bound="Client")
U = typing.TypeVar("U", bound="AsyncClient")
def _is_https_redirect(url: URL, location: URL) -> bool:
"""
Return 'True' if 'location' is a HTTPS upgrade of 'url'
"""
if url.host != location.host:
return False
return (
url.scheme == "http"
and _port_or_default(url) == 80
and location.scheme == "https"
and _port_or_default(location) == 443
)
def _port_or_default(url: URL) -> int | None:
if url.port is not None:
return url.port
return {"http": 80, "https": 443}.get(url.scheme)
def _same_origin(url: URL, other: URL) -> bool:
"""
Return 'True' if the given URLs share the same origin.
"""
return (
url.scheme == other.scheme
and url.host == other.host
and _port_or_default(url) == _port_or_default(other)
)
class UseClientDefault:
"""
For some parameters such as `auth=...` and `timeout=...` we need to be able
to indicate the default "unset" state, in a way that is distinctly different
to using `None`.
The default "unset" state indicates that whatever default is set on the
client should be used. This is different to setting `None`, which
explicitly disables the parameter, possibly overriding a client default.
For example we use `timeout=USE_CLIENT_DEFAULT` in the `request()` signature.
Omitting the `timeout` parameter will send a request using whatever default
timeout has been configured on the client. Including `timeout=None` will
ensure no timeout is used.
Note that user code shouldn't need to use the `USE_CLIENT_DEFAULT` constant,
but it is used internally when a parameter is not included.
"""
USE_CLIENT_DEFAULT = UseClientDefault()
logger = logging.getLogger("httpx")
USER_AGENT = f"python-httpx/{__version__}"
ACCEPT_ENCODING = ", ".join(
[key for key in SUPPORTED_DECODERS.keys() if key != "identity"]
)
class ClientState(enum.Enum):
# UNOPENED:
# The client has been instantiated, but has not been used to send a request,
# or been opened by entering the context of a `with` block.
UNOPENED = 1
# OPENED:
# The client has either sent a request, or is within a `with` block.
OPENED = 2
# CLOSED:
# The client has either exited the `with` block, or `close()` has
# been called explicitly.
CLOSED = 3
class BoundSyncStream(SyncByteStream):
"""
A byte stream that is bound to a given response instance, and that
ensures the `response.elapsed` is set once the response is closed.
"""
def __init__(
self, stream: SyncByteStream, response: Response, start: float
) -> None:
self._stream = stream
self._response = response
self._start = start
def __iter__(self) -> typing.Iterator[bytes]:
for chunk in self._stream:
yield chunk
def close(self) -> None:
elapsed = time.perf_counter() - self._start
self._response.elapsed = datetime.timedelta(seconds=elapsed)
self._stream.close()
class BoundAsyncStream(AsyncByteStream):
"""
An async byte stream that is bound to a given response instance, and that
ensures the `response.elapsed` is set once the response is closed.
"""
def __init__(
self, stream: AsyncByteStream, response: Response, start: float
) -> None:
self._stream = stream
self._response = response
self._start = start
async def __aiter__(self) -> typing.AsyncIterator[bytes]:
async for chunk in self._stream:
yield chunk
async def aclose(self) -> None:
elapsed = time.perf_counter() - self._start
self._response.elapsed = datetime.timedelta(seconds=elapsed)
await self._stream.aclose()
EventHook = typing.Callable[..., typing.Any]
class BaseClient:
def __init__(
self,
*,
auth: AuthTypes | None = None,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
follow_redirects: bool = False,
max_redirects: int = DEFAULT_MAX_REDIRECTS,
event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None,
base_url: URL | str = "",
trust_env: bool = True,
default_encoding: str | typing.Callable[[bytes], str] = "utf-8",
) -> None:
event_hooks = {} if event_hooks is None else event_hooks
self._base_url = self._enforce_trailing_slash(URL(base_url))
self._auth = self._build_auth(auth)
self._params = QueryParams(params)
self.headers = Headers(headers)
self._cookies = Cookies(cookies)
self._timeout = Timeout(timeout)
self.follow_redirects = follow_redirects
self.max_redirects = max_redirects
self._event_hooks = {
"request": list(event_hooks.get("request", [])),
"response": list(event_hooks.get("response", [])),
}
self._trust_env = trust_env
self._default_encoding = default_encoding
self._state = ClientState.UNOPENED
@property
def is_closed(self) -> bool:
"""
Check if the client being closed
"""
return self._state == ClientState.CLOSED
@property
def trust_env(self) -> bool:
return self._trust_env
def _enforce_trailing_slash(self, url: URL) -> URL:
if url.raw_path.endswith(b"/"):
return url
return url.copy_with(raw_path=url.raw_path + b"/")
def _get_proxy_map(
self, proxy: ProxyTypes | None, allow_env_proxies: bool
) -> dict[str, Proxy | None]:
if proxy is None:
if allow_env_proxies:
return {
key: None if url is None else Proxy(url=url)
for key, url in get_environment_proxies().items()
}
return {}
else:
proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy
return {"all://": proxy}
@property
def timeout(self) -> Timeout:
return self._timeout
@timeout.setter
def timeout(self, timeout: TimeoutTypes) -> None:
self._timeout = Timeout(timeout)
@property
def event_hooks(self) -> dict[str, list[EventHook]]:
return self._event_hooks
@event_hooks.setter
def event_hooks(self, event_hooks: dict[str, list[EventHook]]) -> None:
self._event_hooks = {
"request": list(event_hooks.get("request", [])),
"response": list(event_hooks.get("response", [])),
}
@property
def auth(self) -> Auth | None:
"""
Authentication class used when none is passed at the request-level.
See also [Authentication][0].
[0]: /quickstart/#authentication
"""
return self._auth
@auth.setter
def auth(self, auth: AuthTypes) -> None:
self._auth = self._build_auth(auth)
@property
def base_url(self) -> URL:
"""
Base URL to use when sending requests with relative URLs.
"""
return self._base_url
@base_url.setter
def base_url(self, url: URL | str) -> None:
self._base_url = self._enforce_trailing_slash(URL(url))
@property
def headers(self) -> Headers:
"""
HTTP headers to include when sending requests.
"""
return self._headers
@headers.setter
def headers(self, headers: HeaderTypes) -> None:
client_headers = Headers(
{
b"Accept": b"*/*",
b"Accept-Encoding": ACCEPT_ENCODING.encode("ascii"),
b"Connection": b"keep-alive",
b"User-Agent": USER_AGENT.encode("ascii"),
}
)
client_headers.update(headers)
self._headers = client_headers
@property
def cookies(self) -> Cookies:
"""
Cookie values to include when sending requests.
"""
return self._cookies
@cookies.setter
def cookies(self, cookies: CookieTypes) -> None:
self._cookies = Cookies(cookies)
@property
def params(self) -> QueryParams:
"""
Query parameters to include in the URL when sending requests.
"""
return self._params
@params.setter
def params(self, params: QueryParamTypes) -> None:
self._params = QueryParams(params)
def build_request(
self,
method: str,
url: URL | str,
*,
content: RequestContent | None = None,
data: RequestData | None = None,
files: RequestFiles | None = None,
json: typing.Any | None = None,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
extensions: RequestExtensions | None = None,
) -> Request:
"""
Build and return a request instance.
* The `params`, `headers` and `cookies` arguments
are merged with any values set on the client.
* The `url` argument is merged with any `base_url` set on the client.
See also: [Request instances][0]
[0]: /advanced/clients/#request-instances
"""
url = self._merge_url(url)
headers = self._merge_headers(headers)
cookies = self._merge_cookies(cookies)
params = self._merge_queryparams(params)
extensions = {} if extensions is None else extensions
if "timeout" not in extensions:
timeout = (
self.timeout
if isinstance(timeout, UseClientDefault)
else Timeout(timeout)
)
extensions = dict(**extensions, timeout=timeout.as_dict())
return Request(
method,
url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
extensions=extensions,
)
def _merge_url(self, url: URL | str) -> URL:
"""
Merge a URL argument together with any 'base_url' on the client,
to create the URL used for the outgoing request.
"""
merge_url = URL(url)
if merge_url.is_relative_url:
# To merge URLs we always append to the base URL. To get this
# behaviour correct we always ensure the base URL ends in a '/'
# separator, and strip any leading '/' from the merge URL.
#
# So, eg...
#
# >>> client = Client(base_url="https://www.example.com/subpath")
# >>> client.base_url
# URL('https://www.example.com/subpath/')
# >>> client.build_request("GET", "/path").url
# URL('https://www.example.com/subpath/path')
merge_raw_path = self.base_url.raw_path + merge_url.raw_path.lstrip(b"/")
return self.base_url.copy_with(raw_path=merge_raw_path)
return merge_url
def _merge_cookies(self, cookies: CookieTypes | None = None) -> CookieTypes | None:
"""
Merge a cookies argument together with any cookies on the client,
to create the cookies used for the outgoing request.
"""
if cookies or self.cookies:
merged_cookies = Cookies(self.cookies)
merged_cookies.update(cookies)
return merged_cookies
return cookies
def _merge_headers(self, headers: HeaderTypes | None = None) -> HeaderTypes | None:
"""
Merge a headers argument together with any headers on the client,
to create the headers used for the outgoing request.
"""
merged_headers = Headers(self.headers)
merged_headers.update(headers)
return merged_headers
def _merge_queryparams(
self, params: QueryParamTypes | None = None
) -> QueryParamTypes | None:
"""
Merge a queryparams argument together with any queryparams on the client,
to create the queryparams used for the outgoing request.
"""
if params or self.params:
merged_queryparams = QueryParams(self.params)
return merged_queryparams.merge(params)
return params
def _build_auth(self, auth: AuthTypes | None) -> Auth | None:
if auth is None:
return None
elif isinstance(auth, tuple):
return BasicAuth(username=auth[0], password=auth[1])
elif isinstance(auth, Auth):
return auth
elif callable(auth):
return FunctionAuth(func=auth)
else:
raise TypeError(f'Invalid "auth" argument: {auth!r}')
def _build_request_auth(
self,
request: Request,
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
) -> Auth:
auth = (
self._auth if isinstance(auth, UseClientDefault) else self._build_auth(auth)
)
if auth is not None:
return auth
username, password = request.url.username, request.url.password
if username or password:
return BasicAuth(username=username, password=password)
return Auth()
def _build_redirect_request(self, request: Request, response: Response) -> Request:
"""
Given a request and a redirect response, return a new request that
should be used to effect the redirect.
"""
method = self._redirect_method(request, response)
url = self._redirect_url(request, response)
headers = self._redirect_headers(request, url, method)
stream = self._redirect_stream(request, method)
cookies = Cookies(self.cookies)
return Request(
method=method,
url=url,
headers=headers,
cookies=cookies,
stream=stream,
extensions=request.extensions,
)
def _redirect_method(self, request: Request, response: Response) -> str:
"""
When being redirected we may want to change the method of the request
based on certain specs or browser behavior.
"""
method = request.method
# https://tools.ietf.org/html/rfc7231#section-6.4.4
if response.status_code == codes.SEE_OTHER and method != "HEAD":
method = "GET"
# Do what the browsers do, despite standards...
# Turn 302s into GETs.
if response.status_code == codes.FOUND and method != "HEAD":
method = "GET"
# If a POST is responded to with a 301, turn it into a GET.
# This bizarre behaviour is explained in 'requests' issue 1704.
if response.status_code == codes.MOVED_PERMANENTLY and method == "POST":
method = "GET"
return method
def _redirect_url(self, request: Request, response: Response) -> URL:
"""
Return the URL for the redirect to follow.
"""
location = response.headers["Location"]
try:
url = URL(location)
except InvalidURL as exc:
raise RemoteProtocolError(
f"Invalid URL in location header: {exc}.", request=request
) from None
# Handle malformed 'Location' headers that are "absolute" form, have no host.
# See: https://github.com/encode/httpx/issues/771
if url.scheme and not url.host:
url = url.copy_with(host=request.url.host)
# Facilitate relative 'Location' headers, as allowed by RFC 7231.
# (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
if url.is_relative_url:
url = request.url.join(url)
# Attach previous fragment if needed (RFC 7231 7.1.2)
if request.url.fragment and not url.fragment:
url = url.copy_with(fragment=request.url.fragment)
return url
def _redirect_headers(self, request: Request, url: URL, method: str) -> Headers:
"""
Return the headers that should be used for the redirect request.
"""
headers = Headers(request.headers)
if not _same_origin(url, request.url):
if not _is_https_redirect(request.url, url):
# Strip Authorization headers when responses are redirected
# away from the origin. (Except for direct HTTP to HTTPS redirects.)
headers.pop("Authorization", None)
# Update the Host header.
headers["Host"] = url.netloc.decode("ascii")
if method != request.method and method == "GET":
# If we've switch to a 'GET' request, then strip any headers which
# are only relevant to the request body.
headers.pop("Content-Length", None)
headers.pop("Transfer-Encoding", None)
# We should use the client cookie store to determine any cookie header,
# rather than whatever was on the original outgoing request.
headers.pop("Cookie", None)
return headers
def _redirect_stream(
self, request: Request, method: str
) -> SyncByteStream | AsyncByteStream | None:
"""
Return the body that should be used for the redirect request.
"""
if method != request.method and method == "GET":
return None
return request.stream
def _set_timeout(self, request: Request) -> None:
if "timeout" not in request.extensions:
timeout = (
self.timeout
if isinstance(self.timeout, UseClientDefault)
else Timeout(self.timeout)
)
request.extensions = dict(**request.extensions, timeout=timeout.as_dict())
class Client(BaseClient):
"""
An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.
It can be shared between threads.
Usage:
```python
>>> client = httpx.Client()
>>> response = client.get('https://example.org')
```
**Parameters:**
* **auth** - *(optional)* An authentication class to use when sending
requests.
* **params** - *(optional)* Query parameters to include in request URLs, as
a string, dictionary, or sequence of two-tuples.
* **headers** - *(optional)* Dictionary of HTTP headers to include when
sending requests.
* **cookies** - *(optional)* Dictionary of Cookie items to include when
sending requests.
* **verify** - *(optional)* Either `True` to use an SSL context with the
default CA bundle, `False` to disable verification, or an instance of
`ssl.SSLContext` to use a custom context.
* **http2** - *(optional)* A boolean indicating if HTTP/2 support should be
enabled. Defaults to `False`.
* **proxy** - *(optional)* A proxy URL where all the traffic should be routed.
* **timeout** - *(optional)* The timeout configuration to use when sending
requests.
* **limits** - *(optional)* The limits configuration to use.
* **max_redirects** - *(optional)* The maximum number of redirect responses
that should be followed.
* **base_url** - *(optional)* A URL to use as the base when building
request URLs.
* **transport** - *(optional)* A transport class to use for sending requests
over the network.
* **trust_env** - *(optional)* Enables or disables usage of environment
variables for configuration.
* **default_encoding** - *(optional)* The default encoding to use for decoding
response text, if no charset information is included in a response Content-Type
header. Set to a callable for automatic character set detection. Default: "utf-8".
"""
def __init__(
self,
*,
auth: AuthTypes | None = None,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
verify: ssl.SSLContext | str | bool = True,
cert: CertTypes | None = None,
trust_env: bool = True,
http1: bool = True,
http2: bool = False,
proxy: ProxyTypes | None = None,
mounts: None | (typing.Mapping[str, BaseTransport | None]) = None,
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
follow_redirects: bool = False,
limits: Limits = DEFAULT_LIMITS,
max_redirects: int = DEFAULT_MAX_REDIRECTS,
event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None,
base_url: URL | str = "",
transport: BaseTransport | None = None,
default_encoding: str | typing.Callable[[bytes], str] = "utf-8",
) -> None:
super().__init__(
auth=auth,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
follow_redirects=follow_redirects,
max_redirects=max_redirects,
event_hooks=event_hooks,
base_url=base_url,
trust_env=trust_env,
default_encoding=default_encoding,
)
if http2:
try:
import h2 # noqa
except ImportError: # pragma: no cover
raise ImportError(
"Using http2=True, but the 'h2' package is not installed. "
"Make sure to install httpx using `pip install httpx[http2]`."
) from None
allow_env_proxies = trust_env and transport is None
proxy_map = self._get_proxy_map(proxy, allow_env_proxies)
self._transport = self._init_transport(
verify=verify,
cert=cert,
trust_env=trust_env,
http1=http1,
http2=http2,
limits=limits,
transport=transport,
)
self._mounts: dict[URLPattern, BaseTransport | None] = {
URLPattern(key): None
if proxy is None
else self._init_proxy_transport(
proxy,
verify=verify,
cert=cert,
trust_env=trust_env,
http1=http1,
http2=http2,
limits=limits,
)
for key, proxy in proxy_map.items()
}
if mounts is not None:
self._mounts.update(
{URLPattern(key): transport for key, transport in mounts.items()}
)
self._mounts = dict(sorted(self._mounts.items()))
def _init_transport(
self,
verify: ssl.SSLContext | str | bool = True,
cert: CertTypes | None = None,
trust_env: bool = True,
http1: bool = True,
http2: bool = False,
limits: Limits = DEFAULT_LIMITS,
transport: BaseTransport | None = None,
) -> BaseTransport:
if transport is not None:
return transport
return HTTPTransport(
verify=verify,
cert=cert,
trust_env=trust_env,
http1=http1,
http2=http2,
limits=limits,
)
def _init_proxy_transport(
self,
proxy: Proxy,
verify: ssl.SSLContext | str | bool = True,
cert: CertTypes | None = None,
trust_env: bool = True,
http1: bool = True,
http2: bool = False,
limits: Limits = DEFAULT_LIMITS,
) -> BaseTransport:
return HTTPTransport(
verify=verify,
cert=cert,
trust_env=trust_env,
http1=http1,
http2=http2,
limits=limits,
proxy=proxy,
)
def _transport_for_url(self, url: URL) -> BaseTransport:
"""
Returns the transport instance that should be used for a given URL.
This will either be the standard connection pool, or a proxy.
"""
for pattern, transport in self._mounts.items():
if pattern.matches(url):
return self._transport if transport is None else transport
return self._transport
def request(
self,
method: str,
url: URL | str,
*,
content: RequestContent | None = None,
data: RequestData | None = None,
files: RequestFiles | None = None,
json: typing.Any | None = None,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
extensions: RequestExtensions | None = None,
) -> Response:
"""
Build and send a request.
Equivalent to:
```python
request = client.build_request(...)
response = client.send(request, ...)
```
See `Client.build_request()`, `Client.send()` and
[Merging of configuration][0] for how the various parameters
are merged with client-level configuration.
[0]: /advanced/clients/#merging-of-configuration
"""
if cookies is not None:
message = (
"Setting per-request cookies=<...> is being deprecated, because "
"the expected behaviour on cookie persistence is ambiguous. Set "
"cookies directly on the client instance instead."
)
warnings.warn(message, DeprecationWarning, stacklevel=2)
request = self.build_request(
method=method,
url=url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
extensions=extensions,
)
return self.send(request, auth=auth, follow_redirects=follow_redirects)
@contextmanager
def stream(
self,
method: str,
url: URL | str,
*,
content: RequestContent | None = None,
data: RequestData | None = None,
files: RequestFiles | None = None,
json: typing.Any | None = None,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
extensions: RequestExtensions | None = None,
) -> typing.Iterator[Response]:
"""
Alternative to `httpx.request()` that streams the response body
instead of loading it into memory at once.
**Parameters**: See `httpx.request`.
See also: [Streaming Responses][0]
[0]: /quickstart#streaming-responses
"""
request = self.build_request(
method=method,
url=url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
extensions=extensions,
)
response = self.send(
request=request,
auth=auth,
follow_redirects=follow_redirects,
stream=True,
)
try:
yield response
finally:
response.close()
def send(
self,
request: Request,
*,
stream: bool = False,
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
) -> Response:
"""
Send a request.
The request is sent as-is, unmodified.
Typically you'll want to build one with `Client.build_request()`
so that any client-level configuration is merged into the request,
but passing an explicit `httpx.Request()` is supported as well.
See also: [Request instances][0]
[0]: /advanced/clients/#request-instances
"""
if self._state == ClientState.CLOSED:
raise RuntimeError("Cannot send a request, as the client has been closed.")
self._state = ClientState.OPENED
follow_redirects = (
self.follow_redirects
if isinstance(follow_redirects, UseClientDefault)
else follow_redirects
)
self._set_timeout(request)
auth = self._build_request_auth(request, auth)
response = self._send_handling_auth(
request,
auth=auth,
follow_redirects=follow_redirects,
history=[],
)
try:
if not stream:
response.read()
return response
except BaseException as exc:
response.close()
raise exc
def _send_handling_auth(
self,
request: Request,
auth: Auth,
follow_redirects: bool,
history: list[Response],
) -> Response:
auth_flow = auth.sync_auth_flow(request)
try:
request = next(auth_flow)
while True:
response = self._send_handling_redirects(
request,
follow_redirects=follow_redirects,
history=history,
)
try:
try:
next_request = auth_flow.send(response)
except StopIteration:
return response
response.history = list(history)
response.read()
request = next_request
history.append(response)
except BaseException as exc:
response.close()
raise exc
finally:
auth_flow.close()
def _send_handling_redirects(
self,
request: Request,
follow_redirects: bool,
history: list[Response],
) -> Response:
while True:
if len(history) > self.max_redirects:
raise TooManyRedirects(
"Exceeded maximum allowed redirects.", request=request
)
for hook in self._event_hooks["request"]:
hook(request)
response = self._send_single_request(request)
try:
for hook in self._event_hooks["response"]:
hook(response)
response.history = list(history)
if not response.has_redirect_location:
return response
request = self._build_redirect_request(request, response)
history = history + [response]
if follow_redirects:
response.read()
else:
response.next_request = request
return response
except BaseException as exc:
response.close()
raise exc
def _send_single_request(self, request: Request) -> Response:
"""
Sends a single request, without handling any redirections.
"""
transport = self._transport_for_url(request.url)
start = time.perf_counter()
if not isinstance(request.stream, SyncByteStream):
raise RuntimeError(
"Attempted to send an async request with a sync Client instance."
)
with request_context(request=request):
response = transport.handle_request(request)
assert isinstance(response.stream, SyncByteStream)
response.request = request
response.stream = BoundSyncStream(
response.stream, response=response, start=start
)
self.cookies.extract_cookies(response)
response.default_encoding = self._default_encoding
logger.info(
'HTTP Request: %s %s "%s %d %s"',
request.method,
request.url,
response.http_version,
response.status_code,
response.reason_phrase,
)
return response
def get(
self,
url: URL | str,
*,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
extensions: RequestExtensions | None = None,
) -> Response:
"""
Send a `GET` request.
**Parameters**: See `httpx.request`.
"""
return self.request(
"GET",
url,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
extensions=extensions,
)
def options(
self,
url: URL | str,
*,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
extensions: RequestExtensions | None = None,
) -> Response:
"""
Send an `OPTIONS` request.
**Parameters**: See `httpx.request`.
"""
return self.request(
"OPTIONS",
url,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
extensions=extensions,
)
def head(
self,
url: URL | str,
*,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
extensions: RequestExtensions | None = None,
) -> Response:
"""
Send a `HEAD` request.
**Parameters**: See `httpx.request`.
"""
return self.request(
"HEAD",
url,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
extensions=extensions,
)
def post(
self,
url: URL | str,
*,
content: RequestContent | None = None,
data: RequestData | None = None,
files: RequestFiles | None = None,
json: typing.Any | None = None,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
extensions: RequestExtensions | None = None,
) -> Response:
"""
Send a `POST` request.
**Parameters**: See `httpx.request`.
"""
return self.request(
"POST",
url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
extensions=extensions,
)
def put(
self,
url: URL | str,
*,
content: RequestContent | None = None,
data: RequestData | None = None,
files: RequestFiles | None = None,
json: typing.Any | None = None,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
extensions: RequestExtensions | None = None,
) -> Response:
"""
Send a `PUT` request.
**Parameters**: See `httpx.request`.
"""
return self.request(
"PUT",
url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
extensions=extensions,
)
def patch(
self,
url: URL | str,
*,
content: RequestContent | None = None,
data: RequestData | None = None,
files: RequestFiles | None = None,
json: typing.Any | None = None,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
extensions: RequestExtensions | None = None,
) -> Response:
"""
Send a `PATCH` request.
**Parameters**: See `httpx.request`.
"""
return self.request(
"PATCH",
url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
extensions=extensions,
)
def delete(
self,
url: URL | str,
*,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
extensions: RequestExtensions | None = None,
) -> Response:
"""
Send a `DELETE` request.
**Parameters**: See `httpx.request`.
"""
return self.request(
"DELETE",
url,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
extensions=extensions,
)
def close(self) -> None:
"""
Close transport and proxies.
"""
if self._state != ClientState.CLOSED:
self._state = ClientState.CLOSED
self._transport.close()
for transport in self._mounts.values():
if transport is not None:
transport.close()
def __enter__(self: T) -> T:
if self._state != ClientState.UNOPENED:
msg = {
ClientState.OPENED: "Cannot open a client instance more than once.",
ClientState.CLOSED: (
"Cannot reopen a client instance, once it has been closed."
),
}[self._state]
raise RuntimeError(msg)
self._state = ClientState.OPENED
self._transport.__enter__()
for transport in self._mounts.values():
if transport is not None:
transport.__enter__()
return self
def __exit__(
self,
exc_type: type[BaseException] | None = None,
exc_value: BaseException | None = None,
traceback: TracebackType | None = None,
) -> None:
self._state = ClientState.CLOSED
self._transport.__exit__(exc_type, exc_value, traceback)
for transport in self._mounts.values():
if transport is not None:
transport.__exit__(exc_type, exc_value, traceback)
class AsyncClient(BaseClient):
"""
An asynchronous HTTP client, with connection pooling, HTTP/2, redirects,
cookie persistence, etc.
It can be shared between tasks.
Usage:
```python
>>> async with httpx.AsyncClient() as client:
>>> response = await client.get('https://example.org')
```
**Parameters:**
* **auth** - *(optional)* An authentication class to use when sending
requests.
* **params** - *(optional)* Query parameters to include in request URLs, as
a string, dictionary, or sequence of two-tuples.
* **headers** - *(optional)* Dictionary of HTTP headers to include when
sending requests.
* **cookies** - *(optional)* Dictionary of Cookie items to include when
sending requests.
* **verify** - *(optional)* Either `True` to use an SSL context with the
default CA bundle, `False` to disable verification, or an instance of
`ssl.SSLContext` to use a custom context.
* **http2** - *(optional)* A boolean indicating if HTTP/2 support should be
enabled. Defaults to `False`.
* **proxy** - *(optional)* A proxy URL where all the traffic should be routed.
* **timeout** - *(optional)* The timeout configuration to use when sending
requests.
* **limits** - *(optional)* The limits configuration to use.
* **max_redirects** - *(optional)* The maximum number of redirect responses
that should be followed.
* **base_url** - *(optional)* A URL to use as the base when building
request URLs.
* **transport** - *(optional)* A transport class to use for sending requests
over the network.
* **trust_env** - *(optional)* Enables or disables usage of environment
variables for configuration.
* **default_encoding** - *(optional)* The default encoding to use for decoding
response text, if no charset information is included in a response Content-Type
header. Set to a callable for automatic character set detection. Default: "utf-8".
"""
def __init__(
self,
*,
auth: AuthTypes | None = None,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
verify: ssl.SSLContext | str | bool = True,
cert: CertTypes | None = None,
http1: bool = True,
http2: bool = False,
proxy: ProxyTypes | None = None,
mounts: None | (typing.Mapping[str, AsyncBaseTransport | None]) = None,
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
follow_redirects: bool = False,
limits: Limits = DEFAULT_LIMITS,
max_redirects: int = DEFAULT_MAX_REDIRECTS,
event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None,
base_url: URL | str = "",
transport: AsyncBaseTransport | None = None,
trust_env: bool = True,
default_encoding: str | typing.Callable[[bytes], str] = "utf-8",
) -> None:
super().__init__(
auth=auth,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
follow_redirects=follow_redirects,
max_redirects=max_redirects,
event_hooks=event_hooks,
base_url=base_url,
trust_env=trust_env,
default_encoding=default_encoding,
)
if http2:
try:
import h2 # noqa
except ImportError: # pragma: no cover
raise ImportError(
"Using http2=True, but the 'h2' package is not installed. "
"Make sure to install httpx using `pip install httpx[http2]`."
) from None
allow_env_proxies = trust_env and transport is None
proxy_map = self._get_proxy_map(proxy, allow_env_proxies)
self._transport = self._init_transport(
verify=verify,
cert=cert,
trust_env=trust_env,
http1=http1,
http2=http2,
limits=limits,
transport=transport,
)
self._mounts: dict[URLPattern, AsyncBaseTransport | None] = {
URLPattern(key): None
if proxy is None
else self._init_proxy_transport(
proxy,
verify=verify,
cert=cert,
trust_env=trust_env,
http1=http1,
http2=http2,
limits=limits,
)
for key, proxy in proxy_map.items()
}
if mounts is not None:
self._mounts.update(
{URLPattern(key): transport for key, transport in mounts.items()}
)
self._mounts = dict(sorted(self._mounts.items()))
def _init_transport(
self,
verify: ssl.SSLContext | str | bool = True,
cert: CertTypes | None = None,
trust_env: bool = True,
http1: bool = True,
http2: bool = False,
limits: Limits = DEFAULT_LIMITS,
transport: AsyncBaseTransport | None = None,
) -> AsyncBaseTransport:
if transport is not None:
return transport
return AsyncHTTPTransport(
verify=verify,
cert=cert,
trust_env=trust_env,
http1=http1,
http2=http2,
limits=limits,
)
def _init_proxy_transport(
self,
proxy: Proxy,
verify: ssl.SSLContext | str | bool = True,
cert: CertTypes | None = None,
trust_env: bool = True,
http1: bool = True,
http2: bool = False,
limits: Limits = DEFAULT_LIMITS,
) -> AsyncBaseTransport:
return AsyncHTTPTransport(
verify=verify,
cert=cert,
trust_env=trust_env,
http1=http1,
http2=http2,
limits=limits,
proxy=proxy,
)
def _transport_for_url(self, url: URL) -> AsyncBaseTransport:
"""
Returns the transport instance that should be used for a given URL.
This will either be the standard connection pool, or a proxy.
"""
for pattern, transport in self._mounts.items():
if pattern.matches(url):
return self._transport if transport is None else transport
return self._transport
async def request(
self,
method: str,
url: URL | str,
*,
content: RequestContent | None = None,
data: RequestData | None = None,
files: RequestFiles | None = None,
json: typing.Any | None = None,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
extensions: RequestExtensions | None = None,
) -> Response:
"""
Build and send a request.
Equivalent to:
```python
request = client.build_request(...)
response = await client.send(request, ...)
```
See `AsyncClient.build_request()`, `AsyncClient.send()`
and [Merging of configuration][0] for how the various parameters
are merged with client-level configuration.
[0]: /advanced/clients/#merging-of-configuration
"""
if cookies is not None: # pragma: no cover
message = (
"Setting per-request cookies=<...> is being deprecated, because "
"the expected behaviour on cookie persistence is ambiguous. Set "
"cookies directly on the client instance instead."
)
warnings.warn(message, DeprecationWarning, stacklevel=2)
request = self.build_request(
method=method,
url=url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
extensions=extensions,
)
return await self.send(request, auth=auth, follow_redirects=follow_redirects)
@asynccontextmanager
async def stream(
self,
method: str,
url: URL | str,
*,
content: RequestContent | None = None,
data: RequestData | None = None,
files: RequestFiles | None = None,
json: typing.Any | None = None,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
extensions: RequestExtensions | None = None,
) -> typing.AsyncIterator[Response]:
"""
Alternative to `httpx.request()` that streams the response body
instead of loading it into memory at once.
**Parameters**: See `httpx.request`.
See also: [Streaming Responses][0]
[0]: /quickstart#streaming-responses
"""
request = self.build_request(
method=method,
url=url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
extensions=extensions,
)
response = await self.send(
request=request,
auth=auth,
follow_redirects=follow_redirects,
stream=True,
)
try:
yield response
finally:
await response.aclose()
async def send(
self,
request: Request,
*,
stream: bool = False,
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
) -> Response:
"""
Send a request.
The request is sent as-is, unmodified.
Typically you'll want to build one with `AsyncClient.build_request()`
so that any client-level configuration is merged into the request,
but passing an explicit `httpx.Request()` is supported as well.
See also: [Request instances][0]
[0]: /advanced/clients/#request-instances
"""
if self._state == ClientState.CLOSED:
raise RuntimeError("Cannot send a request, as the client has been closed.")
self._state = ClientState.OPENED
follow_redirects = (
self.follow_redirects
if isinstance(follow_redirects, UseClientDefault)
else follow_redirects
)
self._set_timeout(request)
auth = self._build_request_auth(request, auth)
response = await self._send_handling_auth(
request,
auth=auth,
follow_redirects=follow_redirects,
history=[],
)
try:
if not stream:
await response.aread()
return response
except BaseException as exc:
await response.aclose()
raise exc
async def _send_handling_auth(
self,
request: Request,
auth: Auth,
follow_redirects: bool,
history: list[Response],
) -> Response:
auth_flow = auth.async_auth_flow(request)
try:
request = await auth_flow.__anext__()
while True:
response = await self._send_handling_redirects(
request,
follow_redirects=follow_redirects,
history=history,
)
try:
try:
next_request = await auth_flow.asend(response)
except StopAsyncIteration:
return response
response.history = list(history)
await response.aread()
request = next_request
history.append(response)
except BaseException as exc:
await response.aclose()
raise exc
finally:
await auth_flow.aclose()
async def _send_handling_redirects(
self,
request: Request,
follow_redirects: bool,
history: list[Response],
) -> Response:
while True:
if len(history) > self.max_redirects:
raise TooManyRedirects(
"Exceeded maximum allowed redirects.", request=request
)
for hook in self._event_hooks["request"]:
await hook(request)
response = await self._send_single_request(request)
try:
for hook in self._event_hooks["response"]:
await hook(response)
response.history = list(history)
if not response.has_redirect_location:
return response
request = self._build_redirect_request(request, response)
history = history + [response]
if follow_redirects:
await response.aread()
else:
response.next_request = request
return response
except BaseException as exc:
await response.aclose()
raise exc
async def _send_single_request(self, request: Request) -> Response:
"""
Sends a single request, without handling any redirections.
"""
transport = self._transport_for_url(request.url)
start = time.perf_counter()
if not isinstance(request.stream, AsyncByteStream):
raise RuntimeError(
"Attempted to send a sync request with an AsyncClient instance."
)
with request_context(request=request):
response = await transport.handle_async_request(request)
assert isinstance(response.stream, AsyncByteStream)
response.request = request
response.stream = BoundAsyncStream(
response.stream, response=response, start=start
)
self.cookies.extract_cookies(response)
response.default_encoding = self._default_encoding
logger.info(
'HTTP Request: %s %s "%s %d %s"',
request.method,
request.url,
response.http_version,
response.status_code,
response.reason_phrase,
)
return response
async def get(
self,
url: URL | str,
*,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
extensions: RequestExtensions | None = None,
) -> Response:
"""
Send a `GET` request.
**Parameters**: See `httpx.request`.
"""
return await self.request(
"GET",
url,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
extensions=extensions,
)
async def options(
self,
url: URL | str,
*,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
extensions: RequestExtensions | None = None,
) -> Response:
"""
Send an `OPTIONS` request.
**Parameters**: See `httpx.request`.
"""
return await self.request(
"OPTIONS",
url,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
extensions=extensions,
)
async def head(
self,
url: URL | str,
*,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
extensions: RequestExtensions | None = None,
) -> Response:
"""
Send a `HEAD` request.
**Parameters**: See `httpx.request`.
"""
return await self.request(
"HEAD",
url,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
extensions=extensions,
)
async def post(
self,
url: URL | str,
*,
content: RequestContent | None = None,
data: RequestData | None = None,
files: RequestFiles | None = None,
json: typing.Any | None = None,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
extensions: RequestExtensions | None = None,
) -> Response:
"""
Send a `POST` request.
**Parameters**: See `httpx.request`.
"""
return await self.request(
"POST",
url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
extensions=extensions,
)
async def put(
self,
url: URL | str,
*,
content: RequestContent | None = None,
data: RequestData | None = None,
files: RequestFiles | None = None,
json: typing.Any | None = None,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
extensions: RequestExtensions | None = None,
) -> Response:
"""
Send a `PUT` request.
**Parameters**: See `httpx.request`.
"""
return await self.request(
"PUT",
url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
extensions=extensions,
)
async def patch(
self,
url: URL | str,
*,
content: RequestContent | None = None,
data: RequestData | None = None,
files: RequestFiles | None = None,
json: typing.Any | None = None,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
extensions: RequestExtensions | None = None,
) -> Response:
"""
Send a `PATCH` request.
**Parameters**: See `httpx.request`.
"""
return await self.request(
"PATCH",
url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
extensions=extensions,
)
async def delete(
self,
url: URL | str,
*,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
extensions: RequestExtensions | None = None,
) -> Response:
"""
Send a `DELETE` request.
**Parameters**: See `httpx.request`.
"""
return await self.request(
"DELETE",
url,
params=params,
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
timeout=timeout,
extensions=extensions,
)
async def aclose(self) -> None:
"""
Close transport and proxies.
"""
if self._state != ClientState.CLOSED:
self._state = ClientState.CLOSED
await self._transport.aclose()
for proxy in self._mounts.values():
if proxy is not None:
await proxy.aclose()
async def __aenter__(self: U) -> U:
if self._state != ClientState.UNOPENED:
msg = {
ClientState.OPENED: "Cannot open a client instance more than once.",
ClientState.CLOSED: (
"Cannot reopen a client instance, once it has been closed."
),
}[self._state]
raise RuntimeError(msg)
self._state = ClientState.OPENED
await self._transport.__aenter__()
for proxy in self._mounts.values():
if proxy is not None:
await proxy.__aenter__()
return self
async def __aexit__(
self,
exc_type: type[BaseException] | None = None,
exc_value: BaseException | None = None,
traceback: TracebackType | None = None,
) -> None:
self._state = ClientState.CLOSED
await self._transport.__aexit__(exc_type, exc_value, traceback)
for proxy in self._mounts.values():
if proxy is not None:
await proxy.__aexit__(exc_type, exc_value, traceback)
| from __future__ import annotations
import typing
from datetime import timedelta
import chardet
import pytest
import httpx
def autodetect(content):
return chardet.detect(content).get("encoding")
def test_get(server):
url = server.url
with httpx.Client(http2=True) as http:
response = http.get(url)
assert response.status_code == 200
assert response.url == url
assert response.content == b"Hello, world!"
assert response.text == "Hello, world!"
assert response.http_version == "HTTP/1.1"
assert response.encoding == "utf-8"
assert response.request.url == url
assert response.headers
assert response.is_redirect is False
assert repr(response) == "<Response [200 OK]>"
assert response.elapsed > timedelta(0)
@pytest.mark.parametrize(
"url",
[
pytest.param("invalid://example.org", id="scheme-not-http(s)"),
pytest.param("://example.org", id="no-scheme"),
pytest.param("http://", id="no-host"),
],
)
def test_get_invalid_url(server, url):
with httpx.Client() as client:
with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)):
client.get(url)
def test_build_request(server):
url = server.url.copy_with(path="/echo_headers")
headers = {"Custom-header": "value"}
with httpx.Client() as client:
request = client.build_request("GET", url)
request.headers.update(headers)
response = client.send(request)
assert response.status_code == 200
assert response.url == url
assert response.json()["Custom-header"] == "value"
def test_build_post_request(server):
url = server.url.copy_with(path="/echo_headers")
headers = {"Custom-header": "value"}
with httpx.Client() as client:
request = client.build_request("POST", url)
request.headers.update(headers)
response = client.send(request)
assert response.status_code == 200
assert response.url == url
assert response.json()["Content-length"] == "0"
assert response.json()["Custom-header"] == "value"
def test_post(server):
with httpx.Client() as client:
response = client.post(server.url, content=b"Hello, world!")
assert response.status_code == 200
assert response.reason_phrase == "OK"
def test_post_json(server):
with httpx.Client() as client:
response = client.post(server.url, json={"text": "Hello, world!"})
assert response.status_code == 200
assert response.reason_phrase == "OK"
def test_stream_response(server):
with httpx.Client() as client:
with client.stream("GET", server.url) as response:
content = response.read()
assert response.status_code == 200
assert content == b"Hello, world!"
def test_stream_iterator(server):
body = b""
with httpx.Client() as client:
with client.stream("GET", server.url) as response:
for chunk in response.iter_bytes():
body += chunk
assert response.status_code == 200
assert body == b"Hello, world!"
def test_raw_iterator(server):
body = b""
with httpx.Client() as client:
with client.stream("GET", server.url) as response:
for chunk in response.iter_raw():
body += chunk
assert response.status_code == 200
assert body == b"Hello, world!"
def test_cannot_stream_async_request(server):
async def hello_world() -> typing.AsyncIterator[bytes]: # pragma: no cover
yield b"Hello, "
yield b"world!"
with httpx.Client() as client:
with pytest.raises(RuntimeError):
client.post(server.url, content=hello_world())
def test_raise_for_status(server):
with httpx.Client() as client:
for status_code in (200, 400, 404, 500, 505):
response = client.request(
"GET", server.url.copy_with(path=f"/status/{status_code}")
)
if 400 <= status_code < 600:
with pytest.raises(httpx.HTTPStatusError) as exc_info:
response.raise_for_status()
assert exc_info.value.response == response
assert exc_info.value.request.url.path == f"/status/{status_code}"
else:
assert response.raise_for_status() is response
def test_options(server):
with httpx.Client() as client:
response = client.options(server.url)
assert response.status_code == 200
assert response.reason_phrase == "OK"
def test_head(server):
with httpx.Client() as client:
response = client.head(server.url)
assert response.status_code == 200
assert response.reason_phrase == "OK"
def test_put(server):
with httpx.Client() as client:
response = client.put(server.url, content=b"Hello, world!")
assert response.status_code == 200
assert response.reason_phrase == "OK"
def test_patch(server):
with httpx.Client() as client:
response = client.patch(server.url, content=b"Hello, world!")
assert response.status_code == 200
assert response.reason_phrase == "OK"
def test_delete(server):
with httpx.Client() as client:
response = client.delete(server.url)
assert response.status_code == 200
assert response.reason_phrase == "OK"
def test_base_url(server):
base_url = server.url
with httpx.Client(base_url=base_url) as client:
response = client.get("/")
assert response.status_code == 200
assert response.url == base_url
def test_merge_absolute_url():
client = httpx.Client(base_url="https://www.example.com/")
request = client.build_request("GET", "http://www.example.com/")
assert request.url == "http://www.example.com/"
def test_merge_relative_url():
client = httpx.Client(base_url="https://www.example.com/")
request = client.build_request("GET", "/testing/123")
assert request.url == "https://www.example.com/testing/123"
def test_merge_relative_url_with_path():
client = httpx.Client(base_url="https://www.example.com/some/path")
request = client.build_request("GET", "/testing/123")
assert request.url == "https://www.example.com/some/path/testing/123"
def test_merge_relative_url_with_dotted_path():
client = httpx.Client(base_url="https://www.example.com/some/path")
request = client.build_request("GET", "../testing/123")
assert request.url == "https://www.example.com/some/testing/123"
def test_merge_relative_url_with_path_including_colon():
client = httpx.Client(base_url="https://www.example.com/some/path")
request = client.build_request("GET", "/testing:123")
assert request.url == "https://www.example.com/some/path/testing:123"
def test_merge_relative_url_with_encoded_slashes():
client = httpx.Client(base_url="https://www.example.com/")
request = client.build_request("GET", "/testing%2F123")
assert request.url == "https://www.example.com/testing%2F123"
client = httpx.Client(base_url="https://www.example.com/base%2Fpath")
request = client.build_request("GET", "/testing")
assert request.url == "https://www.example.com/base%2Fpath/testing"
def test_context_managed_transport():
class Transport(httpx.BaseTransport):
def __init__(self) -> None:
self.events: list[str] = []
def close(self):
# The base implementation of httpx.BaseTransport just
# calls into `.close`, so simple transport cases can just override
# this method for any cleanup, where more complex cases
# might want to additionally override `__enter__`/`__exit__`.
self.events.append("transport.close")
def __enter__(self):
super().__enter__()
self.events.append("transport.__enter__")
def __exit__(self, *args):
super().__exit__(*args)
self.events.append("transport.__exit__")
transport = Transport()
with httpx.Client(transport=transport):
pass
assert transport.events == [
"transport.__enter__",
"transport.close",
"transport.__exit__",
]
def test_context_managed_transport_and_mount():
class Transport(httpx.BaseTransport):
def __init__(self, name: str) -> None:
self.name: str = name
self.events: list[str] = []
def close(self):
# The base implementation of httpx.BaseTransport just
# calls into `.close`, so simple transport cases can just override
# this method for any cleanup, where more complex cases
# might want to additionally override `__enter__`/`__exit__`.
self.events.append(f"{self.name}.close")
def __enter__(self):
super().__enter__()
self.events.append(f"{self.name}.__enter__")
def __exit__(self, *args):
super().__exit__(*args)
self.events.append(f"{self.name}.__exit__")
transport = Transport(name="transport")
mounted = Transport(name="mounted")
with httpx.Client(transport=transport, mounts={"http://www.example.org": mounted}):
pass
assert transport.events == [
"transport.__enter__",
"transport.close",
"transport.__exit__",
]
assert mounted.events == [
"mounted.__enter__",
"mounted.close",
"mounted.__exit__",
]
def hello_world(request):
return httpx.Response(200, text="Hello, world!")
def test_client_closed_state_using_implicit_open():
client = httpx.Client(transport=httpx.MockTransport(hello_world))
assert not client.is_closed
client.get("http://example.com")
assert not client.is_closed
client.close()
assert client.is_closed
# Once we're close we cannot make any more requests.
with pytest.raises(RuntimeError):
client.get("http://example.com")
# Once we're closed we cannot reopen the client.
with pytest.raises(RuntimeError):
with client:
pass # pragma: no cover
def test_client_closed_state_using_with_block():
with httpx.Client(transport=httpx.MockTransport(hello_world)) as client:
assert not client.is_closed
client.get("http://example.com")
assert client.is_closed
with pytest.raises(RuntimeError):
client.get("http://example.com")
def echo_raw_headers(request: httpx.Request) -> httpx.Response:
data = [
(name.decode("ascii"), value.decode("ascii"))
for name, value in request.headers.raw
]
return httpx.Response(200, json=data)
def test_raw_client_header():
"""
Set a header in the Client.
"""
url = "http://example.org/echo_headers"
headers = {"Example-Header": "example-value"}
client = httpx.Client(
transport=httpx.MockTransport(echo_raw_headers), headers=headers
)
response = client.get(url)
assert response.status_code == 200
assert response.json() == [
["Host", "example.org"],
["Accept", "*/*"],
["Accept-Encoding", "gzip, deflate, br, zstd"],
["Connection", "keep-alive"],
["User-Agent", f"python-httpx/{httpx.__version__}"],
["Example-Header", "example-value"],
]
def unmounted(request: httpx.Request) -> httpx.Response:
data = {"app": "unmounted"}
return httpx.Response(200, json=data)
def mounted(request: httpx.Request) -> httpx.Response:
data = {"app": "mounted"}
return httpx.Response(200, json=data)
def test_mounted_transport():
transport = httpx.MockTransport(unmounted)
mounts = {"custom://": httpx.MockTransport(mounted)}
client = httpx.Client(transport=transport, mounts=mounts)
response = client.get("https://www.example.com")
assert response.status_code == 200
assert response.json() == {"app": "unmounted"}
response = client.get("custom://www.example.com")
assert response.status_code == 200
assert response.json() == {"app": "mounted"}
def test_all_mounted_transport():
mounts = {"all://": httpx.MockTransport(mounted)}
client = httpx.Client(mounts=mounts)
response = client.get("https://www.example.com")
assert response.status_code == 200
assert response.json() == {"app": "mounted"}
def test_server_extensions(server):
url = server.url.copy_with(path="/http_version_2")
with httpx.Client(http2=True) as client:
response = client.get(url)
assert response.status_code == 200
assert response.extensions["http_version"] == b"HTTP/1.1"
def test_client_decode_text_using_autodetect():
# Ensure that a 'default_encoding=autodetect' on the response allows for
# encoding autodetection to be used when no "Content-Type: text/plain; charset=..."
# info is present.
#
# Here we have some french text encoded with ISO-8859-1, rather than UTF-8.
text = (
"Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains "
"que la France a produits, sans excepter Voltaire lui-même, imprégné de "
"l'esprit anglais par son séjour à Londres, c'est incontestablement "
"Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la "
"plus complète le fond du génie français."
)
def cp1252_but_no_content_type(request):
content = text.encode("ISO-8859-1")
return httpx.Response(200, content=content)
transport = httpx.MockTransport(cp1252_but_no_content_type)
with httpx.Client(transport=transport, default_encoding=autodetect) as client:
response = client.get("http://www.example.com")
assert response.status_code == 200
assert response.reason_phrase == "OK"
assert response.encoding == "ISO-8859-1"
assert response.text == text
def test_client_decode_text_using_explicit_encoding():
# Ensure that a 'default_encoding="..."' on the response is used for text decoding
# when no "Content-Type: text/plain; charset=..."" info is present.
#
# Here we have some french text encoded with ISO-8859-1, rather than UTF-8.
text = (
"Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains "
"que la France a produits, sans excepter Voltaire lui-même, imprégné de "
"l'esprit anglais par son séjour à Londres, c'est incontestablement "
"Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la "
"plus complète le fond du génie français."
)
def cp1252_but_no_content_type(request):
content = text.encode("ISO-8859-1")
return httpx.Response(200, content=content)
transport = httpx.MockTransport(cp1252_but_no_content_type)
with httpx.Client(transport=transport, default_encoding=autodetect) as client:
response = client.get("http://www.example.com")
assert response.status_code == 200
assert response.reason_phrase == "OK"
assert response.encoding == "ISO-8859-1"
assert response.text == text
| httpx |
python | import asyncio
import sys
import zlib
from concurrent.futures import Executor
from typing import Any, Final, Protocol, TypedDict, cast
if sys.version_info >= (3, 12):
from collections.abc import Buffer
else:
from typing import Union
Buffer = Union[bytes, bytearray, "memoryview[int]", "memoryview[bytes]"]
try:
try:
import brotlicffi as brotli
except ImportError:
import brotli
HAS_BROTLI = True
except ImportError:
HAS_BROTLI = False
try:
if sys.version_info >= (3, 14):
from compression.zstd import ZstdDecompressor # noqa: I900
else: # TODO(PY314): Remove mentions of backports.zstd across codebase
from backports.zstd import ZstdDecompressor
HAS_ZSTD = True
except ImportError:
HAS_ZSTD = False
MAX_SYNC_CHUNK_SIZE = 1024
class ZLibCompressObjProtocol(Protocol):
def compress(self, data: Buffer) -> bytes: ...
def flush(self, mode: int = ..., /) -> bytes: ...
class ZLibDecompressObjProtocol(Protocol):
def decompress(self, data: Buffer, max_length: int = ...) -> bytes: ...
def flush(self, length: int = ..., /) -> bytes: ...
@property
def eof(self) -> bool: ...
class ZLibBackendProtocol(Protocol):
MAX_WBITS: int
Z_FULL_FLUSH: int
Z_SYNC_FLUSH: int
Z_BEST_SPEED: int
Z_FINISH: int
def compressobj(
self,
level: int = ...,
method: int = ...,
wbits: int = ...,
memLevel: int = ...,
strategy: int = ...,
zdict: Buffer | None = ...,
) -> ZLibCompressObjProtocol: ...
def decompressobj(
self, wbits: int = ..., zdict: Buffer = ...
) -> ZLibDecompressObjProtocol: ...
def compress(
self, data: Buffer, /, level: int = ..., wbits: int = ...
) -> bytes: ...
def decompress(
self, data: Buffer, /, wbits: int = ..., bufsize: int = ...
) -> bytes: ...
class CompressObjArgs(TypedDict, total=False):
wbits: int
strategy: int
level: int
class ZLibBackendWrapper:
def __init__(self, _zlib_backend: ZLibBackendProtocol):
self._zlib_backend: ZLibBackendProtocol = _zlib_backend
@property
def name(self) -> str:
return getattr(self._zlib_backend, "__name__", "undefined")
@property
def MAX_WBITS(self) -> int:
return self._zlib_backend.MAX_WBITS
@property
def Z_FULL_FLUSH(self) -> int:
return self._zlib_backend.Z_FULL_FLUSH
@property
def Z_SYNC_FLUSH(self) -> int:
return self._zlib_backend.Z_SYNC_FLUSH
@property
def Z_BEST_SPEED(self) -> int:
return self._zlib_backend.Z_BEST_SPEED
@property
def Z_FINISH(self) -> int:
return self._zlib_backend.Z_FINISH
def compressobj(self, *args: Any, **kwargs: Any) -> ZLibCompressObjProtocol:
return self._zlib_backend.compressobj(*args, **kwargs)
def decompressobj(self, *args: Any, **kwargs: Any) -> ZLibDecompressObjProtocol:
return self._zlib_backend.decompressobj(*args, **kwargs)
def compress(self, data: Buffer, *args: Any, **kwargs: Any) -> bytes:
return self._zlib_backend.compress(data, *args, **kwargs)
def decompress(self, data: Buffer, *args: Any, **kwargs: Any) -> bytes:
return self._zlib_backend.decompress(data, *args, **kwargs)
# Everything not explicitly listed in the Protocol we just pass through
def __getattr__(self, attrname: str) -> Any:
return getattr(self._zlib_backend, attrname)
ZLibBackend: ZLibBackendWrapper = ZLibBackendWrapper(zlib)
def set_zlib_backend(new_zlib_backend: ZLibBackendProtocol) -> None:
ZLibBackend._zlib_backend = new_zlib_backend
def encoding_to_mode(
encoding: str | None = None,
suppress_deflate_header: bool = False,
) -> int:
if encoding == "gzip":
return 16 + ZLibBackend.MAX_WBITS
return -ZLibBackend.MAX_WBITS if suppress_deflate_header else ZLibBackend.MAX_WBITS
class ZlibBaseHandler:
def __init__(
self,
mode: int,
executor: Executor | None = None,
max_sync_chunk_size: int | None = MAX_SYNC_CHUNK_SIZE,
):
self._mode = mode
self._executor = executor
self._max_sync_chunk_size = max_sync_chunk_size
class ZLibCompressor(ZlibBaseHandler):
def __init__(
self,
encoding: str | None = None,
suppress_deflate_header: bool = False,
level: int | None = None,
wbits: int | None = None,
strategy: int | None = None,
executor: Executor | None = None,
max_sync_chunk_size: int | None = MAX_SYNC_CHUNK_SIZE,
):
super().__init__(
mode=(
encoding_to_mode(encoding, suppress_deflate_header)
if wbits is None
else wbits
),
executor=executor,
max_sync_chunk_size=max_sync_chunk_size,
)
self._zlib_backend: Final = ZLibBackendWrapper(ZLibBackend._zlib_backend)
kwargs: CompressObjArgs = {}
kwargs["wbits"] = self._mode
if strategy is not None:
kwargs["strategy"] = strategy
if level is not None:
kwargs["level"] = level
self._compressor = self._zlib_backend.compressobj(**kwargs)
def compress_sync(self, data: Buffer) -> bytes:
return self._compressor.compress(data)
async def compress(self, data: Buffer) -> bytes:
"""Compress the data and returned the compressed bytes.
Note that flush() must be called after the last call to compress()
If the data size is large than the max_sync_chunk_size, the compression
will be done in the executor. Otherwise, the compression will be done
in the event loop.
**WARNING: This method is NOT cancellation-safe when used with flush().**
If this operation is cancelled, the compressor state may be corrupted.
The connection MUST be closed after cancellation to avoid data corruption
in subsequent compress operations.
For cancellation-safe compression (e.g., WebSocket), the caller MUST wrap
compress() + flush() + send operations in a shield and lock to ensure atomicity.
"""
# For large payloads, offload compression to executor to avoid blocking event loop
should_use_executor = (
self._max_sync_chunk_size is not None
and len(data) > self._max_sync_chunk_size
)
if should_use_executor:
return await asyncio.get_running_loop().run_in_executor(
self._executor, self._compressor.compress, data
)
return self.compress_sync(data)
def flush(self, mode: int | None = None) -> bytes:
"""Flush the compressor synchronously.
**WARNING: This method is NOT cancellation-safe when called after compress().**
The flush() operation accesses shared compressor state. If compress() was
cancelled, calling flush() may result in corrupted data. The connection MUST
be closed after compress() cancellation.
For cancellation-safe compression (e.g., WebSocket), the caller MUST wrap
compress() + flush() + send operations in a shield and lock to ensure atomicity.
"""
return self._compressor.flush(
mode if mode is not None else self._zlib_backend.Z_FINISH
)
class ZLibDecompressor(ZlibBaseHandler):
def __init__(
self,
encoding: str | None = None,
suppress_deflate_header: bool = False,
executor: Executor | None = None,
max_sync_chunk_size: int | None = MAX_SYNC_CHUNK_SIZE,
):
super().__init__(
mode=encoding_to_mode(encoding, suppress_deflate_header),
executor=executor,
max_sync_chunk_size=max_sync_chunk_size,
)
self._zlib_backend: Final = ZLibBackendWrapper(ZLibBackend._zlib_backend)
self._decompressor = self._zlib_backend.decompressobj(wbits=self._mode)
def decompress_sync(self, data: Buffer, max_length: int = 0) -> bytes:
return self._decompressor.decompress(data, max_length)
async def decompress(self, data: Buffer, max_length: int = 0) -> bytes:
"""Decompress the data and return the decompressed bytes.
If the data size is large than the max_sync_chunk_size, the decompression
will be done in the executor. Otherwise, the decompression will be done
in the event loop.
"""
if (
self._max_sync_chunk_size is not None
and len(data) > self._max_sync_chunk_size
):
return await asyncio.get_running_loop().run_in_executor(
self._executor, self._decompressor.decompress, data, max_length
)
return self.decompress_sync(data, max_length)
def flush(self, length: int = 0) -> bytes:
return (
self._decompressor.flush(length)
if length > 0
else self._decompressor.flush()
)
@property
def eof(self) -> bool:
return self._decompressor.eof
class BrotliDecompressor:
# Supports both 'brotlipy' and 'Brotli' packages
# since they share an import name. The top branches
# are for 'brotlipy' and bottom branches for 'Brotli'
def __init__(self) -> None:
if not HAS_BROTLI:
raise RuntimeError(
"The brotli decompression is not available. "
"Please install `Brotli` module"
)
self._obj = brotli.Decompressor()
def decompress_sync(self, data: Buffer) -> bytes:
if hasattr(self._obj, "decompress"):
return cast(bytes, self._obj.decompress(data))
return cast(bytes, self._obj.process(data))
def flush(self) -> bytes:
if hasattr(self._obj, "flush"):
return cast(bytes, self._obj.flush())
return b""
class ZSTDDecompressor:
def __init__(self) -> None:
if not HAS_ZSTD:
raise RuntimeError(
"The zstd decompression is not available. "
"Please install `backports.zstd` module"
)
self._obj = ZstdDecompressor()
def decompress_sync(self, data: bytes) -> bytes:
return self._obj.decompress(data)
def flush(self) -> bytes:
return b""
| """Utilities shared by tests."""
import asyncio
import contextlib
import gc
import ipaddress
import os
import socket
import sys
from abc import ABC, abstractmethod
from collections.abc import Callable, Iterator
from types import TracebackType
from typing import TYPE_CHECKING, Any, Generic, TypeVar, cast, overload
from unittest import IsolatedAsyncioTestCase, mock
from aiosignal import Signal
from multidict import CIMultiDict, CIMultiDictProxy
from yarl import URL
import aiohttp
from aiohttp.client import (
_RequestContextManager,
_RequestOptions,
_WSRequestContextManager,
)
from . import ClientSession, hdrs
from .abc import AbstractCookieJar, AbstractStreamWriter
from .client_reqrep import ClientResponse
from .client_ws import ClientWebSocketResponse
from .http import HttpVersion, RawRequestMessage
from .streams import EMPTY_PAYLOAD, StreamReader
from .typedefs import LooseHeaders, StrOrURL
from .web import (
Application,
AppRunner,
BaseRequest,
BaseRunner,
Request,
RequestHandler,
Server,
ServerRunner,
SockSite,
UrlMappingMatchInfo,
)
from .web_protocol import _RequestHandler
if TYPE_CHECKING:
from ssl import SSLContext
else:
SSLContext = Any
if sys.version_info >= (3, 11) and TYPE_CHECKING:
from typing import Unpack
if sys.version_info >= (3, 11):
from typing import Self
else:
Self = Any
_ApplicationNone = TypeVar("_ApplicationNone", Application, None)
_Request = TypeVar("_Request", bound=BaseRequest)
REUSE_ADDRESS = os.name == "posix" and sys.platform != "cygwin"
def get_unused_port_socket(
host: str, family: socket.AddressFamily = socket.AF_INET
) -> socket.socket:
return get_port_socket(host, 0, family)
def get_port_socket(
host: str, port: int, family: socket.AddressFamily = socket.AF_INET
) -> socket.socket:
s = socket.socket(family, socket.SOCK_STREAM)
if REUSE_ADDRESS:
# Windows has different semantics for SO_REUSEADDR,
# so don't set it. Ref:
# https://docs.microsoft.com/en-us/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
return s
def unused_port() -> int:
"""Return a port that is unused on the current host."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("127.0.0.1", 0))
return cast(int, s.getsockname()[1])
class BaseTestServer(ABC, Generic[_Request]):
__test__ = False
def __init__(
self,
*,
scheme: str = "",
host: str = "127.0.0.1",
port: int | None = None,
skip_url_asserts: bool = False,
socket_factory: Callable[
[str, int, socket.AddressFamily], socket.socket
] = get_port_socket,
**kwargs: Any,
) -> None:
self.runner: BaseRunner[_Request] | None = None
self._root: URL | None = None
self.host = host
self.port = port or 0
self._closed = False
self.scheme = scheme
self.skip_url_asserts = skip_url_asserts
self.socket_factory = socket_factory
async def start_server(self, **kwargs: Any) -> None:
if self.runner:
return
self._ssl = kwargs.pop("ssl", None)
self.runner = await self._make_runner(handler_cancellation=True, **kwargs)
await self.runner.setup()
absolute_host = self.host
try:
version = ipaddress.ip_address(self.host).version
except ValueError:
version = 4
if version == 6:
absolute_host = f"[{self.host}]"
family = socket.AF_INET6 if version == 6 else socket.AF_INET
_sock = self.socket_factory(self.host, self.port, family)
self.host, self.port = _sock.getsockname()[:2]
site = SockSite(self.runner, sock=_sock, ssl_context=self._ssl)
await site.start()
server = site._server
assert server is not None
sockets = server.sockets
assert sockets is not None
self.port = sockets[0].getsockname()[1]
if not self.scheme:
self.scheme = "https" if self._ssl else "http"
self._root = URL(f"{self.scheme}://{absolute_host}:{self.port}")
@abstractmethod
async def _make_runner(self, **kwargs: Any) -> BaseRunner[_Request]:
"""Return a new runner for the server."""
# TODO(PY311): Use Unpack to specify Server kwargs.
def make_url(self, path: StrOrURL) -> URL:
assert self._root is not None
url = URL(path)
if not self.skip_url_asserts:
assert not url.absolute
return self._root.join(url)
else:
return URL(str(self._root) + str(path))
@property
def started(self) -> bool:
return self.runner is not None
@property
def closed(self) -> bool:
return self._closed
@property
def handler(self) -> Server[_Request]:
# for backward compatibility
# web.Server instance
runner = self.runner
assert runner is not None
assert runner.server is not None
return runner.server
async def close(self) -> None:
"""Close all fixtures created by the test client.
After that point, the TestClient is no longer usable.
This is an idempotent function: running close multiple times
will not have any additional effects.
close is also run when the object is garbage collected, and on
exit when used as a context manager.
"""
if self.started and not self.closed:
assert self.runner is not None
await self.runner.cleanup()
self._root = None
self.port = 0
self._closed = True
async def __aenter__(self) -> Self:
await self.start_server()
return self
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
traceback: TracebackType | None,
) -> None:
await self.close()
class TestServer(BaseTestServer[Request]):
def __init__(
self,
app: Application,
*,
scheme: str = "",
host: str = "127.0.0.1",
port: int | None = None,
**kwargs: Any,
):
self.app = app
super().__init__(scheme=scheme, host=host, port=port, **kwargs)
async def _make_runner(self, **kwargs: Any) -> AppRunner:
# TODO(PY311): Use Unpack to specify Server kwargs.
return AppRunner(self.app, **kwargs)
class RawTestServer(BaseTestServer[BaseRequest]):
def __init__(
self,
handler: _RequestHandler[BaseRequest],
*,
scheme: str = "",
host: str = "127.0.0.1",
port: int | None = None,
**kwargs: Any,
) -> None:
self._handler = handler
super().__init__(scheme=scheme, host=host, port=port, **kwargs)
async def _make_runner(self, **kwargs: Any) -> ServerRunner:
# TODO(PY311): Use Unpack to specify Server kwargs.
srv = Server(self._handler, **kwargs)
return ServerRunner(srv, **kwargs)
class TestClient(Generic[_Request, _ApplicationNone]):
"""
A test client implementation.
To write functional tests for aiohttp based servers.
"""
__test__ = False
@overload
def __init__(
self: "TestClient[Request, Application]",
server: TestServer,
*,
cookie_jar: AbstractCookieJar | None = None,
**kwargs: Any,
) -> None: ...
@overload
def __init__(
self: "TestClient[_Request, None]",
server: BaseTestServer[_Request],
*,
cookie_jar: AbstractCookieJar | None = None,
**kwargs: Any,
) -> None: ...
def __init__( # type: ignore[misc]
self,
server: BaseTestServer[_Request],
*,
cookie_jar: AbstractCookieJar | None = None,
**kwargs: Any,
) -> None:
# TODO(PY311): Use Unpack to specify ClientSession kwargs.
if not isinstance(server, BaseTestServer):
raise TypeError(
"server must be TestServer instance, found type: %r" % type(server)
)
self._server = server
if cookie_jar is None:
cookie_jar = aiohttp.CookieJar(unsafe=True)
self._session = ClientSession(cookie_jar=cookie_jar, **kwargs)
self._session._retry_connection = False
self._closed = False
self._responses: list[ClientResponse] = []
self._websockets: list[ClientWebSocketResponse] = []
async def start_server(self) -> None:
await self._server.start_server()
@property
def scheme(self) -> str | object:
return self._server.scheme
@property
def host(self) -> str:
return self._server.host
@property
def port(self) -> int:
return self._server.port
@property
def server(self) -> BaseTestServer[_Request]:
return self._server
@property
def app(self) -> _ApplicationNone:
return getattr(self._server, "app", None) # type: ignore[return-value]
@property
def session(self) -> ClientSession:
"""An internal aiohttp.ClientSession.
Unlike the methods on the TestClient, client session requests
do not automatically include the host in the url queried, and
will require an absolute path to the resource.
"""
return self._session
def make_url(self, path: StrOrURL) -> URL:
return self._server.make_url(path)
async def _request(
self, method: str, path: StrOrURL, **kwargs: Any
) -> ClientResponse:
resp = await self._session.request(method, self.make_url(path), **kwargs)
# save it to close later
self._responses.append(resp)
return resp
if sys.version_info >= (3, 11) and TYPE_CHECKING:
def request(
self, method: str, path: StrOrURL, **kwargs: Unpack[_RequestOptions]
) -> _RequestContextManager: ...
def get(
self,
path: StrOrURL,
**kwargs: Unpack[_RequestOptions],
) -> _RequestContextManager: ...
def options(
self,
path: StrOrURL,
**kwargs: Unpack[_RequestOptions],
) -> _RequestContextManager: ...
def head(
self,
path: StrOrURL,
**kwargs: Unpack[_RequestOptions],
) -> _RequestContextManager: ...
def post(
self,
path: StrOrURL,
**kwargs: Unpack[_RequestOptions],
) -> _RequestContextManager: ...
def put(
self,
path: StrOrURL,
**kwargs: Unpack[_RequestOptions],
) -> _RequestContextManager: ...
def patch(
self,
path: StrOrURL,
**kwargs: Unpack[_RequestOptions],
) -> _RequestContextManager: ...
def delete(
self,
path: StrOrURL,
**kwargs: Unpack[_RequestOptions],
) -> _RequestContextManager: ...
else:
def request(
self, method: str, path: StrOrURL, **kwargs: Any
) -> _RequestContextManager:
"""Routes a request to tested http server.
The interface is identical to aiohttp.ClientSession.request,
except the loop kwarg is overridden by the instance used by the
test server.
"""
return _RequestContextManager(self._request(method, path, **kwargs))
def get(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager:
"""Perform an HTTP GET request."""
return _RequestContextManager(self._request(hdrs.METH_GET, path, **kwargs))
def post(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager:
"""Perform an HTTP POST request."""
return _RequestContextManager(self._request(hdrs.METH_POST, path, **kwargs))
def options(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager:
"""Perform an HTTP OPTIONS request."""
return _RequestContextManager(
self._request(hdrs.METH_OPTIONS, path, **kwargs)
)
def head(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager:
"""Perform an HTTP HEAD request."""
return _RequestContextManager(self._request(hdrs.METH_HEAD, path, **kwargs))
def put(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager:
"""Perform an HTTP PUT request."""
return _RequestContextManager(self._request(hdrs.METH_PUT, path, **kwargs))
def patch(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager:
"""Perform an HTTP PATCH request."""
return _RequestContextManager(
self._request(hdrs.METH_PATCH, path, **kwargs)
)
def delete(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager:
"""Perform an HTTP PATCH request."""
return _RequestContextManager(
self._request(hdrs.METH_DELETE, path, **kwargs)
)
def ws_connect(self, path: StrOrURL, **kwargs: Any) -> _WSRequestContextManager:
"""Initiate websocket connection.
The api corresponds to aiohttp.ClientSession.ws_connect.
"""
return _WSRequestContextManager(self._ws_connect(path, **kwargs))
async def _ws_connect(
self, path: StrOrURL, **kwargs: Any
) -> ClientWebSocketResponse:
ws = await self._session.ws_connect(self.make_url(path), **kwargs)
self._websockets.append(ws)
return ws
async def close(self) -> None:
"""Close all fixtures created by the test client.
After that point, the TestClient is no longer usable.
This is an idempotent function: running close multiple times
will not have any additional effects.
close is also run on exit when used as a(n) (asynchronous)
context manager.
"""
if not self._closed:
for resp in self._responses:
resp.close()
for ws in self._websockets:
await ws.close()
await self._session.close()
await self._server.close()
self._closed = True
async def __aenter__(self) -> Self:
await self.start_server()
return self
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> None:
await self.close()
class AioHTTPTestCase(IsolatedAsyncioTestCase, ABC):
"""A base class to allow for unittest web applications using aiohttp.
Provides the following:
* self.client (aiohttp.test_utils.TestClient): an aiohttp test client.
* self.app (aiohttp.web.Application): the application returned by
self.get_application()
Note that the TestClient's methods are asynchronous: you have to
execute function on the test client using asynchronous methods.
"""
@abstractmethod
async def get_application(self) -> Application:
"""Get application.
This method should be overridden to return the aiohttp.web.Application
object to test.
"""
async def asyncSetUp(self) -> None:
self.app = await self.get_application()
self.server = await self.get_server(self.app)
self.client = await self.get_client(self.server)
await self.client.start_server()
async def asyncTearDown(self) -> None:
await self.client.close()
async def get_server(self, app: Application) -> TestServer:
"""Return a TestServer instance."""
return TestServer(app)
async def get_client(self, server: TestServer) -> TestClient[Request, Application]:
"""Return a TestClient instance."""
return TestClient(server)
_LOOP_FACTORY = Callable[[], asyncio.AbstractEventLoop]
@contextlib.contextmanager
def loop_context(
loop_factory: _LOOP_FACTORY = asyncio.new_event_loop, fast: bool = False
) -> Iterator[asyncio.AbstractEventLoop]:
"""A contextmanager that creates an event_loop, for test purposes.
Handles the creation and cleanup of a test loop.
"""
loop = setup_test_loop(loop_factory)
yield loop
teardown_test_loop(loop, fast=fast)
def setup_test_loop(
loop_factory: _LOOP_FACTORY = asyncio.new_event_loop,
) -> asyncio.AbstractEventLoop:
"""Create and return an asyncio.BaseEventLoop instance.
The caller should also call teardown_test_loop,
once they are done with the loop.
"""
loop = loop_factory()
asyncio.set_event_loop(loop)
return loop
def teardown_test_loop(loop: asyncio.AbstractEventLoop, fast: bool = False) -> None:
"""Teardown and cleanup an event_loop created by setup_test_loop."""
closed = loop.is_closed()
if not closed:
loop.call_soon(loop.stop)
loop.run_forever()
loop.close()
if not fast:
gc.collect()
asyncio.set_event_loop(None)
def _create_app_mock() -> mock.MagicMock:
def get_dict(app: Any, key: str) -> Any:
return app.__app_dict[key]
def set_dict(app: Any, key: str, value: Any) -> None:
app.__app_dict[key] = value
app = mock.MagicMock(spec=Application)
app.__app_dict = {}
app.__getitem__ = get_dict
app.__setitem__ = set_dict
app.on_response_prepare = Signal(app)
app.on_response_prepare.freeze()
return app
def _create_transport(sslcontext: SSLContext | None = None) -> mock.Mock:
transport = mock.Mock()
def get_extra_info(key: str) -> SSLContext | None:
if key == "sslcontext":
return sslcontext
else:
return None
transport.get_extra_info.side_effect = get_extra_info
return transport
def make_mocked_request(
method: str,
path: str,
headers: LooseHeaders | None = None,
*,
match_info: dict[str, str] | None = None,
version: HttpVersion = HttpVersion(1, 1),
closing: bool = False,
app: Application | None = None,
writer: AbstractStreamWriter | None = None,
protocol: RequestHandler[Request] | None = None,
transport: asyncio.Transport | None = None,
payload: StreamReader = EMPTY_PAYLOAD,
sslcontext: SSLContext | None = None,
client_max_size: int = 1024**2,
loop: Any = ...,
) -> Request:
"""Creates mocked web.Request testing purposes.
Useful in unit tests, when spinning full web server is overkill or
specific conditions and errors are hard to trigger.
"""
task = mock.Mock()
if loop is ...:
# no loop passed, try to get the current one if
# its is running as we need a real loop to create
# executor jobs to be able to do testing
# with a real executor
try:
loop = asyncio.get_running_loop()
except RuntimeError:
loop = mock.Mock()
loop.create_future.return_value = ()
if version < HttpVersion(1, 1):
closing = True
if headers:
headers = CIMultiDictProxy(CIMultiDict(headers))
raw_hdrs = tuple(
(k.encode("utf-8"), v.encode("utf-8")) for k, v in headers.items()
)
else:
headers = CIMultiDictProxy(CIMultiDict())
raw_hdrs = ()
chunked = "chunked" in headers.get(hdrs.TRANSFER_ENCODING, "").lower()
message = RawRequestMessage(
method,
path,
version,
headers,
raw_hdrs,
closing,
None,
False,
chunked,
URL(path),
)
if app is None:
app = _create_app_mock()
if transport is None:
transport = _create_transport(sslcontext)
if protocol is None:
protocol = mock.Mock()
protocol.transport = transport
type(protocol).peername = mock.PropertyMock(
return_value=transport.get_extra_info("peername")
)
type(protocol).ssl_context = mock.PropertyMock(return_value=sslcontext)
if writer is None:
writer = mock.Mock()
writer.write_headers = mock.AsyncMock(return_value=None)
writer.write = mock.AsyncMock(return_value=None)
writer.write_eof = mock.AsyncMock(return_value=None)
writer.drain = mock.AsyncMock(return_value=None)
writer.transport = transport
protocol.transport = transport
req = Request(
message, payload, protocol, writer, task, loop, client_max_size=client_max_size
)
match_info = UrlMappingMatchInfo(
{} if match_info is None else match_info, mock.Mock()
)
match_info.add_app(app)
req._match_info = match_info
return req
| aiohttp |
python | import io
from collections.abc import Iterable
from typing import Any
from urllib.parse import urlencode
from multidict import MultiDict, MultiDictProxy
from . import hdrs, multipart, payload
from .helpers import guess_filename
from .payload import Payload
__all__ = ("FormData",)
class FormData:
"""Helper class for form body generation.
Supports multipart/form-data and application/x-www-form-urlencoded.
"""
def __init__(
self,
fields: Iterable[Any] = (),
quote_fields: bool = True,
charset: str | None = None,
boundary: str | None = None,
*,
default_to_multipart: bool = False,
) -> None:
self._boundary = boundary
self._writer = multipart.MultipartWriter("form-data", boundary=self._boundary)
self._fields: list[Any] = []
self._is_multipart = default_to_multipart
self._quote_fields = quote_fields
self._charset = charset
if isinstance(fields, dict):
fields = list(fields.items())
elif not isinstance(fields, (list, tuple)):
fields = (fields,)
self.add_fields(*fields)
@property
def is_multipart(self) -> bool:
return self._is_multipart
def add_field(
self,
name: str,
value: Any,
*,
content_type: str | None = None,
filename: str | None = None,
) -> None:
if isinstance(value, (io.IOBase, bytes, bytearray, memoryview)):
self._is_multipart = True
type_options: MultiDict[str] = MultiDict({"name": name})
if filename is not None and not isinstance(filename, str):
raise TypeError("filename must be an instance of str. Got: %s" % filename)
if filename is None and isinstance(value, io.IOBase):
filename = guess_filename(value, name)
if filename is not None:
type_options["filename"] = filename
self._is_multipart = True
headers = {}
if content_type is not None:
if not isinstance(content_type, str):
raise TypeError(
"content_type must be an instance of str. Got: %s" % content_type
)
headers[hdrs.CONTENT_TYPE] = content_type
self._is_multipart = True
self._fields.append((type_options, headers, value))
def add_fields(self, *fields: Any) -> None:
to_add = list(fields)
while to_add:
rec = to_add.pop(0)
if isinstance(rec, io.IOBase):
k = guess_filename(rec, "unknown")
self.add_field(k, rec) # type: ignore[arg-type]
elif isinstance(rec, (MultiDictProxy, MultiDict)):
to_add.extend(rec.items())
elif isinstance(rec, (list, tuple)) and len(rec) == 2:
k, fp = rec
self.add_field(k, fp)
else:
raise TypeError(
"Only io.IOBase, multidict and (name, file) "
"pairs allowed, use .add_field() for passing "
f"more complex parameters, got {rec!r}"
)
def _gen_form_urlencoded(self) -> payload.BytesPayload:
# form data (x-www-form-urlencoded)
data = []
for type_options, _, value in self._fields:
if not isinstance(value, str):
raise TypeError(f"expected str, got {value!r}")
data.append((type_options["name"], value))
charset = self._charset if self._charset is not None else "utf-8"
if charset == "utf-8":
content_type = "application/x-www-form-urlencoded"
else:
content_type = "application/x-www-form-urlencoded; charset=%s" % charset
return payload.BytesPayload(
urlencode(data, doseq=True, encoding=charset).encode(),
content_type=content_type,
)
def _gen_form_data(self) -> multipart.MultipartWriter:
"""Encode a list of fields using the multipart/form-data MIME format"""
for dispparams, headers, value in self._fields:
try:
if hdrs.CONTENT_TYPE in headers:
part = payload.get_payload(
value,
content_type=headers[hdrs.CONTENT_TYPE],
headers=headers,
encoding=self._charset,
)
else:
part = payload.get_payload(
value, headers=headers, encoding=self._charset
)
except Exception as exc:
raise TypeError(
"Can not serialize value type: %r\n "
"headers: %r\n value: %r" % (type(value), headers, value)
) from exc
if dispparams:
part.set_content_disposition(
"form-data", quote_fields=self._quote_fields, **dispparams
)
# FIXME cgi.FieldStorage doesn't likes body parts with
# Content-Length which were sent via chunked transfer encoding
assert part.headers is not None
part.headers.popall(hdrs.CONTENT_LENGTH, None)
self._writer.append_payload(part)
self._fields.clear()
return self._writer
def __call__(self) -> Payload:
if self._is_multipart:
return self._gen_form_data()
else:
return self._gen_form_urlencoded()
| import io
from unittest import mock
import pytest
from aiohttp import FormData, web
from aiohttp.http_writer import StreamWriter
from aiohttp.pytest_plugin import AiohttpClient
@pytest.fixture
def buf() -> bytearray:
return bytearray()
@pytest.fixture
def writer(buf: bytearray) -> StreamWriter:
writer = mock.create_autospec(StreamWriter, spec_set=True)
async def write(chunk: bytes) -> None:
buf.extend(chunk)
writer.write.side_effect = write
return writer # type: ignore[no-any-return]
def test_formdata_multipart(buf: bytearray) -> None:
form = FormData(default_to_multipart=False)
assert not form.is_multipart
form.add_field("test", b"test", filename="test.txt")
assert form.is_multipart
def test_form_data_is_multipart_param(buf: bytearray) -> None:
form = FormData(default_to_multipart=True)
assert form.is_multipart
form.add_field("test", "test")
assert form.is_multipart
@pytest.mark.parametrize("obj", (object(), None))
def test_invalid_formdata_payload_multipart(obj: object) -> None:
form = FormData()
form.add_field("test", obj, filename="test.txt")
with pytest.raises(TypeError, match="Can not serialize value"):
form()
@pytest.mark.parametrize("obj", (object(), None))
def test_invalid_formdata_payload_urlencoded(obj: object) -> None:
form = FormData({"test": obj})
with pytest.raises(TypeError, match="expected str"):
form()
def test_invalid_formdata_params() -> None:
with pytest.raises(TypeError):
FormData("asdasf")
def test_invalid_formdata_params2() -> None:
with pytest.raises(TypeError):
FormData("as") # 2-char str is not allowed
async def test_formdata_textio_charset(buf: bytearray, writer: StreamWriter) -> None:
form = FormData()
body = io.TextIOWrapper(io.BytesIO(b"\xe6\x97\xa5\xe6\x9c\xac"), encoding="utf-8")
form.add_field("foo", body, content_type="text/plain; charset=shift-jis")
payload = form()
await payload.write(writer)
assert b"charset=shift-jis" in buf
assert b"\x93\xfa\x96{" in buf
def test_invalid_formdata_content_type() -> None:
form = FormData()
invalid_vals = [0, 0.1, {}, [], b"foo"]
for invalid_val in invalid_vals:
with pytest.raises(TypeError):
form.add_field("foo", "bar", content_type=invalid_val) # type: ignore[arg-type]
def test_invalid_formdata_filename() -> None:
form = FormData()
invalid_vals = [0, 0.1, {}, [], b"foo"]
for invalid_val in invalid_vals:
with pytest.raises(TypeError):
form.add_field("foo", "bar", filename=invalid_val) # type: ignore[arg-type]
async def test_formdata_field_name_is_quoted(
buf: bytearray, writer: StreamWriter
) -> None:
form = FormData(charset="ascii")
form.add_field("email 1", "xxx@x.co", content_type="multipart/form-data")
payload = form()
await payload.write(writer)
assert b'name="email\\ 1"' in buf
async def test_formdata_field_name_is_not_quoted(
buf: bytearray, writer: StreamWriter
) -> None:
form = FormData(quote_fields=False, charset="ascii")
form.add_field("email 1", "xxx@x.co", content_type="multipart/form-data")
payload = form()
await payload.write(writer)
assert b'name="email 1"' in buf
async def test_formdata_is_reusable(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
return web.Response()
app = web.Application()
app.add_routes([web.post("/", handler)])
client = await aiohttp_client(app)
data = FormData()
data.add_field("test", "test_value", content_type="application/json")
# First request
resp1 = await client.post("/", data=data)
assert resp1.status == 200
resp1.release()
# Second request - should work without RuntimeError
resp2 = await client.post("/", data=data)
assert resp2.status == 200
resp2.release()
# Third request to ensure continued reusability
resp3 = await client.post("/", data=data)
assert resp3.status == 200
resp3.release()
async def test_formdata_boundary_param() -> None:
boundary = "some_boundary"
form = FormData(boundary=boundary)
assert form._writer.boundary == boundary
async def test_formdata_reusability_multipart(
writer: StreamWriter, buf: bytearray
) -> None:
form = FormData()
form.add_field("name", "value")
form.add_field("file", b"content", filename="test.txt", content_type="text/plain")
# First call - should generate multipart payload
payload1 = form()
assert form.is_multipart
buf.clear()
await payload1.write(writer)
result1 = bytes(buf)
# Verify first result contains expected content
assert b"name" in result1
assert b"value" in result1
assert b"test.txt" in result1
assert b"content" in result1
assert b"text/plain" in result1
# Second call - should generate identical multipart payload
payload2 = form()
buf.clear()
await payload2.write(writer)
result2 = bytes(buf)
# Results should be identical (same boundary and content)
assert result1 == result2
# Third call to ensure continued reusability
payload3 = form()
buf.clear()
await payload3.write(writer)
result3 = bytes(buf)
assert result1 == result3
async def test_formdata_reusability_urlencoded(
writer: StreamWriter, buf: bytearray
) -> None:
form = FormData()
form.add_field("key1", "value1")
form.add_field("key2", "value2")
# First call - should generate urlencoded payload
payload1 = form()
assert not form.is_multipart
buf.clear()
await payload1.write(writer)
result1 = bytes(buf)
# Verify first result contains expected content
assert b"key1=value1" in result1
assert b"key2=value2" in result1
# Second call - should generate identical urlencoded payload
payload2 = form()
buf.clear()
await payload2.write(writer)
result2 = bytes(buf)
# Results should be identical
assert result1 == result2
# Third call to ensure continued reusability
payload3 = form()
buf.clear()
await payload3.write(writer)
result3 = bytes(buf)
assert result1 == result3
async def test_formdata_reusability_after_adding_fields(
writer: StreamWriter, buf: bytearray
) -> None:
form = FormData()
form.add_field("field1", "value1")
# First call
payload1 = form()
buf.clear()
await payload1.write(writer)
result1 = bytes(buf)
# Add more fields after first call
form.add_field("field2", "value2")
# Second call should include new field
payload2 = form()
buf.clear()
await payload2.write(writer)
result2 = bytes(buf)
# Results should be different
assert result1 != result2
assert b"field1=value1" in result2
assert b"field2=value2" in result2
assert b"field2=value2" not in result1
# Third call should be same as second
payload3 = form()
buf.clear()
await payload3.write(writer)
result3 = bytes(buf)
assert result2 == result3
async def test_formdata_reusability_with_io_fields(
writer: StreamWriter, buf: bytearray
) -> None:
form = FormData()
# Create BytesIO and StringIO objects
bytes_io = io.BytesIO(b"bytes content")
string_io = io.StringIO("string content")
form.add_field(
"bytes_field",
bytes_io,
filename="bytes.bin",
content_type="application/octet-stream",
)
form.add_field(
"string_field", string_io, filename="text.txt", content_type="text/plain"
)
# First call
payload1 = form()
buf.clear()
await payload1.write(writer)
result1 = bytes(buf)
assert b"bytes content" in result1
assert b"string content" in result1
# Reset IO objects for reuse
bytes_io.seek(0)
string_io.seek(0)
# Second call - should work with reset IO objects
payload2 = form()
buf.clear()
await payload2.write(writer)
result2 = bytes(buf)
# Should produce identical results
assert result1 == result2
| aiohttp |
python | import abc
import asyncio
import base64
import functools
import hashlib
import html
import inspect
import keyword
import os
import re
import sys
from collections.abc import (
Awaitable,
Callable,
Container,
Generator,
Iterable,
Iterator,
Mapping,
Sized,
)
from pathlib import Path
from re import Pattern
from types import MappingProxyType
from typing import TYPE_CHECKING, Any, Final, NoReturn, Optional, TypedDict, cast
from yarl import URL
from . import hdrs
from .abc import AbstractMatchInfo, AbstractRouter, AbstractView
from .helpers import DEBUG
from .http import HttpVersion11
from .typedefs import Handler, PathLike
from .web_exceptions import (
HTTPException,
HTTPExpectationFailed,
HTTPForbidden,
HTTPMethodNotAllowed,
HTTPNotFound,
)
from .web_fileresponse import FileResponse
from .web_request import Request
from .web_response import Response, StreamResponse
from .web_routedef import AbstractRouteDef
__all__ = (
"UrlDispatcher",
"UrlMappingMatchInfo",
"AbstractResource",
"Resource",
"PlainResource",
"DynamicResource",
"AbstractRoute",
"ResourceRoute",
"StaticResource",
"View",
)
if TYPE_CHECKING:
from .web_app import Application
CIRCULAR_SYMLINK_ERROR = (RuntimeError,) if sys.version_info < (3, 13) else ()
HTTP_METHOD_RE: Final[Pattern[str]] = re.compile(
r"^[0-9A-Za-z!#\$%&'\*\+\-\.\^_`\|~]+$"
)
ROUTE_RE: Final[Pattern[str]] = re.compile(
r"(\{[_a-zA-Z][^{}]*(?:\{[^{}]*\}[^{}]*)*\})"
)
PATH_SEP: Final[str] = re.escape("/")
_ExpectHandler = Callable[[Request], Awaitable[StreamResponse | None]]
_Resolve = tuple[Optional["UrlMappingMatchInfo"], set[str]]
html_escape = functools.partial(html.escape, quote=True)
class _InfoDict(TypedDict, total=False):
path: str
formatter: str
pattern: Pattern[str]
directory: Path
prefix: str
routes: Mapping[str, "AbstractRoute"]
app: "Application"
domain: str
rule: "AbstractRuleMatching"
http_exception: HTTPException
class AbstractResource(Sized, Iterable["AbstractRoute"]):
def __init__(self, *, name: str | None = None) -> None:
self._name = name
@property
def name(self) -> str | None:
return self._name
@property
@abc.abstractmethod
def canonical(self) -> str:
"""Exposes the resource's canonical path.
For example '/foo/bar/{name}'
"""
@abc.abstractmethod # pragma: no branch
def url_for(self, **kwargs: str) -> URL:
"""Construct url for resource with additional params."""
@abc.abstractmethod # pragma: no branch
async def resolve(self, request: Request) -> _Resolve:
"""Resolve resource.
Return (UrlMappingMatchInfo, allowed_methods) pair.
"""
@abc.abstractmethod
def add_prefix(self, prefix: str) -> None:
"""Add a prefix to processed URLs.
Required for subapplications support.
"""
@abc.abstractmethod
def get_info(self) -> _InfoDict:
"""Return a dict with additional info useful for introspection"""
def freeze(self) -> None:
pass
@abc.abstractmethod
def raw_match(self, path: str) -> bool:
"""Perform a raw match against path"""
class AbstractRoute(abc.ABC):
def __init__(
self,
method: str,
handler: Handler | type[AbstractView],
*,
expect_handler: _ExpectHandler | None = None,
resource: AbstractResource | None = None,
) -> None:
if expect_handler is None:
expect_handler = _default_expect_handler
assert inspect.iscoroutinefunction(expect_handler) or (
sys.version_info < (3, 14) and asyncio.iscoroutinefunction(expect_handler)
), f"Coroutine is expected, got {expect_handler!r}"
method = method.upper()
if not HTTP_METHOD_RE.match(method):
raise ValueError(f"{method} is not allowed HTTP method")
if inspect.iscoroutinefunction(handler) or (
sys.version_info < (3, 14) and asyncio.iscoroutinefunction(handler)
):
pass
elif isinstance(handler, type) and issubclass(handler, AbstractView):
pass
else:
raise TypeError(
f"Only async functions are allowed as web-handlers, got {handler!r}"
)
self._method = method
self._handler = handler
self._expect_handler = expect_handler
self._resource = resource
@property
def method(self) -> str:
return self._method
@property
def handler(self) -> Handler:
return self._handler
@property
@abc.abstractmethod
def name(self) -> str | None:
"""Optional route's name, always equals to resource's name."""
@property
def resource(self) -> AbstractResource | None:
return self._resource
@abc.abstractmethod
def get_info(self) -> _InfoDict:
"""Return a dict with additional info useful for introspection"""
@abc.abstractmethod # pragma: no branch
def url_for(self, *args: str, **kwargs: str) -> URL:
"""Construct url for route with additional params."""
async def handle_expect_header(self, request: Request) -> StreamResponse | None:
return await self._expect_handler(request)
class UrlMappingMatchInfo(dict[str, str], AbstractMatchInfo):
__slots__ = ("_route", "_apps", "_current_app", "_frozen")
def __init__(self, match_dict: dict[str, str], route: AbstractRoute) -> None:
super().__init__(match_dict)
self._route = route
self._apps: list[Application] = []
self._current_app: Application | None = None
self._frozen = False
@property
def handler(self) -> Handler:
return self._route.handler
@property
def route(self) -> AbstractRoute:
return self._route
@property
def expect_handler(self) -> _ExpectHandler:
return self._route.handle_expect_header
@property
def http_exception(self) -> HTTPException | None:
return None
def get_info(self) -> _InfoDict: # type: ignore[override]
return self._route.get_info()
@property
def apps(self) -> tuple["Application", ...]:
return tuple(self._apps)
def add_app(self, app: "Application") -> None:
if self._frozen:
raise RuntimeError("Cannot change apps stack after .freeze() call")
if self._current_app is None:
self._current_app = app
self._apps.insert(0, app)
@property
def current_app(self) -> "Application":
app = self._current_app
assert app is not None
return app
@current_app.setter
def current_app(self, app: "Application") -> None:
if DEBUG:
if app not in self._apps:
raise RuntimeError(
f"Expected one of the following apps {self._apps!r}, got {app!r}"
)
self._current_app = app
def freeze(self) -> None:
self._frozen = True
def __repr__(self) -> str:
return f"<MatchInfo {super().__repr__()}: {self._route}>"
class MatchInfoError(UrlMappingMatchInfo):
__slots__ = ("_exception",)
def __init__(self, http_exception: HTTPException) -> None:
self._exception = http_exception
super().__init__({}, SystemRoute(self._exception))
@property
def http_exception(self) -> HTTPException:
return self._exception
def __repr__(self) -> str:
return f"<MatchInfoError {self._exception.status}: {self._exception.reason}>"
async def _default_expect_handler(request: Request) -> None:
"""Default handler for Expect header.
Just send "100 Continue" to client.
raise HTTPExpectationFailed if value of header is not "100-continue"
"""
expect = request.headers.get(hdrs.EXPECT, "")
if request.version == HttpVersion11:
if expect.lower() == "100-continue":
await request.writer.write(b"HTTP/1.1 100 Continue\r\n\r\n")
# Reset output_size as we haven't started the main body yet.
request.writer.output_size = 0
else:
raise HTTPExpectationFailed(text="Unknown Expect: %s" % expect)
class Resource(AbstractResource):
def __init__(self, *, name: str | None = None) -> None:
super().__init__(name=name)
self._routes: dict[str, ResourceRoute] = {}
self._any_route: ResourceRoute | None = None
self._allowed_methods: set[str] = set()
def add_route(
self,
method: str,
handler: type[AbstractView] | Handler,
*,
expect_handler: _ExpectHandler | None = None,
) -> "ResourceRoute":
if route := self._routes.get(method, self._any_route):
raise RuntimeError(
"Added route will never be executed, "
f"method {route.method} is already "
"registered"
)
route_obj = ResourceRoute(method, handler, self, expect_handler=expect_handler)
self.register_route(route_obj)
return route_obj
def register_route(self, route: "ResourceRoute") -> None:
assert isinstance(
route, ResourceRoute
), f"Instance of Route class is required, got {route!r}"
if route.method == hdrs.METH_ANY:
self._any_route = route
self._allowed_methods.add(route.method)
self._routes[route.method] = route
async def resolve(self, request: Request) -> _Resolve:
if (match_dict := self._match(request.rel_url.path_safe)) is None:
return None, set()
if route := self._routes.get(request.method, self._any_route):
return UrlMappingMatchInfo(match_dict, route), self._allowed_methods
return None, self._allowed_methods
@abc.abstractmethod
def _match(self, path: str) -> dict[str, str] | None:
"""Return dict of path values if path matches this resource, otherwise None."""
def __len__(self) -> int:
return len(self._routes)
def __iter__(self) -> Iterator["ResourceRoute"]:
return iter(self._routes.values())
# TODO: implement all abstract methods
class PlainResource(Resource):
def __init__(self, path: str, *, name: str | None = None) -> None:
super().__init__(name=name)
assert not path or path.startswith("/")
self._path = path
@property
def canonical(self) -> str:
return self._path
def freeze(self) -> None:
if not self._path:
self._path = "/"
def add_prefix(self, prefix: str) -> None:
assert prefix.startswith("/")
assert not prefix.endswith("/")
assert len(prefix) > 1
self._path = prefix + self._path
def _match(self, path: str) -> dict[str, str] | None:
# string comparison is about 10 times faster than regexp matching
if self._path == path:
return {}
return None
def raw_match(self, path: str) -> bool:
return self._path == path
def get_info(self) -> _InfoDict:
return {"path": self._path}
def url_for(self) -> URL: # type: ignore[override]
return URL.build(path=self._path, encoded=True)
def __repr__(self) -> str:
name = "'" + self.name + "' " if self.name is not None else ""
return f"<PlainResource {name} {self._path}>"
class DynamicResource(Resource):
DYN = re.compile(r"\{(?P<var>[_a-zA-Z][_a-zA-Z0-9]*)\}")
DYN_WITH_RE = re.compile(r"\{(?P<var>[_a-zA-Z][_a-zA-Z0-9]*):(?P<re>.+)\}")
GOOD = r"[^{}/]+"
def __init__(self, path: str, *, name: str | None = None) -> None:
super().__init__(name=name)
self._orig_path = path
pattern = ""
formatter = ""
for part in ROUTE_RE.split(path):
match = self.DYN.fullmatch(part)
if match:
pattern += "(?P<{}>{})".format(match.group("var"), self.GOOD)
formatter += "{" + match.group("var") + "}"
continue
match = self.DYN_WITH_RE.fullmatch(part)
if match:
pattern += "(?P<{var}>{re})".format(**match.groupdict())
formatter += "{" + match.group("var") + "}"
continue
if "{" in part or "}" in part:
raise ValueError(f"Invalid path '{path}'['{part}']")
part = _requote_path(part)
formatter += part
pattern += re.escape(part)
try:
compiled = re.compile(pattern)
except re.error as exc:
raise ValueError(f"Bad pattern '{pattern}': {exc}") from None
assert compiled.pattern.startswith(PATH_SEP)
assert formatter.startswith("/")
self._pattern = compiled
self._formatter = formatter
@property
def canonical(self) -> str:
return self._formatter
def add_prefix(self, prefix: str) -> None:
assert prefix.startswith("/")
assert not prefix.endswith("/")
assert len(prefix) > 1
self._pattern = re.compile(re.escape(prefix) + self._pattern.pattern)
self._formatter = prefix + self._formatter
def _match(self, path: str) -> dict[str, str] | None:
match = self._pattern.fullmatch(path)
if match is None:
return None
return {
key: _unquote_path_safe(value) for key, value in match.groupdict().items()
}
def raw_match(self, path: str) -> bool:
return self._orig_path == path
def get_info(self) -> _InfoDict:
return {"formatter": self._formatter, "pattern": self._pattern}
def url_for(self, **parts: str) -> URL:
url = self._formatter.format_map({k: _quote_path(v) for k, v in parts.items()})
return URL.build(path=url, encoded=True)
def __repr__(self) -> str:
name = "'" + self.name + "' " if self.name is not None else ""
return f"<DynamicResource {name} {self._formatter}>"
class PrefixResource(AbstractResource):
def __init__(self, prefix: str, *, name: str | None = None) -> None:
assert not prefix or prefix.startswith("/"), prefix
assert prefix in ("", "/") or not prefix.endswith("/"), prefix
super().__init__(name=name)
self._prefix = _requote_path(prefix)
self._prefix2 = self._prefix + "/"
@property
def canonical(self) -> str:
return self._prefix
def add_prefix(self, prefix: str) -> None:
assert prefix.startswith("/")
assert not prefix.endswith("/")
assert len(prefix) > 1
self._prefix = prefix + self._prefix
self._prefix2 = self._prefix + "/"
def raw_match(self, prefix: str) -> bool:
return False
# TODO: impl missing abstract methods
class StaticResource(PrefixResource):
VERSION_KEY = "v"
def __init__(
self,
prefix: str,
directory: PathLike,
*,
name: str | None = None,
expect_handler: _ExpectHandler | None = None,
chunk_size: int = 256 * 1024,
show_index: bool = False,
follow_symlinks: bool = False,
append_version: bool = False,
) -> None:
super().__init__(prefix, name=name)
try:
directory = Path(directory).expanduser().resolve(strict=True)
except FileNotFoundError as error:
raise ValueError(f"'{directory}' does not exist") from error
if not directory.is_dir():
raise ValueError(f"'{directory}' is not a directory")
self._directory = directory
self._show_index = show_index
self._chunk_size = chunk_size
self._follow_symlinks = follow_symlinks
self._expect_handler = expect_handler
self._append_version = append_version
self._routes = {
"GET": ResourceRoute(
"GET", self._handle, self, expect_handler=expect_handler
),
"HEAD": ResourceRoute(
"HEAD", self._handle, self, expect_handler=expect_handler
),
}
self._allowed_methods = set(self._routes)
def url_for( # type: ignore[override]
self,
*,
filename: PathLike,
append_version: bool | None = None,
) -> URL:
if append_version is None:
append_version = self._append_version
filename = str(filename).lstrip("/")
url = URL.build(path=self._prefix, encoded=True)
# filename is not encoded
url = url / filename
if append_version:
unresolved_path = self._directory.joinpath(filename)
try:
if self._follow_symlinks:
normalized_path = Path(os.path.normpath(unresolved_path))
normalized_path.relative_to(self._directory)
filepath = normalized_path.resolve()
else:
filepath = unresolved_path.resolve()
filepath.relative_to(self._directory)
except (ValueError, FileNotFoundError):
# ValueError for case when path point to symlink
# with follow_symlinks is False
return url # relatively safe
if filepath.is_file():
# TODO cache file content
# with file watcher for cache invalidation
with filepath.open("rb") as f:
file_bytes = f.read()
h = self._get_file_hash(file_bytes)
url = url.with_query({self.VERSION_KEY: h})
return url
return url
@staticmethod
def _get_file_hash(byte_array: bytes) -> str:
m = hashlib.sha256() # todo sha256 can be configurable param
m.update(byte_array)
b64 = base64.urlsafe_b64encode(m.digest())
return b64.decode("ascii")
def get_info(self) -> _InfoDict:
return {
"directory": self._directory,
"prefix": self._prefix,
"routes": self._routes,
}
def set_options_route(self, handler: Handler) -> None:
if "OPTIONS" in self._routes:
raise RuntimeError("OPTIONS route was set already")
self._routes["OPTIONS"] = ResourceRoute(
"OPTIONS", handler, self, expect_handler=self._expect_handler
)
self._allowed_methods.add("OPTIONS")
async def resolve(self, request: Request) -> _Resolve:
path = request.rel_url.path_safe
method = request.method
if not path.startswith(self._prefix2) and path != self._prefix:
return None, set()
allowed_methods = self._allowed_methods
if method not in allowed_methods:
return None, allowed_methods
match_dict = {"filename": _unquote_path_safe(path[len(self._prefix) + 1 :])}
return (UrlMappingMatchInfo(match_dict, self._routes[method]), allowed_methods)
def __len__(self) -> int:
return len(self._routes)
def __iter__(self) -> Iterator[AbstractRoute]:
return iter(self._routes.values())
async def _handle(self, request: Request) -> StreamResponse:
rel_url = request.match_info["filename"]
filename = Path(rel_url)
if filename.anchor:
# rel_url is an absolute name like
# /static/\\machine_name\c$ or /static/D:\path
# where the static dir is totally different
raise HTTPForbidden()
unresolved_path = self._directory.joinpath(filename)
loop = asyncio.get_running_loop()
return await loop.run_in_executor(
None, self._resolve_path_to_response, unresolved_path
)
def _resolve_path_to_response(self, unresolved_path: Path) -> StreamResponse:
"""Take the unresolved path and query the file system to form a response."""
# Check for access outside the root directory. For follow symlinks, URI
# cannot traverse out, but symlinks can. Otherwise, no access outside
# root is permitted.
try:
if self._follow_symlinks:
normalized_path = Path(os.path.normpath(unresolved_path))
normalized_path.relative_to(self._directory)
file_path = normalized_path.resolve()
else:
file_path = unresolved_path.resolve()
file_path.relative_to(self._directory)
except (ValueError, *CIRCULAR_SYMLINK_ERROR) as error:
# ValueError is raised for the relative check. Circular symlinks
# raise here on resolving for python < 3.13.
raise HTTPNotFound() from error
# if path is a directory, return the contents if permitted. Note the
# directory check will raise if a segment is not readable.
try:
if file_path.is_dir():
if self._show_index:
return Response(
text=self._directory_as_html(file_path),
content_type="text/html",
)
else:
raise HTTPForbidden()
except PermissionError as error:
raise HTTPForbidden() from error
# Return the file response, which handles all other checks.
return FileResponse(file_path, chunk_size=self._chunk_size)
def _directory_as_html(self, dir_path: Path) -> str:
"""returns directory's index as html."""
assert dir_path.is_dir()
relative_path_to_dir = dir_path.relative_to(self._directory).as_posix()
index_of = f"Index of /{html_escape(relative_path_to_dir)}"
h1 = f"<h1>{index_of}</h1>"
index_list = []
dir_index = dir_path.iterdir()
for _file in sorted(dir_index):
# show file url as relative to static path
rel_path = _file.relative_to(self._directory).as_posix()
quoted_file_url = _quote_path(f"{self._prefix}/{rel_path}")
# if file is a directory, add '/' to the end of the name
if _file.is_dir():
file_name = f"{_file.name}/"
else:
file_name = _file.name
index_list.append(
f'<li><a href="{quoted_file_url}">{html_escape(file_name)}</a></li>'
)
ul = "<ul>\n{}\n</ul>".format("\n".join(index_list))
body = f"<body>\n{h1}\n{ul}\n</body>"
head_str = f"<head>\n<title>{index_of}</title>\n</head>"
html = f"<html>\n{head_str}\n{body}\n</html>"
return html
def __repr__(self) -> str:
name = "'" + self.name + "'" if self.name is not None else ""
return f"<StaticResource {name} {self._prefix} -> {self._directory!r}>"
class PrefixedSubAppResource(PrefixResource):
def __init__(self, prefix: str, app: "Application") -> None:
super().__init__(prefix)
self._app = app
self._add_prefix_to_resources(prefix)
def add_prefix(self, prefix: str) -> None:
super().add_prefix(prefix)
self._add_prefix_to_resources(prefix)
def _add_prefix_to_resources(self, prefix: str) -> None:
router = self._app.router
for resource in router.resources():
# Since the canonical path of a resource is about
# to change, we need to unindex it and then reindex
router.unindex_resource(resource)
resource.add_prefix(prefix)
router.index_resource(resource)
def url_for(self, *args: str, **kwargs: str) -> URL:
raise RuntimeError(".url_for() is not supported by sub-application root")
def get_info(self) -> _InfoDict:
return {"app": self._app, "prefix": self._prefix}
async def resolve(self, request: Request) -> _Resolve:
match_info = await self._app.router.resolve(request)
match_info.add_app(self._app)
if isinstance(match_info.http_exception, HTTPMethodNotAllowed):
methods = match_info.http_exception.allowed_methods
else:
methods = set()
return match_info, methods
def __len__(self) -> int:
return len(self._app.router.routes())
def __iter__(self) -> Iterator[AbstractRoute]:
return iter(self._app.router.routes())
def __repr__(self) -> str:
return f"<PrefixedSubAppResource {self._prefix} -> {self._app!r}>"
class AbstractRuleMatching(abc.ABC):
@abc.abstractmethod # pragma: no branch
async def match(self, request: Request) -> bool:
"""Return bool if the request satisfies the criteria"""
@abc.abstractmethod # pragma: no branch
def get_info(self) -> _InfoDict:
"""Return a dict with additional info useful for introspection"""
@property
@abc.abstractmethod # pragma: no branch
def canonical(self) -> str:
"""Return a str"""
class Domain(AbstractRuleMatching):
re_part = re.compile(r"(?!-)[a-z\d-]{1,63}(?<!-)")
def __init__(self, domain: str) -> None:
super().__init__()
self._domain = self.validation(domain)
@property
def canonical(self) -> str:
return self._domain
def validation(self, domain: str) -> str:
if not isinstance(domain, str):
raise TypeError("Domain must be str")
domain = domain.rstrip(".").lower()
if not domain:
raise ValueError("Domain cannot be empty")
elif "://" in domain:
raise ValueError("Scheme not supported")
url = URL("http://" + domain)
assert url.raw_host is not None
if not all(self.re_part.fullmatch(x) for x in url.raw_host.split(".")):
raise ValueError("Domain not valid")
if url.port == 80:
return url.raw_host
return f"{url.raw_host}:{url.port}"
async def match(self, request: Request) -> bool:
host = request.headers.get(hdrs.HOST)
if not host:
return False
return self.match_domain(host)
def match_domain(self, host: str) -> bool:
return host.lower() == self._domain
def get_info(self) -> _InfoDict:
return {"domain": self._domain}
class MaskDomain(Domain):
re_part = re.compile(r"(?!-)[a-z\d\*-]{1,63}(?<!-)")
def __init__(self, domain: str) -> None:
super().__init__(domain)
mask = self._domain.replace(".", r"\.").replace("*", ".*")
self._mask = re.compile(mask)
@property
def canonical(self) -> str:
return self._mask.pattern
def match_domain(self, host: str) -> bool:
return self._mask.fullmatch(host) is not None
class MatchedSubAppResource(PrefixedSubAppResource):
def __init__(self, rule: AbstractRuleMatching, app: "Application") -> None:
AbstractResource.__init__(self)
self._prefix = ""
self._app = app
self._rule = rule
@property
def canonical(self) -> str:
return self._rule.canonical
def get_info(self) -> _InfoDict:
return {"app": self._app, "rule": self._rule}
async def resolve(self, request: Request) -> _Resolve:
if not await self._rule.match(request):
return None, set()
match_info = await self._app.router.resolve(request)
match_info.add_app(self._app)
if isinstance(match_info.http_exception, HTTPMethodNotAllowed):
methods = match_info.http_exception.allowed_methods
else:
methods = set()
return match_info, methods
def __repr__(self) -> str:
return f"<MatchedSubAppResource -> {self._app!r}>"
class ResourceRoute(AbstractRoute):
"""A route with resource"""
def __init__(
self,
method: str,
handler: Handler | type[AbstractView],
resource: AbstractResource,
*,
expect_handler: _ExpectHandler | None = None,
) -> None:
super().__init__(
method, handler, expect_handler=expect_handler, resource=resource
)
def __repr__(self) -> str:
return f"<ResourceRoute [{self.method}] {self._resource} -> {self.handler!r}"
@property
def name(self) -> str | None:
if self._resource is None:
return None
return self._resource.name
def url_for(self, *args: str, **kwargs: str) -> URL:
"""Construct url for route with additional params."""
assert self._resource is not None
return self._resource.url_for(*args, **kwargs)
def get_info(self) -> _InfoDict:
assert self._resource is not None
return self._resource.get_info()
class SystemRoute(AbstractRoute):
def __init__(self, http_exception: HTTPException) -> None:
super().__init__(hdrs.METH_ANY, self._handle)
self._http_exception = http_exception
def url_for(self, *args: str, **kwargs: str) -> URL:
raise RuntimeError(".url_for() is not allowed for SystemRoute")
@property
def name(self) -> str | None:
return None
def get_info(self) -> _InfoDict:
return {"http_exception": self._http_exception}
async def _handle(self, request: Request) -> StreamResponse:
raise self._http_exception
@property
def status(self) -> int:
return self._http_exception.status
@property
def reason(self) -> str:
return self._http_exception.reason
def __repr__(self) -> str:
return f"<SystemRoute {self.status}: {self.reason}>"
class View(AbstractView):
async def _iter(self) -> StreamResponse:
if self.request.method not in hdrs.METH_ALL:
self._raise_allowed_methods()
method: Callable[[], Awaitable[StreamResponse]] | None = getattr(
self, self.request.method.lower(), None
)
if method is None:
self._raise_allowed_methods()
return await method()
def __await__(self) -> Generator[None, None, StreamResponse]:
return self._iter().__await__()
def _raise_allowed_methods(self) -> NoReturn:
allowed_methods = {m for m in hdrs.METH_ALL if hasattr(self, m.lower())}
raise HTTPMethodNotAllowed(self.request.method, allowed_methods)
class ResourcesView(Sized, Iterable[AbstractResource], Container[AbstractResource]):
def __init__(self, resources: list[AbstractResource]) -> None:
self._resources = resources
def __len__(self) -> int:
return len(self._resources)
def __iter__(self) -> Iterator[AbstractResource]:
yield from self._resources
def __contains__(self, resource: object) -> bool:
return resource in self._resources
class RoutesView(Sized, Iterable[AbstractRoute], Container[AbstractRoute]):
def __init__(self, resources: list[AbstractResource]):
self._routes: list[AbstractRoute] = []
for resource in resources:
for route in resource:
self._routes.append(route)
def __len__(self) -> int:
return len(self._routes)
def __iter__(self) -> Iterator[AbstractRoute]:
yield from self._routes
def __contains__(self, route: object) -> bool:
return route in self._routes
class UrlDispatcher(AbstractRouter, Mapping[str, AbstractResource]):
NAME_SPLIT_RE = re.compile(r"[.:-]")
HTTP_NOT_FOUND = HTTPNotFound()
def __init__(self) -> None:
super().__init__()
self._resources: list[AbstractResource] = []
self._named_resources: dict[str, AbstractResource] = {}
self._resource_index: dict[str, list[AbstractResource]] = {}
self._matched_sub_app_resources: list[MatchedSubAppResource] = []
async def resolve(self, request: Request) -> UrlMappingMatchInfo:
resource_index = self._resource_index
allowed_methods: set[str] = set()
# MatchedSubAppResource is primarily used to match on domain names
# (though custom rules could match on other things). This means that
# the traversal algorithm below can't be applied, and that we likely
# need to check these first so a sub app that defines the same path
# as a parent app will get priority if there's a domain match.
#
# For most cases we do not expect there to be many of these since
# currently they are only added by `.add_domain()`.
for resource in self._matched_sub_app_resources:
match_dict, allowed = await resource.resolve(request)
if match_dict is not None:
return match_dict
else:
allowed_methods |= allowed
# Walk the url parts looking for candidates. We walk the url backwards
# to ensure the most explicit match is found first. If there are multiple
# candidates for a given url part because there are multiple resources
# registered for the same canonical path, we resolve them in a linear
# fashion to ensure registration order is respected.
url_part = request.rel_url.path_safe
while url_part:
for candidate in resource_index.get(url_part, ()):
match_dict, allowed = await candidate.resolve(request)
if match_dict is not None:
return match_dict
else:
allowed_methods |= allowed
if url_part == "/":
break
url_part = url_part.rpartition("/")[0] or "/"
if allowed_methods:
return MatchInfoError(HTTPMethodNotAllowed(request.method, allowed_methods))
return MatchInfoError(self.HTTP_NOT_FOUND)
def __iter__(self) -> Iterator[str]:
return iter(self._named_resources)
def __len__(self) -> int:
return len(self._named_resources)
def __contains__(self, resource: object) -> bool:
return resource in self._named_resources
def __getitem__(self, name: str) -> AbstractResource:
return self._named_resources[name]
def resources(self) -> ResourcesView:
return ResourcesView(self._resources)
def routes(self) -> RoutesView:
return RoutesView(self._resources)
def named_resources(self) -> Mapping[str, AbstractResource]:
return MappingProxyType(self._named_resources)
def register_resource(self, resource: AbstractResource) -> None:
assert isinstance(
resource, AbstractResource
), f"Instance of AbstractResource class is required, got {resource!r}"
if self.frozen:
raise RuntimeError("Cannot register a resource into frozen router.")
name = resource.name
if name is not None:
parts = self.NAME_SPLIT_RE.split(name)
for part in parts:
if keyword.iskeyword(part):
raise ValueError(
f"Incorrect route name {name!r}, "
"python keywords cannot be used "
"for route name"
)
if not part.isidentifier():
raise ValueError(
f"Incorrect route name {name!r}, "
"the name should be a sequence of "
"python identifiers separated "
"by dash, dot or column"
)
if name in self._named_resources:
raise ValueError(
f"Duplicate {name!r}, "
f"already handled by {self._named_resources[name]!r}"
)
self._named_resources[name] = resource
self._resources.append(resource)
if isinstance(resource, MatchedSubAppResource):
# We cannot index match sub-app resources because they have match rules
self._matched_sub_app_resources.append(resource)
else:
self.index_resource(resource)
def _get_resource_index_key(self, resource: AbstractResource) -> str:
"""Return a key to index the resource in the resource index."""
if "{" in (index_key := resource.canonical):
# strip at the first { to allow for variables, and than
# rpartition at / to allow for variable parts in the path
# For example if the canonical path is `/core/locations{tail:.*}`
# the index key will be `/core` since index is based on the
# url parts split by `/`
index_key = index_key.partition("{")[0].rpartition("/")[0]
return index_key.rstrip("/") or "/"
def index_resource(self, resource: AbstractResource) -> None:
"""Add a resource to the resource index."""
resource_key = self._get_resource_index_key(resource)
# There may be multiple resources for a canonical path
# so we keep them in a list to ensure that registration
# order is respected.
self._resource_index.setdefault(resource_key, []).append(resource)
def unindex_resource(self, resource: AbstractResource) -> None:
"""Remove a resource from the resource index."""
resource_key = self._get_resource_index_key(resource)
self._resource_index[resource_key].remove(resource)
def add_resource(self, path: str, *, name: str | None = None) -> Resource:
if path and not path.startswith("/"):
raise ValueError("path should be started with / or be empty")
# Reuse last added resource if path and name are the same
if self._resources:
resource = self._resources[-1]
if resource.name == name and resource.raw_match(path):
return cast(Resource, resource)
if not ("{" in path or "}" in path or ROUTE_RE.search(path)):
resource = PlainResource(path, name=name)
self.register_resource(resource)
return resource
resource = DynamicResource(path, name=name)
self.register_resource(resource)
return resource
def add_route(
self,
method: str,
path: str,
handler: Handler | type[AbstractView],
*,
name: str | None = None,
expect_handler: _ExpectHandler | None = None,
) -> AbstractRoute:
resource = self.add_resource(path, name=name)
return resource.add_route(method, handler, expect_handler=expect_handler)
def add_static(
self,
prefix: str,
path: PathLike,
*,
name: str | None = None,
expect_handler: _ExpectHandler | None = None,
chunk_size: int = 256 * 1024,
show_index: bool = False,
follow_symlinks: bool = False,
append_version: bool = False,
) -> StaticResource:
"""Add static files view.
prefix - url prefix
path - folder with files
"""
assert prefix.startswith("/")
if prefix.endswith("/"):
prefix = prefix[:-1]
resource = StaticResource(
prefix,
path,
name=name,
expect_handler=expect_handler,
chunk_size=chunk_size,
show_index=show_index,
follow_symlinks=follow_symlinks,
append_version=append_version,
)
self.register_resource(resource)
return resource
def add_head(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute:
"""Shortcut for add_route with method HEAD."""
return self.add_route(hdrs.METH_HEAD, path, handler, **kwargs)
def add_options(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute:
"""Shortcut for add_route with method OPTIONS."""
return self.add_route(hdrs.METH_OPTIONS, path, handler, **kwargs)
def add_get(
self,
path: str,
handler: Handler,
*,
name: str | None = None,
allow_head: bool = True,
**kwargs: Any,
) -> AbstractRoute:
"""Shortcut for add_route with method GET.
If allow_head is true, another
route is added allowing head requests to the same endpoint.
"""
resource = self.add_resource(path, name=name)
if allow_head:
resource.add_route(hdrs.METH_HEAD, handler, **kwargs)
return resource.add_route(hdrs.METH_GET, handler, **kwargs)
def add_post(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute:
"""Shortcut for add_route with method POST."""
return self.add_route(hdrs.METH_POST, path, handler, **kwargs)
def add_put(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute:
"""Shortcut for add_route with method PUT."""
return self.add_route(hdrs.METH_PUT, path, handler, **kwargs)
def add_patch(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute:
"""Shortcut for add_route with method PATCH."""
return self.add_route(hdrs.METH_PATCH, path, handler, **kwargs)
def add_delete(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute:
"""Shortcut for add_route with method DELETE."""
return self.add_route(hdrs.METH_DELETE, path, handler, **kwargs)
def add_view(
self, path: str, handler: type[AbstractView], **kwargs: Any
) -> AbstractRoute:
"""Shortcut for add_route with ANY methods for a class-based view."""
return self.add_route(hdrs.METH_ANY, path, handler, **kwargs)
def freeze(self) -> None:
super().freeze()
for resource in self._resources:
resource.freeze()
def add_routes(self, routes: Iterable[AbstractRouteDef]) -> list[AbstractRoute]:
"""Append routes to route table.
Parameter should be a sequence of RouteDef objects.
Returns a list of registered AbstractRoute instances.
"""
registered_routes = []
for route_def in routes:
registered_routes.extend(route_def.register(self))
return registered_routes
def _quote_path(value: str) -> str:
return URL.build(path=value, encoded=False).raw_path
def _unquote_path_safe(value: str) -> str:
if "%" not in value:
return value
return value.replace("%2F", "/").replace("%25", "%")
def _requote_path(value: str) -> str:
# Quote non-ascii characters and other characters which must be quoted,
# but preserve existing %-sequences.
result = _quote_path(value)
if "%" in value:
result = result.replace("%25", "%")
return result
| import asyncio
import pathlib
import re
from collections.abc import (
Awaitable,
Callable,
Container,
Iterable,
Mapping,
MutableMapping,
Sized,
)
from functools import partial
from typing import NoReturn
from urllib.parse import quote, unquote
import pytest
from yarl import URL
import aiohttp
from aiohttp import hdrs, web
from aiohttp.test_utils import make_mocked_request
from aiohttp.web_urldispatcher import (
PATH_SEP,
Domain,
MaskDomain,
SystemRoute,
_default_expect_handler,
)
def make_handler() -> Callable[[web.Request], Awaitable[NoReturn]]:
async def handler(request: web.Request) -> NoReturn:
assert False
return handler
def make_partial_handler() -> Callable[[web.Request], Awaitable[NoReturn]]:
async def handler(a: int, request: web.Request) -> NoReturn:
assert False
return partial(handler, 5)
@pytest.fixture
def app() -> web.Application:
return web.Application()
@pytest.fixture
def router(app: web.Application) -> web.UrlDispatcher:
return app.router
@pytest.fixture
def fill_routes(router: web.UrlDispatcher) -> Callable[[], list[web.AbstractRoute]]:
def go() -> list[web.AbstractRoute]:
route1 = router.add_route("GET", "/plain", make_handler())
route2 = router.add_route("GET", "/variable/{name}", make_handler())
resource = router.add_static("/static", pathlib.Path(aiohttp.__file__).parent)
return [route1, route2] + list(resource)
return go
def test_register_uncommon_http_methods(router: web.UrlDispatcher) -> None:
uncommon_http_methods = {
"PROPFIND",
"PROPPATCH",
"COPY",
"LOCK",
"UNLOCK",
"MOVE",
"SUBSCRIBE",
"UNSUBSCRIBE",
"NOTIFY",
}
for method in uncommon_http_methods:
router.add_route(method, "/handler/to/path", make_handler())
async def test_add_partial_handler(router: web.UrlDispatcher) -> None:
handler = make_partial_handler()
router.add_get("/handler/to/path", handler)
async def test_add_sync_handler(router: web.UrlDispatcher) -> None:
def handler(request: web.Request) -> NoReturn:
assert False
with pytest.raises(TypeError):
router.add_get("/handler/to/path", handler)
async def test_add_route_root(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/", handler)
req = make_mocked_request("GET", "/")
info = await router.resolve(req)
assert info is not None
assert 0 == len(info)
assert handler is info.handler
assert info.route.name is None
async def test_add_route_simple(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/handler/to/path", handler)
req = make_mocked_request("GET", "/handler/to/path")
info = await router.resolve(req)
assert info is not None
assert 0 == len(info)
assert handler is info.handler
assert info.route.name is None
async def test_add_with_matchdict(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/handler/{to}", handler)
req = make_mocked_request("GET", "/handler/tail")
info = await router.resolve(req)
assert info is not None
assert {"to": "tail"} == info
assert handler is info.handler
assert info.route.name is None
async def test_add_with_matchdict_with_colon(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/handler/{to}", handler)
req = make_mocked_request("GET", "/handler/1:2:3")
info = await router.resolve(req)
assert info is not None
assert {"to": "1:2:3"} == info
assert handler is info.handler
assert info.route.name is None
async def test_add_route_with_add_get_shortcut(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_get("/handler/to/path", handler)
req = make_mocked_request("GET", "/handler/to/path")
info = await router.resolve(req)
assert info is not None
assert 0 == len(info)
assert handler is info.handler
assert info.route.name is None
async def test_add_route_with_add_post_shortcut(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_post("/handler/to/path", handler)
req = make_mocked_request("POST", "/handler/to/path")
info = await router.resolve(req)
assert info is not None
assert 0 == len(info)
assert handler is info.handler
assert info.route.name is None
async def test_add_route_with_add_put_shortcut(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_put("/handler/to/path", handler)
req = make_mocked_request("PUT", "/handler/to/path")
info = await router.resolve(req)
assert info is not None
assert 0 == len(info)
assert handler is info.handler
assert info.route.name is None
async def test_add_route_with_add_patch_shortcut(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_patch("/handler/to/path", handler)
req = make_mocked_request("PATCH", "/handler/to/path")
info = await router.resolve(req)
assert info is not None
assert 0 == len(info)
assert handler is info.handler
assert info.route.name is None
async def test_add_route_with_add_delete_shortcut(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_delete("/handler/to/path", handler)
req = make_mocked_request("DELETE", "/handler/to/path")
info = await router.resolve(req)
assert info is not None
assert 0 == len(info)
assert handler is info.handler
assert info.route.name is None
async def test_add_route_with_add_head_shortcut(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_head("/handler/to/path", handler)
req = make_mocked_request("HEAD", "/handler/to/path")
info = await router.resolve(req)
assert info is not None
assert 0 == len(info)
assert handler is info.handler
assert info.route.name is None
async def test_add_with_name(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/handler/to/path", handler, name="name")
req = make_mocked_request("GET", "/handler/to/path")
info = await router.resolve(req)
assert info is not None
assert "name" == info.route.name
async def test_add_with_tailing_slash(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/handler/to/path/", handler)
req = make_mocked_request("GET", "/handler/to/path/")
info = await router.resolve(req)
assert info is not None
assert {} == info
assert handler is info.handler
def test_add_invalid_path(router: web.UrlDispatcher) -> None:
handler = make_handler()
with pytest.raises(ValueError):
router.add_route("GET", "/{/", handler)
def test_add_url_invalid1(router: web.UrlDispatcher) -> None:
handler = make_handler()
with pytest.raises(ValueError):
router.add_route("post", "/post/{id", handler)
def test_add_url_invalid2(router: web.UrlDispatcher) -> None:
handler = make_handler()
with pytest.raises(ValueError):
router.add_route("post", "/post/{id{}}", handler)
def test_add_url_invalid3(router: web.UrlDispatcher) -> None:
handler = make_handler()
with pytest.raises(ValueError):
router.add_route("post", "/post/{id{}", handler)
def test_add_url_invalid4(router: web.UrlDispatcher) -> None:
handler = make_handler()
with pytest.raises(ValueError):
router.add_route("post", '/post/{id"}', handler)
async def test_add_url_escaping(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/+$", handler)
req = make_mocked_request("GET", "/+$")
info = await router.resolve(req)
assert info is not None
assert handler is info.handler
async def test_any_method(router: web.UrlDispatcher) -> None:
handler = make_handler()
route = router.add_route(hdrs.METH_ANY, "/", handler)
req = make_mocked_request("GET", "/")
info1 = await router.resolve(req)
assert info1 is not None
assert route is info1.route
req = make_mocked_request("POST", "/")
info2 = await router.resolve(req)
assert info2 is not None
assert info1.route is info2.route
async def test_any_method_appears_in_routes(router: web.UrlDispatcher) -> None:
handler = make_handler()
route = router.add_route(hdrs.METH_ANY, "/", handler)
assert route in router.routes()
async def test_match_second_result_in_table(router: web.UrlDispatcher) -> None:
handler1 = make_handler()
handler2 = make_handler()
router.add_route("GET", "/h1", handler1)
router.add_route("POST", "/h2", handler2)
req = make_mocked_request("POST", "/h2")
info = await router.resolve(req)
assert info is not None
assert {} == info
assert handler2 is info.handler
async def test_raise_method_not_allowed(router: web.UrlDispatcher) -> None:
handler1 = make_handler()
handler2 = make_handler()
router.add_route("GET", "/", handler1)
router.add_route("POST", "/", handler2)
req = make_mocked_request("PUT", "/")
match_info = await router.resolve(req)
assert isinstance(match_info.route, SystemRoute)
assert {} == match_info
with pytest.raises(web.HTTPMethodNotAllowed) as ctx:
await match_info.handler(req)
exc = ctx.value
assert "PUT" == exc.method
assert 405 == exc.status
assert {"POST", "GET"} == exc.allowed_methods
async def test_raise_method_not_found(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/a", handler)
req = make_mocked_request("GET", "/b")
match_info = await router.resolve(req)
assert isinstance(match_info.route, SystemRoute)
assert {} == match_info
with pytest.raises(web.HTTPNotFound) as ctx:
await match_info.handler(req)
exc = ctx.value
assert 404 == exc.status
def test_double_add_url_with_the_same_name(router: web.UrlDispatcher) -> None:
handler1 = make_handler()
handler2 = make_handler()
router.add_route("GET", "/get", handler1, name="name")
with pytest.raises(ValueError) as ctx:
router.add_route("GET", "/get_other", handler2, name="name")
assert str(ctx.value).startswith("Duplicate 'name', already handled by")
def test_route_plain(router: web.UrlDispatcher) -> None:
handler = make_handler()
route = router.add_route("GET", "/get", handler, name="name")
route2 = next(iter(router["name"]))
url = route2.url_for()
assert "/get" == str(url)
assert route is route2
def test_route_unknown_route_name(router: web.UrlDispatcher) -> None:
with pytest.raises(KeyError):
router["unknown"]
def test_route_dynamic(router: web.UrlDispatcher) -> None:
handler = make_handler()
route = router.add_route("GET", "/get/{name}", handler, name="name")
route2 = next(iter(router["name"]))
url = route2.url_for(name="John")
assert "/get/John" == str(url)
assert route is route2
def test_add_static_path_checks(
router: web.UrlDispatcher, tmp_path: pathlib.Path
) -> None:
"""Test that static paths must exist and be directories."""
with pytest.raises(ValueError, match="does not exist"):
router.add_static("/", tmp_path / "does-not-exist")
with pytest.raises(ValueError, match="is not a directory"):
router.add_static("/", __file__)
def test_add_static_path_resolution(router: web.UrlDispatcher) -> None:
"""Test that static paths are expanded and absolute."""
res = router.add_static("/", "~/..")
directory = str(res.get_info()["directory"])
assert directory == str(pathlib.Path.home().resolve(strict=True).parent)
def test_add_static(router: web.UrlDispatcher) -> None:
resource = router.add_static(
"/st", pathlib.Path(aiohttp.__file__).parent, name="static"
)
assert router["static"] is resource
url = resource.url_for(filename="/dir/a.txt")
assert "/st/dir/a.txt" == str(url)
assert len(resource) == 2
def test_add_static_append_version(router: web.UrlDispatcher) -> None:
resource = router.add_static("/st", pathlib.Path(__file__).parent, name="static")
url = resource.url_for(filename="/data.unknown_mime_type", append_version=True)
expect_url = (
"/st/data.unknown_mime_type?v=aUsn8CHEhhszc81d28QmlcBW0KQpfS2F4trgQKhOYd8%3D"
)
assert expect_url == str(url)
def test_add_static_append_version_set_from_constructor(
router: web.UrlDispatcher,
) -> None:
resource = router.add_static(
"/st", pathlib.Path(__file__).parent, append_version=True, name="static"
)
url = resource.url_for(filename="/data.unknown_mime_type")
expect_url = (
"/st/data.unknown_mime_type?v=aUsn8CHEhhszc81d28QmlcBW0KQpfS2F4trgQKhOYd8%3D"
)
assert expect_url == str(url)
def test_add_static_append_version_override_constructor(
router: web.UrlDispatcher,
) -> None:
resource = router.add_static(
"/st", pathlib.Path(__file__).parent, append_version=True, name="static"
)
url = resource.url_for(filename="/data.unknown_mime_type", append_version=False)
expect_url = "/st/data.unknown_mime_type"
assert expect_url == str(url)
def test_add_static_append_version_filename_without_slash(
router: web.UrlDispatcher,
) -> None:
resource = router.add_static("/st", pathlib.Path(__file__).parent, name="static")
url = resource.url_for(filename="data.unknown_mime_type", append_version=True)
expect_url = (
"/st/data.unknown_mime_type?v=aUsn8CHEhhszc81d28QmlcBW0KQpfS2F4trgQKhOYd8%3D"
)
assert expect_url == str(url)
def test_add_static_append_version_non_exists_file(router: web.UrlDispatcher) -> None:
resource = router.add_static("/st", pathlib.Path(__file__).parent, name="static")
url = resource.url_for(filename="/non_exists_file", append_version=True)
assert "/st/non_exists_file" == str(url)
def test_add_static_append_version_non_exists_file_without_slash(
router: web.UrlDispatcher,
) -> None:
resource = router.add_static("/st", pathlib.Path(__file__).parent, name="static")
url = resource.url_for(filename="non_exists_file", append_version=True)
assert "/st/non_exists_file" == str(url)
def test_add_static_append_version_follow_symlink(
router: web.UrlDispatcher, tmp_path: pathlib.Path
) -> None:
# Tests the access to a symlink, in static folder with apeend_version
symlink_path = tmp_path / "append_version_symlink"
symlink_target_path = pathlib.Path(__file__).parent
pathlib.Path(str(symlink_path)).symlink_to(str(symlink_target_path), True)
# Register global static route:
resource = router.add_static(
"/st", str(tmp_path), follow_symlinks=True, append_version=True
)
url = resource.url_for(filename="/append_version_symlink/data.unknown_mime_type")
expect_url = (
"/st/append_version_symlink/data.unknown_mime_type?"
"v=aUsn8CHEhhszc81d28QmlcBW0KQpfS2F4trgQKhOYd8%3D"
)
assert expect_url == str(url)
def test_add_static_append_version_not_follow_symlink(
router: web.UrlDispatcher, tmp_path: pathlib.Path
) -> None:
# Tests the access to a symlink, in static folder with apeend_version
symlink_path = tmp_path / "append_version_symlink"
symlink_target_path = pathlib.Path(__file__).parent
pathlib.Path(str(symlink_path)).symlink_to(str(symlink_target_path), True)
# Register global static route:
resource = router.add_static(
"/st", str(tmp_path), follow_symlinks=False, append_version=True
)
filename = "/append_version_symlink/data.unknown_mime_type"
url = resource.url_for(filename=filename)
assert "/st/append_version_symlink/data.unknown_mime_type" == str(url)
def test_add_static_quoting(router: web.UrlDispatcher) -> None:
resource = router.add_static(
"/пре %2Fфикс", pathlib.Path(aiohttp.__file__).parent, name="static"
)
assert router["static"] is resource
url = resource.url_for(filename="/1 2/файл%2F.txt")
assert url.path == "/пре /фикс/1 2/файл%2F.txt"
assert str(url) == (
"/%D0%BF%D1%80%D0%B5%20%2F%D1%84%D0%B8%D0%BA%D1%81"
"/1%202/%D1%84%D0%B0%D0%B9%D0%BB%252F.txt"
)
assert len(resource) == 2
def test_plain_not_match(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/get/path", handler, name="name")
route = router["name"]
assert isinstance(route, web.Resource)
assert route._match("/another/path") is None
def test_dynamic_not_match(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/get/{name}", handler, name="name")
route = router["name"]
assert isinstance(route, web.Resource)
assert route._match("/another/path") is None
async def test_static_not_match(router: web.UrlDispatcher) -> None:
router.add_static("/pre", pathlib.Path(aiohttp.__file__).parent, name="name")
resource = router["name"]
ret = await resource.resolve(make_mocked_request("GET", "/another/path"))
assert (None, set()) == ret
async def test_add_static_access_resources(router: web.UrlDispatcher) -> None:
"""Test accessing resource._routes externally.
aiohttp-cors accesses the resource._routes, this test ensures that this
continues to work.
"""
# https://github.com/aio-libs/aiohttp-cors/blob/38c6c17bffc805e46baccd7be1b4fd8c69d95dc3/aiohttp_cors/urldispatcher_router_adapter.py#L187
resource = router.add_static(
"/st", pathlib.Path(aiohttp.__file__).parent, name="static"
)
resource._routes[hdrs.METH_OPTIONS] = resource._routes[hdrs.METH_GET]
resource._allowed_methods.add(hdrs.METH_OPTIONS)
mapping, allowed_methods = await resource.resolve(
make_mocked_request("OPTIONS", "/st/path")
)
assert mapping is not None
assert allowed_methods == {hdrs.METH_GET, hdrs.METH_OPTIONS, hdrs.METH_HEAD}
async def test_add_static_set_options_route(router: web.UrlDispatcher) -> None:
"""Ensure set_options_route works as expected."""
resource = router.add_static(
"/st", pathlib.Path(aiohttp.__file__).parent, name="static"
)
async def handler(request: web.Request) -> NoReturn:
assert False
resource.set_options_route(handler)
mapping, allowed_methods = await resource.resolve(
make_mocked_request("OPTIONS", "/st/path")
)
assert mapping is not None
assert allowed_methods == {hdrs.METH_GET, hdrs.METH_OPTIONS, hdrs.METH_HEAD}
def test_dynamic_with_trailing_slash(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/get/{name}/", handler, name="name")
route = router["name"]
assert isinstance(route, web.Resource)
assert {"name": "John"} == route._match("/get/John/")
def test_len(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/get1", handler, name="name1")
router.add_route("GET", "/get2", handler, name="name2")
assert 2 == len(router)
def test_iter(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/get1", handler, name="name1")
router.add_route("GET", "/get2", handler, name="name2")
assert {"name1", "name2"} == set(iter(router))
def test_contains(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/get1", handler, name="name1")
router.add_route("GET", "/get2", handler, name="name2")
assert "name1" in router
assert "name3" not in router
def test_static_repr(router: web.UrlDispatcher) -> None:
router.add_static("/get", pathlib.Path(aiohttp.__file__).parent, name="name")
assert repr(router["name"]).startswith("<StaticResource 'name' /get")
def test_static_adds_slash(router: web.UrlDispatcher) -> None:
route = router.add_static("/prefix", pathlib.Path(aiohttp.__file__).parent)
assert "/prefix" == route._prefix
def test_static_remove_trailing_slash(router: web.UrlDispatcher) -> None:
route = router.add_static("/prefix/", pathlib.Path(aiohttp.__file__).parent)
assert "/prefix" == route._prefix
@pytest.mark.parametrize(
"pattern,url,expected",
(
(r"{to:\d+}", r"1234", {"to": "1234"}),
("{name}.html", "test.html", {"name": "test"}),
(r"{fn:\w+ \d+}", "abc 123", {"fn": "abc 123"}),
(r"{fn:\w+\s\d+}", "abc 123", {"fn": "abc 123"}),
),
)
async def test_add_route_with_re(
router: web.UrlDispatcher, pattern: str, url: str, expected: dict[str, str]
) -> None:
handler = make_handler()
router.add_route("GET", f"/handler/{pattern}", handler)
req = make_mocked_request("GET", f"/handler/{url}")
info = await router.resolve(req)
assert info is not None
assert info == expected
async def test_add_route_with_re_and_slashes(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", r"/handler/{to:[^/]+/?}", handler)
req = make_mocked_request("GET", "/handler/1234/")
info = await router.resolve(req)
assert info is not None
assert {"to": "1234/"} == info
router.add_route("GET", r"/handler/{to:.+}", handler)
req = make_mocked_request("GET", "/handler/1234/5/6/7")
info = await router.resolve(req)
assert info is not None
assert {"to": "1234/5/6/7"} == info
async def test_add_route_with_re_not_match(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", r"/handler/{to:\d+}", handler)
req = make_mocked_request("GET", "/handler/tail")
match_info = await router.resolve(req)
assert isinstance(match_info.route, SystemRoute)
assert {} == match_info
with pytest.raises(web.HTTPNotFound):
await match_info.handler(req)
async def test_add_route_with_re_including_slashes(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", r"/handler/{to:.+}/tail", handler)
req = make_mocked_request("GET", "/handler/re/with/slashes/tail")
info = await router.resolve(req)
assert info is not None
assert {"to": "re/with/slashes"} == info
def test_add_route_with_invalid_re(router: web.UrlDispatcher) -> None:
handler = make_handler()
with pytest.raises(ValueError) as ctx:
router.add_route("GET", r"/handler/{to:+++}", handler)
s = str(ctx.value)
assert s.startswith(
"Bad pattern '"
+ PATH_SEP
+ "handler"
+ PATH_SEP
+ "(?P<to>+++)': nothing to repeat"
)
assert ctx.value.__cause__ is None
def test_route_dynamic_with_regex_spec(router: web.UrlDispatcher) -> None:
handler = make_handler()
route = router.add_route("GET", r"/get/{num:^\d+}", handler, name="name")
url = route.url_for(num="123")
assert "/get/123" == str(url)
def test_route_dynamic_with_regex_spec_and_trailing_slash(
router: web.UrlDispatcher,
) -> None:
handler = make_handler()
route = router.add_route("GET", r"/get/{num:^\d+}/", handler, name="name")
url = route.url_for(num="123")
assert "/get/123/" == str(url)
def test_route_dynamic_with_regex(router: web.UrlDispatcher) -> None:
handler = make_handler()
route = router.add_route("GET", r"/{one}/{two:.+}", handler)
url = route.url_for(one="1", two="2")
assert "/1/2" == str(url)
def test_route_dynamic_quoting(router: web.UrlDispatcher) -> None:
handler = make_handler()
route = router.add_route("GET", r"/пре %2Fфикс/{arg}", handler)
url = route.url_for(arg="1 2/текст%2F")
assert url.path == "/пре /фикс/1 2/текст%2F"
assert str(url) == (
"/%D0%BF%D1%80%D0%B5%20%2F%D1%84%D0%B8%D0%BA%D1%81"
"/1%202/%D1%82%D0%B5%D0%BA%D1%81%D1%82%252F"
)
async def test_regular_match_info(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/get/{name}", handler)
req = make_mocked_request("GET", "/get/john")
match_info = await router.resolve(req)
assert {"name": "john"} == match_info
assert repr(match_info).startswith("<MatchInfo {'name': 'john'}:")
assert "<Dynamic" in repr(match_info)
async def test_match_info_with_plus(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/get/{version}", handler)
req = make_mocked_request("GET", "/get/1.0+test")
match_info = await router.resolve(req)
assert {"version": "1.0+test"} == match_info
async def test_not_found_repr(router: web.UrlDispatcher) -> None:
req = make_mocked_request("POST", "/path/to")
match_info = await router.resolve(req)
assert "<MatchInfoError 404: Not Found>" == repr(match_info)
async def test_not_allowed_repr(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/path/to", handler)
handler2 = make_handler()
router.add_route("POST", "/path/to", handler2)
req = make_mocked_request("PUT", "/path/to")
match_info = await router.resolve(req)
assert "<MatchInfoError 405: Method Not Allowed>" == repr(match_info)
def test_default_expect_handler(router: web.UrlDispatcher) -> None:
route = router.add_route("GET", "/", make_handler())
assert route._expect_handler is _default_expect_handler
def test_custom_expect_handler_plain(router: web.UrlDispatcher) -> None:
async def handler(request: web.Request) -> NoReturn:
assert False
route = router.add_route("GET", "/", make_handler(), expect_handler=handler)
assert route._expect_handler is handler
assert isinstance(route, web.ResourceRoute)
def test_custom_expect_handler_dynamic(router: web.UrlDispatcher) -> None:
async def handler(request: web.Request) -> NoReturn:
assert False
route = router.add_route(
"GET", "/get/{name}", make_handler(), expect_handler=handler
)
assert route._expect_handler is handler
assert isinstance(route, web.ResourceRoute)
def test_expect_handler_non_coroutine(router: web.UrlDispatcher) -> None:
def handler(request: web.Request) -> NoReturn:
assert False
with pytest.raises(AssertionError):
router.add_route("GET", "/", make_handler(), expect_handler=handler)
async def test_dynamic_match_non_ascii(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/{var}", handler)
req = make_mocked_request(
"GET", "/%D1%80%D1%83%D1%81%20%D1%82%D0%B5%D0%BA%D1%81%D1%82"
)
match_info = await router.resolve(req)
assert {"var": "рус текст"} == match_info
async def test_dynamic_match_with_static_part(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/{name}.html", handler)
req = make_mocked_request("GET", "/file.html")
match_info = await router.resolve(req)
assert {"name": "file"} == match_info
async def test_dynamic_match_two_part2(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/{name}.{ext}", handler)
req = make_mocked_request("GET", "/file.html")
match_info = await router.resolve(req)
assert {"name": "file", "ext": "html"} == match_info
async def test_dynamic_match_unquoted_path(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/{path}/{subpath}", handler)
resource_id = "my%2Fpath%7Cwith%21some%25strange%24characters"
req = make_mocked_request("GET", f"/path/{resource_id}")
match_info = await router.resolve(req)
assert match_info == {"path": "path", "subpath": unquote(resource_id)}
async def test_dynamic_match_double_quoted_path(router: web.UrlDispatcher) -> None:
"""Verify that double-quoted path is unquoted only once."""
handler = make_handler()
router.add_route("GET", "/{path}/{subpath}", handler)
resource_id = quote("my/path|with!some%strange$characters", safe="")
double_quoted_resource_id = quote(resource_id, safe="")
req = make_mocked_request("GET", f"/path/{double_quoted_resource_id}")
match_info = await router.resolve(req)
assert match_info == {"path": "path", "subpath": resource_id}
def test_add_route_not_started_with_slash(router: web.UrlDispatcher) -> None:
with pytest.raises(ValueError):
handler = make_handler()
router.add_route("GET", "invalid_path", handler)
def test_add_route_invalid_method(router: web.UrlDispatcher) -> None:
sample_bad_methods = {
"BAD METHOD",
"B@D_METHOD",
"[BAD_METHOD]",
"{BAD_METHOD}",
"(BAD_METHOD)",
"B?D_METHOD",
}
for bad_method in sample_bad_methods:
with pytest.raises(ValueError):
handler = make_handler()
router.add_route(bad_method, "/path", handler)
def test_routes_view_len(
router: web.UrlDispatcher, fill_routes: Callable[[], list[web.AbstractRoute]]
) -> None:
fill_routes()
assert 4 == len(router.routes())
def test_routes_view_iter(
router: web.UrlDispatcher, fill_routes: Callable[[], list[web.AbstractRoute]]
) -> None:
routes = fill_routes()
assert list(routes) == list(router.routes())
def test_routes_view_contains(
router: web.UrlDispatcher, fill_routes: Callable[[], list[web.AbstractRoute]]
) -> None:
routes = fill_routes()
for route in routes:
assert route in router.routes()
def test_routes_abc(router: web.UrlDispatcher) -> None:
assert isinstance(router.routes(), Sized)
assert isinstance(router.routes(), Iterable)
assert isinstance(router.routes(), Container)
def test_named_resources_abc(router: web.UrlDispatcher) -> None:
assert isinstance(router.named_resources(), Mapping)
assert not isinstance(router.named_resources(), MutableMapping)
def test_named_resources(router: web.UrlDispatcher) -> None:
route1 = router.add_route("GET", "/plain", make_handler(), name="route1")
route2 = router.add_route("GET", "/variable/{name}", make_handler(), name="route2")
route3 = router.add_static(
"/static", pathlib.Path(aiohttp.__file__).parent, name="route3"
)
names = {route1.name, route2.name, route3.name}
assert 3 == len(router.named_resources())
for name in names:
assert name is not None
assert name in router.named_resources()
assert isinstance(router.named_resources()[name], web.AbstractResource)
def test_resource_iter(router: web.UrlDispatcher) -> None:
async def handler(request: web.Request) -> NoReturn:
assert False
resource = router.add_resource("/path")
r1 = resource.add_route("GET", handler)
r2 = resource.add_route("POST", handler)
assert 2 == len(resource)
assert [r1, r2] == list(resource)
def test_view_route(router: web.UrlDispatcher) -> None:
resource = router.add_resource("/path")
route = resource.add_route("*", web.View)
assert web.View is route.handler
def test_resource_route_match(router: web.UrlDispatcher) -> None:
async def handler(request: web.Request) -> NoReturn:
assert False
resource = router.add_resource("/path")
route = resource.add_route("GET", handler)
assert isinstance(route.resource, web.Resource)
assert {} == route.resource._match("/path")
def test_error_on_double_route_adding(router: web.UrlDispatcher) -> None:
async def handler(request: web.Request) -> NoReturn:
assert False
resource = router.add_resource("/path")
resource.add_route("GET", handler)
with pytest.raises(RuntimeError):
resource.add_route("GET", handler)
def test_error_on_adding_route_after_wildcard(router: web.UrlDispatcher) -> None:
async def handler(request: web.Request) -> NoReturn:
assert False
resource = router.add_resource("/path")
resource.add_route("*", handler)
with pytest.raises(RuntimeError):
resource.add_route("GET", handler)
async def test_http_exception_is_none_when_resolved(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/", handler)
req = make_mocked_request("GET", "/")
info = await router.resolve(req)
assert info.http_exception is None
async def test_http_exception_is_not_none_when_not_resolved(
router: web.UrlDispatcher,
) -> None:
handler = make_handler()
router.add_route("GET", "/", handler)
req = make_mocked_request("GET", "/abc")
info = await router.resolve(req)
assert info.http_exception is not None
assert info.http_exception.status == 404
async def test_match_info_get_info_plain(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/", handler)
req = make_mocked_request("GET", "/")
info = await router.resolve(req)
assert info.get_info() == {"path": "/"}
async def test_match_info_get_info_dynamic(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/{a}", handler)
req = make_mocked_request("GET", "/value")
info = await router.resolve(req)
assert info.get_info() == {
"pattern": re.compile(PATH_SEP + "(?P<a>[^{}/]+)"),
"formatter": "/{a}",
}
async def test_match_info_get_info_dynamic2(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/{a}/{b}", handler)
req = make_mocked_request("GET", "/path/to")
info = await router.resolve(req)
assert info.get_info() == {
"pattern": re.compile(
PATH_SEP + "(?P<a>[^{}/]+)" + PATH_SEP + "(?P<b>[^{}/]+)"
),
"formatter": "/{a}/{b}",
}
def test_static_resource_get_info(router: web.UrlDispatcher) -> None:
directory = pathlib.Path(aiohttp.__file__).parent.resolve()
resource = router.add_static("/st", directory)
info = resource.get_info()
assert len(info) == 3
assert info["directory"] == directory
assert info["prefix"] == "/st"
assert all([type(r) is web.ResourceRoute for r in info["routes"].values()])
async def test_system_route_get_info(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/", handler)
req = make_mocked_request("GET", "/abc")
info = await router.resolve(req)
assert info.get_info()["http_exception"].status == 404
def test_resources_view_len(router: web.UrlDispatcher) -> None:
router.add_resource("/plain")
router.add_resource("/variable/{name}")
assert 2 == len(router.resources())
def test_resources_view_iter(router: web.UrlDispatcher) -> None:
resource1 = router.add_resource("/plain")
resource2 = router.add_resource("/variable/{name}")
resources = [resource1, resource2]
assert list(resources) == list(router.resources())
def test_resources_view_contains(router: web.UrlDispatcher) -> None:
resource1 = router.add_resource("/plain")
resource2 = router.add_resource("/variable/{name}")
resources = [resource1, resource2]
for resource in resources:
assert resource in router.resources()
def test_resources_abc(router: web.UrlDispatcher) -> None:
assert isinstance(router.resources(), Sized)
assert isinstance(router.resources(), Iterable)
assert isinstance(router.resources(), Container)
def test_static_route_user_home(router: web.UrlDispatcher) -> None:
here = pathlib.Path(aiohttp.__file__).parent
try:
static_dir = pathlib.Path("~") / here.relative_to(pathlib.Path.home())
except ValueError:
pytest.skip("aiohttp folder is not placed in user's HOME")
route = router.add_static("/st", str(static_dir))
assert here == route.get_info()["directory"]
def test_static_route_points_to_file(router: web.UrlDispatcher) -> None:
here = pathlib.Path(aiohttp.__file__).parent / "__init__.py"
with pytest.raises(ValueError):
router.add_static("/st", here)
async def test_404_for_static_resource(router: web.UrlDispatcher) -> None:
resource = router.add_static("/st", pathlib.Path(aiohttp.__file__).parent)
ret = await resource.resolve(make_mocked_request("GET", "/unknown/path"))
assert (None, set()) == ret
async def test_405_for_resource_adapter(router: web.UrlDispatcher) -> None:
resource = router.add_static("/st", pathlib.Path(aiohttp.__file__).parent)
ret = await resource.resolve(make_mocked_request("POST", "/st/abc.py"))
assert (None, {"HEAD", "GET"}) == ret
async def test_check_allowed_method_for_found_resource(
router: web.UrlDispatcher,
) -> None:
handler = make_handler()
resource = router.add_resource("/")
resource.add_route("GET", handler)
ret = await resource.resolve(make_mocked_request("GET", "/"))
assert ret[0] is not None
assert {"GET"} == ret[1]
def test_url_for_in_static_resource(router: web.UrlDispatcher) -> None:
resource = router.add_static("/static", pathlib.Path(aiohttp.__file__).parent)
assert URL("/static/file.txt") == resource.url_for(filename="file.txt")
def test_url_for_in_static_resource_pathlib(router: web.UrlDispatcher) -> None:
resource = router.add_static("/static", pathlib.Path(aiohttp.__file__).parent)
assert URL("/static/file.txt") == resource.url_for(
filename=pathlib.Path("file.txt")
)
def test_url_for_in_resource_route(router: web.UrlDispatcher) -> None:
route = router.add_route("GET", "/get/{name}", make_handler(), name="name")
assert URL("/get/John") == route.url_for(name="John")
def test_subapp_get_info(app: web.Application) -> None:
subapp = web.Application()
resource = subapp.add_subapp("/pre", subapp)
assert resource.get_info() == {"prefix": "/pre", "app": subapp}
@pytest.mark.parametrize(
"domain,error",
[
(None, TypeError),
("", ValueError),
("http://dom", ValueError),
("*.example.com", ValueError),
("example$com", ValueError),
],
)
def test_domain_validation_error(domain: str | None, error: type[Exception]) -> None:
with pytest.raises(error):
Domain(domain) # type: ignore[arg-type]
def test_domain_valid() -> None:
assert Domain("example.com:81").canonical == "example.com:81"
assert MaskDomain("*.example.com").canonical == r".*\.example\.com"
assert Domain("пуни.код").canonical == "xn--h1ajfq.xn--d1alm"
@pytest.mark.parametrize(
"a,b,result",
[
("example.com", "example.com", True),
("example.com:81", "example.com:81", True),
("example.com:81", "example.com", False),
("пуникод", "xn--d1ahgkhc2a", True),
("*.example.com", "jpg.example.com", True),
("*.example.com", "a.example.com", True),
("*.example.com", "example.com", False),
],
)
def test_match_domain(a: str, b: str, result: bool) -> None:
if "*" in a:
rule: Domain = MaskDomain(a)
else:
rule = Domain(a)
assert rule.match_domain(b) is result
def test_add_subapp_errors(app: web.Application) -> None:
with pytest.raises(TypeError):
app.add_subapp(1, web.Application()) # type: ignore[arg-type]
def test_subapp_rule_resource(app: web.Application) -> None:
subapp = web.Application()
subapp.router.add_get("/", make_handler())
rule = Domain("example.com")
assert rule.get_info() == {"domain": "example.com"}
resource = app.add_domain("example.com", subapp)
assert resource.canonical == "example.com"
assert resource.get_info() == {"rule": resource._rule, "app": subapp}
resource.add_prefix("/a")
resource.raw_match("/b")
assert len(resource)
assert list(resource)
assert repr(resource).startswith("<MatchedSubAppResource")
with pytest.raises(RuntimeError):
resource.url_for()
async def test_add_domain_not_str(
app: web.Application, loop: asyncio.AbstractEventLoop
) -> None:
app = web.Application()
with pytest.raises(TypeError):
app.add_domain(1, app) # type: ignore[arg-type]
async def test_add_domain(
app: web.Application, loop: asyncio.AbstractEventLoop
) -> None:
subapp1 = web.Application()
h1 = make_handler()
subapp1.router.add_get("/", h1)
app.add_domain("example.com", subapp1)
subapp2 = web.Application()
h2 = make_handler()
subapp2.router.add_get("/", h2)
app.add_domain("*.example.com", subapp2)
subapp3 = web.Application()
h3 = make_handler()
subapp3.router.add_get("/", h3)
app.add_domain("*", subapp3)
request = make_mocked_request("GET", "/", {"host": "example.com"})
match_info = await app.router.resolve(request)
assert match_info.route.handler is h1
request = make_mocked_request("GET", "/", {"host": "a.example.com"})
match_info = await app.router.resolve(request)
assert match_info.route.handler is h2
request = make_mocked_request("GET", "/", {"host": "example2.com"})
match_info = await app.router.resolve(request)
assert match_info.route.handler is h3
request = make_mocked_request("POST", "/", {"host": "example.com"})
match_info = await app.router.resolve(request)
assert isinstance(match_info.http_exception, web.HTTPMethodNotAllowed)
def test_subapp_url_for(app: web.Application) -> None:
subapp = web.Application()
resource = app.add_subapp("/pre", subapp)
with pytest.raises(RuntimeError):
resource.url_for()
def test_subapp_repr(app: web.Application) -> None:
subapp = web.Application()
resource = app.add_subapp("/pre", subapp)
assert repr(resource).startswith("<PrefixedSubAppResource /pre -> <Application")
def test_subapp_len(app: web.Application) -> None:
subapp = web.Application()
subapp.router.add_get("/", make_handler(), allow_head=False)
subapp.router.add_post("/", make_handler())
resource = app.add_subapp("/pre", subapp)
assert len(resource) == 2
def test_subapp_iter(app: web.Application) -> None:
subapp = web.Application()
r1 = subapp.router.add_get("/", make_handler(), allow_head=False)
r2 = subapp.router.add_post("/", make_handler())
resource = app.add_subapp("/pre", subapp)
assert list(resource) == [r1, r2]
@pytest.mark.parametrize(
"route_name",
(
"invalid name",
"class",
),
)
def test_invalid_route_name(router: web.UrlDispatcher, route_name: str) -> None:
with pytest.raises(ValueError):
router.add_get("/", make_handler(), name=route_name)
def test_frozen_router(router: web.UrlDispatcher) -> None:
router.freeze()
with pytest.raises(RuntimeError):
router.add_get("/", make_handler())
def test_frozen_router_subapp(app: web.Application) -> None:
subapp = web.Application()
subapp.freeze()
with pytest.raises(RuntimeError):
app.add_subapp("/pre", subapp)
def test_frozen_app_on_subapp(app: web.Application) -> None:
app.freeze()
subapp = web.Application()
with pytest.raises(RuntimeError):
app.add_subapp("/pre", subapp)
def test_set_options_route(router: web.UrlDispatcher) -> None:
resource = router.add_static("/static", pathlib.Path(aiohttp.__file__).parent)
options = None
for route in resource:
if route.method == "OPTIONS":
options = route
assert options is None
resource.set_options_route(make_handler())
for route in resource:
if route.method == "OPTIONS":
options = route
assert options is not None
with pytest.raises(RuntimeError):
resource.set_options_route(make_handler())
def test_dynamic_url_with_name_started_from_underscore(
router: web.UrlDispatcher,
) -> None:
route = router.add_route("GET", "/get/{_name}", make_handler())
assert URL("/get/John") == route.url_for(_name="John")
def test_cannot_add_subapp_with_empty_prefix(app: web.Application) -> None:
subapp = web.Application()
with pytest.raises(ValueError):
app.add_subapp("", subapp)
def test_cannot_add_subapp_with_slash_prefix(app: web.Application) -> None:
subapp = web.Application()
with pytest.raises(ValueError):
app.add_subapp("/", subapp)
async def test_convert_empty_path_to_slash_on_freezing(
router: web.UrlDispatcher,
) -> None:
handler = make_handler()
route = router.add_get("", handler)
resource = route.resource
assert resource is not None
assert resource.get_info() == {"path": ""}
router.freeze()
assert resource.get_info() == {"path": "/"}
def test_plain_resource_canonical() -> None:
canonical = "/plain/path"
res = web.PlainResource(path=canonical)
assert res.canonical == canonical
def test_dynamic_resource_canonical() -> None:
canonicals = {
"/get/{name}": "/get/{name}",
r"/get/{num:^\d+}": "/get/{num}",
r"/handler/{to:\d+}": r"/handler/{to}",
r"/{one}/{two:.+}": r"/{one}/{two}",
}
for pattern, canonical in canonicals.items():
res = web.DynamicResource(path=pattern)
assert res.canonical == canonical
def test_static_resource_canonical() -> None:
prefix = "/prefix"
directory = str(pathlib.Path(aiohttp.__file__).parent)
canonical = prefix
res = web.StaticResource(prefix=prefix, directory=directory)
assert res.canonical == canonical
def test_prefixed_subapp_resource_canonical(app: web.Application) -> None:
canonical = "/prefix"
subapp = web.Application()
res = subapp.add_subapp(canonical, subapp)
assert res.canonical == canonical
async def test_prefixed_subapp_overlap(app: web.Application) -> None:
# Subapp should not overshadow other subapps with overlapping prefixes
subapp1 = web.Application()
handler1 = make_handler()
subapp1.router.add_get("/a", handler1)
app.add_subapp("/s", subapp1)
subapp2 = web.Application()
handler2 = make_handler()
subapp2.router.add_get("/b", handler2)
app.add_subapp("/ss", subapp2)
subapp3 = web.Application()
handler3 = make_handler()
subapp3.router.add_get("/c", handler3)
app.add_subapp("/s/s", subapp3)
match_info = await app.router.resolve(make_mocked_request("GET", "/s/a"))
assert match_info.route.handler is handler1
match_info = await app.router.resolve(make_mocked_request("GET", "/ss/b"))
assert match_info.route.handler is handler2
match_info = await app.router.resolve(make_mocked_request("GET", "/s/s/c"))
assert match_info.route.handler is handler3
async def test_prefixed_subapp_empty_route(app: web.Application) -> None:
subapp = web.Application()
handler = make_handler()
subapp.router.add_get("", handler)
app.add_subapp("/s", subapp)
match_info = await app.router.resolve(make_mocked_request("GET", "/s"))
assert match_info.route.handler is handler
match_info = await app.router.resolve(make_mocked_request("GET", "/s/"))
assert "<MatchInfoError 404: Not Found>" == repr(match_info)
async def test_prefixed_subapp_root_route(app: web.Application) -> None:
subapp = web.Application()
handler = make_handler()
subapp.router.add_get("/", handler)
app.add_subapp("/s", subapp)
match_info = await app.router.resolve(make_mocked_request("GET", "/s/"))
assert match_info.route.handler is handler
match_info = await app.router.resolve(make_mocked_request("GET", "/s"))
assert "<MatchInfoError 404: Not Found>" == repr(match_info)
| aiohttp |
python | import abc
import asyncio
import base64
import functools
import hashlib
import html
import inspect
import keyword
import os
import re
import sys
from collections.abc import (
Awaitable,
Callable,
Container,
Generator,
Iterable,
Iterator,
Mapping,
Sized,
)
from pathlib import Path
from re import Pattern
from types import MappingProxyType
from typing import TYPE_CHECKING, Any, Final, NoReturn, Optional, TypedDict, cast
from yarl import URL
from . import hdrs
from .abc import AbstractMatchInfo, AbstractRouter, AbstractView
from .helpers import DEBUG
from .http import HttpVersion11
from .typedefs import Handler, PathLike
from .web_exceptions import (
HTTPException,
HTTPExpectationFailed,
HTTPForbidden,
HTTPMethodNotAllowed,
HTTPNotFound,
)
from .web_fileresponse import FileResponse
from .web_request import Request
from .web_response import Response, StreamResponse
from .web_routedef import AbstractRouteDef
__all__ = (
"UrlDispatcher",
"UrlMappingMatchInfo",
"AbstractResource",
"Resource",
"PlainResource",
"DynamicResource",
"AbstractRoute",
"ResourceRoute",
"StaticResource",
"View",
)
if TYPE_CHECKING:
from .web_app import Application
CIRCULAR_SYMLINK_ERROR = (RuntimeError,) if sys.version_info < (3, 13) else ()
HTTP_METHOD_RE: Final[Pattern[str]] = re.compile(
r"^[0-9A-Za-z!#\$%&'\*\+\-\.\^_`\|~]+$"
)
ROUTE_RE: Final[Pattern[str]] = re.compile(
r"(\{[_a-zA-Z][^{}]*(?:\{[^{}]*\}[^{}]*)*\})"
)
PATH_SEP: Final[str] = re.escape("/")
_ExpectHandler = Callable[[Request], Awaitable[StreamResponse | None]]
_Resolve = tuple[Optional["UrlMappingMatchInfo"], set[str]]
html_escape = functools.partial(html.escape, quote=True)
class _InfoDict(TypedDict, total=False):
path: str
formatter: str
pattern: Pattern[str]
directory: Path
prefix: str
routes: Mapping[str, "AbstractRoute"]
app: "Application"
domain: str
rule: "AbstractRuleMatching"
http_exception: HTTPException
class AbstractResource(Sized, Iterable["AbstractRoute"]):
def __init__(self, *, name: str | None = None) -> None:
self._name = name
@property
def name(self) -> str | None:
return self._name
@property
@abc.abstractmethod
def canonical(self) -> str:
"""Exposes the resource's canonical path.
For example '/foo/bar/{name}'
"""
@abc.abstractmethod # pragma: no branch
def url_for(self, **kwargs: str) -> URL:
"""Construct url for resource with additional params."""
@abc.abstractmethod # pragma: no branch
async def resolve(self, request: Request) -> _Resolve:
"""Resolve resource.
Return (UrlMappingMatchInfo, allowed_methods) pair.
"""
@abc.abstractmethod
def add_prefix(self, prefix: str) -> None:
"""Add a prefix to processed URLs.
Required for subapplications support.
"""
@abc.abstractmethod
def get_info(self) -> _InfoDict:
"""Return a dict with additional info useful for introspection"""
def freeze(self) -> None:
pass
@abc.abstractmethod
def raw_match(self, path: str) -> bool:
"""Perform a raw match against path"""
class AbstractRoute(abc.ABC):
def __init__(
self,
method: str,
handler: Handler | type[AbstractView],
*,
expect_handler: _ExpectHandler | None = None,
resource: AbstractResource | None = None,
) -> None:
if expect_handler is None:
expect_handler = _default_expect_handler
assert inspect.iscoroutinefunction(expect_handler) or (
sys.version_info < (3, 14) and asyncio.iscoroutinefunction(expect_handler)
), f"Coroutine is expected, got {expect_handler!r}"
method = method.upper()
if not HTTP_METHOD_RE.match(method):
raise ValueError(f"{method} is not allowed HTTP method")
if inspect.iscoroutinefunction(handler) or (
sys.version_info < (3, 14) and asyncio.iscoroutinefunction(handler)
):
pass
elif isinstance(handler, type) and issubclass(handler, AbstractView):
pass
else:
raise TypeError(
f"Only async functions are allowed as web-handlers, got {handler!r}"
)
self._method = method
self._handler = handler
self._expect_handler = expect_handler
self._resource = resource
@property
def method(self) -> str:
return self._method
@property
def handler(self) -> Handler:
return self._handler
@property
@abc.abstractmethod
def name(self) -> str | None:
"""Optional route's name, always equals to resource's name."""
@property
def resource(self) -> AbstractResource | None:
return self._resource
@abc.abstractmethod
def get_info(self) -> _InfoDict:
"""Return a dict with additional info useful for introspection"""
@abc.abstractmethod # pragma: no branch
def url_for(self, *args: str, **kwargs: str) -> URL:
"""Construct url for route with additional params."""
async def handle_expect_header(self, request: Request) -> StreamResponse | None:
return await self._expect_handler(request)
class UrlMappingMatchInfo(dict[str, str], AbstractMatchInfo):
__slots__ = ("_route", "_apps", "_current_app", "_frozen")
def __init__(self, match_dict: dict[str, str], route: AbstractRoute) -> None:
super().__init__(match_dict)
self._route = route
self._apps: list[Application] = []
self._current_app: Application | None = None
self._frozen = False
@property
def handler(self) -> Handler:
return self._route.handler
@property
def route(self) -> AbstractRoute:
return self._route
@property
def expect_handler(self) -> _ExpectHandler:
return self._route.handle_expect_header
@property
def http_exception(self) -> HTTPException | None:
return None
def get_info(self) -> _InfoDict: # type: ignore[override]
return self._route.get_info()
@property
def apps(self) -> tuple["Application", ...]:
return tuple(self._apps)
def add_app(self, app: "Application") -> None:
if self._frozen:
raise RuntimeError("Cannot change apps stack after .freeze() call")
if self._current_app is None:
self._current_app = app
self._apps.insert(0, app)
@property
def current_app(self) -> "Application":
app = self._current_app
assert app is not None
return app
@current_app.setter
def current_app(self, app: "Application") -> None:
if DEBUG:
if app not in self._apps:
raise RuntimeError(
f"Expected one of the following apps {self._apps!r}, got {app!r}"
)
self._current_app = app
def freeze(self) -> None:
self._frozen = True
def __repr__(self) -> str:
return f"<MatchInfo {super().__repr__()}: {self._route}>"
class MatchInfoError(UrlMappingMatchInfo):
__slots__ = ("_exception",)
def __init__(self, http_exception: HTTPException) -> None:
self._exception = http_exception
super().__init__({}, SystemRoute(self._exception))
@property
def http_exception(self) -> HTTPException:
return self._exception
def __repr__(self) -> str:
return f"<MatchInfoError {self._exception.status}: {self._exception.reason}>"
async def _default_expect_handler(request: Request) -> None:
"""Default handler for Expect header.
Just send "100 Continue" to client.
raise HTTPExpectationFailed if value of header is not "100-continue"
"""
expect = request.headers.get(hdrs.EXPECT, "")
if request.version == HttpVersion11:
if expect.lower() == "100-continue":
await request.writer.write(b"HTTP/1.1 100 Continue\r\n\r\n")
# Reset output_size as we haven't started the main body yet.
request.writer.output_size = 0
else:
raise HTTPExpectationFailed(text="Unknown Expect: %s" % expect)
class Resource(AbstractResource):
def __init__(self, *, name: str | None = None) -> None:
super().__init__(name=name)
self._routes: dict[str, ResourceRoute] = {}
self._any_route: ResourceRoute | None = None
self._allowed_methods: set[str] = set()
def add_route(
self,
method: str,
handler: type[AbstractView] | Handler,
*,
expect_handler: _ExpectHandler | None = None,
) -> "ResourceRoute":
if route := self._routes.get(method, self._any_route):
raise RuntimeError(
"Added route will never be executed, "
f"method {route.method} is already "
"registered"
)
route_obj = ResourceRoute(method, handler, self, expect_handler=expect_handler)
self.register_route(route_obj)
return route_obj
def register_route(self, route: "ResourceRoute") -> None:
assert isinstance(
route, ResourceRoute
), f"Instance of Route class is required, got {route!r}"
if route.method == hdrs.METH_ANY:
self._any_route = route
self._allowed_methods.add(route.method)
self._routes[route.method] = route
async def resolve(self, request: Request) -> _Resolve:
if (match_dict := self._match(request.rel_url.path_safe)) is None:
return None, set()
if route := self._routes.get(request.method, self._any_route):
return UrlMappingMatchInfo(match_dict, route), self._allowed_methods
return None, self._allowed_methods
@abc.abstractmethod
def _match(self, path: str) -> dict[str, str] | None:
"""Return dict of path values if path matches this resource, otherwise None."""
def __len__(self) -> int:
return len(self._routes)
def __iter__(self) -> Iterator["ResourceRoute"]:
return iter(self._routes.values())
# TODO: implement all abstract methods
class PlainResource(Resource):
def __init__(self, path: str, *, name: str | None = None) -> None:
super().__init__(name=name)
assert not path or path.startswith("/")
self._path = path
@property
def canonical(self) -> str:
return self._path
def freeze(self) -> None:
if not self._path:
self._path = "/"
def add_prefix(self, prefix: str) -> None:
assert prefix.startswith("/")
assert not prefix.endswith("/")
assert len(prefix) > 1
self._path = prefix + self._path
def _match(self, path: str) -> dict[str, str] | None:
# string comparison is about 10 times faster than regexp matching
if self._path == path:
return {}
return None
def raw_match(self, path: str) -> bool:
return self._path == path
def get_info(self) -> _InfoDict:
return {"path": self._path}
def url_for(self) -> URL: # type: ignore[override]
return URL.build(path=self._path, encoded=True)
def __repr__(self) -> str:
name = "'" + self.name + "' " if self.name is not None else ""
return f"<PlainResource {name} {self._path}>"
class DynamicResource(Resource):
DYN = re.compile(r"\{(?P<var>[_a-zA-Z][_a-zA-Z0-9]*)\}")
DYN_WITH_RE = re.compile(r"\{(?P<var>[_a-zA-Z][_a-zA-Z0-9]*):(?P<re>.+)\}")
GOOD = r"[^{}/]+"
def __init__(self, path: str, *, name: str | None = None) -> None:
super().__init__(name=name)
self._orig_path = path
pattern = ""
formatter = ""
for part in ROUTE_RE.split(path):
match = self.DYN.fullmatch(part)
if match:
pattern += "(?P<{}>{})".format(match.group("var"), self.GOOD)
formatter += "{" + match.group("var") + "}"
continue
match = self.DYN_WITH_RE.fullmatch(part)
if match:
pattern += "(?P<{var}>{re})".format(**match.groupdict())
formatter += "{" + match.group("var") + "}"
continue
if "{" in part or "}" in part:
raise ValueError(f"Invalid path '{path}'['{part}']")
part = _requote_path(part)
formatter += part
pattern += re.escape(part)
try:
compiled = re.compile(pattern)
except re.error as exc:
raise ValueError(f"Bad pattern '{pattern}': {exc}") from None
assert compiled.pattern.startswith(PATH_SEP)
assert formatter.startswith("/")
self._pattern = compiled
self._formatter = formatter
@property
def canonical(self) -> str:
return self._formatter
def add_prefix(self, prefix: str) -> None:
assert prefix.startswith("/")
assert not prefix.endswith("/")
assert len(prefix) > 1
self._pattern = re.compile(re.escape(prefix) + self._pattern.pattern)
self._formatter = prefix + self._formatter
def _match(self, path: str) -> dict[str, str] | None:
match = self._pattern.fullmatch(path)
if match is None:
return None
return {
key: _unquote_path_safe(value) for key, value in match.groupdict().items()
}
def raw_match(self, path: str) -> bool:
return self._orig_path == path
def get_info(self) -> _InfoDict:
return {"formatter": self._formatter, "pattern": self._pattern}
def url_for(self, **parts: str) -> URL:
url = self._formatter.format_map({k: _quote_path(v) for k, v in parts.items()})
return URL.build(path=url, encoded=True)
def __repr__(self) -> str:
name = "'" + self.name + "' " if self.name is not None else ""
return f"<DynamicResource {name} {self._formatter}>"
class PrefixResource(AbstractResource):
def __init__(self, prefix: str, *, name: str | None = None) -> None:
assert not prefix or prefix.startswith("/"), prefix
assert prefix in ("", "/") or not prefix.endswith("/"), prefix
super().__init__(name=name)
self._prefix = _requote_path(prefix)
self._prefix2 = self._prefix + "/"
@property
def canonical(self) -> str:
return self._prefix
def add_prefix(self, prefix: str) -> None:
assert prefix.startswith("/")
assert not prefix.endswith("/")
assert len(prefix) > 1
self._prefix = prefix + self._prefix
self._prefix2 = self._prefix + "/"
def raw_match(self, prefix: str) -> bool:
return False
# TODO: impl missing abstract methods
class StaticResource(PrefixResource):
VERSION_KEY = "v"
def __init__(
self,
prefix: str,
directory: PathLike,
*,
name: str | None = None,
expect_handler: _ExpectHandler | None = None,
chunk_size: int = 256 * 1024,
show_index: bool = False,
follow_symlinks: bool = False,
append_version: bool = False,
) -> None:
super().__init__(prefix, name=name)
try:
directory = Path(directory).expanduser().resolve(strict=True)
except FileNotFoundError as error:
raise ValueError(f"'{directory}' does not exist") from error
if not directory.is_dir():
raise ValueError(f"'{directory}' is not a directory")
self._directory = directory
self._show_index = show_index
self._chunk_size = chunk_size
self._follow_symlinks = follow_symlinks
self._expect_handler = expect_handler
self._append_version = append_version
self._routes = {
"GET": ResourceRoute(
"GET", self._handle, self, expect_handler=expect_handler
),
"HEAD": ResourceRoute(
"HEAD", self._handle, self, expect_handler=expect_handler
),
}
self._allowed_methods = set(self._routes)
def url_for( # type: ignore[override]
self,
*,
filename: PathLike,
append_version: bool | None = None,
) -> URL:
if append_version is None:
append_version = self._append_version
filename = str(filename).lstrip("/")
url = URL.build(path=self._prefix, encoded=True)
# filename is not encoded
url = url / filename
if append_version:
unresolved_path = self._directory.joinpath(filename)
try:
if self._follow_symlinks:
normalized_path = Path(os.path.normpath(unresolved_path))
normalized_path.relative_to(self._directory)
filepath = normalized_path.resolve()
else:
filepath = unresolved_path.resolve()
filepath.relative_to(self._directory)
except (ValueError, FileNotFoundError):
# ValueError for case when path point to symlink
# with follow_symlinks is False
return url # relatively safe
if filepath.is_file():
# TODO cache file content
# with file watcher for cache invalidation
with filepath.open("rb") as f:
file_bytes = f.read()
h = self._get_file_hash(file_bytes)
url = url.with_query({self.VERSION_KEY: h})
return url
return url
@staticmethod
def _get_file_hash(byte_array: bytes) -> str:
m = hashlib.sha256() # todo sha256 can be configurable param
m.update(byte_array)
b64 = base64.urlsafe_b64encode(m.digest())
return b64.decode("ascii")
def get_info(self) -> _InfoDict:
return {
"directory": self._directory,
"prefix": self._prefix,
"routes": self._routes,
}
def set_options_route(self, handler: Handler) -> None:
if "OPTIONS" in self._routes:
raise RuntimeError("OPTIONS route was set already")
self._routes["OPTIONS"] = ResourceRoute(
"OPTIONS", handler, self, expect_handler=self._expect_handler
)
self._allowed_methods.add("OPTIONS")
async def resolve(self, request: Request) -> _Resolve:
path = request.rel_url.path_safe
method = request.method
if not path.startswith(self._prefix2) and path != self._prefix:
return None, set()
allowed_methods = self._allowed_methods
if method not in allowed_methods:
return None, allowed_methods
match_dict = {"filename": _unquote_path_safe(path[len(self._prefix) + 1 :])}
return (UrlMappingMatchInfo(match_dict, self._routes[method]), allowed_methods)
def __len__(self) -> int:
return len(self._routes)
def __iter__(self) -> Iterator[AbstractRoute]:
return iter(self._routes.values())
async def _handle(self, request: Request) -> StreamResponse:
rel_url = request.match_info["filename"]
filename = Path(rel_url)
if filename.anchor:
# rel_url is an absolute name like
# /static/\\machine_name\c$ or /static/D:\path
# where the static dir is totally different
raise HTTPForbidden()
unresolved_path = self._directory.joinpath(filename)
loop = asyncio.get_running_loop()
return await loop.run_in_executor(
None, self._resolve_path_to_response, unresolved_path
)
def _resolve_path_to_response(self, unresolved_path: Path) -> StreamResponse:
"""Take the unresolved path and query the file system to form a response."""
# Check for access outside the root directory. For follow symlinks, URI
# cannot traverse out, but symlinks can. Otherwise, no access outside
# root is permitted.
try:
if self._follow_symlinks:
normalized_path = Path(os.path.normpath(unresolved_path))
normalized_path.relative_to(self._directory)
file_path = normalized_path.resolve()
else:
file_path = unresolved_path.resolve()
file_path.relative_to(self._directory)
except (ValueError, *CIRCULAR_SYMLINK_ERROR) as error:
# ValueError is raised for the relative check. Circular symlinks
# raise here on resolving for python < 3.13.
raise HTTPNotFound() from error
# if path is a directory, return the contents if permitted. Note the
# directory check will raise if a segment is not readable.
try:
if file_path.is_dir():
if self._show_index:
return Response(
text=self._directory_as_html(file_path),
content_type="text/html",
)
else:
raise HTTPForbidden()
except PermissionError as error:
raise HTTPForbidden() from error
# Return the file response, which handles all other checks.
return FileResponse(file_path, chunk_size=self._chunk_size)
def _directory_as_html(self, dir_path: Path) -> str:
"""returns directory's index as html."""
assert dir_path.is_dir()
relative_path_to_dir = dir_path.relative_to(self._directory).as_posix()
index_of = f"Index of /{html_escape(relative_path_to_dir)}"
h1 = f"<h1>{index_of}</h1>"
index_list = []
dir_index = dir_path.iterdir()
for _file in sorted(dir_index):
# show file url as relative to static path
rel_path = _file.relative_to(self._directory).as_posix()
quoted_file_url = _quote_path(f"{self._prefix}/{rel_path}")
# if file is a directory, add '/' to the end of the name
if _file.is_dir():
file_name = f"{_file.name}/"
else:
file_name = _file.name
index_list.append(
f'<li><a href="{quoted_file_url}">{html_escape(file_name)}</a></li>'
)
ul = "<ul>\n{}\n</ul>".format("\n".join(index_list))
body = f"<body>\n{h1}\n{ul}\n</body>"
head_str = f"<head>\n<title>{index_of}</title>\n</head>"
html = f"<html>\n{head_str}\n{body}\n</html>"
return html
def __repr__(self) -> str:
name = "'" + self.name + "'" if self.name is not None else ""
return f"<StaticResource {name} {self._prefix} -> {self._directory!r}>"
class PrefixedSubAppResource(PrefixResource):
def __init__(self, prefix: str, app: "Application") -> None:
super().__init__(prefix)
self._app = app
self._add_prefix_to_resources(prefix)
def add_prefix(self, prefix: str) -> None:
super().add_prefix(prefix)
self._add_prefix_to_resources(prefix)
def _add_prefix_to_resources(self, prefix: str) -> None:
router = self._app.router
for resource in router.resources():
# Since the canonical path of a resource is about
# to change, we need to unindex it and then reindex
router.unindex_resource(resource)
resource.add_prefix(prefix)
router.index_resource(resource)
def url_for(self, *args: str, **kwargs: str) -> URL:
raise RuntimeError(".url_for() is not supported by sub-application root")
def get_info(self) -> _InfoDict:
return {"app": self._app, "prefix": self._prefix}
async def resolve(self, request: Request) -> _Resolve:
match_info = await self._app.router.resolve(request)
match_info.add_app(self._app)
if isinstance(match_info.http_exception, HTTPMethodNotAllowed):
methods = match_info.http_exception.allowed_methods
else:
methods = set()
return match_info, methods
def __len__(self) -> int:
return len(self._app.router.routes())
def __iter__(self) -> Iterator[AbstractRoute]:
return iter(self._app.router.routes())
def __repr__(self) -> str:
return f"<PrefixedSubAppResource {self._prefix} -> {self._app!r}>"
class AbstractRuleMatching(abc.ABC):
@abc.abstractmethod # pragma: no branch
async def match(self, request: Request) -> bool:
"""Return bool if the request satisfies the criteria"""
@abc.abstractmethod # pragma: no branch
def get_info(self) -> _InfoDict:
"""Return a dict with additional info useful for introspection"""
@property
@abc.abstractmethod # pragma: no branch
def canonical(self) -> str:
"""Return a str"""
class Domain(AbstractRuleMatching):
re_part = re.compile(r"(?!-)[a-z\d-]{1,63}(?<!-)")
def __init__(self, domain: str) -> None:
super().__init__()
self._domain = self.validation(domain)
@property
def canonical(self) -> str:
return self._domain
def validation(self, domain: str) -> str:
if not isinstance(domain, str):
raise TypeError("Domain must be str")
domain = domain.rstrip(".").lower()
if not domain:
raise ValueError("Domain cannot be empty")
elif "://" in domain:
raise ValueError("Scheme not supported")
url = URL("http://" + domain)
assert url.raw_host is not None
if not all(self.re_part.fullmatch(x) for x in url.raw_host.split(".")):
raise ValueError("Domain not valid")
if url.port == 80:
return url.raw_host
return f"{url.raw_host}:{url.port}"
async def match(self, request: Request) -> bool:
host = request.headers.get(hdrs.HOST)
if not host:
return False
return self.match_domain(host)
def match_domain(self, host: str) -> bool:
return host.lower() == self._domain
def get_info(self) -> _InfoDict:
return {"domain": self._domain}
class MaskDomain(Domain):
re_part = re.compile(r"(?!-)[a-z\d\*-]{1,63}(?<!-)")
def __init__(self, domain: str) -> None:
super().__init__(domain)
mask = self._domain.replace(".", r"\.").replace("*", ".*")
self._mask = re.compile(mask)
@property
def canonical(self) -> str:
return self._mask.pattern
def match_domain(self, host: str) -> bool:
return self._mask.fullmatch(host) is not None
class MatchedSubAppResource(PrefixedSubAppResource):
def __init__(self, rule: AbstractRuleMatching, app: "Application") -> None:
AbstractResource.__init__(self)
self._prefix = ""
self._app = app
self._rule = rule
@property
def canonical(self) -> str:
return self._rule.canonical
def get_info(self) -> _InfoDict:
return {"app": self._app, "rule": self._rule}
async def resolve(self, request: Request) -> _Resolve:
if not await self._rule.match(request):
return None, set()
match_info = await self._app.router.resolve(request)
match_info.add_app(self._app)
if isinstance(match_info.http_exception, HTTPMethodNotAllowed):
methods = match_info.http_exception.allowed_methods
else:
methods = set()
return match_info, methods
def __repr__(self) -> str:
return f"<MatchedSubAppResource -> {self._app!r}>"
class ResourceRoute(AbstractRoute):
"""A route with resource"""
def __init__(
self,
method: str,
handler: Handler | type[AbstractView],
resource: AbstractResource,
*,
expect_handler: _ExpectHandler | None = None,
) -> None:
super().__init__(
method, handler, expect_handler=expect_handler, resource=resource
)
def __repr__(self) -> str:
return f"<ResourceRoute [{self.method}] {self._resource} -> {self.handler!r}"
@property
def name(self) -> str | None:
if self._resource is None:
return None
return self._resource.name
def url_for(self, *args: str, **kwargs: str) -> URL:
"""Construct url for route with additional params."""
assert self._resource is not None
return self._resource.url_for(*args, **kwargs)
def get_info(self) -> _InfoDict:
assert self._resource is not None
return self._resource.get_info()
class SystemRoute(AbstractRoute):
def __init__(self, http_exception: HTTPException) -> None:
super().__init__(hdrs.METH_ANY, self._handle)
self._http_exception = http_exception
def url_for(self, *args: str, **kwargs: str) -> URL:
raise RuntimeError(".url_for() is not allowed for SystemRoute")
@property
def name(self) -> str | None:
return None
def get_info(self) -> _InfoDict:
return {"http_exception": self._http_exception}
async def _handle(self, request: Request) -> StreamResponse:
raise self._http_exception
@property
def status(self) -> int:
return self._http_exception.status
@property
def reason(self) -> str:
return self._http_exception.reason
def __repr__(self) -> str:
return f"<SystemRoute {self.status}: {self.reason}>"
class View(AbstractView):
async def _iter(self) -> StreamResponse:
if self.request.method not in hdrs.METH_ALL:
self._raise_allowed_methods()
method: Callable[[], Awaitable[StreamResponse]] | None = getattr(
self, self.request.method.lower(), None
)
if method is None:
self._raise_allowed_methods()
return await method()
def __await__(self) -> Generator[None, None, StreamResponse]:
return self._iter().__await__()
def _raise_allowed_methods(self) -> NoReturn:
allowed_methods = {m for m in hdrs.METH_ALL if hasattr(self, m.lower())}
raise HTTPMethodNotAllowed(self.request.method, allowed_methods)
class ResourcesView(Sized, Iterable[AbstractResource], Container[AbstractResource]):
def __init__(self, resources: list[AbstractResource]) -> None:
self._resources = resources
def __len__(self) -> int:
return len(self._resources)
def __iter__(self) -> Iterator[AbstractResource]:
yield from self._resources
def __contains__(self, resource: object) -> bool:
return resource in self._resources
class RoutesView(Sized, Iterable[AbstractRoute], Container[AbstractRoute]):
def __init__(self, resources: list[AbstractResource]):
self._routes: list[AbstractRoute] = []
for resource in resources:
for route in resource:
self._routes.append(route)
def __len__(self) -> int:
return len(self._routes)
def __iter__(self) -> Iterator[AbstractRoute]:
yield from self._routes
def __contains__(self, route: object) -> bool:
return route in self._routes
class UrlDispatcher(AbstractRouter, Mapping[str, AbstractResource]):
NAME_SPLIT_RE = re.compile(r"[.:-]")
HTTP_NOT_FOUND = HTTPNotFound()
def __init__(self) -> None:
super().__init__()
self._resources: list[AbstractResource] = []
self._named_resources: dict[str, AbstractResource] = {}
self._resource_index: dict[str, list[AbstractResource]] = {}
self._matched_sub_app_resources: list[MatchedSubAppResource] = []
async def resolve(self, request: Request) -> UrlMappingMatchInfo:
resource_index = self._resource_index
allowed_methods: set[str] = set()
# MatchedSubAppResource is primarily used to match on domain names
# (though custom rules could match on other things). This means that
# the traversal algorithm below can't be applied, and that we likely
# need to check these first so a sub app that defines the same path
# as a parent app will get priority if there's a domain match.
#
# For most cases we do not expect there to be many of these since
# currently they are only added by `.add_domain()`.
for resource in self._matched_sub_app_resources:
match_dict, allowed = await resource.resolve(request)
if match_dict is not None:
return match_dict
else:
allowed_methods |= allowed
# Walk the url parts looking for candidates. We walk the url backwards
# to ensure the most explicit match is found first. If there are multiple
# candidates for a given url part because there are multiple resources
# registered for the same canonical path, we resolve them in a linear
# fashion to ensure registration order is respected.
url_part = request.rel_url.path_safe
while url_part:
for candidate in resource_index.get(url_part, ()):
match_dict, allowed = await candidate.resolve(request)
if match_dict is not None:
return match_dict
else:
allowed_methods |= allowed
if url_part == "/":
break
url_part = url_part.rpartition("/")[0] or "/"
if allowed_methods:
return MatchInfoError(HTTPMethodNotAllowed(request.method, allowed_methods))
return MatchInfoError(self.HTTP_NOT_FOUND)
def __iter__(self) -> Iterator[str]:
return iter(self._named_resources)
def __len__(self) -> int:
return len(self._named_resources)
def __contains__(self, resource: object) -> bool:
return resource in self._named_resources
def __getitem__(self, name: str) -> AbstractResource:
return self._named_resources[name]
def resources(self) -> ResourcesView:
return ResourcesView(self._resources)
def routes(self) -> RoutesView:
return RoutesView(self._resources)
def named_resources(self) -> Mapping[str, AbstractResource]:
return MappingProxyType(self._named_resources)
def register_resource(self, resource: AbstractResource) -> None:
assert isinstance(
resource, AbstractResource
), f"Instance of AbstractResource class is required, got {resource!r}"
if self.frozen:
raise RuntimeError("Cannot register a resource into frozen router.")
name = resource.name
if name is not None:
parts = self.NAME_SPLIT_RE.split(name)
for part in parts:
if keyword.iskeyword(part):
raise ValueError(
f"Incorrect route name {name!r}, "
"python keywords cannot be used "
"for route name"
)
if not part.isidentifier():
raise ValueError(
f"Incorrect route name {name!r}, "
"the name should be a sequence of "
"python identifiers separated "
"by dash, dot or column"
)
if name in self._named_resources:
raise ValueError(
f"Duplicate {name!r}, "
f"already handled by {self._named_resources[name]!r}"
)
self._named_resources[name] = resource
self._resources.append(resource)
if isinstance(resource, MatchedSubAppResource):
# We cannot index match sub-app resources because they have match rules
self._matched_sub_app_resources.append(resource)
else:
self.index_resource(resource)
def _get_resource_index_key(self, resource: AbstractResource) -> str:
"""Return a key to index the resource in the resource index."""
if "{" in (index_key := resource.canonical):
# strip at the first { to allow for variables, and than
# rpartition at / to allow for variable parts in the path
# For example if the canonical path is `/core/locations{tail:.*}`
# the index key will be `/core` since index is based on the
# url parts split by `/`
index_key = index_key.partition("{")[0].rpartition("/")[0]
return index_key.rstrip("/") or "/"
def index_resource(self, resource: AbstractResource) -> None:
"""Add a resource to the resource index."""
resource_key = self._get_resource_index_key(resource)
# There may be multiple resources for a canonical path
# so we keep them in a list to ensure that registration
# order is respected.
self._resource_index.setdefault(resource_key, []).append(resource)
def unindex_resource(self, resource: AbstractResource) -> None:
"""Remove a resource from the resource index."""
resource_key = self._get_resource_index_key(resource)
self._resource_index[resource_key].remove(resource)
def add_resource(self, path: str, *, name: str | None = None) -> Resource:
if path and not path.startswith("/"):
raise ValueError("path should be started with / or be empty")
# Reuse last added resource if path and name are the same
if self._resources:
resource = self._resources[-1]
if resource.name == name and resource.raw_match(path):
return cast(Resource, resource)
if not ("{" in path or "}" in path or ROUTE_RE.search(path)):
resource = PlainResource(path, name=name)
self.register_resource(resource)
return resource
resource = DynamicResource(path, name=name)
self.register_resource(resource)
return resource
def add_route(
self,
method: str,
path: str,
handler: Handler | type[AbstractView],
*,
name: str | None = None,
expect_handler: _ExpectHandler | None = None,
) -> AbstractRoute:
resource = self.add_resource(path, name=name)
return resource.add_route(method, handler, expect_handler=expect_handler)
def add_static(
self,
prefix: str,
path: PathLike,
*,
name: str | None = None,
expect_handler: _ExpectHandler | None = None,
chunk_size: int = 256 * 1024,
show_index: bool = False,
follow_symlinks: bool = False,
append_version: bool = False,
) -> StaticResource:
"""Add static files view.
prefix - url prefix
path - folder with files
"""
assert prefix.startswith("/")
if prefix.endswith("/"):
prefix = prefix[:-1]
resource = StaticResource(
prefix,
path,
name=name,
expect_handler=expect_handler,
chunk_size=chunk_size,
show_index=show_index,
follow_symlinks=follow_symlinks,
append_version=append_version,
)
self.register_resource(resource)
return resource
def add_head(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute:
"""Shortcut for add_route with method HEAD."""
return self.add_route(hdrs.METH_HEAD, path, handler, **kwargs)
def add_options(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute:
"""Shortcut for add_route with method OPTIONS."""
return self.add_route(hdrs.METH_OPTIONS, path, handler, **kwargs)
def add_get(
self,
path: str,
handler: Handler,
*,
name: str | None = None,
allow_head: bool = True,
**kwargs: Any,
) -> AbstractRoute:
"""Shortcut for add_route with method GET.
If allow_head is true, another
route is added allowing head requests to the same endpoint.
"""
resource = self.add_resource(path, name=name)
if allow_head:
resource.add_route(hdrs.METH_HEAD, handler, **kwargs)
return resource.add_route(hdrs.METH_GET, handler, **kwargs)
def add_post(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute:
"""Shortcut for add_route with method POST."""
return self.add_route(hdrs.METH_POST, path, handler, **kwargs)
def add_put(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute:
"""Shortcut for add_route with method PUT."""
return self.add_route(hdrs.METH_PUT, path, handler, **kwargs)
def add_patch(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute:
"""Shortcut for add_route with method PATCH."""
return self.add_route(hdrs.METH_PATCH, path, handler, **kwargs)
def add_delete(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute:
"""Shortcut for add_route with method DELETE."""
return self.add_route(hdrs.METH_DELETE, path, handler, **kwargs)
def add_view(
self, path: str, handler: type[AbstractView], **kwargs: Any
) -> AbstractRoute:
"""Shortcut for add_route with ANY methods for a class-based view."""
return self.add_route(hdrs.METH_ANY, path, handler, **kwargs)
def freeze(self) -> None:
super().freeze()
for resource in self._resources:
resource.freeze()
def add_routes(self, routes: Iterable[AbstractRouteDef]) -> list[AbstractRoute]:
"""Append routes to route table.
Parameter should be a sequence of RouteDef objects.
Returns a list of registered AbstractRoute instances.
"""
registered_routes = []
for route_def in routes:
registered_routes.extend(route_def.register(self))
return registered_routes
def _quote_path(value: str) -> str:
return URL.build(path=value, encoded=False).raw_path
def _unquote_path_safe(value: str) -> str:
if "%" not in value:
return value
return value.replace("%2F", "/").replace("%25", "%")
def _requote_path(value: str) -> str:
# Quote non-ascii characters and other characters which must be quoted,
# but preserve existing %-sequences.
result = _quote_path(value)
if "%" in value:
result = result.replace("%25", "%")
return result
| import asyncio
import functools
import os
import pathlib
import socket
import sys
from collections.abc import Generator
from stat import S_IFIFO, S_IMODE
from typing import Any, NoReturn
import pytest
import yarl
from aiohttp import web
from aiohttp.pytest_plugin import AiohttpClient
from aiohttp.web_urldispatcher import Resource, SystemRoute
@pytest.mark.parametrize(
"show_index,status,prefix,request_path,data",
[
pytest.param(False, 403, "/", "/", None, id="index_forbidden"),
pytest.param(
True,
200,
"/",
"/",
b"<html>\n<head>\n<title>Index of /.</title>\n</head>\n<body>\n<h1>Index of"
b' /.</h1>\n<ul>\n<li><a href="/my_dir">my_dir/</a></li>\n<li><a href="/my_file">'
b"my_file</a></li>\n</ul>\n</body>\n</html>",
),
pytest.param(
True,
200,
"/static",
"/static",
b"<html>\n<head>\n<title>Index of /.</title>\n</head>\n<body>\n<h1>Index of"
b' /.</h1>\n<ul>\n<li><a href="/static/my_dir">my_dir/</a></li>\n<li><a href="'
b'/static/my_file">my_file</a></li>\n</ul>\n</body>\n</html>',
id="index_static",
),
pytest.param(
True,
200,
"/static",
"/static/my_dir",
b"<html>\n<head>\n<title>Index of /my_dir</title>\n</head>\n<body>\n<h1>"
b'Index of /my_dir</h1>\n<ul>\n<li><a href="/static/my_dir/my_file_in_dir">'
b"my_file_in_dir</a></li>\n</ul>\n</body>\n</html>",
id="index_subdir",
),
],
)
async def test_access_root_of_static_handler(
tmp_path: pathlib.Path,
aiohttp_client: AiohttpClient,
show_index: bool,
status: int,
prefix: str,
request_path: str,
data: bytes | None,
) -> None:
# Tests the operation of static file server.
# Try to access the root of static file server, and make
# sure that correct HTTP statuses are returned depending if we directory
# index should be shown or not.
my_file = tmp_path / "my_file"
my_dir = tmp_path / "my_dir"
my_dir.mkdir()
my_file_in_dir = my_dir / "my_file_in_dir"
with my_file.open("w") as fw:
fw.write("hello")
with my_file_in_dir.open("w") as fw:
fw.write("world")
app = web.Application()
# Register global static route:
app.router.add_static(prefix, str(tmp_path), show_index=show_index)
client = await aiohttp_client(app)
# Request the root of the static directory.
async with await client.get(request_path) as r:
assert r.status == status
if data:
assert r.headers["Content-Type"] == "text/html; charset=utf-8"
read_ = await r.read()
assert read_ == data
@pytest.mark.internal # Dependent on filesystem
@pytest.mark.skipif(
not sys.platform.startswith("linux"),
reason="Invalid filenames on some filesystems (like Windows)",
)
@pytest.mark.parametrize(
"show_index,status,prefix,request_path,data",
[
pytest.param(False, 403, "/", "/", None, id="index_forbidden"),
pytest.param(
True,
200,
"/",
"/",
b"<html>\n<head>\n<title>Index of /.</title>\n</head>\n<body>\n<h1>Index of"
b' /.</h1>\n<ul>\n<li><a href="/%3Cimg%20src=0%20onerror=alert(1)%3E.dir">&l'
b't;img src=0 onerror=alert(1)>.dir/</a></li>\n<li><a href="/%3Cimg%20sr'
b'c=0%20onerror=alert(1)%3E.txt"><img src=0 onerror=alert(1)>.txt</a></l'
b"i>\n</ul>\n</body>\n</html>",
),
pytest.param(
True,
200,
"/static",
"/static",
b"<html>\n<head>\n<title>Index of /.</title>\n</head>\n<body>\n<h1>Index of"
b' /.</h1>\n<ul>\n<li><a href="/static/%3Cimg%20src=0%20onerror=alert(1)%3E.'
b'dir"><img src=0 onerror=alert(1)>.dir/</a></li>\n<li><a href="/stat'
b'ic/%3Cimg%20src=0%20onerror=alert(1)%3E.txt"><img src=0 onerror=alert(1)&'
b"gt;.txt</a></li>\n</ul>\n</body>\n</html>",
id="index_static",
),
pytest.param(
True,
200,
"/static",
"/static/<img src=0 onerror=alert(1)>.dir",
b"<html>\n<head>\n<title>Index of /<img src=0 onerror=alert(1)>.dir</t"
b"itle>\n</head>\n<body>\n<h1>Index of /<img src=0 onerror=alert(1)>.di"
b'r</h1>\n<ul>\n<li><a href="/static/%3Cimg%20src=0%20onerror=alert(1)%3E.di'
b'r/my_file_in_dir">my_file_in_dir</a></li>\n</ul>\n</body>\n</html>',
id="index_subdir",
),
],
)
async def test_access_root_of_static_handler_xss(
tmp_path: pathlib.Path,
aiohttp_client: AiohttpClient,
show_index: bool,
status: int,
prefix: str,
request_path: str,
data: bytes | None,
) -> None:
# Tests the operation of static file server.
# Try to access the root of static file server, and make
# sure that correct HTTP statuses are returned depending if we directory
# index should be shown or not.
# Ensure that html in file names is escaped.
# Ensure that links are url quoted.
my_file = tmp_path / "<img src=0 onerror=alert(1)>.txt"
my_dir = tmp_path / "<img src=0 onerror=alert(1)>.dir"
my_dir.mkdir()
my_file_in_dir = my_dir / "my_file_in_dir"
with my_file.open("w") as fw:
fw.write("hello")
with my_file_in_dir.open("w") as fw:
fw.write("world")
app = web.Application()
# Register global static route:
app.router.add_static(prefix, str(tmp_path), show_index=show_index)
client = await aiohttp_client(app)
# Request the root of the static directory.
async with await client.get(request_path) as r:
assert r.status == status
if data:
assert r.headers["Content-Type"] == "text/html; charset=utf-8"
read_ = await r.read()
assert read_ == data
async def test_follow_symlink(
tmp_path: pathlib.Path, aiohttp_client: AiohttpClient
) -> None:
# Tests the access to a symlink, in static folder
data = "hello world"
my_dir_path = tmp_path / "my_dir"
my_dir_path.mkdir()
my_file_path = my_dir_path / "my_file_in_dir"
with my_file_path.open("w") as fw:
fw.write(data)
my_symlink_path = tmp_path / "my_symlink"
pathlib.Path(str(my_symlink_path)).symlink_to(str(my_dir_path), True)
app = web.Application()
# Register global static route:
app.router.add_static("/", str(tmp_path), follow_symlinks=True)
client = await aiohttp_client(app)
# Request the root of the static directory.
r = await client.get("/my_symlink/my_file_in_dir")
assert r.status == 200
assert (await r.text()) == data
async def test_follow_symlink_directory_traversal(
tmp_path: pathlib.Path, aiohttp_client: AiohttpClient
) -> None:
# Tests that follow_symlinks does not allow directory transversal
data = "private"
private_file = tmp_path / "private_file"
private_file.write_text(data)
safe_path = tmp_path / "safe_dir"
safe_path.mkdir()
app = web.Application()
# Register global static route:
app.router.add_static("/", str(safe_path), follow_symlinks=True)
client = await aiohttp_client(app)
await client.start_server()
# We need to use a raw socket to test this, as the client will normalize
# the path before sending it to the server.
reader, writer = await asyncio.open_connection(client.host, client.port)
writer.write(b"GET /../private_file HTTP/1.1\r\n\r\n")
response = await reader.readuntil(b"\r\n\r\n")
assert b"404 Not Found" in response
writer.close()
await writer.wait_closed()
await client.close()
async def test_follow_symlink_directory_traversal_after_normalization(
tmp_path: pathlib.Path, aiohttp_client: AiohttpClient
) -> None:
# Tests that follow_symlinks does not allow directory transversal
# after normalization
#
# Directory structure
# |-- secret_dir
# | |-- private_file (should never be accessible)
# | |-- symlink_target_dir
# | |-- symlink_target_file (should be accessible via the my_symlink symlink)
# | |-- sandbox_dir
# | |-- my_symlink -> symlink_target_dir
#
secret_path = tmp_path / "secret_dir"
secret_path.mkdir()
# This file is below the symlink target and should not be reachable
private_file = secret_path / "private_file"
private_file.write_text("private")
symlink_target_path = secret_path / "symlink_target_dir"
symlink_target_path.mkdir()
sandbox_path = symlink_target_path / "sandbox_dir"
sandbox_path.mkdir()
# This file should be reachable via the symlink
symlink_target_file = symlink_target_path / "symlink_target_file"
symlink_target_file.write_text("readable")
my_symlink_path = sandbox_path / "my_symlink"
pathlib.Path(str(my_symlink_path)).symlink_to(str(symlink_target_path), True)
app = web.Application()
# Register global static route:
app.router.add_static("/", str(sandbox_path), follow_symlinks=True)
client = await aiohttp_client(app)
await client.start_server()
# We need to use a raw socket to test this, as the client will normalize
# the path before sending it to the server.
reader, writer = await asyncio.open_connection(client.host, client.port)
writer.write(b"GET /my_symlink/../private_file HTTP/1.1\r\n\r\n")
response = await reader.readuntil(b"\r\n\r\n")
assert b"404 Not Found" in response
writer.close()
await writer.wait_closed()
reader, writer = await asyncio.open_connection(client.host, client.port)
writer.write(b"GET /my_symlink/symlink_target_file HTTP/1.1\r\n\r\n")
response = await reader.readuntil(b"\r\n\r\n")
assert b"200 OK" in response
response = await reader.readuntil(b"readable")
assert response == b"readable"
writer.close()
await writer.wait_closed()
await client.close()
@pytest.mark.parametrize(
"dir_name,filename,data",
[
("", "test file.txt", "test text"),
("test dir name", "test dir file .txt", "test text file folder"),
],
)
async def test_access_to_the_file_with_spaces(
tmp_path: pathlib.Path,
aiohttp_client: AiohttpClient,
dir_name: str,
filename: str,
data: str,
) -> None:
# Checks operation of static files with spaces
my_dir_path = tmp_path / dir_name
if my_dir_path != tmp_path:
my_dir_path.mkdir()
my_file_path = my_dir_path / filename
with my_file_path.open("w") as fw:
fw.write(data)
app = web.Application()
url = "/" + str(pathlib.Path(dir_name, filename))
app.router.add_static("/", str(tmp_path))
client = await aiohttp_client(app)
r = await client.get(url)
assert r.status == 200
assert (await r.text()) == data
async def test_access_non_existing_resource(
tmp_path: pathlib.Path, aiohttp_client: AiohttpClient
) -> None:
# Tests accessing non-existing resource
# Try to access a non-exiting resource and make sure that 404 HTTP status
# returned.
app = web.Application()
# Register global static route:
app.router.add_static("/", str(tmp_path), show_index=True)
client = await aiohttp_client(app)
# Request the root of the static directory.
async with client.get("/non_existing_resource") as r:
assert r.status == 404
@pytest.mark.parametrize(
"registered_path,request_url",
[
("/a:b", "/a:b"),
("/a@b", "/a@b"),
("/a:b", "/a%3Ab"),
],
)
async def test_url_escaping(
aiohttp_client: AiohttpClient, registered_path: str, request_url: str
) -> None:
# Tests accessing a resource with
app = web.Application()
async def handler(request: web.Request) -> web.Response:
return web.Response()
app.router.add_get(registered_path, handler)
client = await aiohttp_client(app)
async with client.get(request_url) as r:
assert r.status == 200
async def test_handler_metadata_persistence() -> None:
# Tests accessing metadata of a handler after registering it on the app
# router.
app = web.Application()
async def async_handler(request: web.Request) -> web.Response:
"""Doc"""
assert False
app.router.add_get("/async", async_handler)
for resource in app.router.resources():
for route in resource:
assert route.handler.__doc__ == "Doc"
@pytest.mark.skipif(
sys.platform.startswith("win32"), reason="Cannot remove read access on Windows"
)
@pytest.mark.parametrize("file_request", ["", "my_file.txt"])
async def test_static_directory_without_read_permission(
tmp_path: pathlib.Path, aiohttp_client: AiohttpClient, file_request: str
) -> None:
"""Test static directory without read permission receives forbidden response."""
my_dir = tmp_path / "my_dir"
my_dir.mkdir()
my_dir.chmod(0o000)
app = web.Application()
app.router.add_static("/", str(tmp_path), show_index=True)
client = await aiohttp_client(app)
async with client.get(f"/{my_dir.name}/{file_request}") as r:
assert r.status == 403
@pytest.mark.parametrize("file_request", ["", "my_file.txt"])
async def test_static_directory_with_mock_permission_error(
monkeypatch: pytest.MonkeyPatch,
tmp_path: pathlib.Path,
aiohttp_client: AiohttpClient,
file_request: str,
) -> None:
"""Test static directory with mock permission errors receives forbidden response."""
my_dir = tmp_path / "my_dir"
my_dir.mkdir()
real_iterdir = pathlib.Path.iterdir
real_is_dir = pathlib.Path.is_dir
def mock_iterdir(self: pathlib.Path) -> Generator[pathlib.Path, None, None]:
if my_dir.samefile(self):
raise PermissionError()
return real_iterdir(self)
def mock_is_dir(self: pathlib.Path, **kwargs: Any) -> bool:
if my_dir.samefile(self.parent):
raise PermissionError()
return real_is_dir(self, **kwargs)
monkeypatch.setattr("pathlib.Path.iterdir", mock_iterdir)
monkeypatch.setattr("pathlib.Path.is_dir", mock_is_dir)
app = web.Application()
app.router.add_static("/", str(tmp_path), show_index=True)
client = await aiohttp_client(app)
async with client.get("/") as r:
assert r.status == 200
async with client.get(f"/{my_dir.name}/{file_request}") as r:
assert r.status == 403
@pytest.mark.skipif(
sys.platform.startswith("win32"), reason="Cannot remove read access on Windows"
)
async def test_static_file_without_read_permission(
tmp_path: pathlib.Path, aiohttp_client: AiohttpClient
) -> None:
"""Test static file without read permission receives forbidden response."""
my_file = tmp_path / "my_file.txt"
my_file.write_text("secret")
my_file.chmod(0o000)
app = web.Application()
app.router.add_static("/", str(tmp_path))
client = await aiohttp_client(app)
async with client.get(f"/{my_file.name}") as r:
assert r.status == 403
async def test_static_file_with_mock_permission_error(
monkeypatch: pytest.MonkeyPatch,
tmp_path: pathlib.Path,
aiohttp_client: AiohttpClient,
) -> None:
"""Test static file with mock permission errors receives forbidden response."""
my_file = tmp_path / "my_file.txt"
my_file.write_text("secret")
my_readable = tmp_path / "my_readable.txt"
my_readable.write_text("info")
real_open = pathlib.Path.open
def mock_open(self: pathlib.Path, *args: Any, **kwargs: Any) -> Any:
if my_file.samefile(self):
raise PermissionError()
return real_open(self, *args, **kwargs)
monkeypatch.setattr("pathlib.Path.open", mock_open)
app = web.Application()
app.router.add_static("/", str(tmp_path))
client = await aiohttp_client(app)
# Test the mock only applies to my_file, then test the permission error.
async with client.get(f"/{my_readable.name}") as r:
assert r.status == 200
async with client.get(f"/{my_file.name}") as r:
assert r.status == 403
async def test_access_symlink_loop(
tmp_path: pathlib.Path, aiohttp_client: AiohttpClient
) -> None:
# Tests the access to a looped symlink, which could not be resolved.
my_dir_path = tmp_path / "my_symlink"
pathlib.Path(str(my_dir_path)).symlink_to(str(my_dir_path), True)
app = web.Application()
# Register global static route:
app.router.add_static("/", str(tmp_path), show_index=True)
client = await aiohttp_client(app)
# Request the root of the static directory.
async with client.get("/" + my_dir_path.name) as r:
assert r.status == 404
async def test_access_compressed_file_as_symlink(
tmp_path: pathlib.Path, aiohttp_client: AiohttpClient
) -> None:
"""Test that compressed file variants as symlinks are ignored."""
private_file = tmp_path / "private.txt"
private_file.write_text("private info")
www_dir = tmp_path / "www"
www_dir.mkdir()
gz_link = www_dir / "file.txt.gz"
gz_link.symlink_to(f"../{private_file.name}")
app = web.Application()
app.router.add_static("/", www_dir)
client = await aiohttp_client(app)
# Symlink should be ignored; response reflects missing uncompressed file.
async with client.get(f"/{gz_link.stem}", auto_decompress=False) as resp:
assert resp.status == 404
# Again symlin is ignored, and then uncompressed is served.
txt_file = gz_link.with_suffix("")
txt_file.write_text("public data")
resp = await client.get(f"/{txt_file.name}")
assert resp.status == 200
assert resp.headers.get("Content-Encoding") is None
assert resp.content_type == "text/plain"
assert await resp.text() == "public data"
resp.release()
await client.close()
async def test_access_special_resource(
unix_sockname: str, aiohttp_client: AiohttpClient
) -> None:
"""Test access to non-regular files is forbidden using a UNIX domain socket."""
if not getattr(socket, "AF_UNIX", None):
pytest.skip("UNIX domain sockets not supported")
my_special = pathlib.Path(unix_sockname)
tmp_path = my_special.parent
my_socket = socket.socket(socket.AF_UNIX)
my_socket.bind(str(my_special))
assert my_special.is_socket()
app = web.Application()
app.router.add_static("/", str(tmp_path))
client = await aiohttp_client(app)
async with client.get(f"/{my_special.name}") as r:
assert r.status == 403
my_socket.close()
async def test_access_mock_special_resource(
monkeypatch: pytest.MonkeyPatch,
tmp_path: pathlib.Path,
aiohttp_client: AiohttpClient,
) -> None:
"""Test access to non-regular files is forbidden using a mock FIFO."""
my_special = tmp_path / "my_special"
my_special.touch()
real_result = my_special.stat()
real_stat = os.stat
def mock_stat(path: Any, **kwargs: Any) -> os.stat_result:
s = real_stat(path, **kwargs)
if os.path.samestat(s, real_result):
mock_mode = S_IFIFO | S_IMODE(s.st_mode)
s = os.stat_result([mock_mode] + list(s)[1:])
return s
monkeypatch.setattr("pathlib.Path.stat", mock_stat)
monkeypatch.setattr("os.stat", mock_stat)
app = web.Application()
app.router.add_static("/", str(tmp_path))
client = await aiohttp_client(app)
async with client.get(f"/{my_special.name}") as r:
assert r.status == 403
async def test_partially_applied_handler(aiohttp_client: AiohttpClient) -> None:
app = web.Application()
async def handler(data: bytes, request: web.Request) -> web.Response:
return web.Response(body=data)
app.router.add_route("GET", "/", functools.partial(handler, b"hello"))
client = await aiohttp_client(app)
r = await client.get("/")
data = await r.read()
assert data == b"hello"
async def test_static_head(
tmp_path: pathlib.Path, aiohttp_client: AiohttpClient
) -> None:
# Test HEAD on static route
my_file_path = tmp_path / "test.txt"
with my_file_path.open("wb") as fw:
fw.write(b"should_not_see_this\n")
app = web.Application()
app.router.add_static("/", str(tmp_path))
client = await aiohttp_client(app)
async with client.head("/test.txt") as r:
assert r.status == 200
# Check that there is no content sent (see #4809). This can't easily be
# done with aiohttp_client because the buffering can consume the content.
reader, writer = await asyncio.open_connection(client.host, client.port)
writer.write(b"HEAD /test.txt HTTP/1.1\r\n")
writer.write(b"Host: localhost\r\n")
writer.write(b"Connection: close\r\n")
writer.write(b"\r\n")
while await reader.readline() != b"\r\n":
pass
content = await reader.read()
writer.close()
assert content == b""
def test_system_route() -> None:
route = SystemRoute(web.HTTPCreated(reason="test"))
with pytest.raises(RuntimeError):
route.url_for()
assert route.name is None
assert route.resource is None
assert "<SystemRoute 201: test>" == repr(route)
assert 201 == route.status
assert "test" == route.reason
async def test_allow_head(aiohttp_client: AiohttpClient) -> None:
# Test allow_head on routes.
app = web.Application()
async def handler(request: web.Request) -> web.Response:
return web.Response()
app.router.add_get("/a", handler, name="a")
app.router.add_get("/b", handler, allow_head=False, name="b")
client = await aiohttp_client(app)
async with client.get("/a") as r:
assert r.status == 200
async with client.head("/a") as r:
assert r.status == 200
async with client.get("/b") as r:
assert r.status == 200
async with client.head("/b") as r:
assert r.status == 405
@pytest.mark.parametrize(
"path",
(
"/a",
"/{a}",
"/{a:.*}",
),
)
def test_reuse_last_added_resource(path: str) -> None:
# Test that adding a route with the same name and path of the last added
# resource doesn't create a new resource.
app = web.Application()
async def handler(request: web.Request) -> web.Response:
assert False
app.router.add_get(path, handler, name="a")
app.router.add_post(path, handler, name="a")
assert len(app.router.resources()) == 1
def test_resource_raw_match() -> None:
app = web.Application()
async def handler(request: web.Request) -> web.Response:
assert False
route = app.router.add_get("/a", handler, name="a")
assert route.resource is not None
assert route.resource.raw_match("/a")
route = app.router.add_get("/{b}", handler, name="b")
assert route.resource is not None
assert route.resource.raw_match("/{b}")
resource = app.router.add_static("/static", ".")
assert not resource.raw_match("/static")
async def test_add_view(aiohttp_client: AiohttpClient) -> None:
app = web.Application()
class MyView(web.View):
async def get(self) -> web.Response:
return web.Response()
async def post(self) -> web.Response:
return web.Response()
app.router.add_view("/a", MyView)
client = await aiohttp_client(app)
async with client.get("/a") as r:
assert r.status == 200
async with client.post("/a") as r:
assert r.status == 200
async with client.put("/a") as r:
assert r.status == 405
async def test_decorate_view(aiohttp_client: AiohttpClient) -> None:
routes = web.RouteTableDef()
@routes.view("/a")
class MyView(web.View):
async def get(self) -> web.Response:
return web.Response()
async def post(self) -> web.Response:
return web.Response()
app = web.Application()
app.router.add_routes(routes)
client = await aiohttp_client(app)
async with client.get("/a") as r:
assert r.status == 200
async with client.post("/a") as r:
assert r.status == 200
async with client.put("/a") as r:
assert r.status == 405
async def test_web_view(aiohttp_client: AiohttpClient) -> None:
app = web.Application()
class MyView(web.View):
async def get(self) -> web.Response:
return web.Response()
async def post(self) -> web.Response:
return web.Response()
app.router.add_routes([web.view("/a", MyView)])
client = await aiohttp_client(app)
async with client.get("/a") as r:
assert r.status == 200
async with client.post("/a") as r:
assert r.status == 200
async with client.put("/a") as r:
assert r.status == 405
async def test_static_absolute_url(
aiohttp_client: AiohttpClient, tmp_path: pathlib.Path
) -> None:
# requested url is an absolute name like
# /static/\\machine_name\c$ or /static/D:\path
# where the static dir is totally different
app = web.Application()
file_path = tmp_path / "file.txt"
file_path.write_text("sample text", "ascii")
here = pathlib.Path(__file__).parent
app.router.add_static("/static", here)
client = await aiohttp_client(app)
async with client.get("/static/" + str(file_path.resolve())) as resp:
assert resp.status == 403
async def test_for_issue_5250(
aiohttp_client: AiohttpClient, tmp_path: pathlib.Path
) -> None:
app = web.Application()
app.router.add_static("/foo", tmp_path)
async def get_foobar(request: web.Request) -> web.Response:
return web.Response(body="success!")
app.router.add_get("/foobar", get_foobar)
client = await aiohttp_client(app)
async with await client.get("/foobar") as resp:
assert resp.status == 200
assert (await resp.text()) == "success!"
@pytest.mark.parametrize(
("route_definition", "urlencoded_path", "expected_http_resp_status"),
(
("/467,802,24834/hello", "/467%2C802%2C24834/hello", 200),
("/{user_ids:([0-9]+)(,([0-9]+))*}/hello", "/467%2C802%2C24834/hello", 200),
("/467,802,24834/hello", "/467,802,24834/hello", 200),
("/{user_ids:([0-9]+)(,([0-9]+))*}/hello", "/467,802,24834/hello", 200),
("/1%2C3/hello", "/1%2C3/hello", 404),
),
)
async def test_decoded_url_match(
aiohttp_client: AiohttpClient,
route_definition: str,
urlencoded_path: str,
expected_http_resp_status: int,
) -> None:
app = web.Application()
async def handler(request: web.Request) -> web.Response:
return web.Response()
app.router.add_get(route_definition, handler)
client = await aiohttp_client(app)
async with client.get(yarl.URL(urlencoded_path, encoded=True)) as resp:
assert resp.status == expected_http_resp_status
async def test_decoded_raw_match_regex(aiohttp_client: AiohttpClient) -> None:
"""Verify that raw_match only matches decoded url."""
app = web.Application()
async def handler(request: web.Request) -> NoReturn:
assert False
app.router.add_get("/467%2C802%2C24834%2C24952%2C25362%2C40574/hello", handler)
client = await aiohttp_client(app)
async with client.get(
yarl.URL("/467%2C802%2C24834%2C24952%2C25362%2C40574/hello", encoded=True)
) as resp:
assert resp.status == 404 # should only match decoded url
async def test_order_is_preserved(aiohttp_client: AiohttpClient) -> None:
"""Test route order is preserved.
Note that fixed/static paths are always preferred over a regex path.
"""
app = web.Application()
async def handler(request: web.Request) -> web.Response:
assert isinstance(request.match_info._route.resource, Resource)
return web.Response(text=request.match_info._route.resource.canonical)
app.router.add_get("/first/x/{b}/", handler)
app.router.add_get(r"/first/{x:.*/b}", handler)
app.router.add_get(r"/second/{user}/info", handler)
app.router.add_get("/second/bob/info", handler)
app.router.add_get("/third/bob/info", handler)
app.router.add_get(r"/third/{user}/info", handler)
app.router.add_get(r"/forth/{name:\d+}", handler)
app.router.add_get("/forth/42", handler)
app.router.add_get("/fifth/42", handler)
app.router.add_get(r"/fifth/{name:\d+}", handler)
client = await aiohttp_client(app)
r = await client.get("/first/x/b/")
assert r.status == 200
assert await r.text() == "/first/x/{b}/"
r = await client.get("/second/frank/info")
assert r.status == 200
assert await r.text() == "/second/{user}/info"
# Fixed/static paths are always preferred over regex paths
r = await client.get("/second/bob/info")
assert r.status == 200
assert await r.text() == "/second/bob/info"
r = await client.get("/third/bob/info")
assert r.status == 200
assert await r.text() == "/third/bob/info"
r = await client.get("/third/frank/info")
assert r.status == 200
assert await r.text() == "/third/{user}/info"
r = await client.get("/forth/21")
assert r.status == 200
assert await r.text() == "/forth/{name}"
# Fixed/static paths are always preferred over regex paths
r = await client.get("/forth/42")
assert r.status == 200
assert await r.text() == "/forth/42"
r = await client.get("/fifth/21")
assert r.status == 200
assert await r.text() == "/fifth/{name}"
r = await client.get("/fifth/42")
assert r.status == 200
assert await r.text() == "/fifth/42"
async def test_url_with_many_slashes(aiohttp_client: AiohttpClient) -> None:
app = web.Application()
class MyView(web.View):
async def get(self) -> web.Response:
return web.Response()
app.router.add_routes([web.view("/a", MyView)])
client = await aiohttp_client(app)
async with client.get("///a") as r:
assert r.status == 200
async def test_subapp_domain_routing_same_path(aiohttp_client: AiohttpClient) -> None:
"""Regression test for #11665."""
app = web.Application()
sub_app = web.Application()
async def mainapp_handler(request: web.Request) -> web.Response:
assert False
async def subapp_handler(request: web.Request) -> web.Response:
return web.Response(text="SUBAPP")
app.router.add_get("/", mainapp_handler)
sub_app.router.add_get("/", subapp_handler)
app.add_domain("different.example.com", sub_app)
client = await aiohttp_client(app)
async with client.get("/", headers={"Host": "different.example.com"}) as r:
assert r.status == 200
result = await r.text()
assert result == "SUBAPP"
async def test_route_with_regex(aiohttp_client: AiohttpClient) -> None:
"""Test a route with a regex preceded by a fixed string."""
app = web.Application()
async def handler(request: web.Request) -> web.Response:
assert isinstance(request.match_info._route.resource, Resource)
return web.Response(text=request.match_info._route.resource.canonical)
app.router.add_get("/core/locations{tail:.*}", handler)
client = await aiohttp_client(app)
r = await client.get("/core/locations/tail/here")
assert r.status == 200
assert await r.text() == "/core/locations{tail}"
r = await client.get("/core/locations_tail_here")
assert r.status == 200
assert await r.text() == "/core/locations{tail}"
r = await client.get("/core/locations_tail;id=abcdef")
assert r.status == 200
assert await r.text() == "/core/locations{tail}"
| aiohttp |
python | import re
import warnings
from typing import TYPE_CHECKING, TypeVar
from .typedefs import Handler, Middleware
from .web_exceptions import HTTPMove, HTTPPermanentRedirect
from .web_request import Request
from .web_response import StreamResponse
from .web_urldispatcher import SystemRoute
__all__ = (
"middleware",
"normalize_path_middleware",
)
if TYPE_CHECKING:
from .web_app import Application
_Func = TypeVar("_Func")
async def _check_request_resolves(request: Request, path: str) -> tuple[bool, Request]:
alt_request = request.clone(rel_url=path)
match_info = await request.app.router.resolve(alt_request)
alt_request._match_info = match_info
if match_info.http_exception is None:
return True, alt_request
return False, request
def middleware(f: _Func) -> _Func:
warnings.warn(
"Middleware decorator is deprecated since 4.0 "
"and its behaviour is default, "
"you can simply remove this decorator.",
DeprecationWarning,
stacklevel=2,
)
return f
def normalize_path_middleware(
*,
append_slash: bool = True,
remove_slash: bool = False,
merge_slashes: bool = True,
redirect_class: type[HTTPMove] = HTTPPermanentRedirect,
) -> Middleware:
"""Factory for producing a middleware that normalizes the path of a request.
Normalizing means:
- Add or remove a trailing slash to the path.
- Double slashes are replaced by one.
The middleware returns as soon as it finds a path that resolves
correctly. The order if both merge and append/remove are enabled is
1) merge slashes
2) append/remove slash
3) both merge slashes and append/remove slash.
If the path resolves with at least one of those conditions, it will
redirect to the new path.
Only one of `append_slash` and `remove_slash` can be enabled. If both
are `True` the factory will raise an assertion error
If `append_slash` is `True` the middleware will append a slash when
needed. If a resource is defined with trailing slash and the request
comes without it, it will append it automatically.
If `remove_slash` is `True`, `append_slash` must be `False`. When enabled
the middleware will remove trailing slashes and redirect if the resource
is defined
If merge_slashes is True, merge multiple consecutive slashes in the
path into one.
"""
correct_configuration = not (append_slash and remove_slash)
assert correct_configuration, "Cannot both remove and append slash"
async def impl(request: Request, handler: Handler) -> StreamResponse:
if isinstance(request.match_info.route, SystemRoute):
paths_to_check = []
if "?" in request.raw_path:
path, query = request.raw_path.split("?", 1)
query = "?" + query
else:
query = ""
path = request.raw_path
if merge_slashes:
paths_to_check.append(re.sub("//+", "/", path))
if append_slash and not request.path.endswith("/"):
paths_to_check.append(path + "/")
if remove_slash and request.path.endswith("/"):
paths_to_check.append(path[:-1])
if merge_slashes and append_slash:
paths_to_check.append(re.sub("//+", "/", path + "/"))
if merge_slashes and remove_slash and path.endswith("/"):
merged_slashes = re.sub("//+", "/", path)
paths_to_check.append(merged_slashes[:-1])
for path in paths_to_check:
path = re.sub("^//+", "/", path) # SECURITY: GHSA-v6wp-4m6f-gcjg
resolves, request = await _check_request_resolves(request, path)
if resolves:
raise redirect_class(request.raw_path + query)
return await handler(request)
return impl
def _fix_request_current_app(app: "Application") -> Middleware:
async def impl(request: Request, handler: Handler) -> StreamResponse:
match_info = request.match_info
prev = match_info.current_app
match_info.current_app = app
try:
return await handler(request)
finally:
match_info.current_app = prev
return impl
| import asyncio
from collections.abc import Awaitable, Callable, Iterable
from typing import NoReturn
import pytest
from yarl import URL
from aiohttp import web, web_app
from aiohttp.pytest_plugin import AiohttpClient
from aiohttp.test_utils import TestClient
from aiohttp.typedefs import Handler, Middleware
CLI = Callable[
[Iterable[Middleware]], Awaitable[TestClient[web.Request, web.Application]]
]
async def test_middleware_modifies_response(
loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient
) -> None:
async def handler(request: web.Request) -> web.Response:
return web.Response(body=b"OK")
async def middleware(request: web.Request, handler: Handler) -> web.Response:
resp = await handler(request)
assert 200 == resp.status
resp.set_status(201)
assert isinstance(resp, web.Response)
assert resp.text is not None
resp.text = resp.text + "[MIDDLEWARE]"
return resp
app = web.Application()
app.middlewares.append(middleware)
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
# Call twice to verify cache works
for _ in range(2):
resp = await client.get("/")
assert 201 == resp.status
txt = await resp.text()
assert "OK[MIDDLEWARE]" == txt
async def test_middleware_handles_exception(
loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient
) -> None:
async def handler(request: web.Request) -> NoReturn:
raise RuntimeError("Error text")
async def middleware(request: web.Request, handler: Handler) -> web.Response:
with pytest.raises(RuntimeError) as ctx:
await handler(request)
return web.Response(status=501, text=str(ctx.value) + "[MIDDLEWARE]")
app = web.Application()
app.middlewares.append(middleware)
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
# Call twice to verify cache works
for _ in range(2):
resp = await client.get("/")
assert 501 == resp.status
txt = await resp.text()
assert "Error text[MIDDLEWARE]" == txt
async def test_middleware_chain(
loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient
) -> None:
async def handler(request: web.Request) -> web.Response:
return web.Response(text="OK")
handler.annotation = "annotation_value" # type: ignore[attr-defined]
async def handler2(request: web.Request) -> web.Response:
return web.Response(text="OK")
middleware_annotation_seen_values = []
def make_middleware(num: int) -> Middleware:
async def middleware(request: web.Request, handler: Handler) -> web.Response:
middleware_annotation_seen_values.append(
getattr(handler, "annotation", None)
)
resp = await handler(request)
assert isinstance(resp, web.Response)
assert resp.text is not None
resp.text = resp.text + f"[{num}]"
return resp
return middleware
app = web.Application()
app.middlewares.append(make_middleware(1))
app.middlewares.append(make_middleware(2))
app.router.add_route("GET", "/", handler)
app.router.add_route("GET", "/r2", handler2)
client = await aiohttp_client(app)
resp = await client.get("/")
assert 200 == resp.status
txt = await resp.text()
assert "OK[2][1]" == txt
assert middleware_annotation_seen_values == ["annotation_value", "annotation_value"]
# check that attributes from handler are not applied to handler2
resp = await client.get("/r2")
assert 200 == resp.status
assert middleware_annotation_seen_values == [
"annotation_value",
"annotation_value",
None,
None,
]
async def test_middleware_subapp(
loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient
) -> None:
async def sub_handler(request: web.Request) -> web.Response:
return web.Response(text="OK")
sub_handler.annotation = "annotation_value" # type: ignore[attr-defined]
async def handler(request: web.Request) -> web.Response:
return web.Response(text="OK")
middleware_annotation_seen_values = []
def make_middleware(num: int) -> Middleware:
async def middleware(
request: web.Request, handler: Handler
) -> web.StreamResponse:
annotation = getattr(handler, "annotation", None)
if annotation is not None:
middleware_annotation_seen_values.append(f"{annotation}/{num}")
return await handler(request)
return middleware
app = web.Application()
app.middlewares.append(make_middleware(1))
app.router.add_route("GET", "/r2", handler)
subapp = web.Application()
subapp.middlewares.append(make_middleware(2))
subapp.router.add_route("GET", "/", sub_handler)
app.add_subapp("/sub", subapp)
client = await aiohttp_client(app)
resp = await client.get("/sub/")
assert 200 == resp.status
await resp.text()
assert middleware_annotation_seen_values == [
"annotation_value/1",
"annotation_value/2",
]
# check that attributes from sub_handler are not applied to handler
del middleware_annotation_seen_values[:]
resp = await client.get("/r2")
assert 200 == resp.status
assert middleware_annotation_seen_values == []
@pytest.fixture
def cli(loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient) -> CLI:
async def handler(request: web.Request) -> web.Response:
return web.Response(text="OK")
def wrapper(
extra_middlewares: Iterable[Middleware],
) -> Awaitable[TestClient[web.Request, web.Application]]:
app = web.Application()
app.router.add_route("GET", "/resource1", handler)
app.router.add_route("GET", "/resource2/", handler)
app.router.add_route("GET", "/resource1/a/b", handler)
app.router.add_route("GET", "/resource2/a/b/", handler)
app.router.add_route("GET", "/resource2/a/b%2Fc/", handler)
app.middlewares.extend(extra_middlewares)
return aiohttp_client(app, server_kwargs={"skip_url_asserts": True})
return wrapper
class TestNormalizePathMiddleware:
@pytest.mark.parametrize(
"path, status",
[
("/resource1", 200),
("/resource1/", 404),
("/resource2", 200),
("/resource2/", 200),
("/resource1?p1=1&p2=2", 200),
("/resource1/?p1=1&p2=2", 404),
("/resource2?p1=1&p2=2", 200),
("/resource2/?p1=1&p2=2", 200),
("/resource2/a/b%2Fc", 200),
("/resource2/a/b%2Fc/", 200),
],
)
async def test_add_trailing_when_necessary(
self, path: str, status: int, cli: CLI
) -> None:
extra_middlewares = [web.normalize_path_middleware(merge_slashes=False)]
client = await cli(extra_middlewares)
resp = await client.get(path)
assert resp.status == status
assert resp.url.query == URL(path).query
@pytest.mark.parametrize(
"path, status",
[
("/resource1", 200),
("/resource1/", 200),
("/resource2", 404),
("/resource2/", 200),
("/resource1?p1=1&p2=2", 200),
("/resource1/?p1=1&p2=2", 200),
("/resource2?p1=1&p2=2", 404),
("/resource2/?p1=1&p2=2", 200),
("/resource2/a/b%2Fc", 404),
("/resource2/a/b%2Fc/", 200),
("/resource12", 404),
("/resource12345", 404),
],
)
async def test_remove_trailing_when_necessary(
self, path: str, status: int, cli: CLI
) -> None:
extra_middlewares = [
web.normalize_path_middleware(
append_slash=False, remove_slash=True, merge_slashes=False
)
]
client = await cli(extra_middlewares)
resp = await client.get(path)
assert resp.status == status
assert resp.url.query == URL(path).query
@pytest.mark.parametrize(
"path, status",
[
("/resource1", 200),
("/resource1/", 404),
("/resource2", 404),
("/resource2/", 200),
("/resource1?p1=1&p2=2", 200),
("/resource1/?p1=1&p2=2", 404),
("/resource2?p1=1&p2=2", 404),
("/resource2/?p1=1&p2=2", 200),
("/resource2/a/b%2Fc", 404),
("/resource2/a/b%2Fc/", 200),
],
)
async def test_no_trailing_slash_when_disabled(
self, path: str, status: int, cli: CLI
) -> None:
extra_middlewares = [
web.normalize_path_middleware(append_slash=False, merge_slashes=False)
]
client = await cli(extra_middlewares)
resp = await client.get(path)
assert resp.status == status
assert resp.url.query == URL(path).query
@pytest.mark.parametrize(
"path, status",
[
("/resource1/a/b", 200),
("//resource1//a//b", 200),
("//resource1//a//b/", 404),
("///resource1//a//b", 200),
("/////resource1/a///b", 200),
("/////resource1/a//b/", 404),
("/resource1/a/b?p=1", 200),
("//resource1//a//b?p=1", 200),
("//resource1//a//b/?p=1", 404),
("///resource1//a//b?p=1", 200),
("/////resource1/a///b?p=1", 200),
("/////resource1/a//b/?p=1", 404),
],
)
async def test_merge_slash(self, path: str, status: int, cli: CLI) -> None:
extra_middlewares = [web.normalize_path_middleware(append_slash=False)]
client = await cli(extra_middlewares)
resp = await client.get(path)
assert resp.status == status
assert resp.url.query == URL(path).query
@pytest.mark.parametrize(
"path, status",
[
("/resource1/a/b", 200),
("/resource1/a/b/", 404),
("//resource2//a//b", 200),
("//resource2//a//b/", 200),
("///resource1//a//b", 200),
("///resource1//a//b/", 404),
("/////resource1/a///b", 200),
("/////resource1/a///b/", 404),
("/resource2/a/b", 200),
("//resource2//a//b", 200),
("//resource2//a//b/", 200),
("///resource2//a//b", 200),
("///resource2//a//b/", 200),
("/////resource2/a///b", 200),
("/////resource2/a///b/", 200),
("/resource1/a/b?p=1", 200),
("/resource1/a/b/?p=1", 404),
("//resource2//a//b?p=1", 200),
("//resource2//a//b/?p=1", 200),
("///resource1//a//b?p=1", 200),
("///resource1//a//b/?p=1", 404),
("/////resource1/a///b?p=1", 200),
("/////resource1/a///b/?p=1", 404),
("/resource2/a/b?p=1", 200),
("//resource2//a//b?p=1", 200),
("//resource2//a//b/?p=1", 200),
("///resource2//a//b?p=1", 200),
("///resource2//a//b/?p=1", 200),
("/////resource2/a///b?p=1", 200),
("/////resource2/a///b/?p=1", 200),
],
)
async def test_append_and_merge_slash(
self, path: str, status: int, cli: CLI
) -> None:
extra_middlewares = [web.normalize_path_middleware()]
client = await cli(extra_middlewares)
resp = await client.get(path)
assert resp.status == status
assert resp.url.query == URL(path).query
@pytest.mark.parametrize(
"path, status",
[
("/resource1/a/b", 200),
("/resource1/a/b/", 200),
("//resource2//a//b", 404),
("//resource2//a//b/", 200),
("///resource1//a//b", 200),
("///resource1//a//b/", 200),
("/////resource1/a///b", 200),
("/////resource1/a///b/", 200),
("/////resource1/a///b///", 200),
("/resource2/a/b", 404),
("//resource2//a//b", 404),
("//resource2//a//b/", 200),
("///resource2//a//b", 404),
("///resource2//a//b/", 200),
("/////resource2/a///b", 404),
("/////resource2/a///b/", 200),
("/resource1/a/b?p=1", 200),
("/resource1/a/b/?p=1", 200),
("//resource2//a//b?p=1", 404),
("//resource2//a//b/?p=1", 200),
("///resource1//a//b?p=1", 200),
("///resource1//a//b/?p=1", 200),
("/////resource1/a///b?p=1", 200),
("/////resource1/a///b/?p=1", 200),
("/resource2/a/b?p=1", 404),
("//resource2//a//b?p=1", 404),
("//resource2//a//b/?p=1", 200),
("///resource2//a//b?p=1", 404),
("///resource2//a//b/?p=1", 200),
("/////resource2/a///b?p=1", 404),
("/////resource2/a///b/?p=1", 200),
],
)
async def test_remove_and_merge_slash(
self, path: str, status: int, cli: CLI
) -> None:
extra_middlewares = [
web.normalize_path_middleware(append_slash=False, remove_slash=True)
]
client = await cli(extra_middlewares)
resp = await client.get(path)
assert resp.status == status
assert resp.url.query == URL(path).query
async def test_cannot_remove_and_add_slash(self) -> None:
with pytest.raises(AssertionError):
web.normalize_path_middleware(append_slash=True, remove_slash=True)
@pytest.mark.parametrize(
["append_slash", "remove_slash"],
[
(True, False),
(False, True),
(False, False),
],
)
async def test_open_redirects(
self, append_slash: bool, remove_slash: bool, aiohttp_client: AiohttpClient
) -> None:
async def handle(request: web.Request) -> web.StreamResponse:
pytest.fail(
"Security advisory 'GHSA-v6wp-4m6f-gcjg' test handler "
"matched unexpectedly",
pytrace=False,
)
app = web.Application(
middlewares=[
web.normalize_path_middleware(
append_slash=append_slash, remove_slash=remove_slash
)
]
)
app.add_routes([web.get("/", handle), web.get("/google.com", handle)])
client = await aiohttp_client(app, server_kwargs={"skip_url_asserts": True})
resp = await client.get("//google.com", allow_redirects=False)
assert resp.status == 308
assert resp.headers["Location"] == "/google.com"
assert resp.url.query == URL("//google.com").query
async def test_bug_3669(aiohttp_client: AiohttpClient) -> None:
async def paymethod(request: web.Request) -> NoReturn:
assert False
app = web.Application()
app.router.add_route("GET", "/paymethod", paymethod)
app.middlewares.append(
web.normalize_path_middleware(append_slash=False, remove_slash=True)
)
client = await aiohttp_client(app, server_kwargs={"skip_url_asserts": True})
resp = await client.get("/paymethods")
assert resp.status == 404
assert resp.url.path != "/paymethod"
async def test_old_style_middleware(
loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient
) -> None:
async def view_handler(request: web.Request) -> web.Response:
return web.Response(body=b"OK")
with pytest.deprecated_call(
match=r"^Middleware decorator is deprecated since 4\.0 and its "
r"behaviour is default, you can simply remove this decorator\.$",
):
@web.middleware
async def middleware(request: web.Request, handler: Handler) -> web.Response:
resp = await handler(request)
assert 200 == resp.status
resp.set_status(201)
assert isinstance(resp, web.Response)
assert resp.text is not None
resp.text = resp.text + "[old style middleware]"
return resp
app = web.Application(middlewares=[middleware])
app.router.add_route("GET", "/", view_handler)
client = await aiohttp_client(app)
resp = await client.get("/")
assert 201 == resp.status
txt = await resp.text()
assert "OK[old style middleware]" == txt
async def test_new_style_middleware_class(
loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient
) -> None:
async def handler(request: web.Request) -> web.Response:
return web.Response(body=b"OK")
class Middleware:
async def __call__(
self, request: web.Request, handler: Handler
) -> web.Response:
resp = await handler(request)
assert 200 == resp.status
resp.set_status(201)
assert isinstance(resp, web.Response)
assert resp.text is not None
resp.text = resp.text + "[new style middleware]"
return resp
app = web.Application()
app.middlewares.append(Middleware())
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.get("/")
assert 201 == resp.status
txt = await resp.text()
assert "OK[new style middleware]" == txt
async def test_new_style_middleware_method(
loop: asyncio.AbstractEventLoop, aiohttp_client: AiohttpClient
) -> None:
async def handler(request: web.Request) -> web.Response:
return web.Response(body=b"OK")
class Middleware:
async def call(self, request: web.Request, handler: Handler) -> web.Response:
resp = await handler(request)
assert 200 == resp.status
resp.set_status(201)
assert isinstance(resp, web.Response)
assert resp.text is not None
resp.text = resp.text + "[new style middleware]"
return resp
app = web.Application()
app.middlewares.append(Middleware().call)
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.get("/")
assert 201 == resp.status
txt = await resp.text()
assert "OK[new style middleware]" == txt
async def test_middleware_does_not_leak(aiohttp_client: AiohttpClient) -> None:
async def any_handler(request: web.Request) -> NoReturn:
assert False
class Middleware:
async def call(
self, request: web.Request, handler: Handler
) -> web.StreamResponse:
return await handler(request)
app = web.Application()
app.router.add_route("POST", "/any", any_handler)
app.middlewares.append(Middleware().call)
client = await aiohttp_client(app)
web_app._cached_build_middleware.cache_clear()
for _ in range(10):
resp = await client.get("/any")
assert resp.status == 405
assert web_app._cached_build_middleware.cache_info().currsize < 10
| aiohttp |
python | """Various helper functions"""
import asyncio
import base64
import binascii
import contextlib
import dataclasses
import datetime
import enum
import functools
import inspect
import netrc
import os
import platform
import re
import sys
import time
import warnings
import weakref
from collections import namedtuple
from collections.abc import Callable, Iterable, Iterator, Mapping
from contextlib import suppress
from email.message import EmailMessage
from email.parser import HeaderParser
from email.policy import HTTP
from email.utils import parsedate
from http.cookies import SimpleCookie
from math import ceil
from pathlib import Path
from types import MappingProxyType, TracebackType
from typing import (
TYPE_CHECKING,
Any,
ContextManager,
Generic,
Optional,
Protocol,
TypeVar,
Union,
final,
get_args,
overload,
)
from urllib.parse import quote
from urllib.request import getproxies, proxy_bypass
from multidict import CIMultiDict, MultiDict, MultiDictProxy, MultiMapping
from propcache.api import under_cached_property as reify
from yarl import URL
from . import hdrs
from .log import client_logger
from .typedefs import PathLike # noqa
if sys.version_info >= (3, 11):
import asyncio as async_timeout
else:
import async_timeout
if TYPE_CHECKING:
from dataclasses import dataclass as frozen_dataclass_decorator
else:
frozen_dataclass_decorator = functools.partial(
dataclasses.dataclass, frozen=True, slots=True
)
__all__ = ("BasicAuth", "ChainMapProxy", "ETag", "frozen_dataclass_decorator", "reify")
COOKIE_MAX_LENGTH = 4096
_T = TypeVar("_T")
_S = TypeVar("_S")
_SENTINEL = enum.Enum("_SENTINEL", "sentinel")
sentinel = _SENTINEL.sentinel
NO_EXTENSIONS = bool(os.environ.get("AIOHTTP_NO_EXTENSIONS"))
# https://datatracker.ietf.org/doc/html/rfc9112#section-6.3-2.1
EMPTY_BODY_STATUS_CODES = frozenset((204, 304, *range(100, 200)))
# https://datatracker.ietf.org/doc/html/rfc9112#section-6.3-2.1
# https://datatracker.ietf.org/doc/html/rfc9112#section-6.3-2.2
EMPTY_BODY_METHODS = hdrs.METH_HEAD_ALL
DEBUG = sys.flags.dev_mode or (
not sys.flags.ignore_environment and bool(os.environ.get("PYTHONASYNCIODEBUG"))
)
CHAR = {chr(i) for i in range(0, 128)}
CTL = {chr(i) for i in range(0, 32)} | {
chr(127),
}
SEPARATORS = {
"(",
")",
"<",
">",
"@",
",",
";",
":",
"\\",
'"',
"/",
"[",
"]",
"?",
"=",
"{",
"}",
" ",
chr(9),
}
TOKEN = CHAR ^ CTL ^ SEPARATORS
json_re = re.compile(r"(?:application/|[\w.-]+/[\w.+-]+?\+)json$", re.IGNORECASE)
class BasicAuth(namedtuple("BasicAuth", ["login", "password", "encoding"])):
"""Http basic authentication helper."""
def __new__(
cls, login: str, password: str = "", encoding: str = "latin1"
) -> "BasicAuth":
if login is None:
raise ValueError("None is not allowed as login value")
if password is None:
raise ValueError("None is not allowed as password value")
if ":" in login:
raise ValueError('A ":" is not allowed in login (RFC 1945#section-11.1)')
return super().__new__(cls, login, password, encoding)
@classmethod
def decode(cls, auth_header: str, encoding: str = "latin1") -> "BasicAuth":
"""Create a BasicAuth object from an Authorization HTTP header."""
try:
auth_type, encoded_credentials = auth_header.split(" ", 1)
except ValueError:
raise ValueError("Could not parse authorization header.")
if auth_type.lower() != "basic":
raise ValueError("Unknown authorization method %s" % auth_type)
try:
decoded = base64.b64decode(
encoded_credentials.encode("ascii"), validate=True
).decode(encoding)
except binascii.Error:
raise ValueError("Invalid base64 encoding.")
try:
# RFC 2617 HTTP Authentication
# https://www.ietf.org/rfc/rfc2617.txt
# the colon must be present, but the username and password may be
# otherwise blank.
username, password = decoded.split(":", 1)
except ValueError:
raise ValueError("Invalid credentials.")
return cls(username, password, encoding=encoding)
@classmethod
def from_url(cls, url: URL, *, encoding: str = "latin1") -> Optional["BasicAuth"]:
"""Create BasicAuth from url."""
if not isinstance(url, URL):
raise TypeError("url should be yarl.URL instance")
# Check raw_user and raw_password first as yarl is likely
# to already have these values parsed from the netloc in the cache.
if url.raw_user is None and url.raw_password is None:
return None
return cls(url.user or "", url.password or "", encoding=encoding)
def encode(self) -> str:
"""Encode credentials."""
creds = (f"{self.login}:{self.password}").encode(self.encoding)
return "Basic %s" % base64.b64encode(creds).decode(self.encoding)
def strip_auth_from_url(url: URL) -> tuple[URL, BasicAuth | None]:
"""Remove user and password from URL if present and return BasicAuth object."""
# Check raw_user and raw_password first as yarl is likely
# to already have these values parsed from the netloc in the cache.
if url.raw_user is None and url.raw_password is None:
return url, None
return url.with_user(None), BasicAuth(url.user or "", url.password or "")
def netrc_from_env() -> netrc.netrc | None:
"""Load netrc from file.
Attempt to load it from the path specified by the env-var
NETRC or in the default location in the user's home directory.
Returns None if it couldn't be found or fails to parse.
"""
netrc_env = os.environ.get("NETRC")
if netrc_env is not None:
netrc_path = Path(netrc_env)
else:
try:
home_dir = Path.home()
except RuntimeError as e:
# if pathlib can't resolve home, it may raise a RuntimeError
client_logger.debug(
"Could not resolve home directory when "
"trying to look for .netrc file: %s",
e,
)
return None
netrc_path = home_dir / (
"_netrc" if platform.system() == "Windows" else ".netrc"
)
try:
return netrc.netrc(str(netrc_path))
except netrc.NetrcParseError as e:
client_logger.warning("Could not parse .netrc file: %s", e)
except OSError as e:
netrc_exists = False
with contextlib.suppress(OSError):
netrc_exists = netrc_path.is_file()
# we couldn't read the file (doesn't exist, permissions, etc.)
if netrc_env or netrc_exists:
# only warn if the environment wanted us to load it,
# or it appears like the default file does actually exist
client_logger.warning("Could not read .netrc file: %s", e)
return None
@frozen_dataclass_decorator
class ProxyInfo:
proxy: URL
proxy_auth: BasicAuth | None
def basicauth_from_netrc(netrc_obj: netrc.netrc | None, host: str) -> BasicAuth:
"""
Return :py:class:`~aiohttp.BasicAuth` credentials for ``host`` from ``netrc_obj``.
:raises LookupError: if ``netrc_obj`` is :py:data:`None` or if no
entry is found for the ``host``.
"""
if netrc_obj is None:
raise LookupError("No .netrc file found")
auth_from_netrc = netrc_obj.authenticators(host)
if auth_from_netrc is None:
raise LookupError(f"No entry for {host!s} found in the `.netrc` file.")
login, account, password = auth_from_netrc
# TODO(PY311): username = login or account
# Up to python 3.10, account could be None if not specified,
# and login will be empty string if not specified. From 3.11,
# login and account will be empty string if not specified.
username = login if (login or account is None) else account
# TODO(PY311): Remove this, as password will be empty string
# if not specified
if password is None:
password = "" # type: ignore[unreachable]
return BasicAuth(username, password)
def proxies_from_env() -> dict[str, ProxyInfo]:
proxy_urls = {
k: URL(v)
for k, v in getproxies().items()
if k in ("http", "https", "ws", "wss")
}
netrc_obj = netrc_from_env()
stripped = {k: strip_auth_from_url(v) for k, v in proxy_urls.items()}
ret = {}
for proto, val in stripped.items():
proxy, auth = val
if proxy.scheme in ("https", "wss"):
client_logger.warning(
"%s proxies %s are not supported, ignoring", proxy.scheme.upper(), proxy
)
continue
if netrc_obj and auth is None:
if proxy.host is not None:
try:
auth = basicauth_from_netrc(netrc_obj, proxy.host)
except LookupError:
auth = None
ret[proto] = ProxyInfo(proxy, auth)
return ret
def get_env_proxy_for_url(url: URL) -> tuple[URL, BasicAuth | None]:
"""Get a permitted proxy for the given URL from the env."""
if url.host is not None and proxy_bypass(url.host):
raise LookupError(f"Proxying is disallowed for `{url.host!r}`")
proxies_in_env = proxies_from_env()
try:
proxy_info = proxies_in_env[url.scheme]
except KeyError:
raise LookupError(f"No proxies found for `{url!s}` in the env")
else:
return proxy_info.proxy, proxy_info.proxy_auth
@frozen_dataclass_decorator
class MimeType:
type: str
subtype: str
suffix: str
parameters: "MultiDictProxy[str]"
@functools.lru_cache(maxsize=56)
def parse_mimetype(mimetype: str) -> MimeType:
"""Parses a MIME type into its components.
mimetype is a MIME type string.
Returns a MimeType object.
Example:
>>> parse_mimetype('text/html; charset=utf-8')
MimeType(type='text', subtype='html', suffix='',
parameters={'charset': 'utf-8'})
"""
if not mimetype:
return MimeType(
type="", subtype="", suffix="", parameters=MultiDictProxy(MultiDict())
)
parts = mimetype.split(";")
params: MultiDict[str] = MultiDict()
for item in parts[1:]:
if not item:
continue
key, _, value = item.partition("=")
params.add(key.lower().strip(), value.strip(' "'))
fulltype = parts[0].strip().lower()
if fulltype == "*":
fulltype = "*/*"
mtype, _, stype = fulltype.partition("/")
stype, _, suffix = stype.partition("+")
return MimeType(
type=mtype, subtype=stype, suffix=suffix, parameters=MultiDictProxy(params)
)
class EnsureOctetStream(EmailMessage):
def __init__(self) -> None:
super().__init__()
# https://www.rfc-editor.org/rfc/rfc9110#section-8.3-5
self.set_default_type("application/octet-stream")
def get_content_type(self) -> str:
"""Re-implementation from Message
Returns application/octet-stream in place of plain/text when
value is wrong.
The way this class is used guarantees that content-type will
be present so simplify the checks wrt to the base implementation.
"""
value = self.get("content-type", "").lower()
# Based on the implementation of _splitparam in the standard library
ctype, _, _ = value.partition(";")
ctype = ctype.strip()
if ctype.count("/") != 1:
return self.get_default_type()
return ctype
@functools.lru_cache(maxsize=56)
def parse_content_type(raw: str) -> tuple[str, MappingProxyType[str, str]]:
"""Parse Content-Type header.
Returns a tuple of the parsed content type and a
MappingProxyType of parameters. The default returned value
is `application/octet-stream`
"""
msg = HeaderParser(EnsureOctetStream, policy=HTTP).parsestr(f"Content-Type: {raw}")
content_type = msg.get_content_type()
params = msg.get_params(())
content_dict = dict(params[1:]) # First element is content type again
return content_type, MappingProxyType(content_dict)
def guess_filename(obj: Any, default: str | None = None) -> str | None:
name = getattr(obj, "name", None)
if name and isinstance(name, str) and name[0] != "<" and name[-1] != ">":
return Path(name).name
return default
not_qtext_re = re.compile(r"[^\041\043-\133\135-\176]")
QCONTENT = {chr(i) for i in range(0x20, 0x7F)} | {"\t"}
def quoted_string(content: str) -> str:
"""Return 7-bit content as quoted-string.
Format content into a quoted-string as defined in RFC5322 for
Internet Message Format. Notice that this is not the 8-bit HTTP
format, but the 7-bit email format. Content must be in usascii or
a ValueError is raised.
"""
if not (QCONTENT > set(content)):
raise ValueError(f"bad content for quoted-string {content!r}")
return not_qtext_re.sub(lambda x: "\\" + x.group(0), content)
def content_disposition_header(
disptype: str,
quote_fields: bool = True,
_charset: str = "utf-8",
params: dict[str, str] | None = None,
) -> str:
"""Sets ``Content-Disposition`` header for MIME.
This is the MIME payload Content-Disposition header from RFC 2183
and RFC 7579 section 4.2, not the HTTP Content-Disposition from
RFC 6266.
disptype is a disposition type: inline, attachment, form-data.
Should be valid extension token (see RFC 2183)
quote_fields performs value quoting to 7-bit MIME headers
according to RFC 7578. Set to quote_fields to False if recipient
can take 8-bit file names and field values.
_charset specifies the charset to use when quote_fields is True.
params is a dict with disposition params.
"""
if not disptype or not (TOKEN > set(disptype)):
raise ValueError(f"bad content disposition type {disptype!r}")
value = disptype
if params:
lparams = []
for key, val in params.items():
if not key or not (TOKEN > set(key)):
raise ValueError(f"bad content disposition parameter {key!r}={val!r}")
if quote_fields:
if key.lower() == "filename":
qval = quote(val, "", encoding=_charset)
lparams.append((key, '"%s"' % qval))
else:
try:
qval = quoted_string(val)
except ValueError:
qval = "".join(
(_charset, "''", quote(val, "", encoding=_charset))
)
lparams.append((key + "*", qval))
else:
lparams.append((key, '"%s"' % qval))
else:
qval = val.replace("\\", "\\\\").replace('"', '\\"')
lparams.append((key, '"%s"' % qval))
sparams = "; ".join("=".join(pair) for pair in lparams)
value = "; ".join((value, sparams))
return value
def is_expected_content_type(
response_content_type: str, expected_content_type: str
) -> bool:
"""Checks if received content type is processable as an expected one.
Both arguments should be given without parameters.
"""
if expected_content_type == "application/json":
return json_re.match(response_content_type) is not None
return expected_content_type in response_content_type
def is_ip_address(host: str | None) -> bool:
"""Check if host looks like an IP Address.
This check is only meant as a heuristic to ensure that
a host is not a domain name.
"""
if not host:
return False
# For a host to be an ipv4 address, it must be all numeric.
# The host must contain a colon to be an IPv6 address.
return ":" in host or host.replace(".", "").isdigit()
_cached_current_datetime: int | None = None
_cached_formatted_datetime = ""
def rfc822_formatted_time() -> str:
global _cached_current_datetime
global _cached_formatted_datetime
now = int(time.time())
if now != _cached_current_datetime:
# Weekday and month names for HTTP date/time formatting;
# always English!
# Tuples are constants stored in codeobject!
_weekdayname = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
_monthname = (
"", # Dummy so we can use 1-based month numbers
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
)
year, month, day, hh, mm, ss, wd, *tail = time.gmtime(now)
_cached_formatted_datetime = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
_weekdayname[wd],
day,
_monthname[month],
year,
hh,
mm,
ss,
)
_cached_current_datetime = now
return _cached_formatted_datetime
def _weakref_handle(info: "tuple[weakref.ref[object], str]") -> None:
ref, name = info
ob = ref()
if ob is not None:
with suppress(Exception):
getattr(ob, name)()
def weakref_handle(
ob: object,
name: str,
timeout: float | None,
loop: asyncio.AbstractEventLoop,
timeout_ceil_threshold: float = 5,
) -> asyncio.TimerHandle | None:
if timeout is not None and timeout > 0:
when = loop.time() + timeout
if timeout >= timeout_ceil_threshold:
when = ceil(when)
return loop.call_at(when, _weakref_handle, (weakref.ref(ob), name))
return None
def call_later(
cb: Callable[[], Any],
timeout: float | None,
loop: asyncio.AbstractEventLoop,
timeout_ceil_threshold: float = 5,
) -> asyncio.TimerHandle | None:
if timeout is None or timeout <= 0:
return None
now = loop.time()
when = calculate_timeout_when(now, timeout, timeout_ceil_threshold)
return loop.call_at(when, cb)
def calculate_timeout_when(
loop_time: float,
timeout: float,
timeout_ceiling_threshold: float,
) -> float:
"""Calculate when to execute a timeout."""
when = loop_time + timeout
if timeout > timeout_ceiling_threshold:
return ceil(when)
return when
class TimeoutHandle:
"""Timeout handle"""
__slots__ = ("_timeout", "_loop", "_ceil_threshold", "_callbacks")
def __init__(
self,
loop: asyncio.AbstractEventLoop,
timeout: float | None,
ceil_threshold: float = 5,
) -> None:
self._timeout = timeout
self._loop = loop
self._ceil_threshold = ceil_threshold
self._callbacks: list[
tuple[Callable[..., None], tuple[Any, ...], dict[str, Any]]
] = []
def register(
self, callback: Callable[..., None], *args: Any, **kwargs: Any
) -> None:
self._callbacks.append((callback, args, kwargs))
def close(self) -> None:
self._callbacks.clear()
def start(self) -> asyncio.TimerHandle | None:
timeout = self._timeout
if timeout is not None and timeout > 0:
when = self._loop.time() + timeout
if timeout >= self._ceil_threshold:
when = ceil(when)
return self._loop.call_at(when, self.__call__)
else:
return None
def timer(self) -> "BaseTimerContext":
if self._timeout is not None and self._timeout > 0:
timer = TimerContext(self._loop)
self.register(timer.timeout)
return timer
else:
return TimerNoop()
def __call__(self) -> None:
for cb, args, kwargs in self._callbacks:
with suppress(Exception):
cb(*args, **kwargs)
self._callbacks.clear()
class BaseTimerContext(ContextManager["BaseTimerContext"]):
__slots__ = ()
def assert_timeout(self) -> None:
"""Raise TimeoutError if timeout has been exceeded."""
class TimerNoop(BaseTimerContext):
__slots__ = ()
def __enter__(self) -> BaseTimerContext:
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
return
class TimerContext(BaseTimerContext):
"""Low resolution timeout context manager"""
__slots__ = ("_loop", "_tasks", "_cancelled", "_cancelling")
def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
self._loop = loop
self._tasks: list[asyncio.Task[Any]] = []
self._cancelled = False
self._cancelling = 0
def assert_timeout(self) -> None:
"""Raise TimeoutError if timer has already been cancelled."""
if self._cancelled:
raise asyncio.TimeoutError from None
def __enter__(self) -> BaseTimerContext:
task = asyncio.current_task(loop=self._loop)
if task is None:
raise RuntimeError("Timeout context manager should be used inside a task")
if sys.version_info >= (3, 11):
# Remember if the task was already cancelling
# so when we __exit__ we can decide if we should
# raise asyncio.TimeoutError or let the cancellation propagate
self._cancelling = task.cancelling()
if self._cancelled:
raise asyncio.TimeoutError from None
self._tasks.append(task)
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> bool | None:
enter_task: asyncio.Task[Any] | None = None
if self._tasks:
enter_task = self._tasks.pop()
if exc_type is asyncio.CancelledError and self._cancelled:
assert enter_task is not None
# The timeout was hit, and the task was cancelled
# so we need to uncancel the last task that entered the context manager
# since the cancellation should not leak out of the context manager
if sys.version_info >= (3, 11):
# If the task was already cancelling don't raise
# asyncio.TimeoutError and instead return None
# to allow the cancellation to propagate
if enter_task.uncancel() > self._cancelling:
return None
raise asyncio.TimeoutError from exc_val
return None
def timeout(self) -> None:
if not self._cancelled:
for task in set(self._tasks):
task.cancel()
self._cancelled = True
def ceil_timeout(
delay: float | None, ceil_threshold: float = 5
) -> async_timeout.Timeout:
if delay is None or delay <= 0:
return async_timeout.timeout(None)
loop = asyncio.get_running_loop()
now = loop.time()
when = now + delay
if delay > ceil_threshold:
when = ceil(when)
return async_timeout.timeout_at(when)
class HeadersMixin:
"""Mixin for handling headers."""
_headers: MultiMapping[str]
_content_type: str | None = None
_content_dict: dict[str, str] | None = None
_stored_content_type: str | None | _SENTINEL = sentinel
def _parse_content_type(self, raw: str | None) -> None:
self._stored_content_type = raw
if raw is None:
# default value according to RFC 2616
self._content_type = "application/octet-stream"
self._content_dict = {}
else:
content_type, content_mapping_proxy = parse_content_type(raw)
self._content_type = content_type
# _content_dict needs to be mutable so we can update it
self._content_dict = content_mapping_proxy.copy()
@property
def content_type(self) -> str:
"""The value of content part for Content-Type HTTP header."""
raw = self._headers.get(hdrs.CONTENT_TYPE)
if self._stored_content_type != raw:
self._parse_content_type(raw)
assert self._content_type is not None
return self._content_type
@property
def charset(self) -> str | None:
"""The value of charset part for Content-Type HTTP header."""
raw = self._headers.get(hdrs.CONTENT_TYPE)
if self._stored_content_type != raw:
self._parse_content_type(raw)
assert self._content_dict is not None
return self._content_dict.get("charset")
@property
def content_length(self) -> int | None:
"""The value of Content-Length HTTP header."""
content_length = self._headers.get(hdrs.CONTENT_LENGTH)
return None if content_length is None else int(content_length)
def set_result(fut: "asyncio.Future[_T]", result: _T) -> None:
if not fut.done():
fut.set_result(result)
_EXC_SENTINEL = BaseException()
class ErrorableProtocol(Protocol):
def set_exception(
self,
exc: type[BaseException] | BaseException,
exc_cause: BaseException = ...,
) -> None: ...
def set_exception(
fut: Union["asyncio.Future[_T]", ErrorableProtocol],
exc: type[BaseException] | BaseException,
exc_cause: BaseException = _EXC_SENTINEL,
) -> None:
"""Set future exception.
If the future is marked as complete, this function is a no-op.
:param exc_cause: An exception that is a direct cause of ``exc``.
Only set if provided.
"""
if asyncio.isfuture(fut) and fut.done():
return
exc_is_sentinel = exc_cause is _EXC_SENTINEL
exc_causes_itself = exc is exc_cause
if not exc_is_sentinel and not exc_causes_itself:
exc.__cause__ = exc_cause
fut.set_exception(exc)
@functools.total_ordering
class BaseKey(Generic[_T]):
"""Base for concrete context storage key classes.
Each storage is provided with its own sub-class for the sake of some additional type safety.
"""
__slots__ = ("_name", "_t", "__orig_class__")
# This may be set by Python when instantiating with a generic type. We need to
# support this, in order to support types that are not concrete classes,
# like Iterable, which can't be passed as the second parameter to __init__.
__orig_class__: type[object]
# TODO(PY314): Change Type to TypeForm (this should resolve unreachable below).
def __init__(self, name: str, t: type[_T] | None = None):
# Prefix with module name to help deduplicate key names.
frame = inspect.currentframe()
while frame:
if frame.f_code.co_name == "<module>":
module: str = frame.f_globals["__name__"]
break
frame = frame.f_back
else:
raise RuntimeError("Failed to get module name.")
# https://github.com/python/mypy/issues/14209
self._name = module + "." + name # type: ignore[possibly-undefined]
self._t = t
def __lt__(self, other: object) -> bool:
if isinstance(other, BaseKey):
return self._name < other._name
return True # Order BaseKey above other types.
def __repr__(self) -> str:
t = self._t
if t is None:
with suppress(AttributeError):
# Set to type arg.
t = get_args(self.__orig_class__)[0]
if t is None:
t_repr = "<<Unknown>>"
elif isinstance(t, type):
if t.__module__ == "builtins":
t_repr = t.__qualname__
else:
t_repr = f"{t.__module__}.{t.__qualname__}"
else:
t_repr = repr(t) # type: ignore[unreachable]
return f"<{self.__class__.__name__}({self._name}, type={t_repr})>"
class AppKey(BaseKey[_T]):
"""Keys for static typing support in Application."""
class RequestKey(BaseKey[_T]):
"""Keys for static typing support in Request."""
class ResponseKey(BaseKey[_T]):
"""Keys for static typing support in Response."""
@final
class ChainMapProxy(Mapping[str | AppKey[Any], Any]):
__slots__ = ("_maps",)
def __init__(self, maps: Iterable[Mapping[str | AppKey[Any], Any]]) -> None:
self._maps = tuple(maps)
def __init_subclass__(cls) -> None:
raise TypeError(
f"Inheritance class {cls.__name__} from ChainMapProxy is forbidden"
)
@overload # type: ignore[override]
def __getitem__(self, key: AppKey[_T]) -> _T: ...
@overload
def __getitem__(self, key: str) -> Any: ...
def __getitem__(self, key: str | AppKey[_T]) -> Any:
for mapping in self._maps:
try:
return mapping[key]
except KeyError:
pass
raise KeyError(key)
@overload # type: ignore[override]
def get(self, key: AppKey[_T], default: _S) -> _T | _S: ...
@overload
def get(self, key: AppKey[_T], default: None = ...) -> _T | None: ...
@overload
def get(self, key: str, default: Any = ...) -> Any: ...
def get(self, key: str | AppKey[_T], default: Any = None) -> Any:
try:
return self[key]
except KeyError:
return default
def __len__(self) -> int:
# reuses stored hash values if possible
return len(set().union(*self._maps))
def __iter__(self) -> Iterator[str | AppKey[Any]]:
d: dict[str | AppKey[Any], Any] = {}
for mapping in reversed(self._maps):
# reuses stored hash values if possible
d.update(mapping)
return iter(d)
def __contains__(self, key: object) -> bool:
return any(key in m for m in self._maps)
def __bool__(self) -> bool:
return any(self._maps)
def __repr__(self) -> str:
content = ", ".join(map(repr, self._maps))
return f"ChainMapProxy({content})"
class CookieMixin:
"""Mixin for handling cookies."""
_cookies: SimpleCookie | None = None
@property
def cookies(self) -> SimpleCookie:
if self._cookies is None:
self._cookies = SimpleCookie()
return self._cookies
def set_cookie(
self,
name: str,
value: str,
*,
expires: str | None = None,
domain: str | None = None,
max_age: int | str | None = None,
path: str = "/",
secure: bool | None = None,
httponly: bool | None = None,
samesite: str | None = None,
partitioned: bool | None = None,
) -> None:
"""Set or update response cookie.
Sets new cookie or updates existent with new value.
Also updates only those params which are not None.
"""
if self._cookies is None:
self._cookies = SimpleCookie()
self._cookies[name] = value
c = self._cookies[name]
if expires is not None:
c["expires"] = expires
elif c.get("expires") == "Thu, 01 Jan 1970 00:00:00 GMT":
del c["expires"]
if domain is not None:
c["domain"] = domain
if max_age is not None:
c["max-age"] = str(max_age)
elif "max-age" in c:
del c["max-age"]
c["path"] = path
if secure is not None:
c["secure"] = secure
if httponly is not None:
c["httponly"] = httponly
if samesite is not None:
c["samesite"] = samesite
if partitioned is not None:
c["partitioned"] = partitioned
if DEBUG:
cookie_length = len(c.output(header="")[1:])
if cookie_length > COOKIE_MAX_LENGTH:
warnings.warn(
"The size of is too large, it might get ignored by the client.",
UserWarning,
stacklevel=2,
)
def del_cookie(
self,
name: str,
*,
domain: str | None = None,
path: str = "/",
secure: bool | None = None,
httponly: bool | None = None,
samesite: str | None = None,
) -> None:
"""Delete cookie.
Creates new empty expired cookie.
"""
# TODO: do we need domain/path here?
if self._cookies is not None:
self._cookies.pop(name, None)
self.set_cookie(
name,
"",
max_age=0,
expires="Thu, 01 Jan 1970 00:00:00 GMT",
domain=domain,
path=path,
secure=secure,
httponly=httponly,
samesite=samesite,
)
def populate_with_cookies(headers: "CIMultiDict[str]", cookies: SimpleCookie) -> None:
for cookie in cookies.values():
value = cookie.output(header="")[1:]
headers.add(hdrs.SET_COOKIE, value)
# https://tools.ietf.org/html/rfc7232#section-2.3
_ETAGC = r"[!\x23-\x7E\x80-\xff]+"
_ETAGC_RE = re.compile(_ETAGC)
_QUOTED_ETAG = rf'(W/)?"({_ETAGC})"'
QUOTED_ETAG_RE = re.compile(_QUOTED_ETAG)
LIST_QUOTED_ETAG_RE = re.compile(rf"({_QUOTED_ETAG})(?:\s*,\s*|$)|(.)")
ETAG_ANY = "*"
@frozen_dataclass_decorator
class ETag:
value: str
is_weak: bool = False
def validate_etag_value(value: str) -> None:
if value != ETAG_ANY and not _ETAGC_RE.fullmatch(value):
raise ValueError(
f"Value {value!r} is not a valid etag. Maybe it contains '\"'?"
)
def parse_http_date(date_str: str | None) -> datetime.datetime | None:
"""Process a date string, return a datetime object"""
if date_str is not None:
timetuple = parsedate(date_str)
if timetuple is not None:
with suppress(ValueError):
return datetime.datetime(*timetuple[:6], tzinfo=datetime.timezone.utc)
return None
@functools.lru_cache
def must_be_empty_body(method: str, code: int) -> bool:
"""Check if a request must return an empty body."""
return (
code in EMPTY_BODY_STATUS_CODES
or method in EMPTY_BODY_METHODS
or (200 <= code < 300 and method in hdrs.METH_CONNECT_ALL)
)
def should_remove_content_length(method: str, code: int) -> bool:
"""Check if a Content-Length header should be removed.
This should always be a subset of must_be_empty_body
"""
# https://www.rfc-editor.org/rfc/rfc9110.html#section-8.6-8
# https://www.rfc-editor.org/rfc/rfc9110.html#section-15.4.5-4
return code in EMPTY_BODY_STATUS_CODES or (
200 <= code < 300 and method in hdrs.METH_CONNECT_ALL
)
| import asyncio
import base64
import datetime
import gc
import sys
import weakref
from collections.abc import Iterator
from math import ceil, modf
from pathlib import Path
from types import MappingProxyType
from unittest import mock
from urllib.request import getproxies_environment
import pytest
from multidict import CIMultiDict, MultiDict, MultiDictProxy
from yarl import URL
from aiohttp import helpers, web
from aiohttp.helpers import (
EMPTY_BODY_METHODS,
is_expected_content_type,
must_be_empty_body,
parse_http_date,
should_remove_content_length,
)
# ------------------- parse_mimetype ----------------------------------
@pytest.mark.parametrize(
"mimetype, expected",
[
("", helpers.MimeType("", "", "", MultiDictProxy(MultiDict()))),
("*", helpers.MimeType("*", "*", "", MultiDictProxy(MultiDict()))),
(
"application/json",
helpers.MimeType("application", "json", "", MultiDictProxy(MultiDict())),
),
(
"application/json; charset=utf-8",
helpers.MimeType(
"application",
"json",
"",
MultiDictProxy(MultiDict({"charset": "utf-8"})),
),
),
(
"""application/json; charset=utf-8;""",
helpers.MimeType(
"application",
"json",
"",
MultiDictProxy(MultiDict({"charset": "utf-8"})),
),
),
(
'ApPlIcAtIoN/JSON;ChaRseT="UTF-8"',
helpers.MimeType(
"application",
"json",
"",
MultiDictProxy(MultiDict({"charset": "UTF-8"})),
),
),
(
"application/rss+xml",
helpers.MimeType("application", "rss", "xml", MultiDictProxy(MultiDict())),
),
(
"text/plain;base64",
helpers.MimeType(
"text", "plain", "", MultiDictProxy(MultiDict({"base64": ""}))
),
),
],
)
def test_parse_mimetype(mimetype: str, expected: helpers.MimeType) -> None:
result = helpers.parse_mimetype(mimetype)
assert isinstance(result, helpers.MimeType)
assert result == expected
# ------------------- parse_content_type ------------------------------
@pytest.mark.parametrize(
"content_type, expected",
[
(
"text/plain",
("text/plain", MultiDictProxy(MultiDict())),
),
(
"wrong",
("application/octet-stream", MultiDictProxy(MultiDict())),
),
],
)
def test_parse_content_type(
content_type: str, expected: tuple[str, MappingProxyType[str, str]]
) -> None:
result = helpers.parse_content_type(content_type)
assert result == expected
# ------------------- guess_filename ----------------------------------
def test_guess_filename_with_file_object(tmp_path: Path) -> None:
file_path = tmp_path / "test_guess_filename"
with file_path.open("w+b") as fp:
assert helpers.guess_filename(fp, "no-throw") is not None
def test_guess_filename_with_path(tmp_path: Path) -> None:
file_path = tmp_path / "test_guess_filename"
assert helpers.guess_filename(file_path, "no-throw") is not None
def test_guess_filename_with_default() -> None:
assert helpers.guess_filename(None, "no-throw") == "no-throw"
# ------------------- BasicAuth -----------------------------------
def test_basic_auth1() -> None:
# missing password here
with pytest.raises(ValueError):
helpers.BasicAuth(None) # type: ignore[arg-type]
def test_basic_auth2() -> None:
with pytest.raises(ValueError):
helpers.BasicAuth("nkim", None) # type: ignore[arg-type]
def test_basic_with_auth_colon_in_login() -> None:
with pytest.raises(ValueError):
helpers.BasicAuth("nkim:1", "pwd")
def test_basic_auth3() -> None:
auth = helpers.BasicAuth("nkim")
assert auth.login == "nkim"
assert auth.password == ""
def test_basic_auth4() -> None:
auth = helpers.BasicAuth("nkim", "pwd")
assert auth.login == "nkim"
assert auth.password == "pwd"
assert auth.encode() == "Basic bmtpbTpwd2Q="
@pytest.mark.parametrize(
"header",
(
"Basic bmtpbTpwd2Q=",
"basic bmtpbTpwd2Q=",
),
)
def test_basic_auth_decode(header: str) -> None:
auth = helpers.BasicAuth.decode(header)
assert auth.login == "nkim"
assert auth.password == "pwd"
def test_basic_auth_invalid() -> None:
with pytest.raises(ValueError):
helpers.BasicAuth.decode("bmtpbTpwd2Q=")
def test_basic_auth_decode_not_basic() -> None:
with pytest.raises(ValueError):
helpers.BasicAuth.decode("Complex bmtpbTpwd2Q=")
def test_basic_auth_decode_bad_base64() -> None:
with pytest.raises(ValueError):
helpers.BasicAuth.decode("Basic bmtpbTpwd2Q")
@pytest.mark.parametrize("header", ("Basic ???", "Basic "))
def test_basic_auth_decode_illegal_chars_base64(header: str) -> None:
with pytest.raises(ValueError, match="Invalid base64 encoding."):
helpers.BasicAuth.decode(header)
def test_basic_auth_decode_invalid_credentials() -> None:
with pytest.raises(ValueError, match="Invalid credentials."):
header = "Basic {}".format(base64.b64encode(b"username").decode())
helpers.BasicAuth.decode(header)
@pytest.mark.parametrize(
"credentials, expected_auth",
(
(":", helpers.BasicAuth(login="", password="", encoding="latin1")),
(
"username:",
helpers.BasicAuth(login="username", password="", encoding="latin1"),
),
(
":password",
helpers.BasicAuth(login="", password="password", encoding="latin1"),
),
(
"username:password",
helpers.BasicAuth(login="username", password="password", encoding="latin1"),
),
),
)
def test_basic_auth_decode_blank_username( # type: ignore[misc]
credentials: str, expected_auth: helpers.BasicAuth
) -> None:
header = f"Basic {base64.b64encode(credentials.encode()).decode()}"
assert helpers.BasicAuth.decode(header) == expected_auth
def test_basic_auth_from_url() -> None:
url = URL("http://user:pass@example.com")
auth = helpers.BasicAuth.from_url(url)
assert auth is not None
assert auth.login == "user"
assert auth.password == "pass"
def test_basic_auth_no_user_from_url() -> None:
url = URL("http://:pass@example.com")
auth = helpers.BasicAuth.from_url(url)
assert auth is not None
assert auth.login == ""
assert auth.password == "pass"
def test_basic_auth_no_auth_from_url() -> None:
url = URL("http://example.com")
auth = helpers.BasicAuth.from_url(url)
assert auth is None
def test_basic_auth_from_not_url() -> None:
with pytest.raises(TypeError):
helpers.BasicAuth.from_url("http://user:pass@example.com") # type: ignore[arg-type]
# ----------------------------------- is_ip_address() ----------------------
def test_is_ip_address() -> None:
assert helpers.is_ip_address("127.0.0.1")
assert helpers.is_ip_address("::1")
assert helpers.is_ip_address("FE80:0000:0000:0000:0202:B3FF:FE1E:8329")
# Hostnames
assert not helpers.is_ip_address("localhost")
assert not helpers.is_ip_address("www.example.com")
def test_ipv4_addresses() -> None:
ip_addresses = [
"0.0.0.0",
"127.0.0.1",
"255.255.255.255",
]
for address in ip_addresses:
assert helpers.is_ip_address(address)
def test_ipv6_addresses() -> None:
ip_addresses = [
"0:0:0:0:0:0:0:0",
"FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF",
"00AB:0002:3008:8CFD:00AB:0002:3008:8CFD",
"00ab:0002:3008:8cfd:00ab:0002:3008:8cfd",
"AB:02:3008:8CFD:AB:02:3008:8CFD",
"AB:02:3008:8CFD::02:3008:8CFD",
"::",
"1::1",
]
for address in ip_addresses:
assert helpers.is_ip_address(address)
def test_host_addresses() -> None:
hosts = [
"www.four.part.host",
"www.python.org",
"foo.bar",
"localhost",
]
for host in hosts:
assert not helpers.is_ip_address(host)
def test_is_ip_address_invalid_type() -> None:
with pytest.raises(TypeError):
helpers.is_ip_address(123) # type: ignore[arg-type]
with pytest.raises(TypeError):
helpers.is_ip_address(object()) # type: ignore[arg-type]
# ----------------------------------- TimeoutHandle -------------------
def test_timeout_handle(loop: asyncio.AbstractEventLoop) -> None:
handle = helpers.TimeoutHandle(loop, 10.2)
cb = mock.Mock()
handle.register(cb)
assert cb == handle._callbacks[0][0]
handle.close()
assert not handle._callbacks
def test_when_timeout_smaller_second(loop: asyncio.AbstractEventLoop) -> None:
timeout = 0.1
handle = helpers.TimeoutHandle(loop, timeout)
timer = loop.time() + timeout
start_handle = handle.start()
assert start_handle is not None
when = start_handle.when()
handle.close()
assert isinstance(when, float)
assert when - timer == pytest.approx(0, abs=0.001)
def test_when_timeout_smaller_second_with_low_threshold(
loop: asyncio.AbstractEventLoop,
) -> None:
timeout = 0.1
handle = helpers.TimeoutHandle(loop, timeout, 0.01)
timer = loop.time() + timeout
start_handle = handle.start()
assert start_handle is not None
when = start_handle.when()
handle.close()
assert isinstance(when, int)
assert when == ceil(timer)
def test_timeout_handle_cb_exc(loop: asyncio.AbstractEventLoop) -> None:
handle = helpers.TimeoutHandle(loop, 10.2)
cb = mock.Mock()
handle.register(cb)
cb.side_effect = ValueError()
handle()
assert cb.called
assert not handle._callbacks
def test_timer_context_not_cancelled() -> None:
with mock.patch("aiohttp.helpers.asyncio") as m_asyncio:
m_asyncio.TimeoutError = asyncio.TimeoutError
loop = mock.Mock()
ctx = helpers.TimerContext(loop)
ctx.timeout()
with pytest.raises(asyncio.TimeoutError):
with ctx:
pass
assert not m_asyncio.current_task.return_value.cancel.called
@pytest.mark.skipif(
sys.version_info < (3, 11), reason="Python 3.11+ is required for .cancelling()"
)
async def test_timer_context_timeout_does_not_leak_upward() -> None:
"""Verify that the TimerContext does not leak cancellation outside the context manager."""
loop = asyncio.get_running_loop()
ctx = helpers.TimerContext(loop)
current_task = asyncio.current_task()
assert current_task is not None
with pytest.raises(asyncio.TimeoutError):
with ctx:
assert current_task.cancelling() == 0
loop.call_soon(ctx.timeout)
await asyncio.sleep(1)
# After the context manager exits, the task should no longer be cancelling
assert current_task.cancelling() == 0
@pytest.mark.skipif(
sys.version_info < (3, 11), reason="Python 3.11+ is required for .cancelling()"
)
async def test_timer_context_timeout_does_swallow_cancellation() -> None:
"""Verify that the TimerContext does not swallow cancellation."""
loop = asyncio.get_running_loop()
current_task = asyncio.current_task()
assert current_task is not None
ctx = helpers.TimerContext(loop)
async def task_with_timeout() -> None:
new_task = asyncio.current_task()
assert new_task is not None
with pytest.raises(asyncio.TimeoutError):
with ctx:
assert new_task.cancelling() == 0
await asyncio.sleep(1)
task = asyncio.create_task(task_with_timeout())
await asyncio.sleep(0)
task.cancel()
assert task.cancelling() == 1
ctx.timeout()
# Cancellation should not leak into the current task
assert current_task.cancelling() == 0
# Cancellation should not be swallowed if the task is cancelled
# and it also times out
await asyncio.sleep(0)
with pytest.raises(asyncio.CancelledError):
await task
assert task.cancelling() == 1
def test_timer_context_no_task(loop: asyncio.AbstractEventLoop) -> None:
with pytest.raises(RuntimeError):
with helpers.TimerContext(loop):
pass
async def test_weakref_handle(loop: asyncio.AbstractEventLoop) -> None:
cb = mock.Mock()
helpers.weakref_handle(cb, "test", 0.01, loop)
await asyncio.sleep(0.1)
assert cb.test.called
async def test_weakref_handle_with_small_threshold(
loop: asyncio.AbstractEventLoop,
) -> None:
cb = mock.Mock()
loop = mock.Mock()
loop.time.return_value = 10
helpers.weakref_handle(cb, "test", 0.1, loop, 0.01)
loop.call_at.assert_called_with(
11, helpers._weakref_handle, (weakref.ref(cb), "test")
)
async def test_weakref_handle_weak(loop: asyncio.AbstractEventLoop) -> None:
cb = mock.Mock()
helpers.weakref_handle(cb, "test", 0.01, loop)
del cb
gc.collect()
await asyncio.sleep(0.1)
# -------------------- ceil math -------------------------
def test_ceil_call_later() -> None:
cb = mock.Mock()
loop = mock.Mock()
loop.time.return_value = 10.1
helpers.call_later(cb, 10.1, loop)
loop.call_at.assert_called_with(21.0, cb)
async def test_ceil_timeout_round(loop: asyncio.AbstractEventLoop) -> None:
async with helpers.ceil_timeout(7.5) as cm:
if sys.version_info >= (3, 11):
w = cm.when()
assert w is not None
frac, integer = modf(w)
else:
assert cm.deadline is not None
frac, integer = modf(cm.deadline)
assert frac == 0
async def test_ceil_timeout_small(loop: asyncio.AbstractEventLoop) -> None:
async with helpers.ceil_timeout(1.1) as cm:
if sys.version_info >= (3, 11):
w = cm.when()
assert w is not None
frac, integer = modf(w)
else:
assert cm.deadline is not None
frac, integer = modf(cm.deadline)
# a chance for exact integer with zero fraction is negligible
assert frac != 0
def test_ceil_call_later_with_small_threshold() -> None:
cb = mock.Mock()
loop = mock.Mock()
loop.time.return_value = 10.1
helpers.call_later(cb, 4.5, loop, 1)
loop.call_at.assert_called_with(15, cb)
def test_ceil_call_later_no_timeout() -> None:
cb = mock.Mock()
loop = mock.Mock()
helpers.call_later(cb, 0, loop)
assert not loop.call_at.called
async def test_ceil_timeout_none(loop: asyncio.AbstractEventLoop) -> None:
async with helpers.ceil_timeout(None) as cm:
if sys.version_info >= (3, 11):
assert cm.when() is None
else:
assert cm.deadline is None
async def test_ceil_timeout_small_with_overriden_threshold(
loop: asyncio.AbstractEventLoop,
) -> None:
async with helpers.ceil_timeout(1.5, ceil_threshold=1) as cm:
if sys.version_info >= (3, 11):
w = cm.when()
assert w is not None
frac, integer = modf(w)
else:
assert cm.deadline is not None
frac, integer = modf(cm.deadline)
assert frac == 0
# -------------------------------- ContentDisposition -------------------
@pytest.mark.parametrize(
"params, quote_fields, _charset, expected",
[
(dict(foo="bar"), True, "utf-8", 'attachment; foo="bar"'),
(dict(foo="bar[]"), True, "utf-8", 'attachment; foo="bar[]"'),
(dict(foo=' a""b\\'), True, "utf-8", 'attachment; foo="\\ a\\"\\"b\\\\"'),
(dict(foo="bär"), True, "utf-8", "attachment; foo*=utf-8''b%C3%A4r"),
(dict(foo='bär "\\'), False, "utf-8", 'attachment; foo="bär \\"\\\\"'),
(dict(foo="bär"), True, "latin-1", "attachment; foo*=latin-1''b%E4r"),
(dict(filename="bär"), True, "utf-8", 'attachment; filename="b%C3%A4r"'),
(dict(filename="bär"), True, "latin-1", 'attachment; filename="b%E4r"'),
(
dict(filename='bär "\\'),
False,
"utf-8",
'attachment; filename="bär \\"\\\\"',
),
],
)
def test_content_disposition(
params: dict[str, str], quote_fields: bool, _charset: str, expected: str
) -> None:
result = helpers.content_disposition_header(
"attachment", quote_fields=quote_fields, _charset=_charset, params=params
)
assert result == expected
def test_content_disposition_bad_type() -> None:
with pytest.raises(ValueError):
helpers.content_disposition_header("foo bar")
with pytest.raises(ValueError):
helpers.content_disposition_header("—Ç–µ—Å—Ç")
with pytest.raises(ValueError):
helpers.content_disposition_header("foo\x00bar")
with pytest.raises(ValueError):
helpers.content_disposition_header("")
def test_set_content_disposition_bad_param() -> None:
with pytest.raises(ValueError):
helpers.content_disposition_header("inline", params={"foo bar": "baz"})
with pytest.raises(ValueError):
helpers.content_disposition_header("inline", params={"—Ç–µ—Å—Ç": "baz"})
with pytest.raises(ValueError):
helpers.content_disposition_header("inline", params={"": "baz"})
with pytest.raises(ValueError):
helpers.content_disposition_header("inline", params={"foo\x00bar": "baz"})
# --------------------- proxies_from_env ------------------------------
@pytest.mark.parametrize(
("proxy_env_vars", "url_input", "expected_scheme"),
(
({"http_proxy": "http://aiohttp.io/path"}, "http://aiohttp.io/path", "http"),
({"https_proxy": "http://aiohttp.io/path"}, "http://aiohttp.io/path", "https"),
({"ws_proxy": "http://aiohttp.io/path"}, "http://aiohttp.io/path", "ws"),
({"wss_proxy": "http://aiohttp.io/path"}, "http://aiohttp.io/path", "wss"),
),
indirect=["proxy_env_vars"],
ids=("http", "https", "ws", "wss"),
)
@pytest.mark.usefixtures("proxy_env_vars")
def test_proxies_from_env(url_input: str, expected_scheme: str) -> None:
url = URL(url_input)
ret = helpers.proxies_from_env()
assert ret.keys() == {expected_scheme}
assert ret[expected_scheme].proxy == url
assert ret[expected_scheme].proxy_auth is None
@pytest.mark.parametrize(
("proxy_env_vars", "url_input", "expected_scheme"),
(
(
{"https_proxy": "https://aiohttp.io/path"},
"https://aiohttp.io/path",
"https",
),
({"wss_proxy": "wss://aiohttp.io/path"}, "wss://aiohttp.io/path", "wss"),
),
indirect=["proxy_env_vars"],
ids=("https", "wss"),
)
@pytest.mark.usefixtures("proxy_env_vars")
def test_proxies_from_env_skipped(
caplog: pytest.LogCaptureFixture, url_input: str, expected_scheme: str
) -> None:
url = URL(url_input)
assert helpers.proxies_from_env() == {}
assert len(caplog.records) == 1
log_message = (
f"{expected_scheme.upper()!s} proxies {url!s} are not supported, ignoring"
)
assert caplog.record_tuples == [("aiohttp.client", 30, log_message)]
@pytest.mark.parametrize(
("proxy_env_vars", "url_input", "expected_scheme"),
(
(
{"http_proxy": "http://user:pass@aiohttp.io/path"},
"http://user:pass@aiohttp.io/path",
"http",
),
),
indirect=["proxy_env_vars"],
ids=("http",),
)
@pytest.mark.usefixtures("proxy_env_vars")
def test_proxies_from_env_http_with_auth(url_input: str, expected_scheme: str) -> None:
url = URL("http://user:pass@aiohttp.io/path")
ret = helpers.proxies_from_env()
assert ret.keys() == {expected_scheme}
assert ret[expected_scheme].proxy == url.with_user(None)
proxy_auth = ret[expected_scheme].proxy_auth
assert proxy_auth is not None
assert proxy_auth.login == "user"
assert proxy_auth.password == "pass"
assert proxy_auth.encoding == "latin1"
# --------------------- get_env_proxy_for_url ------------------------------
@pytest.fixture
def proxy_env_vars(
monkeypatch: pytest.MonkeyPatch, request: pytest.FixtureRequest
) -> object:
for schema in getproxies_environment().keys():
monkeypatch.delenv(f"{schema}_proxy", False)
for proxy_type, proxy_list in request.param.items():
monkeypatch.setenv(proxy_type, proxy_list)
return request.param
@pytest.mark.parametrize(
("proxy_env_vars", "url_input", "expected_err_msg"),
(
(
{"no_proxy": "aiohttp.io"},
"http://aiohttp.io/path",
r"Proxying is disallowed for `'aiohttp.io'`",
),
(
{"no_proxy": "aiohttp.io,proxy.com"},
"http://aiohttp.io/path",
r"Proxying is disallowed for `'aiohttp.io'`",
),
(
{"http_proxy": "http://example.com"},
"https://aiohttp.io/path",
r"No proxies found for `https://aiohttp.io/path` in the env",
),
(
{"https_proxy": "https://example.com"},
"http://aiohttp.io/path",
r"No proxies found for `http://aiohttp.io/path` in the env",
),
(
{},
"https://aiohttp.io/path",
r"No proxies found for `https://aiohttp.io/path` in the env",
),
(
{"https_proxy": "https://example.com"},
"",
r"No proxies found for `` in the env",
),
),
indirect=["proxy_env_vars"],
ids=(
"url_matches_the_no_proxy_list",
"url_matches_the_no_proxy_list_multiple",
"url_scheme_does_not_match_http_proxy_list",
"url_scheme_does_not_match_https_proxy_list",
"no_proxies_are_set",
"url_is_empty",
),
)
@pytest.mark.usefixtures("proxy_env_vars")
def test_get_env_proxy_for_url_negative(url_input: str, expected_err_msg: str) -> None:
url = URL(url_input)
with pytest.raises(LookupError, match=expected_err_msg):
helpers.get_env_proxy_for_url(url)
@pytest.mark.parametrize(
("proxy_env_vars", "url_input"),
(
({"http_proxy": "http://example.com"}, "http://aiohttp.io/path"),
({"https_proxy": "http://example.com"}, "https://aiohttp.io/path"),
(
{"http_proxy": "http://example.com,http://proxy.org"},
"http://aiohttp.io/path",
),
),
indirect=["proxy_env_vars"],
ids=(
"url_scheme_match_http_proxy_list",
"url_scheme_match_https_proxy_list",
"url_scheme_match_http_proxy_list_multiple",
),
)
def test_get_env_proxy_for_url(proxy_env_vars: dict[str, str], url_input: str) -> None:
url = URL(url_input)
proxy, proxy_auth = helpers.get_env_proxy_for_url(url)
proxy_list = proxy_env_vars[url.scheme + "_proxy"]
assert proxy == URL(proxy_list)
assert proxy_auth is None
# ------------- set_result / set_exception ----------------------
async def test_set_result(loop: asyncio.AbstractEventLoop) -> None:
fut = loop.create_future()
helpers.set_result(fut, 123)
assert 123 == await fut
async def test_set_result_cancelled(loop: asyncio.AbstractEventLoop) -> None:
fut = loop.create_future()
fut.cancel()
helpers.set_result(fut, 123)
with pytest.raises(asyncio.CancelledError):
await fut
async def test_set_exception(loop: asyncio.AbstractEventLoop) -> None:
fut = loop.create_future()
helpers.set_exception(fut, RuntimeError())
with pytest.raises(RuntimeError):
await fut
async def test_set_exception_cancelled(loop: asyncio.AbstractEventLoop) -> None:
fut = loop.create_future()
fut.cancel()
helpers.set_exception(fut, RuntimeError())
with pytest.raises(asyncio.CancelledError):
await fut
# ----------- ChainMapProxy --------------------------
AppKeyDict = dict[str | web.AppKey[object], object]
class TestChainMapProxy:
def test_inheritance(self) -> None:
with pytest.raises(TypeError):
class A(helpers.ChainMapProxy): # type: ignore[misc]
pass
def test_getitem(self) -> None:
d1: AppKeyDict = {"a": 2, "b": 3}
d2: AppKeyDict = {"a": 1}
cp = helpers.ChainMapProxy([d1, d2])
assert cp["a"] == 2
assert cp["b"] == 3
def test_getitem_not_found(self) -> None:
d: AppKeyDict = {"a": 1}
cp = helpers.ChainMapProxy([d])
with pytest.raises(KeyError):
cp["b"]
def test_get(self) -> None:
d1: AppKeyDict = {"a": 2, "b": 3}
d2: AppKeyDict = {"a": 1}
cp = helpers.ChainMapProxy([d1, d2])
assert cp.get("a") == 2
def test_get_default(self) -> None:
d1: AppKeyDict = {"a": 2, "b": 3}
d2: AppKeyDict = {"a": 1}
cp = helpers.ChainMapProxy([d1, d2])
assert cp.get("c", 4) == 4
def test_get_non_default(self) -> None:
d1: AppKeyDict = {"a": 2, "b": 3}
d2: AppKeyDict = {"a": 1}
cp = helpers.ChainMapProxy([d1, d2])
assert cp.get("a", 4) == 2
def test_len(self) -> None:
d1: AppKeyDict = {"a": 2, "b": 3}
d2: AppKeyDict = {"a": 1}
cp = helpers.ChainMapProxy([d1, d2])
assert len(cp) == 2
def test_iter(self) -> None:
d1: AppKeyDict = {"a": 2, "b": 3}
d2: AppKeyDict = {"a": 1}
cp = helpers.ChainMapProxy([d1, d2])
assert set(cp) == {"a", "b"}
def test_contains(self) -> None:
d1: AppKeyDict = {"a": 2, "b": 3}
d2: AppKeyDict = {"a": 1}
cp = helpers.ChainMapProxy([d1, d2])
assert "a" in cp
assert "b" in cp
assert "c" not in cp
def test_bool(self) -> None:
assert helpers.ChainMapProxy([{"a": 1}])
assert not helpers.ChainMapProxy([{}, {}])
assert not helpers.ChainMapProxy([])
def test_repr(self) -> None:
d1: AppKeyDict = {"a": 2, "b": 3}
d2: AppKeyDict = {"a": 1}
cp = helpers.ChainMapProxy([d1, d2])
expected = f"ChainMapProxy({d1!r}, {d2!r})"
assert expected == repr(cp)
def test_is_expected_content_type_json_match_exact() -> None:
expected_ct = "application/json"
response_ct = "application/json"
assert is_expected_content_type(
response_content_type=response_ct, expected_content_type=expected_ct
)
def test_is_expected_content_type_json_match_partially() -> None:
expected_ct = "application/json"
response_ct = "application/alto-costmap+json" # mime-type from rfc7285
assert is_expected_content_type(
response_content_type=response_ct, expected_content_type=expected_ct
)
def test_is_expected_content_type_non_application_json_suffix() -> None:
expected_ct = "application/json"
response_ct = "model/gltf+json" # rfc 6839
assert is_expected_content_type(
response_content_type=response_ct, expected_content_type=expected_ct
)
def test_is_expected_content_type_non_application_json_private_suffix() -> None:
expected_ct = "application/json"
response_ct = "x-foo/bar+json" # rfc 6839
assert is_expected_content_type(
response_content_type=response_ct, expected_content_type=expected_ct
)
def test_is_expected_content_type_json_non_lowercase() -> None:
"""Per RFC 2045, media type matching is case insensitive."""
expected_ct = "application/json"
response_ct = "Application/JSON"
assert is_expected_content_type(
response_content_type=response_ct, expected_content_type=expected_ct
)
def test_is_expected_content_type_json_trailing_chars() -> None:
expected_ct = "application/json"
response_ct = "application/json-seq"
assert not is_expected_content_type(
response_content_type=response_ct, expected_content_type=expected_ct
)
def test_is_expected_content_type_non_json_match_exact() -> None:
expected_ct = "text/javascript"
response_ct = "text/javascript"
assert is_expected_content_type(
response_content_type=response_ct, expected_content_type=expected_ct
)
def test_is_expected_content_type_non_json_not_match() -> None:
expected_ct = "application/json"
response_ct = "text/plain"
assert not is_expected_content_type(
response_content_type=response_ct, expected_content_type=expected_ct
)
# It's necessary to subclass CookieMixin before using it.
# See the comments on its __slots__.
class CookieImplementation(helpers.CookieMixin):
pass
def test_cookies_mixin() -> None:
sut = CookieImplementation()
assert sut.cookies == {}
assert str(sut.cookies) == ""
sut.set_cookie("name", "value")
assert str(sut.cookies) == "Set-Cookie: name=value; Path=/"
sut.set_cookie("name", "")
assert str(sut.cookies) == 'Set-Cookie: name=""; Path=/'
sut.set_cookie("name", "value")
assert str(sut.cookies) == "Set-Cookie: name=value; Path=/"
sut.set_cookie("name", "other_value")
assert str(sut.cookies) == "Set-Cookie: name=other_value; Path=/"
sut.cookies["name"] = "another_other_value"
sut.cookies["name"]["max-age"] = 10
assert (
str(sut.cookies) == "Set-Cookie: name=another_other_value; Max-Age=10; Path=/"
)
sut.del_cookie("name")
expected = (
'Set-Cookie: name=""; '
"expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/"
)
assert str(sut.cookies) == expected
sut.del_cookie("name")
assert str(sut.cookies) == expected
sut.set_cookie("name", "value", domain="local.host")
expected = "Set-Cookie: name=value; Domain=local.host; Path=/"
assert str(sut.cookies) == expected
def test_cookies_mixin_path() -> None:
sut = CookieImplementation()
assert sut.cookies == {}
sut.set_cookie("name", "value", path="/some/path")
assert str(sut.cookies) == "Set-Cookie: name=value; Path=/some/path"
sut.set_cookie("name", "value", expires="123")
assert str(sut.cookies) == "Set-Cookie: name=value; expires=123; Path=/"
sut.set_cookie(
"name",
"value",
domain="example.com",
path="/home",
expires="123",
max_age="10",
secure=True,
httponly=True,
samesite="lax",
)
assert (
str(sut.cookies).lower() == "set-cookie: name=value; "
"domain=example.com; "
"expires=123; "
"httponly; "
"max-age=10; "
"path=/home; "
"samesite=lax; "
"secure"
)
@pytest.mark.skipif(sys.version_info < (3, 14), reason="No partitioned support")
def test_cookies_mixin_partitioned() -> None:
sut = CookieImplementation()
assert sut.cookies == {}
sut.set_cookie("name", "value", partitioned=False)
assert str(sut.cookies) == "Set-Cookie: name=value; Path=/"
sut.set_cookie("name", "value", partitioned=True)
assert str(sut.cookies) == "Set-Cookie: name=value; Partitioned; Path=/"
def test_sutonse_cookie__issue_del_cookie() -> None:
sut = CookieImplementation()
assert sut.cookies == {}
assert str(sut.cookies) == ""
sut.del_cookie("name")
expected = (
'Set-Cookie: name=""; '
"expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/"
)
assert str(sut.cookies) == expected
def test_cookie_set_after_del() -> None:
sut = CookieImplementation()
sut.del_cookie("name")
sut.set_cookie("name", "val")
# check for Max-Age dropped
expected = "Set-Cookie: name=val; Path=/"
assert str(sut.cookies) == expected
def test_populate_with_cookies() -> None:
cookies_mixin = CookieImplementation()
cookies_mixin.set_cookie("name", "value")
headers = CIMultiDict[str]()
helpers.populate_with_cookies(headers, cookies_mixin.cookies)
assert headers == CIMultiDict({"Set-Cookie": "name=value; Path=/"})
@pytest.mark.parametrize(
["value", "expected"],
[
# email.utils.parsedate returns None
pytest.param("xxyyzz", None),
# datetime.datetime fails with ValueError("year 4446413 is out of range")
pytest.param("Tue, 08 Oct 4446413 00:56:40 GMT", None),
# datetime.datetime fails with ValueError("second must be in 0..59")
pytest.param("Tue, 08 Oct 2000 00:56:80 GMT", None),
# OK
pytest.param(
"Tue, 08 Oct 2000 00:56:40 GMT",
datetime.datetime(2000, 10, 8, 0, 56, 40, tzinfo=datetime.timezone.utc),
),
# OK (ignore timezone and overwrite to UTC)
pytest.param(
"Tue, 08 Oct 2000 00:56:40 +0900",
datetime.datetime(2000, 10, 8, 0, 56, 40, tzinfo=datetime.timezone.utc),
),
],
)
def test_parse_http_date(value: str, expected: datetime.datetime | None) -> None:
assert parse_http_date(value) == expected
@pytest.mark.parametrize(
["netrc_contents", "expected_username"],
[
(
"machine example.com login username password pass\n",
"username",
),
],
indirect=("netrc_contents",),
)
@pytest.mark.usefixtures("netrc_contents")
def test_netrc_from_env(expected_username: str) -> None:
"""Test that reading netrc files from env works as expected"""
netrc_obj = helpers.netrc_from_env()
assert netrc_obj is not None
auth = netrc_obj.authenticators("example.com")
assert auth is not None
assert auth[0] == expected_username
@pytest.fixture
def protected_dir(tmp_path: Path) -> Iterator[Path]:
protected_dir = tmp_path / "protected"
protected_dir.mkdir()
try:
protected_dir.chmod(0o600)
yield protected_dir
finally:
protected_dir.rmdir()
def test_netrc_from_home_does_not_raise_if_access_denied(
protected_dir: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(Path, "home", lambda: protected_dir)
monkeypatch.delenv("NETRC", raising=False)
helpers.netrc_from_env()
@pytest.mark.parametrize(
["netrc_contents", "expected_auth"],
[
(
"machine example.com login username password pass\n",
helpers.BasicAuth("username", "pass"),
),
(
"machine example.com account username password pass\n",
helpers.BasicAuth("username", "pass"),
),
(
"machine example.com password pass\n",
helpers.BasicAuth("", "pass"),
),
],
indirect=("netrc_contents",),
)
@pytest.mark.usefixtures("netrc_contents")
def test_basicauth_present_in_netrc( # type: ignore[misc]
expected_auth: helpers.BasicAuth,
) -> None:
"""Test that netrc file contents are properly parsed into BasicAuth tuples"""
netrc_obj = helpers.netrc_from_env()
assert expected_auth == helpers.basicauth_from_netrc(netrc_obj, "example.com")
@pytest.mark.parametrize(
["netrc_contents"],
[
("",),
],
indirect=("netrc_contents",),
)
@pytest.mark.usefixtures("netrc_contents")
def test_read_basicauth_from_empty_netrc() -> None:
"""Test that an error is raised if netrc doesn't have an entry for our host"""
netrc_obj = helpers.netrc_from_env()
with pytest.raises(
LookupError, match="No entry for example.com found in the `.netrc` file."
):
helpers.basicauth_from_netrc(netrc_obj, "example.com")
def test_method_must_be_empty_body() -> None:
"""Test that HEAD is the only method that unequivocally must have an empty body."""
assert "HEAD" in EMPTY_BODY_METHODS
# CONNECT is only empty on a successful response
assert "CONNECT" not in EMPTY_BODY_METHODS
def test_should_remove_content_length_is_subset_of_must_be_empty_body() -> None:
"""Test should_remove_content_length is always a subset of must_be_empty_body."""
assert should_remove_content_length("GET", 101) is True
assert must_be_empty_body("GET", 101) is True
assert should_remove_content_length("GET", 102) is True
assert must_be_empty_body("GET", 102) is True
assert should_remove_content_length("GET", 204) is True
assert must_be_empty_body("GET", 204) is True
assert should_remove_content_length("GET", 204) is True
assert must_be_empty_body("GET", 204) is True
assert should_remove_content_length("GET", 200) is False
assert must_be_empty_body("GET", 200) is False
assert should_remove_content_length("HEAD", 200) is False
assert must_be_empty_body("HEAD", 200) is True
# CONNECT is only empty on a successful response
assert should_remove_content_length("CONNECT", 200) is True
assert must_be_empty_body("CONNECT", 200) is True
assert should_remove_content_length("CONNECT", 201) is True
assert must_be_empty_body("CONNECT", 201) is True
assert should_remove_content_length("CONNECT", 300) is False
assert must_be_empty_body("CONNECT", 300) is False
| aiohttp |
python | import asyncio
import datetime
import io
import re
import socket
import string
import sys
import tempfile
import types
from collections.abc import Iterator, Mapping, MutableMapping
from re import Pattern
from types import MappingProxyType
from typing import TYPE_CHECKING, Any, Final, Optional, TypeVar, cast, overload
from urllib.parse import parse_qsl
from multidict import CIMultiDict, CIMultiDictProxy, MultiDict, MultiDictProxy
from yarl import URL
from . import hdrs
from ._cookie_helpers import parse_cookie_header
from .abc import AbstractStreamWriter
from .helpers import (
_SENTINEL,
ETAG_ANY,
LIST_QUOTED_ETAG_RE,
ChainMapProxy,
ETag,
HeadersMixin,
RequestKey,
frozen_dataclass_decorator,
is_expected_content_type,
parse_http_date,
reify,
sentinel,
set_exception,
)
from .http_parser import RawRequestMessage
from .http_writer import HttpVersion
from .multipart import BodyPartReader, MultipartReader
from .streams import EmptyStreamReader, StreamReader
from .typedefs import (
DEFAULT_JSON_DECODER,
JSONDecoder,
LooseHeaders,
RawHeaders,
StrOrURL,
)
from .web_exceptions import (
HTTPBadRequest,
HTTPRequestEntityTooLarge,
HTTPUnsupportedMediaType,
)
from .web_response import StreamResponse
if sys.version_info >= (3, 11):
from typing import Self
else:
Self = Any
__all__ = ("BaseRequest", "FileField", "Request")
if TYPE_CHECKING:
from .web_app import Application
from .web_protocol import RequestHandler
from .web_urldispatcher import UrlMappingMatchInfo
_T = TypeVar("_T")
@frozen_dataclass_decorator
class FileField:
name: str
filename: str
file: io.BufferedReader
content_type: str
headers: CIMultiDictProxy[str]
_TCHAR: Final[str] = string.digits + string.ascii_letters + r"!#$%&'*+.^_`|~-"
# '-' at the end to prevent interpretation as range in a char class
_TOKEN: Final[str] = rf"[{_TCHAR}]+"
_QDTEXT: Final[str] = r"[{}]".format(
r"".join(chr(c) for c in (0x09, 0x20, 0x21) + tuple(range(0x23, 0x7F)))
)
# qdtext includes 0x5C to escape 0x5D ('\]')
# qdtext excludes obs-text (because obsoleted, and encoding not specified)
_QUOTED_PAIR: Final[str] = r"\\[\t !-~]"
_QUOTED_STRING: Final[str] = rf'"(?:{_QUOTED_PAIR}|{_QDTEXT})*"'
_FORWARDED_PAIR: Final[str] = rf"({_TOKEN})=({_TOKEN}|{_QUOTED_STRING})(:\d{{1,4}})?"
_QUOTED_PAIR_REPLACE_RE: Final[Pattern[str]] = re.compile(r"\\([\t !-~])")
# same pattern as _QUOTED_PAIR but contains a capture group
_FORWARDED_PAIR_RE: Final[Pattern[str]] = re.compile(_FORWARDED_PAIR)
############################################################
# HTTP Request
############################################################
class BaseRequest(MutableMapping[str | RequestKey[Any], Any], HeadersMixin):
POST_METHODS = {
hdrs.METH_PATCH,
hdrs.METH_POST,
hdrs.METH_PUT,
hdrs.METH_TRACE,
hdrs.METH_DELETE,
}
_post: MultiDictProxy[str | bytes | FileField] | None = None
_read_bytes: bytes | None = None
def __init__(
self,
message: RawRequestMessage,
payload: StreamReader,
protocol: "RequestHandler[Self]",
payload_writer: AbstractStreamWriter,
task: "asyncio.Task[None]",
loop: asyncio.AbstractEventLoop,
*,
client_max_size: int = 1024**2,
state: dict[RequestKey[Any] | str, Any] | None = None,
scheme: str | None = None,
host: str | None = None,
remote: str | None = None,
) -> None:
self._message = message
self._protocol = protocol
self._payload_writer = payload_writer
self._payload = payload
self._headers: CIMultiDictProxy[str] = message.headers
self._method = message.method
self._version = message.version
self._cache: dict[str, Any] = {}
url = message.url
if url.absolute:
if scheme is not None:
url = url.with_scheme(scheme)
if host is not None:
url = url.with_host(host)
# absolute URL is given,
# override auto-calculating url, host, and scheme
# all other properties should be good
self._cache["url"] = url
self._cache["host"] = url.host
self._cache["scheme"] = url.scheme
self._rel_url = url.relative()
else:
self._rel_url = url
if scheme is not None:
self._cache["scheme"] = scheme
if host is not None:
self._cache["host"] = host
self._state = {} if state is None else state
self._task = task
self._client_max_size = client_max_size
self._loop = loop
self._transport_sslcontext = protocol.ssl_context
self._transport_peername = protocol.peername
if remote is not None:
self._cache["remote"] = remote
def clone(
self,
*,
method: str | _SENTINEL = sentinel,
rel_url: StrOrURL | _SENTINEL = sentinel,
headers: LooseHeaders | _SENTINEL = sentinel,
scheme: str | _SENTINEL = sentinel,
host: str | _SENTINEL = sentinel,
remote: str | _SENTINEL = sentinel,
client_max_size: int | _SENTINEL = sentinel,
) -> "BaseRequest":
"""Clone itself with replacement some attributes.
Creates and returns a new instance of Request object. If no parameters
are given, an exact copy is returned. If a parameter is not passed, it
will reuse the one from the current request object.
"""
if self._read_bytes:
raise RuntimeError("Cannot clone request after reading its content")
dct: dict[str, Any] = {}
if method is not sentinel:
dct["method"] = method
if rel_url is not sentinel:
new_url: URL = URL(rel_url)
dct["url"] = new_url
dct["path"] = str(new_url)
if headers is not sentinel:
# a copy semantic
new_headers = CIMultiDictProxy(CIMultiDict(headers))
dct["headers"] = new_headers
dct["raw_headers"] = tuple(
(k.encode("utf-8"), v.encode("utf-8")) for k, v in new_headers.items()
)
message = self._message._replace(**dct)
kwargs: dict[str, str] = {}
if scheme is not sentinel:
kwargs["scheme"] = scheme
if host is not sentinel:
kwargs["host"] = host
if remote is not sentinel:
kwargs["remote"] = remote
if client_max_size is sentinel:
client_max_size = self._client_max_size
return self.__class__(
message,
self._payload,
self._protocol, # type: ignore[arg-type]
self._payload_writer,
self._task,
self._loop,
client_max_size=client_max_size,
state=self._state.copy(),
**kwargs,
)
@property
def task(self) -> "asyncio.Task[None]":
return self._task
@property
def protocol(self) -> "RequestHandler[Self]":
return self._protocol
@property
def transport(self) -> asyncio.Transport | None:
return self._protocol.transport
@property
def writer(self) -> AbstractStreamWriter:
return self._payload_writer
@property
def client_max_size(self) -> int:
return self._client_max_size
@reify
def rel_url(self) -> URL:
return self._rel_url
# MutableMapping API
@overload # type: ignore[override]
def __getitem__(self, key: RequestKey[_T]) -> _T: ...
@overload
def __getitem__(self, key: str) -> Any: ...
def __getitem__(self, key: str | RequestKey[_T]) -> Any:
return self._state[key]
@overload # type: ignore[override]
def __setitem__(self, key: RequestKey[_T], value: _T) -> None: ...
@overload
def __setitem__(self, key: str, value: Any) -> None: ...
def __setitem__(self, key: str | RequestKey[_T], value: Any) -> None:
self._state[key] = value
def __delitem__(self, key: str | RequestKey[_T]) -> None:
del self._state[key]
def __len__(self) -> int:
return len(self._state)
def __iter__(self) -> Iterator[str | RequestKey[Any]]:
return iter(self._state)
########
@reify
def secure(self) -> bool:
"""A bool indicating if the request is handled with SSL."""
return self.scheme == "https"
@reify
def forwarded(self) -> tuple[Mapping[str, str], ...]:
"""A tuple containing all parsed Forwarded header(s).
Makes an effort to parse Forwarded headers as specified by RFC 7239:
- It adds one (immutable) dictionary per Forwarded 'field-value', ie
per proxy. The element corresponds to the data in the Forwarded
field-value added by the first proxy encountered by the client. Each
subsequent item corresponds to those added by later proxies.
- It checks that every value has valid syntax in general as specified
in section 4: either a 'token' or a 'quoted-string'.
- It un-escapes found escape sequences.
- It does NOT validate 'by' and 'for' contents as specified in section
6.
- It does NOT validate 'host' contents (Host ABNF).
- It does NOT validate 'proto' contents for valid URI scheme names.
Returns a tuple containing one or more immutable dicts
"""
elems = []
for field_value in self._message.headers.getall(hdrs.FORWARDED, ()):
length = len(field_value)
pos = 0
need_separator = False
elem: dict[str, str] = {}
elems.append(types.MappingProxyType(elem))
while 0 <= pos < length:
match = _FORWARDED_PAIR_RE.match(field_value, pos)
if match is not None: # got a valid forwarded-pair
if need_separator:
# bad syntax here, skip to next comma
pos = field_value.find(",", pos)
else:
name, value, port = match.groups()
if value[0] == '"':
# quoted string: remove quotes and unescape
value = _QUOTED_PAIR_REPLACE_RE.sub(r"\1", value[1:-1])
if port:
value += port
elem[name.lower()] = value
pos += len(match.group(0))
need_separator = True
elif field_value[pos] == ",": # next forwarded-element
need_separator = False
elem = {}
elems.append(types.MappingProxyType(elem))
pos += 1
elif field_value[pos] == ";": # next forwarded-pair
need_separator = False
pos += 1
elif field_value[pos] in " \t":
# Allow whitespace even between forwarded-pairs, though
# RFC 7239 doesn't. This simplifies code and is in line
# with Postel's law.
pos += 1
else:
# bad syntax here, skip to next comma
pos = field_value.find(",", pos)
return tuple(elems)
@reify
def scheme(self) -> str:
"""A string representing the scheme of the request.
Hostname is resolved in this order:
- overridden value by .clone(scheme=new_scheme) call.
- type of connection to peer: HTTPS if socket is SSL, HTTP otherwise.
'http' or 'https'.
"""
if self._transport_sslcontext:
return "https"
else:
return "http"
@reify
def method(self) -> str:
"""Read only property for getting HTTP method.
The value is upper-cased str like 'GET', 'POST', 'PUT' etc.
"""
return self._method
@reify
def version(self) -> HttpVersion:
"""Read only property for getting HTTP version of request.
Returns aiohttp.protocol.HttpVersion instance.
"""
return self._version
@reify
def host(self) -> str:
"""Hostname of the request.
Hostname is resolved in this order:
- overridden value by .clone(host=new_host) call.
- HOST HTTP header
- socket.getfqdn() value
For example, 'example.com' or 'localhost:8080'.
For historical reasons, the port number may be included.
"""
host = self._message.headers.get(hdrs.HOST)
if host is not None:
return host
return socket.getfqdn()
@reify
def remote(self) -> str | None:
"""Remote IP of client initiated HTTP request.
The IP is resolved in this order:
- overridden value by .clone(remote=new_remote) call.
- peername of opened socket
"""
if self._transport_peername is None:
return None
if isinstance(self._transport_peername, (list, tuple)):
return str(self._transport_peername[0])
return str(self._transport_peername)
@reify
def url(self) -> URL:
"""The full URL of the request."""
# authority is used here because it may include the port number
# and we want yarl to parse it correctly
return URL.build(scheme=self.scheme, authority=self.host).join(self._rel_url)
@reify
def path(self) -> str:
"""The URL including *PATH INFO* without the host or scheme.
E.g., ``/app/blog``
"""
return self._rel_url.path
@reify
def path_qs(self) -> str:
"""The URL including PATH_INFO and the query string.
E.g, /app/blog?id=10
"""
return str(self._rel_url)
@reify
def raw_path(self) -> str:
"""The URL including raw *PATH INFO* without the host or scheme.
Warning, the path is unquoted and may contains non valid URL characters
E.g., ``/my%2Fpath%7Cwith%21some%25strange%24characters``
"""
return self._message.path
@reify
def query(self) -> MultiDictProxy[str]:
"""A multidict with all the variables in the query string."""
return self._rel_url.query
@reify
def query_string(self) -> str:
"""The query string in the URL.
E.g., id=10
"""
return self._rel_url.query_string
@reify
def headers(self) -> CIMultiDictProxy[str]:
"""A case-insensitive multidict proxy with all headers."""
return self._headers
@reify
def raw_headers(self) -> RawHeaders:
"""A sequence of pairs for all headers."""
return self._message.raw_headers
@reify
def if_modified_since(self) -> datetime.datetime | None:
"""The value of If-Modified-Since HTTP header, or None.
This header is represented as a `datetime` object.
"""
return parse_http_date(self.headers.get(hdrs.IF_MODIFIED_SINCE))
@reify
def if_unmodified_since(self) -> datetime.datetime | None:
"""The value of If-Unmodified-Since HTTP header, or None.
This header is represented as a `datetime` object.
"""
return parse_http_date(self.headers.get(hdrs.IF_UNMODIFIED_SINCE))
@staticmethod
def _etag_values(etag_header: str) -> Iterator[ETag]:
"""Extract `ETag` objects from raw header."""
if etag_header == ETAG_ANY:
yield ETag(
is_weak=False,
value=ETAG_ANY,
)
else:
for match in LIST_QUOTED_ETAG_RE.finditer(etag_header):
is_weak, value, garbage = match.group(2, 3, 4)
# Any symbol captured by 4th group means
# that the following sequence is invalid.
if garbage:
break
yield ETag(
is_weak=bool(is_weak),
value=value,
)
@classmethod
def _if_match_or_none_impl(
cls, header_value: str | None
) -> tuple[ETag, ...] | None:
if not header_value:
return None
return tuple(cls._etag_values(header_value))
@reify
def if_match(self) -> tuple[ETag, ...] | None:
"""The value of If-Match HTTP header, or None.
This header is represented as a `tuple` of `ETag` objects.
"""
return self._if_match_or_none_impl(self.headers.get(hdrs.IF_MATCH))
@reify
def if_none_match(self) -> tuple[ETag, ...] | None:
"""The value of If-None-Match HTTP header, or None.
This header is represented as a `tuple` of `ETag` objects.
"""
return self._if_match_or_none_impl(self.headers.get(hdrs.IF_NONE_MATCH))
@reify
def if_range(self) -> datetime.datetime | None:
"""The value of If-Range HTTP header, or None.
This header is represented as a `datetime` object.
"""
return parse_http_date(self.headers.get(hdrs.IF_RANGE))
@reify
def keep_alive(self) -> bool:
"""Is keepalive enabled by client?"""
return not self._message.should_close
@reify
def cookies(self) -> Mapping[str, str]:
"""Return request cookies.
A read-only dictionary-like object.
"""
# Use parse_cookie_header for RFC 6265 compliant Cookie header parsing
# that accepts special characters in cookie names (fixes #2683)
parsed = parse_cookie_header(self.headers.get(hdrs.COOKIE, ""))
# Extract values from Morsel objects
return MappingProxyType({name: morsel.value for name, morsel in parsed})
@reify
def http_range(self) -> "slice[int, int, int]":
"""The content of Range HTTP header.
Return a slice instance.
"""
rng = self._headers.get(hdrs.RANGE)
start, end = None, None
if rng is not None:
try:
pattern = r"^bytes=(\d*)-(\d*)$"
start, end = re.findall(pattern, rng)[0]
except IndexError: # pattern was not found in header
raise ValueError("range not in acceptable format")
end = int(end) if end else None
start = int(start) if start else None
if start is None and end is not None:
# end with no start is to return tail of content
start = -end
end = None
if start is not None and end is not None:
# end is inclusive in range header, exclusive for slice
end += 1
if start >= end:
raise ValueError("start cannot be after end")
if start is end is None: # No valid range supplied
raise ValueError("No start or end of range specified")
return slice(start, end, 1)
@reify
def content(self) -> StreamReader:
"""Return raw payload stream."""
return self._payload
@property
def can_read_body(self) -> bool:
"""Return True if request's HTTP BODY can be read, False otherwise."""
return not self._payload.at_eof()
@reify
def body_exists(self) -> bool:
"""Return True if request has HTTP BODY, False otherwise."""
return type(self._payload) is not EmptyStreamReader
async def release(self) -> None:
"""Release request.
Eat unread part of HTTP BODY if present.
"""
while not self._payload.at_eof():
await self._payload.readany()
async def read(self) -> bytes:
"""Read request body if present.
Returns bytes object with full request content.
"""
if self._read_bytes is None:
body = bytearray()
while True:
chunk = await self._payload.readany()
body.extend(chunk)
if self._client_max_size:
body_size = len(body)
if body_size > self._client_max_size:
raise HTTPRequestEntityTooLarge(
max_size=self._client_max_size, actual_size=body_size
)
if not chunk:
break
self._read_bytes = bytes(body)
return self._read_bytes
async def text(self) -> str:
"""Return BODY as text using encoding from .charset."""
bytes_body = await self.read()
encoding = self.charset or "utf-8"
try:
return bytes_body.decode(encoding)
except LookupError:
raise HTTPUnsupportedMediaType()
async def json(
self,
*,
loads: JSONDecoder = DEFAULT_JSON_DECODER,
content_type: str | None = "application/json",
) -> Any:
"""Return BODY as JSON."""
body = await self.text()
if content_type:
if not is_expected_content_type(self.content_type, content_type):
raise HTTPBadRequest(
text=(
"Attempt to decode JSON with "
"unexpected mimetype: %s" % self.content_type
)
)
return loads(body)
async def multipart(self) -> MultipartReader:
"""Return async iterator to process BODY as multipart."""
return MultipartReader(self._headers, self._payload)
async def post(self) -> "MultiDictProxy[str | bytes | FileField]":
"""Return POST parameters."""
if self._post is not None:
return self._post
if self._method not in self.POST_METHODS:
self._post = MultiDictProxy(MultiDict())
return self._post
content_type = self.content_type
if content_type not in (
"",
"application/x-www-form-urlencoded",
"multipart/form-data",
):
self._post = MultiDictProxy(MultiDict())
return self._post
out: MultiDict[str | bytes | FileField] = MultiDict()
if content_type == "multipart/form-data":
multipart = await self.multipart()
max_size = self._client_max_size
field = await multipart.next()
while field is not None:
size = 0
field_ct = field.headers.get(hdrs.CONTENT_TYPE)
if isinstance(field, BodyPartReader):
assert field.name is not None
# Note that according to RFC 7578, the Content-Type header
# is optional, even for files, so we can't assume it's
# present.
# https://tools.ietf.org/html/rfc7578#section-4.4
if field.filename:
# store file in temp file
tmp = await self._loop.run_in_executor(
None, tempfile.TemporaryFile
)
chunk = await field.read_chunk(size=2**16)
while chunk:
chunk = field.decode(chunk)
await self._loop.run_in_executor(None, tmp.write, chunk)
size += len(chunk)
if 0 < max_size < size:
await self._loop.run_in_executor(None, tmp.close)
raise HTTPRequestEntityTooLarge(
max_size=max_size, actual_size=size
)
chunk = await field.read_chunk(size=2**16)
await self._loop.run_in_executor(None, tmp.seek, 0)
if field_ct is None:
field_ct = "application/octet-stream"
ff = FileField(
field.name,
field.filename,
cast(io.BufferedReader, tmp),
field_ct,
field.headers,
)
out.add(field.name, ff)
else:
# deal with ordinary data
value = await field.read(decode=True)
if field_ct is None or field_ct.startswith("text/"):
charset = field.get_charset(default="utf-8")
out.add(field.name, value.decode(charset))
else:
out.add(field.name, value)
size += len(value)
if 0 < max_size < size:
raise HTTPRequestEntityTooLarge(
max_size=max_size, actual_size=size
)
else:
raise ValueError(
"To decode nested multipart you need to use custom reader",
)
field = await multipart.next()
else:
data = await self.read()
if data:
charset = self.charset or "utf-8"
bytes_query = data.rstrip()
try:
query = bytes_query.decode(charset)
except LookupError:
raise HTTPUnsupportedMediaType()
out.extend(
parse_qsl(qs=query, keep_blank_values=True, encoding=charset)
)
self._post = MultiDictProxy(out)
return self._post
def get_extra_info(self, name: str, default: Any = None) -> Any:
"""Extra info from protocol transport"""
transport = self._protocol.transport
if transport is None:
return default
return transport.get_extra_info(name, default)
def __repr__(self) -> str:
ascii_encodable_path = self.path.encode("ascii", "backslashreplace").decode(
"ascii"
)
return f"<{self.__class__.__name__} {self._method} {ascii_encodable_path} >"
def __eq__(self, other: object) -> bool:
return id(self) == id(other)
def __bool__(self) -> bool:
return True
async def _prepare_hook(self, response: StreamResponse) -> None:
return
def _cancel(self, exc: BaseException) -> None:
set_exception(self._payload, exc)
def _finish(self) -> None:
if self._post is None or self.content_type != "multipart/form-data":
return
# NOTE: Release file descriptors for the
# NOTE: `tempfile.Temporaryfile`-created `_io.BufferedRandom`
# NOTE: instances of files sent within multipart request body
# NOTE: via HTTP POST request.
for file_name, file_field_object in self._post.items():
if isinstance(file_field_object, FileField):
file_field_object.file.close()
class Request(BaseRequest):
_match_info: Optional["UrlMappingMatchInfo"] = None
def clone(
self,
*,
method: str | _SENTINEL = sentinel,
rel_url: StrOrURL | _SENTINEL = sentinel,
headers: LooseHeaders | _SENTINEL = sentinel,
scheme: str | _SENTINEL = sentinel,
host: str | _SENTINEL = sentinel,
remote: str | _SENTINEL = sentinel,
client_max_size: int | _SENTINEL = sentinel,
) -> "Request":
ret = super().clone(
method=method,
rel_url=rel_url,
headers=headers,
scheme=scheme,
host=host,
remote=remote,
client_max_size=client_max_size,
)
new_ret = cast(Request, ret)
new_ret._match_info = self._match_info
return new_ret
@reify
def match_info(self) -> "UrlMappingMatchInfo":
"""Result of route resolving."""
match_info = self._match_info
assert match_info is not None
return match_info
@property
def app(self) -> "Application":
"""Application instance."""
match_info = self._match_info
assert match_info is not None
return match_info.current_app
@property
def config_dict(self) -> ChainMapProxy:
match_info = self._match_info
assert match_info is not None
lst = match_info.apps
app = self.app
idx = lst.index(app)
sublist = list(reversed(lst[: idx + 1]))
return ChainMapProxy(sublist)
async def _prepare_hook(self, response: StreamResponse) -> None:
match_info = self._match_info
if match_info is None:
return
for app in match_info._apps:
if on_response_prepare := app.on_response_prepare:
await on_response_prepare.send(self, response)
| import asyncio
import datetime
import socket
import ssl
import sys
import weakref
from collections.abc import Iterator, MutableMapping
from typing import NoReturn
from unittest import mock
import pytest
from multidict import CIMultiDict, CIMultiDictProxy, MultiDict
from yarl import URL
from aiohttp import ETag, HttpVersion, web
from aiohttp.base_protocol import BaseProtocol
from aiohttp.http_parser import RawRequestMessage
from aiohttp.pytest_plugin import AiohttpClient
from aiohttp.streams import StreamReader
from aiohttp.test_utils import make_mocked_request
@pytest.fixture
def protocol() -> mock.Mock:
return mock.Mock(_reading_paused=False)
def test_base_ctor() -> None:
message = RawRequestMessage(
"GET",
"/path/to?a=1&b=2",
HttpVersion(1, 1),
CIMultiDictProxy(CIMultiDict()),
(),
False,
None,
False,
False,
URL("/path/to?a=1&b=2"),
)
req = web.BaseRequest(
message, mock.Mock(), mock.Mock(), mock.Mock(), mock.Mock(), mock.Mock()
)
assert "GET" == req.method
assert HttpVersion(1, 1) == req.version
# MacOS may return CamelCased host name, need .lower()
# FQDN can be wider than host, e.g.
# 'fv-az397-495' in 'fv-az397-495.internal.cloudapp.net'
assert req.host.lower() in socket.getfqdn().lower()
assert "/path/to?a=1&b=2" == req.path_qs
assert "/path/to" == req.path
assert "a=1&b=2" == req.query_string
assert CIMultiDict() == req.headers
assert () == req.raw_headers
get = req.query
assert MultiDict([("a", "1"), ("b", "2")]) == get
# second call should return the same object
assert get is req.query
assert req.keep_alive
assert req
def test_ctor() -> None:
req = make_mocked_request("GET", "/path/to?a=1&b=2")
assert "GET" == req.method
assert HttpVersion(1, 1) == req.version
# MacOS may return CamelCased host name, need .lower()
# FQDN can be wider than host, e.g.
# 'fv-az397-495' in 'fv-az397-495.internal.cloudapp.net'
assert req.host.lower() in socket.getfqdn().lower()
assert "/path/to?a=1&b=2" == req.path_qs
assert "/path/to" == req.path
assert "a=1&b=2" == req.query_string
assert CIMultiDict() == req.headers
assert () == req.raw_headers
get = req.query
assert MultiDict([("a", "1"), ("b", "2")]) == get
# second call should return the same object
assert get is req.query
assert req.keep_alive
# just make sure that all lines of make_mocked_request covered
headers = CIMultiDict(FOO="bar")
payload = mock.Mock()
protocol = mock.Mock()
app = mock.Mock()
req = make_mocked_request(
"GET",
"/path/to?a=1&b=2",
headers=headers,
protocol=protocol,
payload=payload,
app=app,
)
assert req.app is app
assert req.content is payload
assert req.protocol is protocol
assert req.transport is protocol.transport
assert req.headers == headers
assert req.raw_headers == ((b"FOO", b"bar"),)
assert req.task is req._task
def test_doubleslashes() -> None:
# NB: //foo/bar is an absolute URL with foo netloc and /bar path
req = make_mocked_request("GET", "/bar//foo/")
assert "/bar//foo/" == req.path
def test_content_type_not_specified() -> None:
req = make_mocked_request("Get", "/")
assert "application/octet-stream" == req.content_type
def test_content_type_from_spec() -> None:
req = make_mocked_request(
"Get", "/", CIMultiDict([("CONTENT-TYPE", "application/json")])
)
assert "application/json" == req.content_type
def test_content_type_from_spec_with_charset() -> None:
req = make_mocked_request(
"Get", "/", CIMultiDict([("CONTENT-TYPE", "text/html; charset=UTF-8")])
)
assert "text/html" == req.content_type
assert "UTF-8" == req.charset
def test_calc_content_type_on_getting_charset() -> None:
req = make_mocked_request(
"Get", "/", CIMultiDict([("CONTENT-TYPE", "text/html; charset=UTF-8")])
)
assert "UTF-8" == req.charset
assert "text/html" == req.content_type
def test_urlencoded_querystring() -> None:
req = make_mocked_request("GET", "/yandsearch?text=%D1%82%D0%B5%D0%BA%D1%81%D1%82")
assert {"text": "текст"} == req.query
def test_non_ascii_path() -> None:
req = make_mocked_request("GET", "/путь")
assert "/путь" == req.path
def test_non_ascii_raw_path() -> None:
req = make_mocked_request("GET", "/путь")
assert "/путь" == req.raw_path
def test_absolute_url() -> None:
req = make_mocked_request("GET", "https://example.com/path/to?a=1")
assert req.url == URL("https://example.com/path/to?a=1")
assert req.scheme == "https"
assert req.host == "example.com"
assert req.rel_url == URL.build(path="/path/to", query={"a": "1"})
def test_clone_absolute_scheme() -> None:
req = make_mocked_request("GET", "https://example.com/path/to?a=1")
assert req.scheme == "https"
req2 = req.clone(scheme="http")
assert req2.scheme == "http"
assert req2.url.scheme == "http"
def test_clone_absolute_host() -> None:
req = make_mocked_request("GET", "https://example.com/path/to?a=1")
assert req.host == "example.com"
req2 = req.clone(host="foo.test")
assert req2.host == "foo.test"
assert req2.url.host == "foo.test"
def test_content_length() -> None:
req = make_mocked_request("Get", "/", CIMultiDict([("CONTENT-LENGTH", "123")]))
assert 123 == req.content_length
def test_range_to_slice_head() -> None:
req = make_mocked_request(
"GET", "/", headers=CIMultiDict([("RANGE", "bytes=0-499")])
)
assert isinstance(req.http_range, slice)
assert req.http_range.start == 0 and req.http_range.stop == 500
def test_range_to_slice_mid() -> None:
req = make_mocked_request(
"GET", "/", headers=CIMultiDict([("RANGE", "bytes=500-999")])
)
assert isinstance(req.http_range, slice)
assert req.http_range.start == 500 and req.http_range.stop == 1000
def test_range_to_slice_tail_start() -> None:
req = make_mocked_request(
"GET", "/", headers=CIMultiDict([("RANGE", "bytes=9500-")])
)
assert isinstance(req.http_range, slice)
assert req.http_range.start == 9500 and req.http_range.stop is None
def test_range_to_slice_tail_stop() -> None:
req = make_mocked_request(
"GET", "/", headers=CIMultiDict([("RANGE", "bytes=-500")])
)
assert isinstance(req.http_range, slice)
assert req.http_range.start == -500 and req.http_range.stop is None
def test_non_keepalive_on_http10() -> None:
req = make_mocked_request("GET", "/", version=HttpVersion(1, 0))
assert not req.keep_alive
def test_non_keepalive_on_closing() -> None:
req = make_mocked_request("GET", "/", closing=True)
assert not req.keep_alive
async def test_call_POST_on_GET_request() -> None:
req = make_mocked_request("GET", "/")
ret = await req.post()
assert CIMultiDict() == ret
async def test_call_POST_on_weird_content_type() -> None:
req = make_mocked_request(
"POST", "/", headers=CIMultiDict({"CONTENT-TYPE": "something/weird"})
)
ret = await req.post()
assert CIMultiDict() == ret
async def test_call_POST_twice() -> None:
req = make_mocked_request("GET", "/")
ret1 = await req.post()
ret2 = await req.post()
assert ret1 is ret2
def test_no_request_cookies() -> None:
req = make_mocked_request("GET", "/")
assert req.cookies == {}
cookies = req.cookies
assert cookies is req.cookies
def test_request_cookie() -> None:
headers = CIMultiDict(COOKIE="cookie1=value1; cookie2=value2")
req = make_mocked_request("GET", "/", headers=headers)
assert req.cookies == {"cookie1": "value1", "cookie2": "value2"}
def test_request_cookie__set_item() -> None:
headers = CIMultiDict(COOKIE="name=value")
req = make_mocked_request("GET", "/", headers=headers)
assert req.cookies == {"name": "value"}
with pytest.raises(TypeError):
req.cookies["my"] = "value" # type: ignore[index]
def test_request_cookies_with_special_characters() -> None:
"""Test that cookies with special characters in names are accepted.
This tests the fix for issue #2683 where cookies with special characters
like {, }, / in their names would cause a 500 error. The fix makes the
cookie parser more tolerant to handle real-world cookies.
"""
# Test cookie names with curly braces (e.g., ISAWPLB{DB45DF86-F806-407C-932C-D52A60E4019E})
headers = CIMultiDict(COOKIE="{test}=value1; normal=value2")
req = make_mocked_request("GET", "/", headers=headers)
# Both cookies should be parsed successfully
assert req.cookies == {"{test}": "value1", "normal": "value2"}
# Test cookie names with forward slash
headers = CIMultiDict(COOKIE="test/name=value1; valid=value2")
req = make_mocked_request("GET", "/", headers=headers)
assert req.cookies == {"test/name": "value1", "valid": "value2"}
# Test cookie names with various special characters
headers = CIMultiDict(
COOKIE="test{foo}bar=value1; test/path=value2; normal_cookie=value3"
)
req = make_mocked_request("GET", "/", headers=headers)
assert req.cookies == {
"test{foo}bar": "value1",
"test/path": "value2",
"normal_cookie": "value3",
}
def test_request_cookies_real_world_examples() -> None:
"""Test handling of real-world cookie examples from issue #2683."""
# Example from the issue: ISAWPLB{DB45DF86-F806-407C-932C-D52A60E4019E}
headers = CIMultiDict(
COOKIE="ISAWPLB{DB45DF86-F806-407C-932C-D52A60E4019E}=val1; normal_cookie=val2"
)
req = make_mocked_request("GET", "/", headers=headers)
# All cookies should be parsed successfully
assert req.cookies == {
"ISAWPLB{DB45DF86-F806-407C-932C-D52A60E4019E}": "val1",
"normal_cookie": "val2",
}
# Multiple cookies with special characters
headers = CIMultiDict(
COOKIE="{cookie1}=val1; cookie/2=val2; cookie[3]=val3; cookie(4)=val4"
)
req = make_mocked_request("GET", "/", headers=headers)
assert req.cookies == {
"{cookie1}": "val1",
"cookie/2": "val2",
"cookie[3]": "val3",
"cookie(4)": "val4",
}
def test_request_cookies_edge_cases() -> None:
"""Test edge cases for cookie parsing."""
# Empty cookie value
headers = CIMultiDict(COOKIE="test=; normal=value")
req = make_mocked_request("GET", "/", headers=headers)
assert req.cookies == {"test": "", "normal": "value"}
# Cookie with quoted value
headers = CIMultiDict(COOKIE='test="quoted value"; normal=unquoted')
req = make_mocked_request("GET", "/", headers=headers)
assert req.cookies == {"test": "quoted value", "normal": "unquoted"}
def test_request_cookies_no_500_error() -> None:
"""Test that cookies with special characters don't cause 500 errors.
This specifically tests that issue #2683 is fixed - previously cookies
with characters like { } would cause CookieError and 500 responses.
"""
# This cookie format previously caused 500 errors
headers = CIMultiDict(COOKIE="ISAWPLB{DB45DF86-F806-407C-932C-D52A60E4019E}=test")
# Should not raise any exception when accessing cookies
req = make_mocked_request("GET", "/", headers=headers)
cookies = req.cookies # This used to raise CookieError
# Verify the cookie was parsed successfully
assert "ISAWPLB{DB45DF86-F806-407C-932C-D52A60E4019E}" in cookies
assert cookies["ISAWPLB{DB45DF86-F806-407C-932C-D52A60E4019E}"] == "test"
def test_request_cookies_quoted_values() -> None:
"""Test that quoted cookie values are handled consistently.
This tests the fix for issue #5397 where quoted cookie values were
handled inconsistently based on whether domain attributes were present.
The new parser should always unquote cookie values consistently.
"""
# Test simple quoted cookie value
headers = CIMultiDict(COOKIE='sess="quoted_value"')
req = make_mocked_request("GET", "/", headers=headers)
# Quotes should be removed consistently
assert req.cookies == {"sess": "quoted_value"}
# Test quoted cookie with semicolon in value
headers = CIMultiDict(COOKIE='data="value;with;semicolons"')
req = make_mocked_request("GET", "/", headers=headers)
assert req.cookies == {"data": "value;with;semicolons"}
# Test mixed quoted and unquoted cookies
headers = CIMultiDict(
COOKIE='quoted="value1"; unquoted=value2; also_quoted="value3"'
)
req = make_mocked_request("GET", "/", headers=headers)
assert req.cookies == {
"quoted": "value1",
"unquoted": "value2",
"also_quoted": "value3",
}
# Test escaped quotes in cookie value
headers = CIMultiDict(COOKIE=r'escaped="value with \" quote"')
req = make_mocked_request("GET", "/", headers=headers)
assert req.cookies == {"escaped": 'value with " quote'}
# Test empty quoted value
headers = CIMultiDict(COOKIE='empty=""')
req = make_mocked_request("GET", "/", headers=headers)
assert req.cookies == {"empty": ""}
def test_request_cookies_with_attributes() -> None:
"""Test that cookie attributes are parsed as cookies per RFC 6265.
Per RFC 6265 Section 5.4, Cookie headers contain only name-value pairs.
Names that match attribute names (Domain, Path, etc.) should be treated
as regular cookies, not as attributes.
"""
# Cookie with domain - both should be parsed as cookies
headers = CIMultiDict(COOKIE='sess="quoted_value"; Domain=.example.com')
req = make_mocked_request("GET", "/", headers=headers)
assert req.cookies == {"sess": "quoted_value", "Domain": ".example.com"}
# Cookie with multiple attribute names - all parsed as cookies
headers = CIMultiDict(COOKIE='token="abc123"; Path=/; Secure; HttpOnly')
req = make_mocked_request("GET", "/", headers=headers)
assert req.cookies == {"token": "abc123", "Path": "/", "Secure": "", "HttpOnly": ""}
# Multiple cookies with attribute names mixed in
headers = CIMultiDict(
COOKIE='c1="v1"; Domain=.example.com; c2="v2"; Path=/api; c3=v3; Secure'
)
req = make_mocked_request("GET", "/", headers=headers)
assert req.cookies == {
"c1": "v1",
"Domain": ".example.com",
"c2": "v2",
"Path": "/api",
"c3": "v3",
"Secure": "",
}
def test_match_info() -> None:
req = make_mocked_request("GET", "/")
assert req._match_info is req.match_info
def test_request_is_mutable_mapping() -> None:
req = make_mocked_request("GET", "/")
assert isinstance(req, MutableMapping)
assert req # even when the MutableMapping is empty, request should always be True
req["key"] = "value"
assert "value" == req["key"]
def test_request_delitem() -> None:
req = make_mocked_request("GET", "/")
req["key"] = "value"
assert "value" == req["key"]
del req["key"]
assert "key" not in req
def test_request_len() -> None:
req = make_mocked_request("GET", "/")
assert len(req) == 0
req["key"] = "value"
assert len(req) == 1
def test_request_iter() -> None:
req = make_mocked_request("GET", "/")
req["key"] = "value"
req["key2"] = "value2"
key3 = web.RequestKey("key3", str)
req[key3] = "value3"
assert set(req) == {"key", "key2", key3}
def test_requestkey() -> None:
req = make_mocked_request("GET", "/")
key = web.RequestKey("key", str)
req[key] = "value"
assert req[key] == "value"
assert len(req) == 1
del req[key]
assert len(req) == 0
def test_request_get_requestkey() -> None:
req = make_mocked_request("GET", "/")
key = web.RequestKey("key", int)
assert req.get(key, "foo") == "foo"
req[key] = 5
assert req.get(key, "foo") == 5
def test_requestkey_repr_concrete() -> None:
key = web.RequestKey("key", int)
assert repr(key) in (
"<RequestKey(__channelexec__.key, type=int)>", # pytest-xdist
"<RequestKey(__main__.key, type=int)>",
)
key2 = web.RequestKey("key", web.Request)
assert repr(key2) in (
# pytest-xdist:
"<RequestKey(__channelexec__.key, type=aiohttp.web_request.Request)>",
"<RequestKey(__main__.key, type=aiohttp.web_request.Request)>",
)
def test_requestkey_repr_nonconcrete() -> None:
key = web.RequestKey("key", Iterator[int])
if sys.version_info < (3, 11):
assert repr(key) in (
# pytest-xdist:
"<RequestKey(__channelexec__.key, type=collections.abc.Iterator)>",
"<RequestKey(__main__.key, type=collections.abc.Iterator)>",
)
else:
assert repr(key) in (
# pytest-xdist:
"<RequestKey(__channelexec__.key, type=collections.abc.Iterator[int])>",
"<RequestKey(__main__.key, type=collections.abc.Iterator[int])>",
)
def test_requestkey_repr_annotated() -> None:
key = web.RequestKey[Iterator[int]]("key")
if sys.version_info < (3, 11):
assert repr(key) in (
# pytest-xdist:
"<RequestKey(__channelexec__.key, type=collections.abc.Iterator)>",
"<RequestKey(__main__.key, type=collections.abc.Iterator)>",
)
else:
assert repr(key) in (
# pytest-xdist:
"<RequestKey(__channelexec__.key, type=collections.abc.Iterator[int])>",
"<RequestKey(__main__.key, type=collections.abc.Iterator[int])>",
)
def test___repr__() -> None:
req = make_mocked_request("GET", "/path/to")
assert "<Request GET /path/to >" == repr(req)
def test___repr___non_ascii_path() -> None:
req = make_mocked_request("GET", "/path/\U0001f415\U0001f308")
assert "<Request GET /path/\\U0001f415\\U0001f308 >" == repr(req)
def test_http_scheme() -> None:
req = make_mocked_request("GET", "/", headers={"Host": "example.com"})
assert "http" == req.scheme
assert req.secure is False
def test_https_scheme_by_ssl_transport() -> None:
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
req = make_mocked_request(
"GET", "/", headers={"Host": "example.com"}, sslcontext=context
)
assert "https" == req.scheme
assert req.secure is True
def test_single_forwarded_header() -> None:
header = "by=identifier;for=identifier;host=identifier;proto=identifier"
req = make_mocked_request("GET", "/", headers=CIMultiDict({"Forwarded": header}))
assert req.forwarded[0]["by"] == "identifier"
assert req.forwarded[0]["for"] == "identifier"
assert req.forwarded[0]["host"] == "identifier"
assert req.forwarded[0]["proto"] == "identifier"
@pytest.mark.parametrize(
"forward_for_in, forward_for_out",
[
("1.2.3.4:1234", "1.2.3.4:1234"),
("1.2.3.4", "1.2.3.4"),
('"[2001:db8:cafe::17]:1234"', "[2001:db8:cafe::17]:1234"),
('"[2001:db8:cafe::17]"', "[2001:db8:cafe::17]"),
],
)
def test_forwarded_node_identifier(forward_for_in: str, forward_for_out: str) -> None:
header = f"for={forward_for_in}"
req = make_mocked_request("GET", "/", headers=CIMultiDict({"Forwarded": header}))
assert req.forwarded == ({"for": forward_for_out},)
def test_single_forwarded_header_camelcase() -> None:
header = "bY=identifier;fOr=identifier;HOst=identifier;pRoTO=identifier"
req = make_mocked_request("GET", "/", headers=CIMultiDict({"Forwarded": header}))
assert req.forwarded[0]["by"] == "identifier"
assert req.forwarded[0]["for"] == "identifier"
assert req.forwarded[0]["host"] == "identifier"
assert req.forwarded[0]["proto"] == "identifier"
def test_single_forwarded_header_single_param() -> None:
header = "BY=identifier"
req = make_mocked_request("GET", "/", headers=CIMultiDict({"Forwarded": header}))
assert req.forwarded[0]["by"] == "identifier"
def test_single_forwarded_header_multiple_param() -> None:
header = "By=identifier1,BY=identifier2, By=identifier3 , BY=identifier4"
req = make_mocked_request("GET", "/", headers=CIMultiDict({"Forwarded": header}))
assert len(req.forwarded) == 4
assert req.forwarded[0]["by"] == "identifier1"
assert req.forwarded[1]["by"] == "identifier2"
assert req.forwarded[2]["by"] == "identifier3"
assert req.forwarded[3]["by"] == "identifier4"
def test_single_forwarded_header_quoted_escaped() -> None:
header = r'BY=identifier;pROTO="\lala lan\d\~ 123\!&"'
req = make_mocked_request("GET", "/", headers=CIMultiDict({"Forwarded": header}))
assert req.forwarded[0]["by"] == "identifier"
assert req.forwarded[0]["proto"] == "lala land~ 123!&"
def test_single_forwarded_header_custom_param() -> None:
header = r'BY=identifier;PROTO=https;SOME="other, \"value\""'
req = make_mocked_request("GET", "/", headers=CIMultiDict({"Forwarded": header}))
assert len(req.forwarded) == 1
assert req.forwarded[0]["by"] == "identifier"
assert req.forwarded[0]["proto"] == "https"
assert req.forwarded[0]["some"] == 'other, "value"'
def test_single_forwarded_header_empty_params() -> None:
# This is allowed by the grammar given in RFC 7239
header = ";For=identifier;;PROTO=https;;;"
req = make_mocked_request("GET", "/", headers=CIMultiDict({"Forwarded": header}))
assert req.forwarded[0]["for"] == "identifier"
assert req.forwarded[0]["proto"] == "https"
def test_single_forwarded_header_bad_separator() -> None:
header = "BY=identifier PROTO=https"
req = make_mocked_request("GET", "/", headers=CIMultiDict({"Forwarded": header}))
assert "proto" not in req.forwarded[0]
def test_single_forwarded_header_injection1() -> None:
# We might receive a header like this if we're sitting behind a reverse
# proxy that blindly appends a forwarded-element without checking
# the syntax of existing field-values. We should be able to recover
# the appended element anyway.
header = 'for=_injected;by=", for=_real'
req = make_mocked_request("GET", "/", headers=CIMultiDict({"Forwarded": header}))
assert len(req.forwarded) == 2
assert "by" not in req.forwarded[0]
assert req.forwarded[1]["for"] == "_real"
def test_single_forwarded_header_injection2() -> None:
header = "very bad syntax, for=_real"
req = make_mocked_request("GET", "/", headers=CIMultiDict({"Forwarded": header}))
assert len(req.forwarded) == 2
assert "for" not in req.forwarded[0]
assert req.forwarded[1]["for"] == "_real"
def test_single_forwarded_header_long_quoted_string() -> None:
header = 'for="' + "\\\\" * 5000 + '"'
req = make_mocked_request("GET", "/", headers=CIMultiDict({"Forwarded": header}))
assert req.forwarded[0]["for"] == "\\" * 5000
def test_multiple_forwarded_headers() -> None:
headers = CIMultiDict[str]()
headers.add("Forwarded", "By=identifier1;for=identifier2, BY=identifier3")
headers.add("Forwarded", "By=identifier4;fOr=identifier5")
req = make_mocked_request("GET", "/", headers=headers)
assert len(req.forwarded) == 3
assert req.forwarded[0]["by"] == "identifier1"
assert req.forwarded[0]["for"] == "identifier2"
assert req.forwarded[1]["by"] == "identifier3"
assert req.forwarded[2]["by"] == "identifier4"
assert req.forwarded[2]["for"] == "identifier5"
def test_multiple_forwarded_headers_bad_syntax() -> None:
headers = CIMultiDict[str]()
headers.add("Forwarded", "for=_1;by=_2")
headers.add("Forwarded", "invalid value")
headers.add("Forwarded", "")
headers.add("Forwarded", "for=_3;by=_4")
req = make_mocked_request("GET", "/", headers=headers)
assert len(req.forwarded) == 4
assert req.forwarded[0]["for"] == "_1"
assert "for" not in req.forwarded[1]
assert "for" not in req.forwarded[2]
assert req.forwarded[3]["by"] == "_4"
def test_multiple_forwarded_headers_injection() -> None:
headers = CIMultiDict[str]()
# This could be sent by an attacker, hoping to "shadow" the second header.
headers.add("Forwarded", 'for=_injected;by="')
# This is added by our trusted reverse proxy.
headers.add("Forwarded", "for=_real;by=_actual_proxy")
req = make_mocked_request("GET", "/", headers=headers)
assert len(req.forwarded) == 2
assert "by" not in req.forwarded[0]
assert req.forwarded[1]["for"] == "_real"
assert req.forwarded[1]["by"] == "_actual_proxy"
def test_host_by_host_header() -> None:
req = make_mocked_request("GET", "/", headers=CIMultiDict({"Host": "example.com"}))
assert req.host == "example.com"
def test_raw_headers() -> None:
req = make_mocked_request("GET", "/", headers=CIMultiDict({"X-HEADER": "aaa"}))
assert req.raw_headers == ((b"X-HEADER", b"aaa"),)
def test_rel_url() -> None:
req = make_mocked_request("GET", "/path")
assert URL("/path") == req.rel_url
def test_url_url() -> None:
req = make_mocked_request("GET", "/path", headers={"HOST": "example.com"})
assert URL("http://example.com/path") == req.url
def test_url_non_default_port() -> None:
req = make_mocked_request("GET", "/path", headers={"HOST": "example.com:8123"})
assert req.url == URL("http://example.com:8123/path")
def test_url_ipv6() -> None:
req = make_mocked_request("GET", "/path", headers={"HOST": "[::1]:8123"})
assert req.url == URL("http://[::1]:8123/path")
def test_clone() -> None:
req = make_mocked_request("GET", "/path")
req2 = req.clone()
assert req2.method == "GET"
assert req2.rel_url == URL("/path")
def test_clone_client_max_size() -> None:
req = make_mocked_request("GET", "/path", client_max_size=1024)
req2 = req.clone()
assert req._client_max_size == req2._client_max_size
assert req2._client_max_size == 1024
def test_clone_override_client_max_size() -> None:
req = make_mocked_request("GET", "/path", client_max_size=1024)
req2 = req.clone(client_max_size=2048)
assert req2.client_max_size == 2048
def test_clone_method() -> None:
req = make_mocked_request("GET", "/path")
req2 = req.clone(method="POST")
assert req2.method == "POST"
assert req2.rel_url == URL("/path")
def test_clone_rel_url() -> None:
req = make_mocked_request("GET", "/path")
req2 = req.clone(rel_url=URL("/path2"))
assert req2.rel_url == URL("/path2")
def test_clone_rel_url_str() -> None:
req = make_mocked_request("GET", "/path")
req2 = req.clone(rel_url="/path2")
assert req2.rel_url == URL("/path2")
def test_clone_headers() -> None:
req = make_mocked_request("GET", "/path", headers={"A": "B"})
req2 = req.clone(headers=CIMultiDict({"B": "C"}))
assert req2.headers == CIMultiDict({"B": "C"})
assert req2.raw_headers == ((b"B", b"C"),)
def test_clone_headers_dict() -> None:
req = make_mocked_request("GET", "/path", headers={"A": "B"})
req2 = req.clone(headers={"B": "C"})
assert req2.headers == CIMultiDict({"B": "C"})
assert req2.raw_headers == ((b"B", b"C"),)
async def test_cannot_clone_after_read(protocol: BaseProtocol) -> None:
payload = StreamReader(protocol, 2**16, loop=asyncio.get_event_loop())
payload.feed_data(b"data")
payload.feed_eof()
req = make_mocked_request("GET", "/path", payload=payload)
await req.read()
with pytest.raises(RuntimeError):
req.clone()
async def test_make_too_big_request(protocol: BaseProtocol) -> None:
payload = StreamReader(protocol, 2**16, loop=asyncio.get_event_loop())
large_file = 1024**2 * b"x"
too_large_file = large_file + b"x"
payload.feed_data(too_large_file)
payload.feed_eof()
req = make_mocked_request("POST", "/", payload=payload)
with pytest.raises(web.HTTPRequestEntityTooLarge) as err:
await req.read()
assert err.value.status_code == 413
async def test_request_with_wrong_content_type_encoding(protocol: BaseProtocol) -> None:
payload = StreamReader(protocol, 2**16, loop=asyncio.get_event_loop())
payload.feed_data(b"{}")
payload.feed_eof()
headers = {"Content-Type": "text/html; charset=test"}
req = make_mocked_request("POST", "/", payload=payload, headers=headers)
with pytest.raises(web.HTTPUnsupportedMediaType) as err:
await req.text()
assert err.value.status_code == 415
async def test_make_too_big_request_same_size_to_max(protocol: BaseProtocol) -> None:
payload = StreamReader(protocol, 2**16, loop=asyncio.get_event_loop())
large_file = 1024**2 * b"x"
payload.feed_data(large_file)
payload.feed_eof()
req = make_mocked_request("POST", "/", payload=payload)
resp_text = await req.read()
assert resp_text == large_file
async def test_make_too_big_request_adjust_limit(protocol: BaseProtocol) -> None:
payload = StreamReader(protocol, 2**16, loop=asyncio.get_event_loop())
large_file = 1024**2 * b"x"
too_large_file = large_file + b"x"
payload.feed_data(too_large_file)
payload.feed_eof()
max_size = 1024**2 + 2
req = make_mocked_request("POST", "/", payload=payload, client_max_size=max_size)
txt = await req.read()
assert len(txt) == 1024**2 + 1
async def test_multipart_formdata(protocol: BaseProtocol) -> None:
payload = StreamReader(protocol, 2**16, loop=asyncio.get_event_loop())
payload.feed_data(
b"-----------------------------326931944431359\r\n"
b'Content-Disposition: form-data; name="a"\r\n'
b"\r\n"
b"b\r\n"
b"-----------------------------326931944431359\r\n"
b'Content-Disposition: form-data; name="c"\r\n'
b"\r\n"
b"d\r\n"
b"-----------------------------326931944431359--\r\n"
)
content_type = (
"multipart/form-data; boundary=---------------------------326931944431359"
)
payload.feed_eof()
req = make_mocked_request(
"POST", "/", headers={"CONTENT-TYPE": content_type}, payload=payload
)
result = await req.post()
assert dict(result) == {"a": "b", "c": "d"}
async def test_multipart_formdata_file(protocol: BaseProtocol) -> None:
# Make sure file uploads work, even without a content type
payload = StreamReader(protocol, 2**16, loop=asyncio.get_event_loop())
payload.feed_data(
b"-----------------------------326931944431359\r\n"
b'Content-Disposition: form-data; name="a_file"; filename="binary"\r\n'
b"\r\n"
b"\ff\r\n"
b"-----------------------------326931944431359--\r\n"
)
content_type = (
"multipart/form-data; boundary=---------------------------326931944431359"
)
payload.feed_eof()
req = make_mocked_request(
"POST", "/", headers={"CONTENT-TYPE": content_type}, payload=payload
)
result = await req.post()
assert hasattr(result["a_file"], "file")
content = result["a_file"].file.read()
assert content == b"\ff"
req._finish()
async def test_make_too_big_request_limit_None(protocol: BaseProtocol) -> None:
payload = StreamReader(protocol, 2**16, loop=asyncio.get_event_loop())
large_file = 1024**2 * b"x"
too_large_file = large_file + b"x"
payload.feed_data(too_large_file)
payload.feed_eof()
req = make_mocked_request("POST", "/", payload=payload, client_max_size=0)
txt = await req.read()
assert len(txt) == 1024**2 + 1
def test_remote_peername_tcp() -> None:
transp = mock.Mock()
transp.get_extra_info.return_value = ("10.10.10.10", 1234)
req = make_mocked_request("GET", "/", transport=transp)
assert req.remote == "10.10.10.10"
def test_remote_peername_unix() -> None:
transp = mock.Mock()
transp.get_extra_info.return_value = "/path/to/sock"
req = make_mocked_request("GET", "/", transport=transp)
assert req.remote == "/path/to/sock"
def test_save_state_on_clone() -> None:
req = make_mocked_request("GET", "/")
req["key"] = "val"
req2 = req.clone()
req2["key"] = "val2"
assert req["key"] == "val"
assert req2["key"] == "val2"
def test_clone_scheme() -> None:
req = make_mocked_request("GET", "/")
assert req.scheme == "http"
req2 = req.clone(scheme="https")
assert req2.scheme == "https"
assert req2.url.scheme == "https"
def test_clone_host() -> None:
req = make_mocked_request("GET", "/")
assert req.host != "example.com"
req2 = req.clone(host="example.com")
assert req2.host == "example.com"
assert req2.url.host == "example.com"
def test_clone_remote() -> None:
req = make_mocked_request("GET", "/")
assert req.remote != "11.11.11.11"
req2 = req.clone(remote="11.11.11.11")
assert req2.remote == "11.11.11.11"
def test_remote_with_closed_transport() -> None:
transp = mock.Mock()
transp.get_extra_info.return_value = ("10.10.10.10", 1234)
req = make_mocked_request("GET", "/", transport=transp)
req._protocol = None # type: ignore[assignment]
assert req.remote == "10.10.10.10"
def test_url_http_with_closed_transport() -> None:
req = make_mocked_request("GET", "/")
req._protocol = None # type: ignore[assignment]
assert str(req.url).startswith("http://")
def test_url_https_with_closed_transport() -> None:
c = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
req = make_mocked_request("GET", "/", sslcontext=c)
req._protocol = None # type: ignore[assignment]
assert str(req.url).startswith("https://")
async def test_get_extra_info() -> None:
valid_key = "test"
valid_value = "existent"
default_value = "default"
def get_extra_info(name: str, default: object = None) -> object:
return {valid_key: valid_value}.get(name, default)
transp = mock.Mock()
transp.get_extra_info.side_effect = get_extra_info
req = make_mocked_request("GET", "/", transport=transp)
assert req is not None
req_extra_info = req.get_extra_info(valid_key, default_value)
assert req._protocol.transport is not None
transp_extra_info = req._protocol.transport.get_extra_info(valid_key, default_value)
assert req_extra_info == transp_extra_info
req._protocol.transport = None
extra_info = req.get_extra_info(valid_key, default_value)
assert extra_info == default_value
def test_eq() -> None:
req1 = make_mocked_request("GET", "/path/to?a=1&b=2")
req2 = make_mocked_request("GET", "/path/to?a=1&b=2")
assert req1 != req2
assert req1 == req1
async def test_json(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
body_text = await request.text()
assert body_text == '{"some": "data"}'
assert request.headers["Content-Type"] == "application/json"
body_json = await request.json()
assert body_json == {"some": "data"}
return web.Response()
app = web.Application()
app.router.add_post("/", handler)
client = await aiohttp_client(app)
json_data = {"some": "data"}
async with client.post("/", json=json_data) as resp:
assert 200 == resp.status
async def test_json_invalid_content_type(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> NoReturn:
body_text = await request.text()
assert body_text == '{"some": "data"}'
assert request.headers["Content-Type"] == "text/plain"
await request.json() # raises HTTP 400
assert False
app = web.Application()
app.router.add_post("/", handler)
client = await aiohttp_client(app)
json_data = {"some": "data"}
headers = {"Content-Type": "text/plain"}
async with client.post("/", json=json_data, headers=headers) as resp:
assert 400 == resp.status
resp_text = await resp.text()
assert resp_text == (
"Attempt to decode JSON with unexpected mimetype: text/plain"
)
def test_weakref_creation() -> None:
req = make_mocked_request("GET", "/")
weakref.ref(req)
@pytest.mark.parametrize(
("header", "header_attr"),
(
pytest.param("If-Match", "if_match"),
pytest.param("If-None-Match", "if_none_match"),
),
)
@pytest.mark.parametrize(
("header_val", "expected"),
(
pytest.param(
'"67ab43", W/"54ed21", "7892,dd"',
(
ETag(is_weak=False, value="67ab43"),
ETag(is_weak=True, value="54ed21"),
ETag(is_weak=False, value="7892,dd"),
),
),
pytest.param(
'"bfc1ef-5b2c2730249c88ca92d82d"',
(ETag(is_weak=False, value="bfc1ef-5b2c2730249c88ca92d82d"),),
),
pytest.param(
'"valid-tag", "also-valid-tag",somegarbage"last-tag"',
(
ETag(is_weak=False, value="valid-tag"),
ETag(is_weak=False, value="also-valid-tag"),
),
),
pytest.param(
'"ascii", "это точно не ascii", "ascii again"',
(ETag(is_weak=False, value="ascii"),),
),
pytest.param(
"*",
(ETag(is_weak=False, value="*"),),
),
),
)
def test_etag_headers(
header: str, header_attr: str, header_val: str, expected: tuple[ETag, ...]
) -> None:
req = make_mocked_request("GET", "/", headers={header: header_val})
assert getattr(req, header_attr) == expected
@pytest.mark.parametrize(
("header", "header_attr"),
(
pytest.param("If-Modified-Since", "if_modified_since"),
pytest.param("If-Unmodified-Since", "if_unmodified_since"),
pytest.param("If-Range", "if_range"),
),
)
@pytest.mark.parametrize(
("header_val", "expected"),
(
pytest.param("xxyyzz", None),
pytest.param("Tue, 08 Oct 4446413 00:56:40 GMT", None),
pytest.param("Tue, 08 Oct 2000 00:56:80 GMT", None),
pytest.param(
"Tue, 08 Oct 2000 00:56:40 GMT",
datetime.datetime(2000, 10, 8, 0, 56, 40, tzinfo=datetime.timezone.utc),
),
),
)
def test_datetime_headers(
header: str,
header_attr: str,
header_val: str,
expected: datetime.datetime | None,
) -> None:
req = make_mocked_request("GET", "/", headers={header: header_val})
assert getattr(req, header_attr) == expected
| aiohttp |
python | import asyncio
import enum
import io
import json
import mimetypes
import os
import sys
import warnings
from abc import ABC, abstractmethod
from collections.abc import AsyncIterable, AsyncIterator, Iterable
from itertools import chain
from typing import IO, Any, Final, TextIO
from multidict import CIMultiDict
from . import hdrs
from .abc import AbstractStreamWriter
from .helpers import (
_SENTINEL,
content_disposition_header,
guess_filename,
parse_mimetype,
sentinel,
)
from .streams import StreamReader
from .typedefs import JSONEncoder
__all__ = (
"PAYLOAD_REGISTRY",
"get_payload",
"payload_type",
"Payload",
"BytesPayload",
"StringPayload",
"IOBasePayload",
"BytesIOPayload",
"BufferedReaderPayload",
"TextIOPayload",
"StringIOPayload",
"JsonPayload",
"AsyncIterablePayload",
)
TOO_LARGE_BYTES_BODY: Final[int] = 2**20 # 1 MB
READ_SIZE: Final[int] = 2**16 # 64 KB
_CLOSE_FUTURES: set[asyncio.Future[None]] = set()
class LookupError(Exception):
"""Raised when no payload factory is found for the given data type."""
class Order(str, enum.Enum):
normal = "normal"
try_first = "try_first"
try_last = "try_last"
def get_payload(data: Any, *args: Any, **kwargs: Any) -> "Payload":
return PAYLOAD_REGISTRY.get(data, *args, **kwargs)
def register_payload(
factory: type["Payload"], type: Any, *, order: Order = Order.normal
) -> None:
PAYLOAD_REGISTRY.register(factory, type, order=order)
class payload_type:
def __init__(self, type: Any, *, order: Order = Order.normal) -> None:
self.type = type
self.order = order
def __call__(self, factory: type["Payload"]) -> type["Payload"]:
register_payload(factory, self.type, order=self.order)
return factory
PayloadType = type["Payload"]
_PayloadRegistryItem = tuple[PayloadType, Any]
class PayloadRegistry:
"""Payload registry.
note: we need zope.interface for more efficient adapter search
"""
__slots__ = ("_first", "_normal", "_last", "_normal_lookup")
def __init__(self) -> None:
self._first: list[_PayloadRegistryItem] = []
self._normal: list[_PayloadRegistryItem] = []
self._last: list[_PayloadRegistryItem] = []
self._normal_lookup: dict[Any, PayloadType] = {}
def get(
self,
data: Any,
*args: Any,
_CHAIN: "type[chain[_PayloadRegistryItem]]" = chain,
**kwargs: Any,
) -> "Payload":
if self._first:
for factory, type_ in self._first:
if isinstance(data, type_):
return factory(data, *args, **kwargs)
# Try the fast lookup first
if lookup_factory := self._normal_lookup.get(type(data)):
return lookup_factory(data, *args, **kwargs)
# Bail early if its already a Payload
if isinstance(data, Payload):
return data
# Fallback to the slower linear search
for factory, type_ in _CHAIN(self._normal, self._last):
if isinstance(data, type_):
return factory(data, *args, **kwargs)
raise LookupError()
def register(
self, factory: PayloadType, type: Any, *, order: Order = Order.normal
) -> None:
if order is Order.try_first:
self._first.append((factory, type))
elif order is Order.normal:
self._normal.append((factory, type))
if isinstance(type, Iterable):
for t in type:
self._normal_lookup[t] = factory
else:
self._normal_lookup[type] = factory
elif order is Order.try_last:
self._last.append((factory, type))
else:
raise ValueError(f"Unsupported order {order!r}")
class Payload(ABC):
_default_content_type: str = "application/octet-stream"
_size: int | None = None
_consumed: bool = False # Default: payload has not been consumed yet
_autoclose: bool = False # Default: assume resource needs explicit closing
def __init__(
self,
value: Any,
headers: (
CIMultiDict[str] | dict[str, str] | Iterable[tuple[str, str]] | None
) = None,
content_type: None | str | _SENTINEL = sentinel,
filename: str | None = None,
encoding: str | None = None,
**kwargs: Any,
) -> None:
self._encoding = encoding
self._filename = filename
self._headers = CIMultiDict[str]()
self._value = value
if content_type is not sentinel and content_type is not None:
assert isinstance(content_type, str)
self._headers[hdrs.CONTENT_TYPE] = content_type
elif self._filename is not None:
if sys.version_info >= (3, 13):
guesser = mimetypes.guess_file_type
else:
guesser = mimetypes.guess_type
content_type = guesser(self._filename)[0]
if content_type is None:
content_type = self._default_content_type
self._headers[hdrs.CONTENT_TYPE] = content_type
else:
self._headers[hdrs.CONTENT_TYPE] = self._default_content_type
if headers:
self._headers.update(headers)
@property
def size(self) -> int | None:
"""Size of the payload in bytes.
Returns the number of bytes that will be transmitted when the payload
is written. For string payloads, this is the size after encoding to bytes,
not the length of the string.
"""
return self._size
@property
def filename(self) -> str | None:
"""Filename of the payload."""
return self._filename
@property
def headers(self) -> CIMultiDict[str]:
"""Custom item headers"""
return self._headers
@property
def _binary_headers(self) -> bytes:
return (
"".join([k + ": " + v + "\r\n" for k, v in self.headers.items()]).encode(
"utf-8"
)
+ b"\r\n"
)
@property
def encoding(self) -> str | None:
"""Payload encoding"""
return self._encoding
@property
def content_type(self) -> str:
"""Content type"""
return self._headers[hdrs.CONTENT_TYPE]
@property
def consumed(self) -> bool:
"""Whether the payload has been consumed and cannot be reused."""
return self._consumed
@property
def autoclose(self) -> bool:
"""
Whether the payload can close itself automatically.
Returns True if the payload has no file handles or resources that need
explicit closing. If False, callers must await close() to release resources.
"""
return self._autoclose
def set_content_disposition(
self,
disptype: str,
quote_fields: bool = True,
_charset: str = "utf-8",
**params: str,
) -> None:
"""Sets ``Content-Disposition`` header."""
self._headers[hdrs.CONTENT_DISPOSITION] = content_disposition_header(
disptype, quote_fields=quote_fields, _charset=_charset, params=params
)
@abstractmethod
def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str:
"""
Return string representation of the value.
This is named decode() to allow compatibility with bytes objects.
"""
@abstractmethod
async def write(self, writer: AbstractStreamWriter) -> None:
"""
Write payload to the writer stream.
Args:
writer: An AbstractStreamWriter instance that handles the actual writing
This is a legacy method that writes the entire payload without length constraints.
Important:
For new implementations, use write_with_length() instead of this method.
This method is maintained for backwards compatibility and will eventually
delegate to write_with_length(writer, None) in all implementations.
All payload subclasses must override this method for backwards compatibility,
but new code should use write_with_length for more flexibility and control.
"""
# write_with_length is new in aiohttp 3.12
# it should be overridden by subclasses
async def write_with_length(
self, writer: AbstractStreamWriter, content_length: int | None
) -> None:
"""
Write payload with a specific content length constraint.
Args:
writer: An AbstractStreamWriter instance that handles the actual writing
content_length: Maximum number of bytes to write (None for unlimited)
This method allows writing payload content with a specific length constraint,
which is particularly useful for HTTP responses with Content-Length header.
Note:
This is the base implementation that provides backwards compatibility
for subclasses that don't override this method. Specific payload types
should override this method to implement proper length-constrained writing.
"""
# Backwards compatibility for subclasses that don't override this method
# and for the default implementation
await self.write(writer)
async def as_bytes(self, encoding: str = "utf-8", errors: str = "strict") -> bytes:
"""
Return bytes representation of the value.
This is a convenience method that calls decode() and encodes the result
to bytes using the specified encoding.
"""
# Use instance encoding if available, otherwise use parameter
actual_encoding = self._encoding or encoding
return self.decode(actual_encoding, errors).encode(actual_encoding)
def _close(self) -> None:
"""
Async safe synchronous close operations for backwards compatibility.
This method exists only for backwards compatibility with code that
needs to clean up payloads synchronously. In the future, we will
drop this method and only support the async close() method.
WARNING: This method must be safe to call from within the event loop
without blocking. Subclasses should not perform any blocking I/O here.
WARNING: This method must be called from within an event loop for
certain payload types (e.g., IOBasePayload). Calling it outside an
event loop may raise RuntimeError.
"""
# This is a no-op by default, but subclasses can override it
# for non-blocking cleanup operations.
async def close(self) -> None:
"""
Close the payload if it holds any resources.
IMPORTANT: This method must not await anything that might not finish
immediately, as it may be called during cleanup/cancellation. Schedule
any long-running operations without awaiting them.
In the future, this will be the only close method supported.
"""
self._close()
class BytesPayload(Payload):
_value: bytes
# _consumed = False (inherited) - Bytes are immutable and can be reused
_autoclose = True # No file handle, just bytes in memory
def __init__(
self, value: bytes | bytearray | memoryview, *args: Any, **kwargs: Any
) -> None:
if "content_type" not in kwargs:
kwargs["content_type"] = "application/octet-stream"
super().__init__(value, *args, **kwargs)
if isinstance(value, memoryview):
self._size = value.nbytes
elif isinstance(value, (bytes, bytearray)):
self._size = len(value)
else:
raise TypeError(f"value argument must be byte-ish, not {type(value)!r}")
if self._size > TOO_LARGE_BYTES_BODY:
warnings.warn(
"Sending a large body directly with raw bytes might"
" lock the event loop. You should probably pass an "
"io.BytesIO object instead",
ResourceWarning,
source=self,
)
def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str:
return self._value.decode(encoding, errors)
async def as_bytes(self, encoding: str = "utf-8", errors: str = "strict") -> bytes:
"""
Return bytes representation of the value.
This method returns the raw bytes content of the payload.
It is equivalent to accessing the _value attribute directly.
"""
return self._value
async def write(self, writer: AbstractStreamWriter) -> None:
"""
Write the entire bytes payload to the writer stream.
Args:
writer: An AbstractStreamWriter instance that handles the actual writing
This method writes the entire bytes content without any length constraint.
Note:
For new implementations that need length control, use write_with_length().
This method is maintained for backwards compatibility and is equivalent
to write_with_length(writer, None).
"""
await writer.write(self._value)
async def write_with_length(
self, writer: AbstractStreamWriter, content_length: int | None
) -> None:
"""
Write bytes payload with a specific content length constraint.
Args:
writer: An AbstractStreamWriter instance that handles the actual writing
content_length: Maximum number of bytes to write (None for unlimited)
This method writes either the entire byte sequence or a slice of it
up to the specified content_length. For BytesPayload, this operation
is performed efficiently using array slicing.
"""
if content_length is not None:
await writer.write(self._value[:content_length])
else:
await writer.write(self._value)
class StringPayload(BytesPayload):
def __init__(
self,
value: str,
*args: Any,
encoding: str | None = None,
content_type: str | None = None,
**kwargs: Any,
) -> None:
if encoding is None:
if content_type is None:
real_encoding = "utf-8"
content_type = "text/plain; charset=utf-8"
else:
mimetype = parse_mimetype(content_type)
real_encoding = mimetype.parameters.get("charset", "utf-8")
else:
if content_type is None:
content_type = "text/plain; charset=%s" % encoding
real_encoding = encoding
super().__init__(
value.encode(real_encoding),
encoding=real_encoding,
content_type=content_type,
*args,
**kwargs,
)
class StringIOPayload(StringPayload):
def __init__(self, value: IO[str], *args: Any, **kwargs: Any) -> None:
super().__init__(value.read(), *args, **kwargs)
class IOBasePayload(Payload):
_value: io.IOBase
# _consumed = False (inherited) - File can be re-read from the same position
_start_position: int | None = None
# _autoclose = False (inherited) - Has file handle that needs explicit closing
def __init__(
self, value: IO[Any], disposition: str = "attachment", *args: Any, **kwargs: Any
) -> None:
if "filename" not in kwargs:
kwargs["filename"] = guess_filename(value)
super().__init__(value, *args, **kwargs)
if self._filename is not None and disposition is not None:
if hdrs.CONTENT_DISPOSITION not in self.headers:
self.set_content_disposition(disposition, filename=self._filename)
def _set_or_restore_start_position(self) -> None:
"""Set or restore the start position of the file-like object."""
if self._start_position is None:
try:
self._start_position = self._value.tell()
except (OSError, AttributeError):
self._consumed = True # Cannot seek, mark as consumed
return
try:
self._value.seek(self._start_position)
except (OSError, AttributeError):
# Failed to seek back - mark as consumed since we've already read
self._consumed = True
def _read_and_available_len(
self, remaining_content_len: int | None
) -> tuple[int | None, bytes]:
"""
Read the file-like object and return both its total size and the first chunk.
Args:
remaining_content_len: Optional limit on how many bytes to read in this operation.
If None, READ_SIZE will be used as the default chunk size.
Returns:
A tuple containing:
- The total size of the remaining unread content (None if size cannot be determined)
- The first chunk of bytes read from the file object
This method is optimized to perform both size calculation and initial read
in a single operation, which is executed in a single executor job to minimize
context switches and file operations when streaming content.
"""
self._set_or_restore_start_position()
size = self.size # Call size only once since it does I/O
return size, self._value.read(
min(READ_SIZE, size or READ_SIZE, remaining_content_len or READ_SIZE)
)
def _read(self, remaining_content_len: int | None) -> bytes:
"""
Read a chunk of data from the file-like object.
Args:
remaining_content_len: Optional maximum number of bytes to read.
If None, READ_SIZE will be used as the default chunk size.
Returns:
A chunk of bytes read from the file object, respecting the
remaining_content_len limit if specified.
This method is used for subsequent reads during streaming after
the initial _read_and_available_len call has been made.
"""
return self._value.read(remaining_content_len or READ_SIZE) # type: ignore[no-any-return]
@property
def size(self) -> int | None:
"""
Size of the payload in bytes.
Returns the total size of the payload content from the initial position.
This ensures consistent Content-Length for requests, including 307/308 redirects
where the same payload instance is reused.
Returns None if the size cannot be determined (e.g., for unseekable streams).
"""
try:
# Store the start position on first access.
# This is critical when the same payload instance is reused (e.g., 307/308
# redirects). Without storing the initial position, after the payload is
# read once, the file position would be at EOF, which would cause the
# size calculation to return 0 (file_size - EOF position).
# By storing the start position, we ensure the size calculation always
# returns the correct total size for any subsequent use.
if self._start_position is None:
self._start_position = self._value.tell()
# Return the total size from the start position
# This ensures Content-Length is correct even after reading
return os.fstat(self._value.fileno()).st_size - self._start_position
except (AttributeError, OSError):
return None
async def write(self, writer: AbstractStreamWriter) -> None:
"""
Write the entire file-like payload to the writer stream.
Args:
writer: An AbstractStreamWriter instance that handles the actual writing
This method writes the entire file content without any length constraint.
It delegates to write_with_length() with no length limit for implementation
consistency.
Note:
For new implementations that need length control, use write_with_length() directly.
This method is maintained for backwards compatibility with existing code.
"""
await self.write_with_length(writer, None)
async def write_with_length(
self, writer: AbstractStreamWriter, content_length: int | None
) -> None:
"""
Write file-like payload with a specific content length constraint.
Args:
writer: An AbstractStreamWriter instance that handles the actual writing
content_length: Maximum number of bytes to write (None for unlimited)
This method implements optimized streaming of file content with length constraints:
1. File reading is performed in a thread pool to avoid blocking the event loop
2. Content is read and written in chunks to maintain memory efficiency
3. Writing stops when either:
- All available file content has been written (when size is known)
- The specified content_length has been reached
4. File resources are properly closed even if the operation is cancelled
The implementation carefully handles both known-size and unknown-size payloads,
as well as constrained and unconstrained content lengths.
"""
loop = asyncio.get_running_loop()
total_written_len = 0
remaining_content_len = content_length
# Get initial data and available length
available_len, chunk = await loop.run_in_executor(
None, self._read_and_available_len, remaining_content_len
)
# Process data chunks until done
while chunk:
chunk_len = len(chunk)
# Write data with or without length constraint
if remaining_content_len is None:
await writer.write(chunk)
else:
await writer.write(chunk[:remaining_content_len])
remaining_content_len -= chunk_len
total_written_len += chunk_len
# Check if we're done writing
if self._should_stop_writing(
available_len, total_written_len, remaining_content_len
):
return
# Read next chunk
chunk = await loop.run_in_executor(
None,
self._read,
(
min(READ_SIZE, remaining_content_len)
if remaining_content_len is not None
else READ_SIZE
),
)
def _should_stop_writing(
self,
available_len: int | None,
total_written_len: int,
remaining_content_len: int | None,
) -> bool:
"""
Determine if we should stop writing data.
Args:
available_len: Known size of the payload if available (None if unknown)
total_written_len: Number of bytes already written
remaining_content_len: Remaining bytes to be written for content-length limited responses
Returns:
True if we should stop writing data, based on either:
- Having written all available data (when size is known)
- Having written all requested content (when content-length is specified)
"""
return (available_len is not None and total_written_len >= available_len) or (
remaining_content_len is not None and remaining_content_len <= 0
)
def _close(self) -> None:
"""
Async safe synchronous close operations for backwards compatibility.
This method exists only for backwards
compatibility. Use the async close() method instead.
WARNING: This method MUST be called from within an event loop.
Calling it outside an event loop will raise RuntimeError.
"""
# Skip if already consumed
if self._consumed:
return
self._consumed = True # Mark as consumed to prevent further writes
# Schedule file closing without awaiting to prevent cancellation issues
loop = asyncio.get_running_loop()
close_future = loop.run_in_executor(None, self._value.close)
# Hold a strong reference to the future to prevent it from being
# garbage collected before it completes.
_CLOSE_FUTURES.add(close_future)
close_future.add_done_callback(_CLOSE_FUTURES.remove)
async def close(self) -> None:
"""
Close the payload if it holds any resources.
IMPORTANT: This method must not await anything that might not finish
immediately, as it may be called during cleanup/cancellation. Schedule
any long-running operations without awaiting them.
"""
self._close()
def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str:
"""
Return string representation of the value.
WARNING: This method does blocking I/O and should not be called in the event loop.
"""
return self._read_all().decode(encoding, errors)
def _read_all(self) -> bytes:
"""Read the entire file-like object and return its content as bytes."""
self._set_or_restore_start_position()
# Use readlines() to ensure we get all content
return b"".join(self._value.readlines())
async def as_bytes(self, encoding: str = "utf-8", errors: str = "strict") -> bytes:
"""
Return bytes representation of the value.
This method reads the entire file content and returns it as bytes.
It is equivalent to reading the file-like object directly.
The file reading is performed in an executor to avoid blocking the event loop.
"""
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, self._read_all)
class TextIOPayload(IOBasePayload):
_value: io.TextIOBase
# _autoclose = False (inherited) - Has text file handle that needs explicit closing
def __init__(
self,
value: TextIO,
*args: Any,
encoding: str | None = None,
content_type: str | None = None,
**kwargs: Any,
) -> None:
if encoding is None:
if content_type is None:
encoding = "utf-8"
content_type = "text/plain; charset=utf-8"
else:
mimetype = parse_mimetype(content_type)
encoding = mimetype.parameters.get("charset", "utf-8")
else:
if content_type is None:
content_type = "text/plain; charset=%s" % encoding
super().__init__(
value,
content_type=content_type,
encoding=encoding,
*args,
**kwargs,
)
def _read_and_available_len(
self, remaining_content_len: int | None
) -> tuple[int | None, bytes]:
"""
Read the text file-like object and return both its total size and the first chunk.
Args:
remaining_content_len: Optional limit on how many bytes to read in this operation.
If None, READ_SIZE will be used as the default chunk size.
Returns:
A tuple containing:
- The total size of the remaining unread content (None if size cannot be determined)
- The first chunk of bytes read from the file object, encoded using the payload's encoding
This method is optimized to perform both size calculation and initial read
in a single operation, which is executed in a single executor job to minimize
context switches and file operations when streaming content.
Note:
TextIOPayload handles encoding of the text content before writing it
to the stream. If no encoding is specified, UTF-8 is used as the default.
"""
self._set_or_restore_start_position()
size = self.size
chunk = self._value.read(
min(READ_SIZE, size or READ_SIZE, remaining_content_len or READ_SIZE)
)
return size, chunk.encode(self._encoding) if self._encoding else chunk.encode()
def _read(self, remaining_content_len: int | None) -> bytes:
"""
Read a chunk of data from the text file-like object.
Args:
remaining_content_len: Optional maximum number of bytes to read.
If None, READ_SIZE will be used as the default chunk size.
Returns:
A chunk of bytes read from the file object and encoded using the payload's
encoding. The data is automatically converted from text to bytes.
This method is used for subsequent reads during streaming after
the initial _read_and_available_len call has been made. It properly
handles text encoding, converting the text content to bytes using
the specified encoding (or UTF-8 if none was provided).
"""
chunk = self._value.read(remaining_content_len or READ_SIZE)
return chunk.encode(self._encoding) if self._encoding else chunk.encode()
def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str:
"""
Return string representation of the value.
WARNING: This method does blocking I/O and should not be called in the event loop.
"""
self._set_or_restore_start_position()
return self._value.read()
async def as_bytes(self, encoding: str = "utf-8", errors: str = "strict") -> bytes:
"""
Return bytes representation of the value.
This method reads the entire text file content and returns it as bytes.
It encodes the text content using the specified encoding.
The file reading is performed in an executor to avoid blocking the event loop.
"""
loop = asyncio.get_running_loop()
# Use instance encoding if available, otherwise use parameter
actual_encoding = self._encoding or encoding
def _read_and_encode() -> bytes:
self._set_or_restore_start_position()
# TextIO read() always returns the full content
return self._value.read().encode(actual_encoding, errors)
return await loop.run_in_executor(None, _read_and_encode)
class BytesIOPayload(IOBasePayload):
_value: io.BytesIO
_size: int # Always initialized in __init__
_autoclose = True # BytesIO is in-memory, safe to auto-close
def __init__(self, value: io.BytesIO, *args: Any, **kwargs: Any) -> None:
super().__init__(value, *args, **kwargs)
# Calculate size once during initialization
self._size = len(self._value.getbuffer()) - self._value.tell()
@property
def size(self) -> int:
"""Size of the payload in bytes.
Returns the number of bytes in the BytesIO buffer that will be transmitted.
This is calculated once during initialization for efficiency.
"""
return self._size
def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str:
self._set_or_restore_start_position()
return self._value.read().decode(encoding, errors)
async def write(self, writer: AbstractStreamWriter) -> None:
return await self.write_with_length(writer, None)
async def write_with_length(
self, writer: AbstractStreamWriter, content_length: int | None
) -> None:
"""
Write BytesIO payload with a specific content length constraint.
Args:
writer: An AbstractStreamWriter instance that handles the actual writing
content_length: Maximum number of bytes to write (None for unlimited)
This implementation is specifically optimized for BytesIO objects:
1. Reads content in chunks to maintain memory efficiency
2. Yields control back to the event loop periodically to prevent blocking
when dealing with large BytesIO objects
3. Respects content_length constraints when specified
4. Properly cleans up by closing the BytesIO object when done or on error
The periodic yielding to the event loop is important for maintaining
responsiveness when processing large in-memory buffers.
"""
self._set_or_restore_start_position()
loop_count = 0
remaining_bytes = content_length
while chunk := self._value.read(READ_SIZE):
if loop_count > 0:
# Avoid blocking the event loop
# if they pass a large BytesIO object
# and we are not in the first iteration
# of the loop
await asyncio.sleep(0)
if remaining_bytes is None:
await writer.write(chunk)
else:
await writer.write(chunk[:remaining_bytes])
remaining_bytes -= len(chunk)
if remaining_bytes <= 0:
return
loop_count += 1
async def as_bytes(self, encoding: str = "utf-8", errors: str = "strict") -> bytes:
"""
Return bytes representation of the value.
This method reads the entire BytesIO content and returns it as bytes.
It is equivalent to accessing the _value attribute directly.
"""
self._set_or_restore_start_position()
return self._value.read()
async def close(self) -> None:
"""
Close the BytesIO payload.
This does nothing since BytesIO is in-memory and does not require explicit closing.
"""
class BufferedReaderPayload(IOBasePayload):
_value: io.BufferedIOBase
# _autoclose = False (inherited) - Has buffered file handle that needs explicit closing
def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str:
self._set_or_restore_start_position()
return self._value.read().decode(encoding, errors)
class JsonPayload(BytesPayload):
def __init__(
self,
value: Any,
encoding: str = "utf-8",
content_type: str = "application/json",
dumps: JSONEncoder = json.dumps,
*args: Any,
**kwargs: Any,
) -> None:
super().__init__(
dumps(value).encode(encoding),
content_type=content_type,
encoding=encoding,
*args,
**kwargs,
)
class AsyncIterablePayload(Payload):
_iter: AsyncIterator[bytes] | None = None
_value: AsyncIterable[bytes]
_cached_chunks: list[bytes] | None = None
# _consumed stays False to allow reuse with cached content
_autoclose = True # Iterator doesn't need explicit closing
def __init__(self, value: AsyncIterable[bytes], *args: Any, **kwargs: Any) -> None:
if not isinstance(value, AsyncIterable):
raise TypeError(
"value argument must support "
"collections.abc.AsyncIterable interface, "
f"got {type(value)!r}"
)
if "content_type" not in kwargs:
kwargs["content_type"] = "application/octet-stream"
super().__init__(value, *args, **kwargs)
self._iter = value.__aiter__()
async def write(self, writer: AbstractStreamWriter) -> None:
"""
Write the entire async iterable payload to the writer stream.
Args:
writer: An AbstractStreamWriter instance that handles the actual writing
This method iterates through the async iterable and writes each chunk
to the writer without any length constraint.
Note:
For new implementations that need length control, use write_with_length() directly.
This method is maintained for backwards compatibility with existing code.
"""
await self.write_with_length(writer, None)
async def write_with_length(
self, writer: AbstractStreamWriter, content_length: int | None
) -> None:
"""
Write async iterable payload with a specific content length constraint.
Args:
writer: An AbstractStreamWriter instance that handles the actual writing
content_length: Maximum number of bytes to write (None for unlimited)
This implementation handles streaming of async iterable content with length constraints:
1. If cached chunks are available, writes from them
2. Otherwise iterates through the async iterable one chunk at a time
3. Respects content_length constraints when specified
4. Does NOT generate cache - that's done by as_bytes()
"""
# If we have cached chunks, use them
if self._cached_chunks is not None:
remaining_bytes = content_length
for chunk in self._cached_chunks:
if remaining_bytes is None:
await writer.write(chunk)
elif remaining_bytes > 0:
await writer.write(chunk[:remaining_bytes])
remaining_bytes -= len(chunk)
else:
break
return
# If iterator is exhausted and we don't have cached chunks, nothing to write
if self._iter is None:
return
# Stream from the iterator
remaining_bytes = content_length
try:
while True:
chunk = await anext(self._iter)
if remaining_bytes is None:
await writer.write(chunk)
# If we have a content length limit
elif remaining_bytes > 0:
await writer.write(chunk[:remaining_bytes])
remaining_bytes -= len(chunk)
# We still want to exhaust the iterator even
# if we have reached the content length limit
# since the file handle may not get closed by
# the iterator if we don't do this
except StopAsyncIteration:
# Iterator is exhausted
self._iter = None
self._consumed = True # Mark as consumed when streamed without caching
def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str:
"""Decode the payload content as a string if cached chunks are available."""
if self._cached_chunks is not None:
return b"".join(self._cached_chunks).decode(encoding, errors)
raise TypeError("Unable to decode - content not cached. Call as_bytes() first.")
async def as_bytes(self, encoding: str = "utf-8", errors: str = "strict") -> bytes:
"""
Return bytes representation of the value.
This method reads the entire async iterable content and returns it as bytes.
It generates and caches the chunks for future reuse.
"""
# If we have cached chunks, return them joined
if self._cached_chunks is not None:
return b"".join(self._cached_chunks)
# If iterator is exhausted and no cache, return empty
if self._iter is None:
return b""
# Read all chunks and cache them
chunks: list[bytes] = []
async for chunk in self._iter:
chunks.append(chunk)
# Iterator is exhausted, cache the chunks
self._iter = None
self._cached_chunks = chunks
# Keep _consumed as False to allow reuse with cached chunks
return b"".join(chunks)
class StreamReaderPayload(AsyncIterablePayload):
def __init__(self, value: StreamReader, *args: Any, **kwargs: Any) -> None:
super().__init__(value.iter_any(), *args, **kwargs)
PAYLOAD_REGISTRY = PayloadRegistry()
PAYLOAD_REGISTRY.register(BytesPayload, (bytes, bytearray, memoryview))
PAYLOAD_REGISTRY.register(StringPayload, str)
PAYLOAD_REGISTRY.register(StringIOPayload, io.StringIO)
PAYLOAD_REGISTRY.register(TextIOPayload, io.TextIOBase)
PAYLOAD_REGISTRY.register(BytesIOPayload, io.BytesIO)
PAYLOAD_REGISTRY.register(BufferedReaderPayload, (io.BufferedReader, io.BufferedRandom))
PAYLOAD_REGISTRY.register(IOBasePayload, io.IOBase)
PAYLOAD_REGISTRY.register(StreamReaderPayload, StreamReader)
# try_last for giving a chance to more specialized async interables like
# multipart.BodyPartReaderPayload override the default
PAYLOAD_REGISTRY.register(AsyncIterablePayload, AsyncIterable, order=Order.try_last)
| import array
import asyncio
import io
import json
import unittest.mock
from collections.abc import AsyncIterator, Iterator
from io import StringIO
from pathlib import Path
from typing import TextIO, Union
import pytest
from multidict import CIMultiDict
from aiohttp import payload
from aiohttp.abc import AbstractStreamWriter
from aiohttp.payload import READ_SIZE
class BufferWriter(AbstractStreamWriter):
"""Test writer that captures written bytes in a buffer."""
def __init__(self) -> None:
self.buffer = bytearray()
async def write(
self, chunk: Union[bytes, bytearray, "memoryview[int]", "memoryview[bytes]"]
) -> None:
self.buffer.extend(bytes(chunk))
async def write_eof(self, chunk: bytes = b"") -> None:
"""No-op for test writer."""
async def drain(self) -> None:
"""No-op for test writer."""
def enable_compression(
self, encoding: str = "deflate", strategy: int | None = None
) -> None:
"""Compression not implemented for test writer."""
def enable_chunking(self) -> None:
"""Chunking not implemented for test writer."""
async def write_headers(self, status_line: str, headers: CIMultiDict[str]) -> None:
"""Headers not captured for payload tests."""
@pytest.fixture(autouse=True)
def cleanup(
cleanup_payload_pending_file_closes: None,
) -> None:
"""Ensure all pending file close operations complete during test teardown."""
@pytest.fixture
def registry() -> Iterator[payload.PayloadRegistry]:
old = payload.PAYLOAD_REGISTRY
reg = payload.PAYLOAD_REGISTRY = payload.PayloadRegistry()
yield reg
payload.PAYLOAD_REGISTRY = old
class Payload(payload.Payload):
def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str:
assert False
async def write(self, writer: AbstractStreamWriter) -> None:
pass
def test_register_type(registry: payload.PayloadRegistry) -> None:
class TestProvider:
pass
payload.register_payload(Payload, TestProvider)
p = payload.get_payload(TestProvider())
assert isinstance(p, Payload)
def test_register_unsupported_order(registry: payload.PayloadRegistry) -> None:
class TestProvider:
pass
with pytest.raises(ValueError):
payload.register_payload(
Payload, TestProvider, order=object() # type: ignore[arg-type]
)
def test_payload_ctor() -> None:
p = Payload("test", encoding="utf-8", filename="test.txt")
assert p._value == "test"
assert p._encoding == "utf-8"
assert p.size is None
assert p.filename == "test.txt"
assert p.content_type == "text/plain"
def test_payload_content_type() -> None:
p = Payload("test", headers={"content-type": "application/json"})
assert p.content_type == "application/json"
def test_bytes_payload_default_content_type() -> None:
p = payload.BytesPayload(b"data")
assert p.content_type == "application/octet-stream"
def test_bytes_payload_explicit_content_type() -> None:
p = payload.BytesPayload(b"data", content_type="application/custom")
assert p.content_type == "application/custom"
def test_bytes_payload_bad_type() -> None:
with pytest.raises(TypeError):
payload.BytesPayload(object()) # type: ignore[arg-type]
def test_bytes_payload_memoryview_correct_size() -> None:
mv = memoryview(array.array("H", [1, 2, 3]))
p = payload.BytesPayload(mv)
assert p.size == 6
def test_string_payload() -> None:
p = payload.StringPayload("test")
assert p.encoding == "utf-8"
assert p.content_type == "text/plain; charset=utf-8"
p = payload.StringPayload("test", encoding="koi8-r")
assert p.encoding == "koi8-r"
assert p.content_type == "text/plain; charset=koi8-r"
p = payload.StringPayload("test", content_type="text/plain; charset=koi8-r")
assert p.encoding == "koi8-r"
assert p.content_type == "text/plain; charset=koi8-r"
def test_string_io_payload() -> None:
s = StringIO("ű" * 5000)
p = payload.StringIOPayload(s)
assert p.encoding == "utf-8"
assert p.content_type == "text/plain; charset=utf-8"
assert p.size == 10000
def test_async_iterable_payload_default_content_type() -> None:
async def gen() -> AsyncIterator[bytes]:
return
yield b"abc" # type: ignore[unreachable] # pragma: no cover
p = payload.AsyncIterablePayload(gen())
assert p.content_type == "application/octet-stream"
def test_async_iterable_payload_explicit_content_type() -> None:
async def gen() -> AsyncIterator[bytes]:
return
yield b"abc" # type: ignore[unreachable] # pragma: no cover
p = payload.AsyncIterablePayload(gen(), content_type="application/custom")
assert p.content_type == "application/custom"
def test_async_iterable_payload_not_async_iterable() -> None:
with pytest.raises(TypeError):
payload.AsyncIterablePayload(object()) # type: ignore[arg-type]
class MockStreamWriter(AbstractStreamWriter):
"""Mock stream writer for testing payload writes."""
def __init__(self) -> None:
self.written: list[bytes] = []
async def write(
self, chunk: Union[bytes, bytearray, "memoryview[int]", "memoryview[bytes]"]
) -> None:
"""Store the chunk in the written list."""
self.written.append(bytes(chunk))
async def write_eof(self, chunk: bytes | None = None) -> None:
"""write_eof implementation - no-op for tests."""
async def drain(self) -> None:
"""Drain implementation - no-op for tests."""
def enable_compression(
self, encoding: str = "deflate", strategy: int | None = None
) -> None:
"""Enable compression - no-op for tests."""
def enable_chunking(self) -> None:
"""Enable chunking - no-op for tests."""
async def write_headers(self, status_line: str, headers: CIMultiDict[str]) -> None:
"""Write headers - no-op for tests."""
def get_written_bytes(self) -> bytes:
"""Return all written bytes as a single bytes object."""
return b"".join(self.written)
async def test_bytes_payload_write_with_length_no_limit() -> None:
"""Test BytesPayload writing with no content length limit."""
data = b"0123456789"
p = payload.BytesPayload(data)
writer = MockStreamWriter()
await p.write_with_length(writer, None)
assert writer.get_written_bytes() == data
assert len(writer.get_written_bytes()) == 10
async def test_bytes_payload_write_with_length_exact() -> None:
"""Test BytesPayload writing with exact content length."""
data = b"0123456789"
p = payload.BytesPayload(data)
writer = MockStreamWriter()
await p.write_with_length(writer, 10)
assert writer.get_written_bytes() == data
assert len(writer.get_written_bytes()) == 10
async def test_bytes_payload_write_with_length_truncated() -> None:
"""Test BytesPayload writing with truncated content length."""
data = b"0123456789"
p = payload.BytesPayload(data)
writer = MockStreamWriter()
await p.write_with_length(writer, 5)
assert writer.get_written_bytes() == b"01234"
assert len(writer.get_written_bytes()) == 5
async def test_iobase_payload_write_with_length_no_limit() -> None:
"""Test IOBasePayload writing with no content length limit."""
data = b"0123456789"
p = payload.IOBasePayload(io.BytesIO(data))
writer = MockStreamWriter()
await p.write_with_length(writer, None)
assert writer.get_written_bytes() == data
assert len(writer.get_written_bytes()) == 10
async def test_iobase_payload_write_with_length_exact() -> None:
"""Test IOBasePayload writing with exact content length."""
data = b"0123456789"
p = payload.IOBasePayload(io.BytesIO(data))
writer = MockStreamWriter()
await p.write_with_length(writer, 10)
assert writer.get_written_bytes() == data
assert len(writer.get_written_bytes()) == 10
async def test_iobase_payload_write_with_length_truncated() -> None:
"""Test IOBasePayload writing with truncated content length."""
data = b"0123456789"
p = payload.IOBasePayload(io.BytesIO(data))
writer = MockStreamWriter()
await p.write_with_length(writer, 5)
assert writer.get_written_bytes() == b"01234"
assert len(writer.get_written_bytes()) == 5
async def test_bytesio_payload_write_with_length_no_limit() -> None:
"""Test BytesIOPayload writing with no content length limit."""
data = b"0123456789"
p = payload.BytesIOPayload(io.BytesIO(data))
writer = MockStreamWriter()
await p.write_with_length(writer, None)
assert writer.get_written_bytes() == data
assert len(writer.get_written_bytes()) == 10
async def test_bytesio_payload_write_with_length_exact() -> None:
"""Test BytesIOPayload writing with exact content length."""
data = b"0123456789"
p = payload.BytesIOPayload(io.BytesIO(data))
writer = MockStreamWriter()
await p.write_with_length(writer, 10)
assert writer.get_written_bytes() == data
assert len(writer.get_written_bytes()) == 10
async def test_bytesio_payload_write_with_length_truncated() -> None:
"""Test BytesIOPayload writing with truncated content length."""
data = b"0123456789"
payload_bytesio = payload.BytesIOPayload(io.BytesIO(data))
writer = MockStreamWriter()
await payload_bytesio.write_with_length(writer, 5)
assert writer.get_written_bytes() == b"01234"
assert len(writer.get_written_bytes()) == 5
async def test_bytesio_payload_write_with_length_remaining_zero() -> None:
"""Test BytesIOPayload with content_length smaller than first read chunk."""
data = b"0123456789" * 10 # 100 bytes
bio = io.BytesIO(data)
payload_bytesio = payload.BytesIOPayload(bio)
writer = MockStreamWriter()
# Mock the read method to return smaller chunks
original_read = bio.read
read_calls = 0
def mock_read(size: int | None = None) -> bytes:
nonlocal read_calls
read_calls += 1
if read_calls == 1:
# First call: return 3 bytes (less than content_length=5)
return original_read(3)
else:
# Subsequent calls return remaining data normally
return original_read(size)
with unittest.mock.patch.object(bio, "read", mock_read):
await payload_bytesio.write_with_length(writer, 5)
assert len(writer.get_written_bytes()) == 5
assert writer.get_written_bytes() == b"01234"
async def test_bytesio_payload_large_data_multiple_chunks() -> None:
"""Test BytesIOPayload with large data requiring multiple read chunks."""
chunk_size = 2**16 # 64KB (READ_SIZE)
data = b"x" * (chunk_size + 1000) # Slightly larger than READ_SIZE
payload_bytesio = payload.BytesIOPayload(io.BytesIO(data))
writer = MockStreamWriter()
await payload_bytesio.write_with_length(writer, None)
assert writer.get_written_bytes() == data
assert len(writer.get_written_bytes()) == chunk_size + 1000
async def test_bytesio_payload_remaining_bytes_exhausted() -> None:
"""Test BytesIOPayload when remaining_bytes becomes <= 0."""
data = b"0123456789abcdef" * 1000 # 16000 bytes
payload_bytesio = payload.BytesIOPayload(io.BytesIO(data))
writer = MockStreamWriter()
await payload_bytesio.write_with_length(writer, 8000) # Exactly half the data
written = writer.get_written_bytes()
assert len(written) == 8000
assert written == data[:8000]
async def test_iobase_payload_exact_chunk_size_limit() -> None:
"""Test IOBasePayload with content length matching exactly one read chunk."""
chunk_size = 2**16 # 65536 bytes (READ_SIZE)
data = b"x" * chunk_size + b"extra" # Slightly larger than one read chunk
p = payload.IOBasePayload(io.BytesIO(data))
writer = MockStreamWriter()
await p.write_with_length(writer, chunk_size)
written = writer.get_written_bytes()
assert len(written) == chunk_size
assert written == data[:chunk_size]
async def test_iobase_payload_reads_in_chunks() -> None:
"""Test IOBasePayload reads data in chunks of READ_SIZE, not all at once."""
# Create a large file that's multiple times larger than READ_SIZE
large_data = b"x" * (READ_SIZE * 3 + 1000) # ~192KB + 1000 bytes
# Mock the file-like object to track read calls
mock_file = unittest.mock.Mock(spec=io.BytesIO)
mock_file.tell.return_value = 0
mock_file.fileno.side_effect = AttributeError # Make size return None
# Track the sizes of read() calls
read_sizes = []
def mock_read(size: int) -> bytes:
read_sizes.append(size)
# Return data based on how many times read was called
call_count = len(read_sizes)
if call_count == 1:
return large_data[:size]
elif call_count == 2:
return large_data[READ_SIZE : READ_SIZE + size]
elif call_count == 3:
return large_data[READ_SIZE * 2 : READ_SIZE * 2 + size]
else:
return large_data[READ_SIZE * 3 :]
mock_file.read.side_effect = mock_read
payload_obj = payload.IOBasePayload(mock_file)
writer = MockStreamWriter()
# Write with a large content_length
await payload_obj.write_with_length(writer, len(large_data))
# Verify that reads were limited to READ_SIZE
assert len(read_sizes) > 1 # Should have multiple reads
for read_size in read_sizes:
assert (
read_size <= READ_SIZE
), f"Read size {read_size} exceeds READ_SIZE {READ_SIZE}"
async def test_iobase_payload_large_content_length() -> None:
"""Test IOBasePayload with very large content_length doesn't read all at once."""
data = b"x" * (READ_SIZE + 1000)
# Create a custom file-like object that tracks read sizes
class TrackingBytesIO(io.BytesIO):
def __init__(self, data: bytes) -> None:
super().__init__(data)
self.read_sizes: list[int] = []
def read(self, size: int | None = -1) -> bytes:
self.read_sizes.append(size if size is not None else -1)
return super().read(size)
tracking_file = TrackingBytesIO(data)
payload_obj = payload.IOBasePayload(tracking_file)
writer = MockStreamWriter()
# Write with a very large content_length (simulating the bug scenario)
large_content_length = 10 * 1024 * 1024 # 10MB
await payload_obj.write_with_length(writer, large_content_length)
# Verify no single read exceeded READ_SIZE
for read_size in tracking_file.read_sizes:
assert (
read_size <= READ_SIZE
), f"Read size {read_size} exceeds READ_SIZE {READ_SIZE}"
# Verify the correct amount of data was written
assert writer.get_written_bytes() == data
async def test_textio_payload_reads_in_chunks() -> None:
"""Test TextIOPayload reads data in chunks of READ_SIZE, not all at once."""
# Create a large text file that's multiple times larger than READ_SIZE
large_text = "x" * (READ_SIZE * 3 + 1000) # ~192KB + 1000 chars
# Mock the file-like object to track read calls
mock_file = unittest.mock.Mock(spec=io.StringIO)
mock_file.tell.return_value = 0
mock_file.fileno.side_effect = AttributeError # Make size return None
mock_file.encoding = "utf-8"
# Track the sizes of read() calls
read_sizes = []
def mock_read(size: int) -> str:
read_sizes.append(size)
# Return data based on how many times read was called
call_count = len(read_sizes)
if call_count == 1:
return large_text[:size]
elif call_count == 2:
return large_text[READ_SIZE : READ_SIZE + size]
elif call_count == 3:
return large_text[READ_SIZE * 2 : READ_SIZE * 2 + size]
else:
return large_text[READ_SIZE * 3 :]
mock_file.read.side_effect = mock_read
payload_obj = payload.TextIOPayload(mock_file)
writer = MockStreamWriter()
# Write with a large content_length
await payload_obj.write_with_length(writer, len(large_text.encode("utf-8")))
# Verify that reads were limited to READ_SIZE
assert len(read_sizes) > 1 # Should have multiple reads
for read_size in read_sizes:
assert (
read_size <= READ_SIZE
), f"Read size {read_size} exceeds READ_SIZE {READ_SIZE}"
async def test_textio_payload_large_content_length() -> None:
"""Test TextIOPayload with very large content_length doesn't read all at once."""
text_data = "x" * (READ_SIZE + 1000)
# Create a custom file-like object that tracks read sizes
class TrackingStringIO(io.StringIO):
def __init__(self, data: str) -> None:
super().__init__(data)
self.read_sizes: list[int] = []
def read(self, size: int | None = -1) -> str:
self.read_sizes.append(size if size is not None else -1)
return super().read(size)
tracking_file = TrackingStringIO(text_data)
payload_obj = payload.TextIOPayload(tracking_file)
writer = MockStreamWriter()
# Write with a very large content_length (simulating the bug scenario)
large_content_length = 10 * 1024 * 1024 # 10MB
await payload_obj.write_with_length(writer, large_content_length)
# Verify no single read exceeded READ_SIZE
for read_size in tracking_file.read_sizes:
assert (
read_size <= READ_SIZE
), f"Read size {read_size} exceeds READ_SIZE {READ_SIZE}"
# Verify the correct amount of data was written
assert writer.get_written_bytes() == text_data.encode("utf-8")
async def test_async_iterable_payload_write_with_length_no_limit() -> None:
"""Test AsyncIterablePayload writing with no content length limit."""
async def gen() -> AsyncIterator[bytes]:
yield b"0123"
yield b"4567"
yield b"89"
p = payload.AsyncIterablePayload(gen())
writer = MockStreamWriter()
await p.write_with_length(writer, None)
assert writer.get_written_bytes() == b"0123456789"
assert len(writer.get_written_bytes()) == 10
async def test_async_iterable_payload_write_with_length_exact() -> None:
"""Test AsyncIterablePayload writing with exact content length."""
async def gen() -> AsyncIterator[bytes]:
yield b"0123"
yield b"4567"
yield b"89"
p = payload.AsyncIterablePayload(gen())
writer = MockStreamWriter()
await p.write_with_length(writer, 10)
assert writer.get_written_bytes() == b"0123456789"
assert len(writer.get_written_bytes()) == 10
async def test_async_iterable_payload_write_with_length_truncated_mid_chunk() -> None:
"""Test AsyncIterablePayload writing with content length truncating mid-chunk."""
async def gen() -> AsyncIterator[bytes]:
yield b"0123"
yield b"4567"
yield b"89" # pragma: no cover
p = payload.AsyncIterablePayload(gen())
writer = MockStreamWriter()
await p.write_with_length(writer, 6)
assert writer.get_written_bytes() == b"012345"
assert len(writer.get_written_bytes()) == 6
async def test_async_iterable_payload_write_with_length_truncated_at_chunk() -> None:
"""Test AsyncIterablePayload writing with content length truncating at chunk boundary."""
async def gen() -> AsyncIterator[bytes]:
yield b"0123"
yield b"4567" # pragma: no cover
yield b"89" # pragma: no cover
p = payload.AsyncIterablePayload(gen())
writer = MockStreamWriter()
await p.write_with_length(writer, 4)
assert writer.get_written_bytes() == b"0123"
assert len(writer.get_written_bytes()) == 4
async def test_bytes_payload_backwards_compatibility() -> None:
"""Test BytesPayload.write() backwards compatibility delegates to write_with_length()."""
p = payload.BytesPayload(b"1234567890")
writer = MockStreamWriter()
await p.write(writer)
assert writer.get_written_bytes() == b"1234567890"
async def test_textio_payload_with_encoding() -> None:
"""Test TextIOPayload reading with encoding and size constraints."""
data = io.StringIO("hello world")
p = payload.TextIOPayload(data, encoding="utf-8")
writer = MockStreamWriter()
await p.write_with_length(writer, 8)
# Should write exactly 8 bytes: "hello wo"
assert writer.get_written_bytes() == b"hello wo"
async def test_textio_payload_as_bytes() -> None:
"""Test TextIOPayload.as_bytes method with different encodings."""
# Test with UTF-8 encoding
data = io.StringIO("Hello 世界")
p = payload.TextIOPayload(data, encoding="utf-8")
# Test as_bytes() method
result = await p.as_bytes()
assert result == "Hello 世界".encode()
# Test that position is restored for multiple reads
result2 = await p.as_bytes()
assert result2 == "Hello 世界".encode()
# Test with different encoding parameter (should use instance encoding)
result3 = await p.as_bytes(encoding="latin-1")
assert result3 == "Hello 世界".encode() # Should still use utf-8
# Test with different encoding in payload
data2 = io.StringIO("Hello World")
p2 = payload.TextIOPayload(data2, encoding="latin-1")
result4 = await p2.as_bytes()
assert result4 == b"Hello World" # latin-1 encoding
# Test with no explicit encoding (defaults to utf-8)
data3 = io.StringIO("Test データ")
p3 = payload.TextIOPayload(data3)
result5 = await p3.as_bytes()
assert result5 == "Test データ".encode()
# Test with encoding errors parameter
data4 = io.StringIO("Test")
p4 = payload.TextIOPayload(data4, encoding="ascii")
result6 = await p4.as_bytes(errors="strict")
assert result6 == b"Test"
async def test_bytesio_payload_backwards_compatibility() -> None:
"""Test BytesIOPayload.write() backwards compatibility delegates to write_with_length()."""
data = io.BytesIO(b"test data")
p = payload.BytesIOPayload(data)
writer = MockStreamWriter()
await p.write(writer)
assert writer.get_written_bytes() == b"test data"
async def test_async_iterable_payload_backwards_compatibility() -> None:
"""Test AsyncIterablePayload.write() backwards compatibility delegates to write_with_length()."""
async def gen() -> AsyncIterator[bytes]:
yield b"chunk1"
yield b"chunk2" # pragma: no cover
p = payload.AsyncIterablePayload(gen())
writer = MockStreamWriter()
await p.write(writer)
assert writer.get_written_bytes() == b"chunk1chunk2"
async def test_async_iterable_payload_with_none_iterator() -> None:
"""Test AsyncIterablePayload with None iterator returns early without writing."""
async def gen() -> AsyncIterator[bytes]:
yield b"test" # pragma: no cover
p = payload.AsyncIterablePayload(gen())
# Manually set _iter to None to test the guard clause
p._iter = None
writer = MockStreamWriter()
# Should return early without writing anything
await p.write_with_length(writer, 10)
assert writer.get_written_bytes() == b""
async def test_async_iterable_payload_caching() -> None:
"""Test AsyncIterablePayload caching behavior."""
async def gen() -> AsyncIterator[bytes]:
yield b"Hello"
yield b" "
yield b"World"
p = payload.AsyncIterablePayload(gen())
# First call to as_bytes should consume iterator and cache
result1 = await p.as_bytes()
assert result1 == b"Hello World"
assert p._iter is None # Iterator exhausted
assert p._cached_chunks == [b"Hello", b" ", b"World"] # Chunks cached
assert p._consumed is False # Not marked as consumed to allow reuse
# Second call should use cache
result2 = await p.as_bytes()
assert result2 == b"Hello World"
assert p._cached_chunks == [b"Hello", b" ", b"World"] # Still cached
# decode should work with cached chunks
decoded = p.decode()
assert decoded == "Hello World"
# write_with_length should use cached chunks
writer = MockStreamWriter()
await p.write_with_length(writer, None)
assert writer.get_written_bytes() == b"Hello World"
# write_with_length with limit should respect it
writer2 = MockStreamWriter()
await p.write_with_length(writer2, 5)
assert writer2.get_written_bytes() == b"Hello"
async def test_async_iterable_payload_decode_without_cache() -> None:
"""Test AsyncIterablePayload decode raises error without cache."""
async def gen() -> AsyncIterator[bytes]:
yield b"test"
p = payload.AsyncIterablePayload(gen())
# decode should raise without cache
with pytest.raises(TypeError) as excinfo:
p.decode()
assert "Unable to decode - content not cached" in str(excinfo.value)
# After as_bytes, decode should work
await p.as_bytes()
assert p.decode() == "test"
async def test_async_iterable_payload_write_then_cache() -> None:
"""Test AsyncIterablePayload behavior when written before caching."""
async def gen() -> AsyncIterator[bytes]:
yield b"Hello"
yield b"World"
p = payload.AsyncIterablePayload(gen())
# First write without caching (streaming)
writer1 = MockStreamWriter()
await p.write_with_length(writer1, None)
assert writer1.get_written_bytes() == b"HelloWorld"
assert p._iter is None # Iterator exhausted
assert p._cached_chunks is None # No cache created
assert p._consumed is True # Marked as consumed
# Subsequent operations should handle exhausted iterator
result = await p.as_bytes()
assert result == b"" # Empty since iterator exhausted without cache
# Write should also be empty
writer2 = MockStreamWriter()
await p.write_with_length(writer2, None)
assert writer2.get_written_bytes() == b""
async def test_bytes_payload_reusability() -> None:
"""Test that BytesPayload can be written and read multiple times."""
data = b"test payload data"
p = payload.BytesPayload(data)
# First write_with_length
writer1 = MockStreamWriter()
await p.write_with_length(writer1, None)
assert writer1.get_written_bytes() == data
# Second write_with_length (simulating redirect)
writer2 = MockStreamWriter()
await p.write_with_length(writer2, None)
assert writer2.get_written_bytes() == data
# Write with partial length
writer3 = MockStreamWriter()
await p.write_with_length(writer3, 5)
assert writer3.get_written_bytes() == b"test "
# Test as_bytes multiple times
bytes1 = await p.as_bytes()
bytes2 = await p.as_bytes()
bytes3 = await p.as_bytes()
assert bytes1 == bytes2 == bytes3 == data
async def test_string_payload_reusability() -> None:
"""Test that StringPayload can be written and read multiple times."""
text = "test string data"
expected_bytes = text.encode("utf-8")
p = payload.StringPayload(text)
# First write_with_length
writer1 = MockStreamWriter()
await p.write_with_length(writer1, None)
assert writer1.get_written_bytes() == expected_bytes
# Second write_with_length (simulating redirect)
writer2 = MockStreamWriter()
await p.write_with_length(writer2, None)
assert writer2.get_written_bytes() == expected_bytes
# Write with partial length
writer3 = MockStreamWriter()
await p.write_with_length(writer3, 5)
assert writer3.get_written_bytes() == b"test "
# Test as_bytes multiple times
bytes1 = await p.as_bytes()
bytes2 = await p.as_bytes()
bytes3 = await p.as_bytes()
assert bytes1 == bytes2 == bytes3 == expected_bytes
async def test_bytes_io_payload_reusability() -> None:
"""Test that BytesIOPayload can be written and read multiple times."""
data = b"test bytesio payload"
bytes_io = io.BytesIO(data)
p = payload.BytesIOPayload(bytes_io)
# First write_with_length
writer1 = MockStreamWriter()
await p.write_with_length(writer1, None)
assert writer1.get_written_bytes() == data
# Second write_with_length (simulating redirect)
writer2 = MockStreamWriter()
await p.write_with_length(writer2, None)
assert writer2.get_written_bytes() == data
# Write with partial length
writer3 = MockStreamWriter()
await p.write_with_length(writer3, 5)
assert writer3.get_written_bytes() == b"test "
# Test as_bytes multiple times
bytes1 = await p.as_bytes()
bytes2 = await p.as_bytes()
bytes3 = await p.as_bytes()
assert bytes1 == bytes2 == bytes3 == data
async def test_string_io_payload_reusability() -> None:
"""Test that StringIOPayload can be written and read multiple times."""
text = "test stringio payload"
expected_bytes = text.encode("utf-8")
string_io = io.StringIO(text)
p = payload.StringIOPayload(string_io)
# Note: StringIOPayload reads all content in __init__ and becomes a StringPayload
# So it should be fully reusable
# First write_with_length
writer1 = MockStreamWriter()
await p.write_with_length(writer1, None)
assert writer1.get_written_bytes() == expected_bytes
# Second write_with_length (simulating redirect)
writer2 = MockStreamWriter()
await p.write_with_length(writer2, None)
assert writer2.get_written_bytes() == expected_bytes
# Write with partial length
writer3 = MockStreamWriter()
await p.write_with_length(writer3, 5)
assert writer3.get_written_bytes() == b"test "
# Test as_bytes multiple times
bytes1 = await p.as_bytes()
bytes2 = await p.as_bytes()
bytes3 = await p.as_bytes()
assert bytes1 == bytes2 == bytes3 == expected_bytes
async def test_buffered_reader_payload_reusability() -> None:
"""Test that BufferedReaderPayload can be written and read multiple times."""
data = b"test buffered reader payload"
buffer = io.BufferedReader(io.BytesIO(data))
p = payload.BufferedReaderPayload(buffer)
# First write_with_length
writer1 = MockStreamWriter()
await p.write_with_length(writer1, None)
assert writer1.get_written_bytes() == data
# Second write_with_length (simulating redirect)
writer2 = MockStreamWriter()
await p.write_with_length(writer2, None)
assert writer2.get_written_bytes() == data
# Write with partial length
writer3 = MockStreamWriter()
await p.write_with_length(writer3, 5)
assert writer3.get_written_bytes() == b"test "
# Test as_bytes multiple times
bytes1 = await p.as_bytes()
bytes2 = await p.as_bytes()
bytes3 = await p.as_bytes()
assert bytes1 == bytes2 == bytes3 == data
async def test_async_iterable_payload_reusability_with_cache() -> None:
"""Test that AsyncIterablePayload can be reused when cached via as_bytes."""
async def gen() -> AsyncIterator[bytes]:
yield b"async "
yield b"iterable "
yield b"payload"
expected_data = b"async iterable payload"
p = payload.AsyncIterablePayload(gen())
# First call to as_bytes should cache the data
bytes1 = await p.as_bytes()
assert bytes1 == expected_data
assert p._cached_chunks is not None
assert p._iter is None # Iterator exhausted
# Subsequent as_bytes calls should use cache
bytes2 = await p.as_bytes()
bytes3 = await p.as_bytes()
assert bytes1 == bytes2 == bytes3 == expected_data
# Now writes should also use the cached data
writer1 = MockStreamWriter()
await p.write_with_length(writer1, None)
assert writer1.get_written_bytes() == expected_data
# Second write should also work
writer2 = MockStreamWriter()
await p.write_with_length(writer2, None)
assert writer2.get_written_bytes() == expected_data
# Write with partial length
writer3 = MockStreamWriter()
await p.write_with_length(writer3, 5)
assert writer3.get_written_bytes() == b"async"
async def test_async_iterable_payload_no_reuse_without_cache() -> None:
"""Test that AsyncIterablePayload cannot be reused without caching."""
async def gen() -> AsyncIterator[bytes]:
yield b"test "
yield b"data"
p = payload.AsyncIterablePayload(gen())
# First write exhausts the iterator
writer1 = MockStreamWriter()
await p.write_with_length(writer1, None)
assert writer1.get_written_bytes() == b"test data"
assert p._iter is None # Iterator exhausted
assert p._consumed is True
# Second write should produce empty result
writer2 = MockStreamWriter()
await p.write_with_length(writer2, None)
assert writer2.get_written_bytes() == b""
async def test_bytes_io_payload_close_does_not_close_io() -> None:
"""Test that BytesIOPayload close() does not close the underlying BytesIO."""
bytes_io = io.BytesIO(b"data")
bytes_io_payload = payload.BytesIOPayload(bytes_io)
# Close the payload
await bytes_io_payload.close()
# BytesIO should NOT be closed
assert not bytes_io.closed
# Can still write after close
writer = MockStreamWriter()
await bytes_io_payload.write_with_length(writer, None)
assert writer.get_written_bytes() == b"data"
async def test_custom_payload_backwards_compat_as_bytes() -> None:
"""Test backwards compatibility for custom Payload that only implements decode()."""
class LegacyPayload(payload.Payload):
"""A custom payload that only implements decode() like old code might do."""
def __init__(self, data: str) -> None:
super().__init__(data, headers=CIMultiDict())
self._data = data
def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str:
"""Custom decode implementation."""
return self._data
async def write(self, writer: AbstractStreamWriter) -> None:
"""Write implementation which is a no-op for this test."""
# Create instance with test data
p = LegacyPayload("Hello, World!")
# Test that as_bytes() works even though it's not explicitly implemented
# The base class should call decode() and encode the result
result = await p.as_bytes()
assert result == b"Hello, World!"
# Test with different text
p2 = LegacyPayload("Test with special chars: café")
result_utf8 = await p2.as_bytes(encoding="utf-8")
assert result_utf8 == "Test with special chars: café".encode()
# Test that decode() still works as expected
assert p.decode() == "Hello, World!"
assert p2.decode() == "Test with special chars: café"
async def test_custom_payload_with_encoding_backwards_compat() -> None:
"""Test custom Payload with encoding set uses instance encoding for as_bytes()."""
class EncodedPayload(payload.Payload):
"""A custom payload with specific encoding."""
def __init__(self, data: str, encoding: str) -> None:
super().__init__(data, headers=CIMultiDict(), encoding=encoding)
self._data = data
def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str:
"""Custom decode implementation."""
return self._data
async def write(self, writer: AbstractStreamWriter) -> None:
"""Write implementation is a no-op."""
# Create instance with specific encoding
p = EncodedPayload("Test data", encoding="latin-1")
# as_bytes() should use the instance encoding (latin-1) not the default utf-8
result = await p.as_bytes()
assert result == b"Test data" # ASCII chars are same in latin-1
# Test with non-ASCII that differs between encodings
p2 = EncodedPayload("café", encoding="latin-1")
result_latin1 = await p2.as_bytes()
assert result_latin1 == "café".encode("latin-1")
assert result_latin1 != "café".encode() # Should be different bytes
async def test_iobase_payload_close_idempotent() -> None:
"""Test that IOBasePayload.close() is idempotent and covers the _consumed check."""
file_like = io.BytesIO(b"test data")
p = payload.IOBasePayload(file_like)
# First close should set _consumed to True
await p.close()
assert p._consumed is True
# Second close should be a no-op due to _consumed check (line 621)
await p.close()
assert p._consumed is True
def test_iobase_payload_decode() -> None:
"""Test IOBasePayload.decode() returns correct string."""
# Test with UTF-8 encoded text
text = "Hello, 世界! 🌍"
file_like = io.BytesIO(text.encode("utf-8"))
p = payload.IOBasePayload(file_like)
# decode() should return the original string
assert p.decode() == text
# Test with different encoding
latin1_text = "café"
file_like2 = io.BytesIO(latin1_text.encode("latin-1"))
p2 = payload.IOBasePayload(file_like2)
assert p2.decode("latin-1") == latin1_text
# Test that file position is restored
file_like3 = io.BytesIO(b"test data")
file_like3.read(4) # Move position forward
p3 = payload.IOBasePayload(file_like3)
# decode() should read from the stored start position (4)
assert p3.decode() == " data"
def test_bytes_payload_size() -> None:
"""Test BytesPayload.size property returns correct byte length."""
# Test with bytes
bp = payload.BytesPayload(b"Hello World")
assert bp.size == 11
# Test with empty bytes
bp_empty = payload.BytesPayload(b"")
assert bp_empty.size == 0
# Test with bytearray
ba = bytearray(b"Hello World")
bp_array = payload.BytesPayload(ba)
assert bp_array.size == 11
def test_string_payload_size() -> None:
"""Test StringPayload.size property with different encodings."""
# Test ASCII string with default UTF-8 encoding
sp = payload.StringPayload("Hello World")
assert sp.size == 11
# Test Unicode string with default UTF-8 encoding
unicode_str = "Hello 世界"
sp_unicode = payload.StringPayload(unicode_str)
assert sp_unicode.size == len(unicode_str.encode("utf-8"))
# Test with UTF-16 encoding
sp_utf16 = payload.StringPayload("Hello World", encoding="utf-16")
assert sp_utf16.size == len("Hello World".encode("utf-16"))
# Test with latin-1 encoding
sp_latin1 = payload.StringPayload("café", encoding="latin-1")
assert sp_latin1.size == len("café".encode("latin-1"))
def test_string_io_payload_size() -> None:
"""Test StringIOPayload.size property."""
# Test normal string
sio = StringIO("Hello World")
siop = payload.StringIOPayload(sio)
assert siop.size == 11
# Test Unicode string
sio_unicode = StringIO("Hello 世界")
siop_unicode = payload.StringIOPayload(sio_unicode)
assert siop_unicode.size == len("Hello 世界".encode())
# Test with custom encoding
sio_custom = StringIO("Hello")
siop_custom = payload.StringIOPayload(sio_custom, encoding="utf-16")
assert siop_custom.size == len("Hello".encode("utf-16"))
# Test with emoji to ensure correct byte count
sio_emoji = StringIO("Hello 👋🌍")
siop_emoji = payload.StringIOPayload(sio_emoji)
assert siop_emoji.size == len("Hello 👋🌍".encode())
# Verify it's not the string length
assert siop_emoji.size != len("Hello 👋🌍")
def test_all_string_payloads_size_is_bytes() -> None:
"""Test that all string-like payload classes report size in bytes, not string length."""
# Test string with multibyte characters
test_str = "Hello 👋 世界 🌍" # Contains emoji and Chinese characters
# StringPayload
sp = payload.StringPayload(test_str)
assert sp.size == len(test_str.encode("utf-8"))
assert sp.size != len(test_str) # Ensure it's not string length
# StringIOPayload
sio = StringIO(test_str)
siop = payload.StringIOPayload(sio)
assert siop.size == len(test_str.encode("utf-8"))
assert siop.size != len(test_str)
# Test with different encoding
sp_utf16 = payload.StringPayload(test_str, encoding="utf-16")
assert sp_utf16.size == len(test_str.encode("utf-16"))
assert sp_utf16.size != sp.size # Different encoding = different size
# JsonPayload (which extends BytesPayload)
json_data = {"message": test_str}
jp = payload.JsonPayload(json_data)
# JSON escapes Unicode, so we need to check the actual encoded size
json_str = json.dumps(json_data)
assert jp.size == len(json_str.encode("utf-8"))
# Test JsonPayload with ensure_ascii=False to get actual UTF-8 encoding
jp_utf8 = payload.JsonPayload(
json_data, dumps=lambda x: json.dumps(x, ensure_ascii=False)
)
json_str_utf8 = json.dumps(json_data, ensure_ascii=False)
assert jp_utf8.size == len(json_str_utf8.encode("utf-8"))
assert jp_utf8.size != len(
json_str_utf8
) # Now it's different due to multibyte chars
def test_bytes_io_payload_size() -> None:
"""Test BytesIOPayload.size property."""
# Test normal bytes
bio = io.BytesIO(b"Hello World")
biop = payload.BytesIOPayload(bio)
assert biop.size == 11
# Test empty BytesIO
bio_empty = io.BytesIO(b"")
biop_empty = payload.BytesIOPayload(bio_empty)
assert biop_empty.size == 0
# Test with position not at start
bio_pos = io.BytesIO(b"Hello World")
bio_pos.seek(5)
biop_pos = payload.BytesIOPayload(bio_pos)
assert biop_pos.size == 6 # Size should be from position to end
def test_json_payload_size() -> None:
"""Test JsonPayload.size property."""
# Test simple dict
data = {"hello": "world"}
jp = payload.JsonPayload(data)
expected_json = json.dumps(data) # Use actual json.dumps output
assert jp.size == len(expected_json.encode("utf-8"))
# Test with Unicode
data_unicode = {"message": "Hello 世界"}
jp_unicode = payload.JsonPayload(data_unicode)
expected_unicode = json.dumps(data_unicode)
assert jp_unicode.size == len(expected_unicode.encode("utf-8"))
# Test with custom encoding
data_custom = {"test": "data"}
jp_custom = payload.JsonPayload(data_custom, encoding="utf-16")
expected_custom = json.dumps(data_custom)
assert jp_custom.size == len(expected_custom.encode("utf-16"))
async def test_text_io_payload_size_matches_file_encoding(tmp_path: Path) -> None:
"""Test TextIOPayload.size when file encoding matches payload encoding."""
# Create UTF-8 file
utf8_file = tmp_path / "test_utf8.txt"
content = "Hello 世界"
# Write file in executor
loop = asyncio.get_running_loop()
await loop.run_in_executor(None, utf8_file.write_text, content, "utf-8")
# Open file in executor
def open_file() -> TextIO:
return open(utf8_file, encoding="utf-8")
f = await loop.run_in_executor(None, open_file)
try:
tiop = payload.TextIOPayload(f)
# Size should match the actual UTF-8 encoded size
assert tiop.size == len(content.encode("utf-8"))
finally:
await loop.run_in_executor(None, f.close)
async def test_text_io_payload_size_utf16(tmp_path: Path) -> None:
"""Test TextIOPayload.size reports correct size with utf-16."""
# Create UTF-16 file
utf16_file = tmp_path / "test_utf16.txt"
content = "Hello World"
loop = asyncio.get_running_loop()
# Write file in executor
await loop.run_in_executor(None, utf16_file.write_text, content, "utf-16")
# Get file size in executor
utf16_file_size = await loop.run_in_executor(
None, lambda: utf16_file.stat().st_size
)
# Open file in executor
def open_file() -> TextIO:
return open(utf16_file, encoding="utf-16")
f = await loop.run_in_executor(None, open_file)
try:
tiop = payload.TextIOPayload(f, encoding="utf-16")
# Payload reports file size on disk (UTF-16)
assert tiop.size == utf16_file_size
# Write to a buffer to see what actually gets sent
writer = BufferWriter()
await tiop.write(writer)
# Check that the actual written bytes match file size
assert len(writer.buffer) == utf16_file_size
finally:
await loop.run_in_executor(None, f.close)
async def test_iobase_payload_size_after_reading(tmp_path: Path) -> None:
"""Test that IOBasePayload.size returns correct size after file has been read.
This verifies that size calculation properly accounts for the initial
file position, which is critical for 307/308 redirects where the same
payload instance is reused.
"""
# Create a test file with known content
test_file = tmp_path / "test.txt"
content = b"Hello, World! This is test content."
await asyncio.to_thread(test_file.write_bytes, content)
expected_size = len(content)
# Open the file and create payload
f = await asyncio.to_thread(open, test_file, "rb")
try:
p = payload.BufferedReaderPayload(f)
# First size check - should return full file size
assert p.size == expected_size
# Read the file (simulating first request)
writer = BufferWriter()
await p.write(writer)
assert len(writer.buffer) == expected_size
# Second size check - should still return full file size
assert p.size == expected_size
# Attempting to write again should write the full content
writer2 = BufferWriter()
await p.write(writer2)
assert len(writer2.buffer) == expected_size
finally:
await asyncio.to_thread(f.close)
async def test_iobase_payload_size_unseekable() -> None:
"""Test that IOBasePayload.size returns None for unseekable files."""
class UnseekableFile:
"""Mock file object that doesn't support seeking."""
def __init__(self, content: bytes) -> None:
self.content = content
self.pos = 0
def read(self, size: int) -> bytes:
result = self.content[self.pos : self.pos + size]
self.pos += len(result)
return result
def tell(self) -> int:
raise OSError("Unseekable file")
content = b"Unseekable content"
f = UnseekableFile(content)
p = payload.IOBasePayload(f) # type: ignore[arg-type]
# Size should return None for unseekable files
assert p.size is None
# Payload should not be consumed before writing
assert p.consumed is False
# Writing should still work
writer = BufferWriter()
await p.write(writer)
assert writer.buffer == content
# For unseekable files that can't tell() or seek(),
# they are marked as consumed after the first write
assert p.consumed is True
async def test_empty_bytes_payload_is_reusable() -> None:
"""Test that empty BytesPayload can be safely reused across requests."""
empty_payload = payload.PAYLOAD_REGISTRY.get(b"", disposition=None)
assert isinstance(empty_payload, payload.BytesPayload)
assert empty_payload.size == 0
assert empty_payload.consumed is False
assert empty_payload.autoclose is True
initial_headers = dict(empty_payload.headers)
for i in range(3):
writer = BufferWriter()
await empty_payload.write_with_length(writer, None)
assert writer.buffer == b""
assert empty_payload.consumed is False, f"consumed flag changed on write {i+1}"
assert (
dict(empty_payload.headers) == initial_headers
), f"headers mutated on write {i+1}"
assert empty_payload.size == 0, f"size changed on write {i+1}"
assert empty_payload.headers == CIMultiDict(initial_headers)
| aiohttp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.