diff --git a/Lib/mimetypes.py b/Lib/mimetypes.py index d7c4e8444f8dec..6c7d343135088e 100644 --- a/Lib/mimetypes.py +++ b/Lib/mimetypes.py @@ -94,7 +94,12 @@ def add_type(self, type, ext, strict=True): If strict is true, information will be added to list of standard types, else to the list of non-standard types. + + Valid extensions are empty or start with a '.'. + Raise a ValueError for invalid extensions. """ + if ext and not ext.startswith('.'): + raise ValueError("Extensions should start with a '.' or be empty") self.types_map[strict][ext] = type exts = self.types_map_inv[strict].setdefault(type, []) if ext not in exts: diff --git a/Lib/test/test_mimetypes.py b/Lib/test/test_mimetypes.py index 58f6a4dfae08ba..9bb00c106f4b5c 100644 --- a/Lib/test/test_mimetypes.py +++ b/Lib/test/test_mimetypes.py @@ -3,6 +3,7 @@ import os import sys import unittest.mock +import warnings from test import support from test.support import os_helper @@ -305,6 +306,24 @@ def test_keywords_args_api(self): self.assertEqual(self.db.guess_extension( type='image/jpg', strict=False), '.jpg') + def test_added_types_are_used(self): + mimetypes.add_type('testing/default-type', '') + mime_type, _ = mimetypes.guess_type('') + self.assertEqual(mime_type, 'testing/default-type') + + mime_type, _ = mimetypes.guess_type('test.myext') + self.assertEqual(mime_type, None) + + mimetypes.add_type('testing/type', '.myext') + mime_type, _ = mimetypes.guess_type('test.myext') + self.assertEqual(mime_type, 'testing/type') + + def test_add_type_with_undotted_extension_raises_exception(self): + with self.assertRaisesRegex( + ValueError, "Extensions should start with a '.' or be empty" + ): + mimetypes.add_type('testing/type', 'undotted') + @unittest.skipUnless(sys.platform.startswith("win"), "Windows only") class Win32MimeTypesTestCase(unittest.TestCase): diff --git a/Misc/NEWS.d/next/Library/2019-09-10-09-28-52.gh-issue-75223.VyAJS9.rst b/Misc/NEWS.d/next/Library/2019-09-10-09-28-52.gh-issue-75223.VyAJS9.rst new file mode 100644 index 00000000000000..bafcbe1b714b72 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2019-09-10-09-28-52.gh-issue-75223.VyAJS9.rst @@ -0,0 +1 @@ +Reject undotted extensions in :meth:`mimetypes.MimeTypes.add_type`.