Debian Codegraph @

tests/test_compat.py

raw
1 from typing import Any, cast
2
3 from fastapi import FastAPI, UploadFile
4 from fastapi._compat import (
5 Undefined,
6 is_uploadfile_sequence_annotation,
7 )
8 from fastapi._compat.shared import is_bytes_sequence_annotation
9 from fastapi.testclient import TestClient
10 from pydantic import BaseModel, ConfigDict
11 from pydantic.fields import FieldInfo
12
13
14 def test_model_field_default_required():
15 from fastapi._compat import v2
16
17 # For coverage
18 field_info = FieldInfo(annotation=str)
19 field = v2.ModelField(name="foo", field_info=field_info)
20 assert field.default is Undefined
21
22
23 def test_complex():
24 app = FastAPI()
25
26 @app.post("/")
27 def foo(foo: str | list[int]):
28 return foo
29
30 client = TestClient(app)
31
32 response = client.post("/", json="bar")
33 assert response.status_code == 200, response.text
34 assert response.json() == "bar"
35
36 response2 = client.post("/", json=[1, 2])
37 assert response2.status_code == 200, response2.text
38 assert response2.json() == [1, 2]
39
40
41 def test_propagates_pydantic2_model_config():
42 app = FastAPI()
43
44 class Missing:
45 def __bool__(self):
46 return False
47
48 class EmbeddedModel(BaseModel):
49 model_config = ConfigDict(arbitrary_types_allowed=True)
50 value: str | Missing = Missing()
51
52 class Model(BaseModel):
53 model_config = ConfigDict(
54 arbitrary_types_allowed=True,
55 )
56 value: str | Missing = Missing()
57 embedded_model: EmbeddedModel = EmbeddedModel()
58
59 @app.post("/")
60 def foo(req: Model) -> dict[str, str | None]:
61 value = req.value
62 if isinstance(value, Missing):
63 value = None
64 embedded_value = req.embedded_model.value
65 if isinstance(embedded_value, Missing):
66 embedded_value = None
67 return {
68 "value": value,
69 "embedded_value": embedded_value,
70 }
71
72 client = TestClient(app)
73
74 response = client.post("/", json={})
75 assert response.status_code == 200, response.text
76 assert response.json() == {
77 "value": None,
78 "embedded_value": None,
79 }
80
81 response2 = client.post(
82 "/", json={"value": "foo", "embedded_model": {"value": "bar"}}
83 )
84 assert response2.status_code == 200, response2.text
85 assert response2.json() == {
86 "value": "foo",
87 "embedded_value": "bar",
88 }
89
90
91 def test_is_bytes_sequence_annotation_union():
92 # For coverage
93 # TODO: in theory this would allow declaring types that could be lists of bytes
94 # to be read from files and other types, but I'm not even sure it's a good idea
95 # to support it as a first class "feature"
96 assert is_bytes_sequence_annotation(list[str] | list[bytes])
97
98
99 def test_is_uploadfile_sequence_annotation():
100 # For coverage
101 # TODO: in theory this would allow declaring types that could be lists of UploadFile
102 # and other types, but I'm not even sure it's a good idea to support it as a first
103 # class "feature"
104 assert is_uploadfile_sequence_annotation(list[str] | list[UploadFile])
105
106
107 def test_serialize_sequence_value_with_optional_list():
108 """Test that serialize_sequence_value handles optional lists correctly."""
109 from fastapi._compat import v2
110
111 field_info = FieldInfo(annotation=cast(Any, list[str] | None))
112 field = v2.ModelField(name="items", field_info=field_info)
113 result = v2.serialize_sequence_value(field=field, value=["a", "b", "c"])
114 assert result == ["a", "b", "c"]
115 assert isinstance(result, list)
116
117
118 def test_serialize_sequence_value_with_optional_list_pipe_union():
119 """Test that serialize_sequence_value handles optional lists correctly (with new syntax)."""
120 from fastapi._compat import v2
121
122 field_info = FieldInfo(annotation=cast(Any, list[str] | None))
123 field = v2.ModelField(name="items", field_info=field_info)
124 result = v2.serialize_sequence_value(field=field, value=["a", "b", "c"])
125 assert result == ["a", "b", "c"]
126 assert isinstance(result, list)
127
128
129 def test_serialize_sequence_value_with_none_first_in_union():
130 """Test that serialize_sequence_value handles Union[None, List[...]] correctly."""
131 from typing import Union
132
133 from fastapi._compat import v2
134
135 # Use Union[None, list[str]] to ensure None comes first in the union args
136 field_info = FieldInfo(annotation=cast(Any, Union[None, list[str]])) # noqa: UP007
137 field = v2.ModelField(name="items", field_info=field_info)
138 result = v2.serialize_sequence_value(field=field, value=["x", "y"])
139 assert result == ["x", "y"]
140 assert isinstance(result, list)