Skip to content
Draft
Show file tree
Hide file tree
Changes from 5 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
7 changes: 7 additions & 0 deletions Lib/mimetypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import sys
import posixpath
import urllib.parse
import warnings

try:
from _winapi import _mimetypes_read_windows_registry
Expand Down Expand Up @@ -94,7 +95,13 @@ 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.

Non-empty extensions that don't start with a '.' are not
valid, so a ValueError will be raised if they are
specified.
"""
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:
Expand Down
19 changes: 19 additions & 0 deletions Lib/test/test_mimetypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import os
import sys
import unittest.mock
import warnings

from test import support
from test.support import os_helper
Expand Down Expand Up @@ -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):
mime_type, _ = mimetypes.guess_type('test.myext')
self.assertEqual(None, mime_type)
mimetypes.add_type('testing/type', '.myext')
mime_type, _ = mimetypes.guess_type('test.myext')
self.assertEqual('testing/type', mime_type)

def test_add_type_with_undotted_extension_raises_exception(self):
with self.assertRaises(ValueError):
mimetypes.add_type('testing/type', 'undotted')

def test_add_type_with_empty_extension_emits_warning(self):
with warnings.catch_warnings(record=True) as wlog:
mimetypes.add_type('testing/type', '')
self.assertEqual(1, len(wlog))
warning = wlog[0]
self.assertEqual('Empty extension specified', str(warning.message))


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