Skip to content

Handle missing MIME type in MediaTypeFinder #371

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions openapi_core/templating/media_types/finders.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()))
47 changes: 47 additions & 0 deletions tests/unit/templating/test_media_types_finders.py
Original file line number Diff line number Diff line change
@@ -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)