Skip to content

Commit 1485be9

Browse files
committed
bpo-31040: Reject undotted extensions in mimetypes.add_type
Extensions that don't start with a dot will never be found by methods/functions that act on the registry, so we should stop users from mistakenly adding them. The one exception is the empty string extension. This could be in use to detect absent extensions, so instead of raising a ValueError we emit a warning.
1 parent 2e6a0e5 commit 1485be9

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

Lib/mimetypes.py

+9
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
import sys
2828
import posixpath
2929
import urllib.parse
30+
import warnings
3031
try:
3132
import winreg as _winreg
3233
except ImportError:
@@ -88,7 +89,15 @@ def add_type(self, type, ext, strict=True):
8889
If strict is true, information will be added to
8990
list of standard types, else to the list of non-standard
9091
types.
92+
93+
Non-empty extensions that don't start with a '.' are not
94+
valid, so a ValueError will be raised if they are
95+
specified.
9196
"""
97+
if not ext:
98+
warnings.warn('Empty extension specified')
99+
elif not ext.startswith('.'):
100+
raise ValueError("Extensions should start with a '.'")
92101
self.types_map[strict][ext] = type
93102
exts = self.types_map_inv[strict].setdefault(type, [])
94103
if ext not in exts:

Lib/test/test_mimetypes.py

+12
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import pathlib
55
import sys
66
import unittest
7+
import warnings
78

89
from test import support
910
from platform import win32_edition
@@ -168,6 +169,17 @@ def test_added_types_are_used(self):
168169
mime_type, _ = mimetypes.guess_type('test.myext')
169170
self.assertEqual('testing/type', mime_type)
170171

172+
def test_add_type_with_undotted_extension_raises_exception(self):
173+
with self.assertRaises(ValueError):
174+
mimetypes.add_type('testing/type', 'undotted')
175+
176+
def test_add_type_with_empty_extension_emits_warning(self):
177+
with warnings.catch_warnings(record=True) as wlog:
178+
mimetypes.add_type('testing/type', '')
179+
self.assertEqual(1, len(wlog))
180+
warning = wlog[0]
181+
self.assertEqual('Empty extension specified', str(warning.message))
182+
171183

172184
@unittest.skipUnless(sys.platform.startswith("win"), "Windows only")
173185
class Win32MimeTypesTestCase(unittest.TestCase):
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Reject undotted extensions in mimetypes.add_type.

0 commit comments

Comments
 (0)