Skip to content

Commit

Permalink
馃悰 Fix response_model not invalidating None (#2725)
Browse files Browse the repository at this point in the history
Co-authored-by: Taneli Hukkinen <hukkinj1@users.noreply.github.com>
Co-authored-by: Sebasti谩n Ram铆rez <tiangolo@gmail.com>
  • Loading branch information
3 people committed Aug 22, 2022
1 parent 12f60ca commit 634cf22
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
2 changes: 1 addition & 1 deletion fastapi/utils.py
Expand Up @@ -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,
Expand Down
34 changes: 33 additions & 1 deletion tests/test_validate_response.py
@@ -1,4 +1,4 @@
from typing import List, Optional
from typing import List, Optional, Union

import pytest
from fastapi import FastAPI
Expand All @@ -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"]}
Expand All @@ -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")
Expand Down

0 comments on commit 634cf22

Please sign in to comment.