From 57ff677027eec19c0d659e050675e7a320123637 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 22 Dec 2018 18:20:01 +0400 Subject: [PATCH] :white_check_mark: Add tests for validation errors in response --- tests/test_serialize_response.py | 51 ++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 tests/test_serialize_response.py diff --git a/tests/test_serialize_response.py b/tests/test_serialize_response.py new file mode 100644 index 000000000..c0382b899 --- /dev/null +++ b/tests/test_serialize_response.py @@ -0,0 +1,51 @@ +from typing import List + +import pytest +from fastapi import FastAPI +from pydantic import BaseModel, ValidationError +from starlette.testclient import TestClient + +app = FastAPI() + + +class Item(BaseModel): + name: str + price: float = None + owner_ids: List[int] = None + + +@app.get("/items/invalid", response_model=Item) +def get_invalid(): + return {"name": "invalid", "price": "foo"} + + +@app.get("/items/innerinvalid", response_model=Item) +def get_innerinvalid(): + return {"name": "double invalid", "price": "foo", "owner_ids": ["foo", "bar"]} + + +@app.get("/items/invalidlist", response_model=List[Item]) +def get_invalidlist(): + return [ + {"name": "foo"}, + {"name": "bar", "price": "bar"}, + {"name": "baz", "price": "baz"}, + ] + + +client = TestClient(app) + + +def test_invalid(): + with pytest.raises(ValidationError): + client.get("/items/invalid") + + +def test_double_invalid(): + with pytest.raises(ValidationError): + client.get("/items/innerinvalid") + + +def test_invalid_list(): + with pytest.raises(ValidationError): + client.get("/items/invalidlist")