pgjones / quart-schema

Quart-Schema is a Quart extension that provides schema validation and auto-generated API documentation.
MIT License
78 stars 23 forks source link

Response header validation with pydantic Base Model class #52

Closed bselman1 closed 1 year ago

bselman1 commented 1 year ago

An exception is raised when using the validate_response decorator with a header class argument set to a class that inherits from a pydantic base model instead of a dataclass or dictionary.

class TestModel(BaseModel):
    id: int

class TestHeaders(BaseModel):
    content_type: str = Field(default = 'text/html', const = True, alias = 'content-type')

@validate_response(TestModel, 200, TestHeaders)
def test_endpoint():
    model = TestModel(id = 1)
    headers = TestHeaders()
    return model, 200, headers

During request execution a ResponseHeadersValidationError exception will be raised on line 243 of validation.py.

The issue seems to be that the line is incorrectly checking the type of the value model against the expected header class:

if isinstance(headers, dict):
    headers_model_value = _convert_headers(headers, headers_model_class)
elif type(value) == headers_model_class:
    headers_model_value = headers
elif is_dataclass(headers):
    headers_model_value = headers_model_class(**asdict(headers))
else:
    raise ResponseHeadersValidationError()

when it should instead be checking the type of the provided headers against the expected header class:

if isinstance(headers, dict):
    headers_model_value = _convert_headers(headers, headers_model_class)
elif type(headers) == headers_model_class:
    headers_model_value = headers
elif is_dataclass(headers):
    headers_model_value = headers_model_class(**asdict(headers))
else:
    raise ResponseHeadersValidationError()
pgjones commented 1 year ago

Fixed in 070cd043622e2d67db6a9ab7297c9c09b11745c2