Skip to content
Closed
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
4 changes: 3 additions & 1 deletion mimeparse/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ def best_match(supported: Iterable[str], header: str) -> str:
conforms to the format of the HTTP Accept: header. The value of 'supported'
is a list of mime-types. The list of supported mime-types should be sorted
in order of increasing desirability, in case of a situation where there is
a tie.
a tie. Returns an empty string if no supported mime-type is acceptable.

>>> best_match(['application/xbel+xml', 'text/xml'],
'text/*;q=0.5,*/*; q=0.1')
Expand All @@ -205,6 +205,8 @@ def best_match(supported: Iterable[str], header: str) -> str:
mime_type
))
pos += 1
if not weighted_matches:
return ''
weighted_matches.sort()

return weighted_matches[-1][0][0] and weighted_matches[-1][2] or ''
Expand Down
16 changes: 16 additions & 0 deletions mimeparse_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,22 @@ def test_best_match(self):
for args, expected, description in self.test_data['best_match']:
self._test_best_match(args, expected, description)

def test_best_match_empty_iterables(self):
for supported in ((), iter([]), (item for item in [])):
with self.subTest(supported=supported):
self.assertEqual(mimeparse.best_match(supported, '*/*'), '')

def test_best_match_generator(self):
supported = (item for item in ['text/plain', 'application/json'])
self.assertEqual(
mimeparse.best_match(supported, 'application/json'),
'application/json',
)

def test_best_match_empty_supported_invalid_header(self):
with self.assertRaises(mimeparse.MimeTypeParseException):
mimeparse.best_match([], 'invalid')

def test_parse_mime_type(self):
for args, expected in self.test_data['parse_mime_type']:
self._test_parse_mime_type(args, expected)
Expand Down
8 changes: 8 additions & 0 deletions testdata.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,14 @@
],

"best_match": [
[
[
[],
"application/json"
],
"",
"no match when no media types are supported"
],
[
[
["application/json", "text/html"],
Expand Down