From 4588bc1e8fdf7c2155dde2c6796a507209ff2eb6 Mon Sep 17 00:00:00 2001 From: Yushion Yang <2685310462@qq.com> Date: Fri, 23 Oct 2026 19:14:24 +0800 Subject: [PATCH] Return no match for empty supported media types --- mimeparse/__init__.py | 4 +++- mimeparse_test.py | 16 ++++++++++++++++ testdata.json | 8 ++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/mimeparse/__init__.py b/mimeparse/__init__.py index d4c3683..dc80a28 100644 --- a/mimeparse/__init__.py +++ b/mimeparse/__init__.py @@ -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') @@ -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 '' diff --git a/mimeparse_test.py b/mimeparse_test.py index 5e413e3..19691a5 100755 --- a/mimeparse_test.py +++ b/mimeparse_test.py @@ -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) diff --git a/testdata.json b/testdata.json index 2ceee39..1d80c20 100644 --- a/testdata.json +++ b/testdata.json @@ -66,6 +66,14 @@ ], "best_match": [ + [ + [ + [], + "application/json" + ], + "", + "no match when no media types are supported" + ], [ [ ["application/json", "text/html"],