Skip to content

Commit 7703591

Browse files
committed
Handle missing MIME types in MediaTypeFinder
It's possible for a request not to have a MIME type (mimetype=None). Previously, this would result in an exception from within fnmatch(): TypeError: expected str, bytes or os.PathLike object, not NoneType This change guards against that condition and raises MediaTypeNotFound instead. Tests have also been added for this module.
1 parent 4ce032c commit 7703591

File tree

2 files changed

+62
-3
lines changed

2 files changed

+62
-3
lines changed

openapi_core/templating/media_types/finders.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,9 @@ def find(self, request):
1212
if request.mimetype in self.content:
1313
return self.content / request.mimetype, request.mimetype
1414

15-
for key, value in self.content.items():
16-
if fnmatch.fnmatch(request.mimetype, key):
17-
return value, key
15+
if request.mimetype:
16+
for key, value in self.content.items():
17+
if fnmatch.fnmatch(request.mimetype, key):
18+
return value, key
1819

1920
raise MediaTypeNotFound(request.mimetype, list(self.content.keys()))
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import pytest
2+
3+
from openapi_core.spec.paths import SpecPath
4+
from openapi_core.templating.media_types.exceptions import MediaTypeNotFound
5+
from openapi_core.templating.media_types.finders import MediaTypeFinder
6+
from openapi_core.testing import MockRequest
7+
8+
9+
class TestMediaTypes:
10+
@pytest.fixture(scope="class")
11+
def spec(self):
12+
return {
13+
"application/json": {"schema": {"type": "object"}},
14+
"text/*": {"schema": {"type": "object"}},
15+
}
16+
17+
@pytest.fixture(scope="class")
18+
def content(self, spec):
19+
return SpecPath.from_spec(spec)
20+
21+
@pytest.fixture(scope="class")
22+
def finder(self, content):
23+
return MediaTypeFinder(content)
24+
25+
def test_exact(self, finder, content):
26+
request = MockRequest(
27+
"http://petstore.swagger.io",
28+
"get",
29+
"/pets",
30+
mimetype="application/json",
31+
)
32+
33+
_, mimetype = finder.find(request)
34+
assert mimetype == "application/json"
35+
36+
def test_match(self, finder, content):
37+
request = MockRequest(
38+
"http://petstore.swagger.io", "get", "/pets", mimetype="text/html"
39+
)
40+
41+
_, mimetype = finder.find(request)
42+
assert mimetype == "text/*"
43+
44+
def test_not_found(self, finder, content):
45+
request = MockRequest(
46+
"http://petstore.swagger.io", "get", "/pets", mimetype="unknown"
47+
)
48+
49+
with pytest.raises(MediaTypeNotFound):
50+
finder.find(request)
51+
52+
def test_missing(self, finder, content):
53+
request = MockRequest(
54+
"http://petstore.swagger.io", "get", "/pets", mimetype=None
55+
)
56+
57+
with pytest.raises(MediaTypeNotFound):
58+
finder.find(request)

0 commit comments

Comments
 (0)