diff --git a/openapi_core/templating/media_types/finders.py b/openapi_core/templating/media_types/finders.py index c9fa7d86..3425be96 100644 --- a/openapi_core/templating/media_types/finders.py +++ b/openapi_core/templating/media_types/finders.py @@ -12,8 +12,9 @@ def find(self, request): if request.mimetype in self.content: return self.content / request.mimetype, request.mimetype - for key, value in self.content.items(): - if fnmatch.fnmatch(request.mimetype, key): - return value, key + if request.mimetype: + for key, value in self.content.items(): + if fnmatch.fnmatch(request.mimetype, key): + return value, key raise MediaTypeNotFound(request.mimetype, list(self.content.keys())) diff --git a/tests/unit/templating/test_media_types_finders.py b/tests/unit/templating/test_media_types_finders.py new file mode 100644 index 00000000..4c1fe9ef --- /dev/null +++ b/tests/unit/templating/test_media_types_finders.py @@ -0,0 +1,47 @@ +import pytest + +from openapi_core.spec.paths import SpecPath +from openapi_core.templating.media_types.exceptions import MediaTypeNotFound +from openapi_core.templating.media_types.finders import MediaTypeFinder +from openapi_core.testing import MockResponse + + +class TestMediaTypes: + @pytest.fixture(scope="class") + def spec(self): + return { + "application/json": {"schema": {"type": "object"}}, + "text/*": {"schema": {"type": "object"}}, + } + + @pytest.fixture(scope="class") + def content(self, spec): + return SpecPath.from_spec(spec) + + @pytest.fixture(scope="class") + def finder(self, content): + return MediaTypeFinder(content) + + def test_exact(self, finder, content): + response = MockResponse("", mimetype="application/json") + + _, mimetype = finder.find(response) + assert mimetype == "application/json" + + def test_match(self, finder, content): + response = MockResponse("", mimetype="text/html") + + _, mimetype = finder.find(response) + assert mimetype == "text/*" + + def test_not_found(self, finder, content): + response = MockResponse("", mimetype="unknown") + + with pytest.raises(MediaTypeNotFound): + finder.find(response) + + def test_missing(self, finder, content): + response = MockResponse("", mimetype=None) + + with pytest.raises(MediaTypeNotFound): + finder.find(response)