Browse Source

Merge 46b43e13df into 1d434dec47

pull/9704/merge
vvanglro 3 days ago
committed by GitHub
parent
commit
ed39c52ace
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 1
      fastapi/utils.py
  2. 52
      tests/test_response_model_default_factory.py

1
fastapi/utils.py

@ -137,6 +137,7 @@ def create_cloned_field(
new_field.alias = field.alias # type: ignore[misc]
new_field.class_validators = field.class_validators # type: ignore[attr-defined]
new_field.default = field.default # type: ignore[misc]
new_field.default_factory = field.default_factory # type: ignore[attr-defined]
new_field.required = field.required # type: ignore[misc]
new_field.model_config = field.model_config # type: ignore[attr-defined]
new_field.field_info = field.field_info

52
tests/test_response_model_default_factory.py

@ -0,0 +1,52 @@
import functools
import random
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
app = FastAPI()
messages = ["操作成功.", "Successful operation."]
class ResponseModel(BaseModel):
code: int = 200
message: str = Field(default_factory=functools.partial(random.choice, messages))
@app.get(
"/response_model_has_default_factory_return_dict",
response_model=ResponseModel,
)
async def response_model_has_default_factory_return_dict():
return {"code": 200}
@app.get(
"/response_model_has_default_factory_return_model",
response_model=ResponseModel,
)
async def response_model_has_default_factory_return_model():
return ResponseModel()
client = TestClient(app)
def test_response_model_has_default_factory_return_dict():
response = client.get("/response_model_has_default_factory_return_dict")
assert response.status_code == 200, response.text
assert response.json()["code"] == 200
assert response.json()["message"] in messages
def test_response_model_has_default_factory_return_model():
response = client.get("/response_model_has_default_factory_return_model")
assert response.status_code == 200, response.text
assert response.json()["code"] == 200
assert response.json()["message"] in messages
Loading…
Cancel
Save