fastapi-rfc9457 0.2.0__tar.gz → 0.2.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/PKG-INFO +16 -2
  2. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/README.md +14 -0
  3. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/src/fastapi_rfc9457/__init__.py +2 -0
  4. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/src/fastapi_rfc9457/_version.py +2 -2
  5. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/src/fastapi_rfc9457/builtins.py +41 -1
  6. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/src/fastapi_rfc9457/handlers.py +6 -7
  7. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/src/fastapi_rfc9457/openapi.py +38 -1
  8. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/src/fastapi_rfc9457/problem.py +37 -3
  9. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/tests/static/expected_errors.py +5 -1
  10. fastapi_rfc9457-0.2.2/tests/static/valid_usage.py +31 -0
  11. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/tests/test_builtins.py +2 -0
  12. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/tests/test_problem.py +51 -0
  13. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/tests/test_public_api.py +1 -0
  14. fastapi_rfc9457-0.2.2/tests/test_response_headers.py +143 -0
  15. fastapi_rfc9457-0.2.0/tests/static/valid_usage.py +0 -19
  16. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/.gitignore +0 -0
  17. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/LICENSE +0 -0
  18. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/example/README.md +0 -0
  19. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/pyproject.toml +0 -0
  20. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/src/fastapi_rfc9457/client.py +0 -0
  21. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/src/fastapi_rfc9457/docs.py +0 -0
  22. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/src/fastapi_rfc9457/integration.py +0 -0
  23. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/src/fastapi_rfc9457/models.py +0 -0
  24. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/src/fastapi_rfc9457/py.typed +0 -0
  25. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/src/fastapi_rfc9457/server.py +0 -0
  26. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/src/fastapi_rfc9457/uris.py +0 -0
  27. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/tests/conftest.py +0 -0
  28. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/tests/test_client.py +0 -0
  29. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/tests/test_client_install.py +0 -0
  30. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/tests/test_docs.py +0 -0
  31. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/tests/test_example.py +0 -0
  32. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/tests/test_example_client.py +0 -0
  33. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/tests/test_extension_fields_pep563.py +0 -0
  34. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/tests/test_handlers.py +0 -0
  35. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/tests/test_integration.py +0 -0
  36. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/tests/test_lifespan.py +0 -0
  37. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/tests/test_models.py +0 -0
  38. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/tests/test_openapi.py +0 -0
  39. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/tests/test_static_typing.py +0 -0
  40. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/tests/test_type_uri_resolution.py +0 -0
  41. {fastapi_rfc9457-0.2.0 → fastapi_rfc9457-0.2.2}/tests/test_yield_dependency.py +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: fastapi-rfc9457
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: Typed, batteries-included RFC 9457 Problem Details for FastAPI & Pydantic v2.
5
5
  Project-URL: Repository, https://github.com/PythonFZ/fastapi-rfc9457
6
6
  Project-URL: Releases, https://github.com/PythonFZ/fastapi-rfc9457/releases
@@ -76,6 +76,20 @@ explicitly to emit a literal URI instead.
76
76
 
77
77
  ![Problem type documentation page](https://raw.githubusercontent.com/PythonFZ/fastapi-rfc9457/main/docs/img/doc-page.png)
78
78
 
79
+ ## Response headers
80
+
81
+ A problem type declares the headers it sends in `headers` (name → OpenAPI description) and
82
+ returns their values from `response_headers()`. The built-ins send the headers RFC 9110 asks for:
83
+
84
+ ```python
85
+ raise NotAuthenticated() # WWW-Authenticate: Bearer
86
+ raise TooManyRequests(retry_after=30) # Retry-After: 30
87
+ raise MethodNotAllowed(allow=["GET"]) # Allow: GET
88
+
89
+ class BasicAuthRequired(NotAuthenticated):
90
+ challenge = 'Basic realm="api"' # WWW-Authenticate: Basic realm="api"
91
+ ```
92
+
79
93
  ## Typed exceptions on the client
80
94
 
81
95
  Client-side, the package can parse
@@ -61,6 +61,20 @@ explicitly to emit a literal URI instead.
61
61
 
62
62
  ![Problem type documentation page](https://raw.githubusercontent.com/PythonFZ/fastapi-rfc9457/main/docs/img/doc-page.png)
63
63
 
64
+ ## Response headers
65
+
66
+ A problem type declares the headers it sends in `headers` (name → OpenAPI description) and
67
+ returns their values from `response_headers()`. The built-ins send the headers RFC 9110 asks for:
68
+
69
+ ```python
70
+ raise NotAuthenticated() # WWW-Authenticate: Bearer
71
+ raise TooManyRequests(retry_after=30) # Retry-After: 30
72
+ raise MethodNotAllowed(allow=["GET"]) # Allow: GET
73
+
74
+ class BasicAuthRequired(NotAuthenticated):
75
+ challenge = 'Basic realm="api"' # WWW-Authenticate: Basic realm="api"
76
+ ```
77
+
64
78
  ## Typed exceptions on the client
65
79
 
66
80
  Client-side, the package can parse
@@ -10,6 +10,7 @@ from .builtins import (
10
10
  Forbidden,
11
11
  InternalServerError,
12
12
  InvalidParam,
13
+ MethodNotAllowed,
13
14
  NotAuthenticated,
14
15
  NotFound,
15
16
  TooManyRequests,
@@ -32,6 +33,7 @@ __all__ = [
32
33
  "Forbidden",
33
34
  "InternalServerError",
34
35
  "InvalidParam",
36
+ "MethodNotAllowed",
35
37
  "NotAuthenticated",
36
38
  "NotFound",
37
39
  "Problem",
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '0.2.0'
22
- __version_tuple__ = version_tuple = (0, 2, 0)
21
+ __version__ = version = '0.2.2'
22
+ __version_tuple__ = version_tuple = (0, 2, 2)
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -2,7 +2,8 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from typing import Any
5
+ from collections.abc import Mapping
6
+ from typing import Any, ClassVar
6
7
 
7
8
  from pydantic import BaseModel
8
9
 
@@ -21,6 +22,21 @@ class NotAuthenticated(Problem):
21
22
 
22
23
  title = "Unauthorized"
23
24
  status = 401
25
+ headers: ClassVar[Mapping[str, str]] = {
26
+ "WWW-Authenticate": "The challenge(s) the client must answer to authenticate "
27
+ "(RFC 9110 §11.6.1)."
28
+ }
29
+ #: The ``WWW-Authenticate`` challenge, e.g. ``'Basic realm="api"'`` in a subclass.
30
+ challenge: ClassVar[str] = "Bearer"
31
+
32
+ def response_headers(self) -> Mapping[str, str]:
33
+ """Send the class's ``challenge`` as ``WWW-Authenticate``."""
34
+ return {"WWW-Authenticate": self.challenge}
35
+
36
+ @classmethod
37
+ def header_examples(cls) -> Mapping[str, str]:
38
+ """Document the class's ``challenge`` as the ``WWW-Authenticate`` example."""
39
+ return {"WWW-Authenticate": cls.challenge}
24
40
 
25
41
 
26
42
  class Forbidden(Problem):
@@ -37,6 +53,21 @@ class NotFound(Problem):
37
53
  status = 404
38
54
 
39
55
 
56
+ class MethodNotAllowed(Problem):
57
+ """The request method is not supported by the target resource."""
58
+
59
+ title = "Method Not Allowed"
60
+ status = 405
61
+ headers: ClassVar[Mapping[str, str]] = {
62
+ "Allow": "The methods the target resource supports (RFC 9110 §10.2.1)."
63
+ }
64
+ allow: list[str]
65
+
66
+ def response_headers(self) -> Mapping[str, str]:
67
+ """Send ``allow`` as the ``Allow`` header."""
68
+ return {"Allow": ", ".join(self.allow)}
69
+
70
+
40
71
  class Conflict(Problem):
41
72
  """The request conflicts with the current state of the resource."""
42
73
 
@@ -56,6 +87,15 @@ class TooManyRequests(Problem):
56
87
 
57
88
  title = "Too Many Requests"
58
89
  status = 429
90
+ headers: ClassVar[Mapping[str, str]] = {
91
+ "Retry-After": "Seconds to wait before retrying (RFC 9110 §10.2.3)."
92
+ }
93
+ #: Seconds the client waits before retrying; sent as ``Retry-After`` when set.
94
+ retry_after: int | None = None
95
+
96
+ def response_headers(self) -> Mapping[str, str]:
97
+ """Send ``retry_after`` as ``Retry-After`` when set."""
98
+ return {} if self.retry_after is None else {"Retry-After": str(self.retry_after)}
59
99
 
60
100
 
61
101
  class InternalServerError(Problem):
@@ -2,7 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from collections.abc import Awaitable, Callable
5
+ from collections.abc import Awaitable, Callable, Mapping
6
6
  from http import HTTPStatus
7
7
  from typing import cast
8
8
 
@@ -49,10 +49,11 @@ def build_wire(problem: Problem, *, instance: str | None, type_uri: str) -> Prob
49
49
  )
50
50
 
51
51
 
52
- def _respond(detail: ProblemDetail) -> Response:
52
+ def _respond(detail: ProblemDetail, headers: Mapping[str, str] | None = None) -> Response:
53
53
  return Response(
54
54
  content=detail.model_dump_json(exclude_none=True),
55
55
  status_code=detail.status,
56
+ headers=headers,
56
57
  media_type=PROBLEM_MEDIA_TYPE,
57
58
  )
58
59
 
@@ -78,7 +79,8 @@ def make_handlers(*, strip_debug: bool, instance_from_request: bool) -> dict[typ
78
79
 
79
80
  async def problem_handler(request: Request, exc: Problem) -> Response:
80
81
  type_uri = resolve_type_uri(request.app, type(exc))
81
- return _respond(build_wire(exc, instance=_instance(request), type_uri=type_uri))
82
+ wire = build_wire(exc, instance=_instance(request), type_uri=type_uri)
83
+ return _respond(wire, exc.response_headers())
82
84
 
83
85
  async def validation_handler(request: Request, exc: RequestValidationError) -> Response:
84
86
  params: list[InvalidParam] = []
@@ -116,10 +118,7 @@ def make_handlers(*, strip_debug: bool, instance_from_request: bool) -> dict[typ
116
118
  detail=exc.detail if isinstance(exc.detail, str) else None,
117
119
  instance=_instance(request),
118
120
  )
119
- response = _respond(wire)
120
- if exc.headers:
121
- response.headers.update(exc.headers)
122
- return response
121
+ return _respond(wire, exc.headers)
123
122
 
124
123
  async def unhandled_handler(request: Request, exc: Exception) -> Response:
125
124
  wire = ProblemDetail(
@@ -11,6 +11,7 @@ response to ``application/problem+json`` (FastAPI emits models under
11
11
 
12
12
  from __future__ import annotations
13
13
 
14
+ import dataclasses
14
15
  import json
15
16
  import types
16
17
  from functools import reduce
@@ -74,7 +75,11 @@ def _wire_model(cls: type[Problem]) -> type[BaseModel]:
74
75
  cached = _WIRE_CACHE.get(cls)
75
76
  if cached is not None:
76
77
  return cached
77
- fields: dict[str, Any] = {name: (typ, ...) for name, typ in extension_fields(cls).items()}
78
+ defaults = {f.name: f.default for f in dataclasses.fields(cls)}
79
+ fields: dict[str, Any] = {
80
+ name: (typ, ... if defaults[name] is dataclasses.MISSING else defaults[name])
81
+ for name, typ in extension_fields(cls).items()
82
+ }
78
83
  model = create_model( # type: ignore[call-overload]
79
84
  cls.__name__,
80
85
  __base__=_WireBase,
@@ -116,9 +121,41 @@ def problems(*types_: type[Problem]) -> dict[int | str, dict[str, Any]]:
116
121
  model: Any = wires[0] if len(wires) == 1 else _union(wires)
117
122
  descriptions = [(t.__doc__ or t.title).strip() for t in group]
118
123
  responses[status] = {"model": model, "description": " / ".join(descriptions)}
124
+ headers = _header_objects(group)
125
+ if headers:
126
+ responses[status]["headers"] = headers
119
127
  return responses
120
128
 
121
129
 
130
+ def _header_objects(group: list[type[Problem]]) -> dict[str, dict[str, Any]]:
131
+ """Build OpenAPI Header Objects for the problem types sharing one status.
132
+
133
+ Parameters
134
+ ----------
135
+ group : list[type[Problem]]
136
+ The problem types documented under one status code.
137
+
138
+ Returns
139
+ -------
140
+ dict[str, dict[str, Any]]
141
+ Header name -> Header Object. One example value is set as ``example``;
142
+ several distinct values are listed under ``examples``, keyed by class name.
143
+ """
144
+ objects: dict[str, dict[str, Any]] = {}
145
+ examples: dict[str, dict[str, str]] = {}
146
+ for problem_type in group:
147
+ for name, description in problem_type.headers.items():
148
+ objects.setdefault(name, {"description": description, "schema": {"type": "string"}})
149
+ for name, value in problem_type.header_examples().items():
150
+ examples.setdefault(name, {})[problem_type.__name__] = value
151
+ for name, by_class in examples.items():
152
+ if len(set(by_class.values())) == 1:
153
+ objects[name]["example"] = next(iter(by_class.values()))
154
+ else:
155
+ objects[name]["examples"] = {cls: {"value": v} for cls, v in by_class.items()}
156
+ return objects
157
+
158
+
122
159
  def _problem_wire_members(model: Any) -> list[type[BaseModel]] | None:
123
160
  """Return the problem wire models behind a response ``model``, or ``None``.
124
161
 
@@ -4,7 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  import dataclasses
6
6
  import re
7
- from collections.abc import Iterator
7
+ from collections.abc import Iterator, Mapping
8
8
  from typing import ClassVar, dataclass_transform, get_type_hints
9
9
 
10
10
  import pydantic
@@ -118,13 +118,47 @@ class Problem(Exception, metaclass=_ProblemMeta):
118
118
  #: ``type`` is emitted verbatim; a derived one is resolved against the docs
119
119
  #: mount at serialize time (see uris.resolve_type_uri).
120
120
  _type_is_explicit: ClassVar[bool] = False
121
+ #: Response headers this problem type sends, as name -> OpenAPI description.
122
+ headers: ClassVar[Mapping[str, str]] = {}
121
123
  detail: str | None = None
122
124
  instance: str | None = None
123
125
 
124
126
  def __init_subclass__(cls, **kwargs) -> None:
125
127
  super().__init_subclass__(**kwargs)
126
- cls._type_is_explicit = cls.__dict__.get("type") is not None
127
- cls.type = cls.type if cls.type is not None else _derive_type(cls.__name__)
128
+ own_type = cls.__dict__.get("type")
129
+ cls._type_is_explicit = own_type is not None
130
+ cls.type = own_type if own_type is not None else _derive_type(cls.__name__)
131
+
132
+ def response_headers(self) -> Mapping[str, str]:
133
+ """Return the header values sent with this problem's response.
134
+
135
+ Override alongside ``headers`` to send headers built from the
136
+ instance's fields.
137
+
138
+ Returns
139
+ -------
140
+ Mapping[str, str]
141
+ Header name -> value, a subset of the names declared in ``headers``.
142
+ """
143
+ return {}
144
+
145
+ @classmethod
146
+ def header_examples(cls) -> Mapping[str, str]:
147
+ """Return example header values for the OpenAPI docs.
148
+
149
+ Returns
150
+ -------
151
+ Mapping[str, str]
152
+ Header name -> example value, a subset of the names declared in ``headers``.
153
+ """
154
+ return {}
155
+
156
+ def __str__(self) -> str:
157
+ """Human-readable representation for logs and traceback tails."""
158
+
159
+ head = f"{getattr(self, 'status', '')} {getattr(self, 'title', '')}".strip()
160
+ head = head or type(self).__name__
161
+ return f"{head} — {self.detail}" if self.detail else head
128
162
 
129
163
 
130
164
  def iter_problem_types() -> Iterator[type[Problem]]:
@@ -4,7 +4,7 @@ It is EXCLUDED from the main pyright run (see pyproject [tool.pyright].exclude)
4
4
  and checked instead by tests/test_static_typing.py.
5
5
  """
6
6
 
7
- from fastapi_rfc9457 import Problem
7
+ from fastapi_rfc9457 import MethodNotAllowed, NotAuthenticated, Problem
8
8
 
9
9
 
10
10
  class OutOfCredit(Problem):
@@ -22,3 +22,7 @@ OutOfCredit(status=404) # status can not be set dynamically.
22
22
  class BadStatus(Problem):
23
23
  title = "x"
24
24
  status = "nope" # reportAssignmentType: status is int
25
+
26
+
27
+ MethodNotAllowed() # reportCallIssue: missing allow
28
+ NotAuthenticated(headers={"X": "y"}) # reportCallIssue: headers is a ClassVar
@@ -0,0 +1,31 @@
1
+ """This file MUST type-check clean — it is part of the main pyright run."""
2
+
3
+ from collections.abc import Mapping
4
+ from typing import assert_type
5
+
6
+ from fastapi_rfc9457 import MethodNotAllowed, NotAuthenticated, Problem, TooManyRequests
7
+
8
+
9
+ class OutOfCredit(Problem):
10
+ """The account does not have enough credit."""
11
+
12
+ title = "Out of Credit"
13
+ status = 403
14
+ balance: int
15
+ accounts: list[str]
16
+
17
+
18
+ err = OutOfCredit(detail="x", balance=30, accounts=["/acct/12"])
19
+ assert_type(err.balance, int)
20
+ assert_type(err.accounts, list[str])
21
+
22
+
23
+ class BasicAuthRequired(NotAuthenticated):
24
+ """Basic credentials are required."""
25
+
26
+ challenge = 'Basic realm="api"'
27
+
28
+
29
+ assert_type(TooManyRequests(retry_after=30).retry_after, int | None)
30
+ assert_type(MethodNotAllowed(allow=["GET"]).allow, list[str])
31
+ assert_type(BasicAuthRequired().response_headers(), Mapping[str, str])
@@ -4,6 +4,7 @@ from fastapi_rfc9457.builtins import (
4
4
  Forbidden,
5
5
  InternalServerError,
6
6
  InvalidParam,
7
+ MethodNotAllowed,
7
8
  NotAuthenticated,
8
9
  NotFound,
9
10
  TooManyRequests,
@@ -18,6 +19,7 @@ def test_builtin_statuses():
18
19
  assert NotAuthenticated.status == 401
19
20
  assert Forbidden.status == 403
20
21
  assert NotFound.status == 404
22
+ assert MethodNotAllowed.status == 405
21
23
  assert Conflict.status == 409
22
24
  assert UnprocessableContent.status == 422
23
25
  assert TooManyRequests.status == 429
@@ -117,6 +117,41 @@ def test_explicit_type_override_is_respected():
117
117
  assert PostNotFound.type == "/problems/tp-post-not-found"
118
118
 
119
119
 
120
+ def test_child_of_intermediate_base_derives_its_own_slug():
121
+ # An intermediate Problem base derives and stores its own `type`. A child must
122
+ # still derive from its OWN name, not inherit the base's slug — otherwise every
123
+ # child of a shared base collides on one type URI and never round-trips.
124
+ class BillingProblem(Problem):
125
+ title = "Billing"
126
+ status = 402
127
+
128
+ class OutOfCreditB(BillingProblem):
129
+ pass
130
+
131
+ class RateLimitedB(BillingProblem):
132
+ pass
133
+
134
+ assert BillingProblem.type == "billing"
135
+ assert OutOfCreditB.type == "out-of-credit-b"
136
+ assert RateLimitedB.type == "rate-limited-b"
137
+ assert not OutOfCreditB._type_is_explicit
138
+
139
+
140
+ def test_child_of_explicitly_typed_base_derives_not_inherits():
141
+ # A child of a base with an *explicit* type is not itself explicit: it derives
142
+ # its own type rather than silently sharing the base's URI.
143
+ class RootProblem(Problem):
144
+ type = "/problems/root"
145
+ title = "Root"
146
+ status = 400
147
+
148
+ class LeafProblem(RootProblem):
149
+ pass
150
+
151
+ assert LeafProblem.type == "leaf"
152
+ assert not LeafProblem._type_is_explicit
153
+
154
+
120
155
  def test_iter_problem_types_discovers_defined_subclasses():
121
156
  discovered = set(iter_problem_types())
122
157
  assert OutOfCredit in discovered
@@ -144,6 +179,22 @@ def test_extension_fields_excludes_standard_members():
144
179
  assert extension_fields(PostNotFound) == {}
145
180
 
146
181
 
182
+ def test_str_is_human_readable_with_detail():
183
+ err = OutOfCredit(detail="Your balance is too low.", balance=30, accounts=[])
184
+ assert str(err) == "403 Out of Credit — Your balance is too low."
185
+
186
+
187
+ def test_str_omits_detail_when_absent():
188
+ err = OutOfCredit(balance=30, accounts=[])
189
+ assert str(err) == "403 Out of Credit"
190
+
191
+
192
+ def test_str_falls_back_when_status_and_title_unset():
193
+ # A bare `Problem` (or a half-authored subclass) has no `status`/`title`.
194
+ # `str()` must still yield something rather than raising.
195
+ assert str(Problem(detail="boom")) == "Problem — boom"
196
+
197
+
147
198
  def test_problem_error_wraps_a_detail():
148
199
  pd = ProblemDetail(title="Gone", status=410)
149
200
  err = ProblemError(pd)
@@ -17,6 +17,7 @@ def test_client_symbols_are_exported():
17
17
  "httpx_raise_hook",
18
18
  "BadRequest",
19
19
  "NotAuthenticated",
20
+ "MethodNotAllowed",
20
21
  "Forbidden",
21
22
  "NotFound",
22
23
  "Conflict",
@@ -0,0 +1,143 @@
1
+ from collections.abc import Mapping
2
+ from typing import ClassVar
3
+
4
+ from fastapi import FastAPI
5
+ from fastapi.testclient import TestClient
6
+
7
+ from fastapi_rfc9457 import MethodNotAllowed, NotAuthenticated, NotFound, Problem, TooManyRequests
8
+ from fastapi_rfc9457.handlers import make_handlers
9
+ from fastapi_rfc9457.openapi import problems, register_problem_components
10
+
11
+
12
+ class BasicAuthRequired(NotAuthenticated):
13
+ """Basic credentials are required."""
14
+
15
+ challenge = 'Basic realm="api"'
16
+
17
+
18
+ class Moved(Problem):
19
+ """Moved elsewhere."""
20
+
21
+ title = "Moved"
22
+ status = 410
23
+ location: str
24
+ headers: ClassVar[Mapping[str, str]] = {"Location": "Where the resource lives now."}
25
+
26
+ def response_headers(self) -> Mapping[str, str]:
27
+ return {"Location": self.location}
28
+
29
+
30
+ def _client(*raises: Problem) -> TestClient:
31
+ app = FastAPI()
32
+ for exc_type, handler in make_handlers(strip_debug=False, instance_from_request=True).items():
33
+ app.add_exception_handler(exc_type, handler)
34
+ for i, problem in enumerate(raises):
35
+ app.get(f"/{i}")(_raiser(problem))
36
+ return TestClient(app)
37
+
38
+
39
+ def _raiser(problem: Problem):
40
+ def route() -> None:
41
+ raise problem
42
+
43
+ return route
44
+
45
+
46
+ def test_not_authenticated_sends_bearer_challenge():
47
+ resp = _client(NotAuthenticated()).get("/0")
48
+ assert resp.headers["www-authenticate"] == "Bearer"
49
+
50
+
51
+ def test_not_authenticated_subclass_names_its_challenge():
52
+ resp = _client(BasicAuthRequired()).get("/0")
53
+ assert resp.headers["www-authenticate"] == 'Basic realm="api"'
54
+
55
+
56
+ def test_custom_problem_renders_its_response_headers():
57
+ resp = _client(Moved(location="/new")).get("/0")
58
+ assert resp.headers["location"] == "/new"
59
+ assert resp.json()["location"] == "/new"
60
+
61
+
62
+ def test_too_many_requests_sends_retry_after_when_set():
63
+ resp = _client(TooManyRequests(retry_after=30)).get("/0")
64
+ assert resp.headers["retry-after"] == "30"
65
+ assert resp.json()["retry_after"] == 30
66
+
67
+
68
+ def test_too_many_requests_omits_retry_after_by_default():
69
+ resp = _client(TooManyRequests()).get("/0")
70
+ assert "retry-after" not in resp.headers
71
+ assert "retry_after" not in resp.json()
72
+
73
+
74
+ def test_method_not_allowed_sends_allow():
75
+ resp = _client(MethodNotAllowed(allow=["GET", "POST"])).get("/0")
76
+ assert resp.status_code == 405
77
+ assert resp.headers["allow"] == "GET, POST"
78
+ assert resp.json()["allow"] == ["GET", "POST"]
79
+
80
+
81
+ def _responses(*types_: type[Problem]) -> dict:
82
+ app = FastAPI()
83
+
84
+ @app.get("/x", responses=problems(*types_))
85
+ async def x() -> None: ...
86
+
87
+ register_problem_components(app)
88
+ return TestClient(app).get("/openapi.json").json()["paths"]["/x"]["get"]["responses"]
89
+
90
+
91
+ def test_openapi_documents_declared_headers():
92
+ responses = _responses(NotAuthenticated, TooManyRequests, MethodNotAllowed)
93
+ assert set(responses["401"]["headers"]) == {"WWW-Authenticate"}
94
+ assert set(responses["429"]["headers"]) == {"Retry-After"}
95
+ assert set(responses["405"]["headers"]) == {"Allow"}
96
+ assert responses["401"]["headers"]["WWW-Authenticate"]["schema"] == {"type": "string"}
97
+
98
+
99
+ def test_openapi_merges_headers_of_a_shared_status():
100
+ responses = _responses(Moved, _Gone)
101
+ assert set(responses["410"]["headers"]) == {"Location", "Sunset"}
102
+
103
+
104
+ def test_openapi_omits_headers_for_problems_without_them():
105
+ assert "headers" not in _responses(NotFound)["404"]
106
+
107
+
108
+ def test_openapi_documents_optional_extension_as_optional():
109
+ app = FastAPI()
110
+
111
+ @app.get("/x", responses=problems(TooManyRequests))
112
+ async def x() -> None: ...
113
+
114
+ register_problem_components(app)
115
+ schema = TestClient(app).get("/openapi.json").json()["components"]["schemas"]["TooManyRequests"]
116
+ assert "retry_after" not in schema.get("required", [])
117
+
118
+
119
+ class _Gone(Problem):
120
+ """Gone for good."""
121
+
122
+ title = "Gone"
123
+ status = 410
124
+ headers: ClassVar[Mapping[str, str]] = {"Sunset": "When the resource went away."}
125
+
126
+
127
+ def test_openapi_shows_the_challenge_as_header_example():
128
+ header = _responses(NotAuthenticated)["401"]["headers"]["WWW-Authenticate"]
129
+ assert header["example"] == "Bearer"
130
+
131
+
132
+ def test_openapi_shows_a_subclass_challenge_as_header_example():
133
+ header = _responses(BasicAuthRequired)["401"]["headers"]["WWW-Authenticate"]
134
+ assert header["example"] == 'Basic realm="api"'
135
+
136
+
137
+ def test_openapi_lists_each_challenge_of_a_shared_status():
138
+ header = _responses(NotAuthenticated, BasicAuthRequired)["401"]["headers"]["WWW-Authenticate"]
139
+ assert "example" not in header
140
+ assert header["examples"] == {
141
+ "NotAuthenticated": {"value": "Bearer"},
142
+ "BasicAuthRequired": {"value": 'Basic realm="api"'},
143
+ }
@@ -1,19 +0,0 @@
1
- """This file MUST type-check clean — it is part of the main pyright run."""
2
-
3
- from typing import assert_type
4
-
5
- from fastapi_rfc9457 import Problem
6
-
7
-
8
- class OutOfCredit(Problem):
9
- """The account does not have enough credit."""
10
-
11
- title = "Out of Credit"
12
- status = 403
13
- balance: int
14
- accounts: list[str]
15
-
16
-
17
- err = OutOfCredit(detail="x", balance=30, accounts=["/acct/12"])
18
- assert_type(err.balance, int)
19
- assert_type(err.accounts, list[str])
File without changes