mirror of https://github.com/tiangolo/fastapi.git
🐛 Fix `response_model` not invalidating `None` (#2725)
Co-authored-by: Taneli Hukkinen <hukkinj1@users.noreply.github.com> Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
This commit is contained in:
parent
12f60cac7a
commit
634cf22584
|
|
@ -50,7 +50,7 @@ def create_response_field(
|
|||
type_: Type[Any],
|
||||
class_validators: Optional[Dict[str, Validator]] = None,
|
||||
default: Optional[Any] = None,
|
||||
required: Union[bool, UndefinedType] = False,
|
||||
required: Union[bool, UndefinedType] = True,
|
||||
model_config: Type[BaseConfig] = BaseConfig,
|
||||
field_info: Optional[FieldInfo] = None,
|
||||
alias: Optional[str] = None,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
from typing import List, Optional
|
||||
from typing import List, Optional, Union
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
|
|
@ -19,6 +19,19 @@ def get_invalid():
|
|||
return {"name": "invalid", "price": "foo"}
|
||||
|
||||
|
||||
@app.get("/items/invalidnone", response_model=Item)
|
||||
def get_invalid_none():
|
||||
return None
|
||||
|
||||
|
||||
@app.get("/items/validnone", response_model=Union[Item, None])
|
||||
def get_valid_none(send_none: bool = False):
|
||||
if send_none:
|
||||
return None
|
||||
else:
|
||||
return {"name": "invalid", "price": 3.2}
|
||||
|
||||
|
||||
@app.get("/items/innerinvalid", response_model=Item)
|
||||
def get_innerinvalid():
|
||||
return {"name": "double invalid", "price": "foo", "owner_ids": ["foo", "bar"]}
|
||||
|
|
@ -41,6 +54,25 @@ def test_invalid():
|
|||
client.get("/items/invalid")
|
||||
|
||||
|
||||
def test_invalid_none():
|
||||
with pytest.raises(ValidationError):
|
||||
client.get("/items/invalidnone")
|
||||
|
||||
|
||||
def test_valid_none_data():
|
||||
response = client.get("/items/validnone")
|
||||
data = response.json()
|
||||
assert response.status_code == 200
|
||||
assert data == {"name": "invalid", "price": 3.2, "owner_ids": None}
|
||||
|
||||
|
||||
def test_valid_none_none():
|
||||
response = client.get("/items/validnone", params={"send_none": "true"})
|
||||
data = response.json()
|
||||
assert response.status_code == 200
|
||||
assert data is None
|
||||
|
||||
|
||||
def test_double_invalid():
|
||||
with pytest.raises(ValidationError):
|
||||
client.get("/items/innerinvalid")
|
||||
|
|
|
|||
Loading…
Reference in New Issue