Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛 Fix response_model not invalidating None #2725

Merged
merged 5 commits into from Aug 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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