|
| 1 | +"""Tests for ``BaseError`` and the ``BaseErrorMeta`` metaclass.""" |
| 2 | + |
| 3 | +from enum import StrEnum |
| 4 | +from http import HTTPStatus |
| 5 | +from typing import Literal |
| 6 | + |
| 7 | +import pytest |
| 8 | + |
| 9 | +from fastapi_typed_errors import BaseError, ErrorResponse |
| 10 | +from fastapi_typed_errors.core.base import BaseErrorMeta |
| 11 | + |
| 12 | + |
| 13 | +class Code(StrEnum): |
| 14 | + """Error codes used by the test error classes.""" |
| 15 | + |
| 16 | + NOT_FOUND = "NOT_FOUND" |
| 17 | + FORBIDDEN = "FORBIDDEN" |
| 18 | + |
| 19 | + |
| 20 | +class NotFoundError(BaseError[Literal[Code.NOT_FOUND]]): |
| 21 | + """Test error with a description.""" |
| 22 | + |
| 23 | + http_status = HTTPStatus.NOT_FOUND |
| 24 | + description = "Entity does not exist" |
| 25 | + |
| 26 | + |
| 27 | +class ForbiddenError(BaseError[Literal[Code.FORBIDDEN]]): |
| 28 | + """Test error without a description.""" |
| 29 | + |
| 30 | + http_status = HTTPStatus.FORBIDDEN |
| 31 | + |
| 32 | + |
| 33 | +class WideResponse[T: str](ErrorResponse[T]): |
| 34 | + """Custom response base with an extra field.""" |
| 35 | + |
| 36 | + extra: str = "x" |
| 37 | + |
| 38 | + |
| 39 | +class AppError[T: str](BaseError[T]): |
| 40 | + """Intermediate generic base carrying a custom ``response_base``.""" |
| 41 | + |
| 42 | + response_base = WideResponse |
| 43 | + |
| 44 | + |
| 45 | +class CustomError(AppError[Literal[Code.FORBIDDEN]]): |
| 46 | + """Concrete error inheriting the custom response base.""" |
| 47 | + |
| 48 | + http_status = HTTPStatus.FORBIDDEN |
| 49 | + |
| 50 | + |
| 51 | +def test_code_extracted_from_enum_literal() -> None: |
| 52 | + """The metaclass pulls the code out of the ``Literal`` generic parameter.""" |
| 53 | + assert NotFoundError.error_code is Code.NOT_FOUND |
| 54 | + |
| 55 | + |
| 56 | +def test_code_extracted_from_bare_string_literal() -> None: |
| 57 | + """A plain string ``Literal`` works as the error code too.""" |
| 58 | + |
| 59 | + class BareError(BaseError[Literal["BARE"]]): |
| 60 | + """Error declared without an enum.""" |
| 61 | + |
| 62 | + http_status = HTTPStatus.CONFLICT |
| 63 | + |
| 64 | + assert BareError.error_code == "BARE" |
| 65 | + |
| 66 | + |
| 67 | +def test_error_classes_use_the_metaclass() -> None: |
| 68 | + """Concrete errors are instances of the public ``BaseErrorMeta``.""" |
| 69 | + assert type(NotFoundError) is BaseErrorMeta |
| 70 | + |
| 71 | + |
| 72 | +def test_model_is_parametrized_response() -> None: |
| 73 | + """The derived model validates the exact declared code.""" |
| 74 | + instance = NotFoundError.model(code=Code.NOT_FOUND, detail="gone") |
| 75 | + |
| 76 | + assert isinstance(instance, ErrorResponse) |
| 77 | + assert instance.code is Code.NOT_FOUND |
| 78 | + |
| 79 | + |
| 80 | +def test_model_title_is_clean() -> None: |
| 81 | + """OpenAPI titles render the code value, not the enum ``repr()``.""" |
| 82 | + assert NotFoundError.model.model_json_schema()["title"] == "ErrorResponse[NOT_FOUND]" |
| 83 | + |
| 84 | + |
| 85 | +def test_unparametrized_model_title_is_class_name() -> None: |
| 86 | + """The generic base keeps its plain class name as the title.""" |
| 87 | + assert ErrorResponse.model_json_schema()["title"] == "ErrorResponse" |
| 88 | + |
| 89 | + |
| 90 | +def test_intermediate_base_has_no_code() -> None: |
| 91 | + """A generic base parametrized with a ``TypeVar`` declares no code.""" |
| 92 | + with pytest.raises(AttributeError, match="error_code is not defined"): |
| 93 | + _ = AppError.error_code |
| 94 | + |
| 95 | + |
| 96 | +def test_intermediate_base_has_no_model() -> None: |
| 97 | + """A generic base parametrized with a ``TypeVar`` declares no model.""" |
| 98 | + with pytest.raises(AttributeError, match="model is not defined"): |
| 99 | + _ = AppError.model |
| 100 | + |
| 101 | + |
| 102 | +def test_non_literal_parametrization_rejected() -> None: |
| 103 | + """``BaseError[str]`` fails at class definition time, not at request time.""" |
| 104 | + with pytest.raises(TypeError, match="exactly one string code"): |
| 105 | + |
| 106 | + class _Bad(BaseError[str]): |
| 107 | + http_status = HTTPStatus.BAD_REQUEST |
| 108 | + |
| 109 | + |
| 110 | +def test_enum_class_parametrization_rejected() -> None: |
| 111 | + """Passing the whole enum instead of ``Literal[member]`` is rejected.""" |
| 112 | + with pytest.raises(TypeError, match="exactly one string code"): |
| 113 | + |
| 114 | + class _Bad(BaseError[Code]): |
| 115 | + http_status = HTTPStatus.BAD_REQUEST |
| 116 | + |
| 117 | + |
| 118 | +def test_multi_literal_parametrization_rejected() -> None: |
| 119 | + """A ``Literal`` with several codes is rejected.""" |
| 120 | + with pytest.raises(TypeError, match="exactly one string code"): |
| 121 | + |
| 122 | + class _Bad(BaseError[Literal[Code.NOT_FOUND, Code.FORBIDDEN]]): |
| 123 | + http_status = HTTPStatus.BAD_REQUEST |
| 124 | + |
| 125 | + |
| 126 | +def test_response_base_inherited_from_generic_base() -> None: |
| 127 | + """A concrete error parametrizes the ``response_base`` of its base class.""" |
| 128 | + response = CustomError("no").to_response() |
| 129 | + |
| 130 | + assert isinstance(response, WideResponse) |
| 131 | + assert response.extra == "x" |
| 132 | + |
| 133 | + |
| 134 | +def test_response_base_declared_in_own_namespace() -> None: |
| 135 | + """A class declaring both code and ``response_base`` uses its own base.""" |
| 136 | + |
| 137 | + class InlineError(BaseError[Literal["INLINE"]]): |
| 138 | + """Error overriding the response base in place.""" |
| 139 | + |
| 140 | + http_status = HTTPStatus.CONFLICT |
| 141 | + response_base = WideResponse |
| 142 | + |
| 143 | + assert isinstance(InlineError("x").to_response(), WideResponse) |
| 144 | + |
| 145 | + |
| 146 | +def test_detail_defaults_to_description() -> None: |
| 147 | + """Without an explicit detail the ``description`` is used.""" |
| 148 | + assert NotFoundError().detail == "Entity does not exist" |
| 149 | + |
| 150 | + |
| 151 | +def test_detail_falls_back_to_status_phrase() -> None: |
| 152 | + """Without a description the HTTP status phrase is used.""" |
| 153 | + assert ForbiddenError().detail == HTTPStatus.FORBIDDEN.phrase |
| 154 | + |
| 155 | + |
| 156 | +def test_explicit_detail_wins() -> None: |
| 157 | + """An explicit detail overrides all defaults.""" |
| 158 | + assert NotFoundError("gone").detail == "gone" |
| 159 | + |
| 160 | + |
| 161 | +def test_headers_are_stored() -> None: |
| 162 | + """Extra headers are passed through to ``HTTPException``.""" |
| 163 | + assert NotFoundError(headers={"WWW-Authenticate": "Bearer"}).headers == {"WWW-Authenticate": "Bearer"} |
| 164 | + |
| 165 | + |
| 166 | +def test_status_code_comes_from_http_status() -> None: |
| 167 | + """The ``HTTPException`` status code mirrors ``http_status``.""" |
| 168 | + assert NotFoundError().status_code == HTTPStatus.NOT_FOUND |
| 169 | + |
| 170 | + |
| 171 | +def test_to_response_carries_code_and_detail() -> None: |
| 172 | + """``to_response()`` builds the parametrized model from the instance.""" |
| 173 | + response = NotFoundError("gone").to_response() |
| 174 | + |
| 175 | + assert type(response) is NotFoundError.model |
| 176 | + assert response.code is Code.NOT_FOUND |
| 177 | + assert response.detail == "gone" |
| 178 | + |
| 179 | + |
| 180 | +def test_metaclass_standalone_defaults_to_error_response() -> None: |
| 181 | + """The metaclass works without ``BaseError``, falling back to ``ErrorResponse``.""" |
| 182 | + |
| 183 | + class RogueBase[T: str](metaclass=BaseErrorMeta): |
| 184 | + """Generic base using the metaclass directly.""" |
| 185 | + |
| 186 | + class RogueError(RogueBase[Literal["ROGUE"]]): |
| 187 | + """Concrete error outside the BaseError hierarchy.""" |
| 188 | + |
| 189 | + assert issubclass(RogueError.model, ErrorResponse) |
| 190 | + |
| 191 | + |
| 192 | +def test_two_parameter_generic_base_declares_no_code() -> None: |
| 193 | + """A base parametrized with two arguments is skipped by code extraction.""" |
| 194 | + |
| 195 | + class TwoParam[T: str, U: str](BaseError[T]): |
| 196 | + """Base carrying an extra, unrelated type parameter.""" |
| 197 | + |
| 198 | + class Odd(TwoParam[Literal["ODD"], Literal["X"]]): |
| 199 | + """Parametrization the extractor must skip.""" |
| 200 | + |
| 201 | + http_status = HTTPStatus.BAD_REQUEST |
| 202 | + |
| 203 | + with pytest.raises(AttributeError, match="error_code is not defined"): |
| 204 | + _ = Odd.error_code |
0 commit comments