python-openapi / openapi-core

Openapi-core is a Python library that adds client-side and server-side support for the OpenAPI v3.0 and OpenAPI v3.1 specification.
BSD 3-Clause "New" or "Revised" License
307 stars 132 forks source link

[Bug]: `DjangoOpenAPIResponse` no longer type compatible with `unmarshal_response` #938

Open jceipek opened 2 weeks ago

jceipek commented 2 weeks ago

Actual Behavior

There is a type error here when using werkzeug Version 3.1.2 or newer:

from django.conf import settings
from openapi_core import unmarshal_response
from openapi_core.contrib.django import DjangoOpenAPIRequest, DjangoOpenAPIResponse

def test(openapi_request: DjangoOpenAPIRequest, openapi_response: DjangoOpenAPIResponse):
        return unmarshal_response(
            request=openapi_request,
            response=openapi_response, # type error on this line
            spec=settings.OPENAPI_SPEC,
        )

Expected Behavior

No type errors in the provided sample code.

Steps to Reproduce

Typecheck the provided sample code using mypy.

OpenAPI Core Version

3.0.0

OpenAPI Core Integration

django

Affected Area(s)

casting, dependencies, unmarshalling

References

Anything else we need to know?

werkzeug Version 3.1.2 changed the definition of Headers because it isn't technically a MutableMapping.

The Response protocol in openapi_core here has Mapping[str, Any]: https://github.com/python-openapi/openapi-core/blob/b8f0644bde3afb4e0273c4cfa8f2ac3eee9f76b3/openapi_core/protocols.py#L122-L123

DjangoOpenAPIResponse has headers typed as Headers from werkzeug: https://github.com/python-openapi/openapi-core/blob/b8f0644bde3afb4e0273c4cfa8f2ac3eee9f76b3/openapi_core/contrib/django/responses.py#L33-L35

Since these are no longer compatible, unmarshal_response can no longer accept DjangoOpenAPIResponse as a response parameter without failing typechecking.

Would you like to implement a fix?

None

andersk commented 1 week ago

MockResponse is also incompatible with Response for the same reason.

https://github.com/python-openapi/openapi-core/blob/b8f0644bde3afb4e0273c4cfa8f2ac3eee9f76b3/openapi_core/testing/responses.py#L20