From 634cf22584fc4fd9ee53cfdf0ad6d48a2830ac34 Mon Sep 17 00:00:00 2001 From: Taneli Hukkinen <3275109+hukkin@users.noreply.github.com> Date: Mon, 22 Aug 2022 22:17:45 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Fix=20`response=5Fmodel`=20not?= =?UTF-8?q?=20invalidating=20`None`=20(#2725)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Taneli Hukkinen Co-authored-by: Sebastián Ramírez --- fastapi/utils.py | 2 +- tests/test_validate_response.py | 34 ++++++++++++++++++++++++++++++++- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/fastapi/utils.py b/fastapi/utils.py index 887d57c90..40750a5b3 100644 --- a/fastapi/utils.py +++ b/fastapi/utils.py @@ -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, diff --git a/tests/test_validate_response.py b/tests/test_validate_response.py index 45d303e20..62f51c960 100644 --- a/tests/test_validate_response.py +++ b/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 @@ -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")