|
| 1 | +"""The test is kept in a separate file to avoid accidental importing of Literal""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from typing import Annotated # Note: _no_ import of Literal. This triggers the bug! |
| 6 | + |
| 7 | +import fastapi |
| 8 | +import pytest |
| 9 | +from fastapi import Depends |
| 10 | +from fastapi.testclient import TestClient |
| 11 | +from pydantic import BaseModel, Field |
| 12 | + |
| 13 | +import cadwyn |
| 14 | +from cadwyn import current_dependency_solver |
| 15 | +from cadwyn.applications import Cadwyn |
| 16 | +from cadwyn.route_generation import VersionedAPIRouter |
| 17 | +from cadwyn.structure.schemas import schema |
| 18 | +from cadwyn.structure.versions import Version, VersionBundle, VersionChange |
| 19 | + |
| 20 | + |
| 21 | +def test__missing_an_import_used_in_annotations_with_from_future_import_annotations(): |
| 22 | + """Regression test for https://github.com/zmievsa/cadwyn/issues/324""" |
| 23 | + |
| 24 | + class MySchema(BaseModel): |
| 25 | + foo: str = Field(coerce_numbers_to_str=True) |
| 26 | + |
| 27 | + class MyVersionChange(VersionChange): |
| 28 | + description = "Hello" |
| 29 | + instructions_to_migrate_to_previous_version = ( |
| 30 | + schema(MySchema).field("foo").had(type=int), |
| 31 | + schema(MySchema).field("foo").didnt_have("coerce_numbers_to_str"), |
| 32 | + ) |
| 33 | + |
| 34 | + app = Cadwyn(versions=VersionBundle(Version("2001-01-01", MyVersionChange), Version("2000-01-01"))) |
| 35 | + router = VersionedAPIRouter() |
| 36 | + |
| 37 | + async def dep_with_solver( |
| 38 | + dependency_solver: Annotated[Literal[fastapi, cadwyn], Depends(current_dependency_solver)], # noqa: F821 # pyright: ignore[reportUndefinedVariable] |
| 39 | + ): |
| 40 | + pass |
| 41 | + |
| 42 | + @router.post( |
| 43 | + "/test", |
| 44 | + dependencies=[Depends(dep_with_solver)], |
| 45 | + ) |
| 46 | + async def route_with_inner_schema_forwardref(dep: MySchema) -> MySchema: |
| 47 | + return dep |
| 48 | + |
| 49 | + app.generate_and_include_versioned_routers(router) |
| 50 | + client_2000 = TestClient(app, headers={app.router.api_version_parameter_name: "2000-01-01"}) |
| 51 | + with pytest.raises( |
| 52 | + ImportError, |
| 53 | + match="You are likely missing an import from typing such as typing.Literal which causes RecursionError", |
| 54 | + ): |
| 55 | + assert client_2000.post("/test", json={"foo": 1}).json() == {"foo": 1} |
0 commit comments