Browse Source

🐛 Fix `response_model` not invalidating `None` (#2725)

Co-authored-by: Taneli Hukkinen <[email protected]>
Co-authored-by: Sebastián Ramírez <[email protected]>
pull/5301/head
Taneli Hukkinen 3 years ago
committed by GitHub
parent
commit
634cf22584
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 2
      fastapi/utils.py
  2. 34
      tests/test_validate_response.py

2
fastapi/utils.py

@ -50,7 +50,7 @@ def create_response_field(
type_: Type[Any], type_: Type[Any],
class_validators: Optional[Dict[str, Validator]] = None, class_validators: Optional[Dict[str, Validator]] = None,
default: Optional[Any] = None, default: Optional[Any] = None,
required: Union[bool, UndefinedType] = False, required: Union[bool, UndefinedType] = True,
model_config: Type[BaseConfig] = BaseConfig, model_config: Type[BaseConfig] = BaseConfig,
field_info: Optional[FieldInfo] = None, field_info: Optional[FieldInfo] = None,
alias: Optional[str] = None, alias: Optional[str] = None,

34
tests/test_validate_response.py

@ -1,4 +1,4 @@
from typing import List, Optional from typing import List, Optional, Union
import pytest import pytest
from fastapi import FastAPI from fastapi import FastAPI
@ -19,6 +19,19 @@ def get_invalid():
return {"name": "invalid", "price": "foo"} 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) @app.get("/items/innerinvalid", response_model=Item)
def get_innerinvalid(): def get_innerinvalid():
return {"name": "double invalid", "price": "foo", "owner_ids": ["foo", "bar"]} return {"name": "double invalid", "price": "foo", "owner_ids": ["foo", "bar"]}
@ -41,6 +54,25 @@ def test_invalid():
client.get("/items/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(): def test_double_invalid():
with pytest.raises(ValidationError): with pytest.raises(ValidationError):
client.get("/items/innerinvalid") client.get("/items/innerinvalid")

Loading…
Cancel
Save