Debian Codegraph @

Lib/test/test_mimetypes.py

raw
1 import io
2 import mimetypes
3 import os
4 import sys
5 import unittest.mock
6
7 from test import support
8 from test.support import os_helper
9 from platform import win32_edition
10
11 try:
12 import _winapi
13 except ImportError:
14 _winapi = None
15
16
17 def setUpModule():
18 global knownfiles
19 knownfiles = mimetypes.knownfiles
20
21 # Tell it we don't know about external files:
22 mimetypes.knownfiles = []
23 mimetypes.inited = False
24 mimetypes._default_mime_types()
25
26
27 def tearDownModule():
28 # Restore knownfiles to its initial state
29 mimetypes.knownfiles = knownfiles
30
31
32 class MimeTypesTestCase(unittest.TestCase):
33 def setUp(self):
34 self.db = mimetypes.MimeTypes()
35
36 def test_case_sensitivity(self):
37 eq = self.assertEqual
38 eq(self.db.guess_file_type("foobar.html"), ("text/html", None))
39 eq(self.db.guess_type("scheme:foobar.html"), ("text/html", None))
40 eq(self.db.guess_file_type("foobar.HTML"), ("text/html", None))
41 eq(self.db.guess_type("scheme:foobar.HTML"), ("text/html", None))
42 eq(self.db.guess_file_type("foobar.tgz"), ("application/x-tar", "gzip"))
43 eq(self.db.guess_type("scheme:foobar.tgz"), ("application/x-tar", "gzip"))
44 eq(self.db.guess_file_type("foobar.TGZ"), ("application/x-tar", "gzip"))
45 eq(self.db.guess_type("scheme:foobar.TGZ"), ("application/x-tar", "gzip"))
46 eq(self.db.guess_file_type("foobar.tar.Z"), ("application/x-tar", "compress"))
47 eq(self.db.guess_type("scheme:foobar.tar.Z"), ("application/x-tar", "compress"))
48 eq(self.db.guess_file_type("foobar.tar.z"), (None, None))
49 eq(self.db.guess_type("scheme:foobar.tar.z"), (None, None))
50
51 def test_default_data(self):
52 eq = self.assertEqual
53 eq(self.db.guess_file_type("foo.html"), ("text/html", None))
54 eq(self.db.guess_file_type("foo.HTML"), ("text/html", None))
55 eq(self.db.guess_file_type("foo.tgz"), ("application/x-tar", "gzip"))
56 eq(self.db.guess_file_type("foo.tar.gz"), ("application/x-tar", "gzip"))
57 eq(self.db.guess_file_type("foo.tar.Z"), ("application/x-tar", "compress"))
58 eq(self.db.guess_file_type("foo.tar.bz2"), ("application/x-tar", "bzip2"))
59 eq(self.db.guess_file_type("foo.tar.xz"), ("application/x-tar", "xz"))
60
61 def test_data_urls(self):
62 eq = self.assertEqual
63 guess_type = self.db.guess_type
64 eq(guess_type("data:invalidDataWithoutComma"), (None, None))
65 eq(guess_type("data:,thisIsTextPlain"), ("text/plain", None))
66 eq(guess_type("data:;base64,thisIsTextPlain"), ("text/plain", None))
67 eq(guess_type("data:text/x-foo,thisIsTextXFoo"), ("text/x-foo", None))
68
69 def test_file_parsing(self):
70 eq = self.assertEqual
71 sio = io.StringIO("x-application/x-unittest pyunit\n")
72 self.db.readfp(sio)
73 eq(self.db.guess_file_type("foo.pyunit"),
74 ("x-application/x-unittest", None))
75 eq(self.db.guess_extension("x-application/x-unittest"), ".pyunit")
76
77 def test_read_mime_types(self):
78 eq = self.assertEqual
79
80 # Unreadable file returns None
81 self.assertIsNone(mimetypes.read_mime_types("non-existent"))
82
83 with os_helper.temp_dir() as directory:
84 data = "x-application/x-unittest pyunit\n"
85 file = os.path.join(directory, "sample.mimetype")
86 with open(file, 'w', encoding="utf-8") as f:
87 f.write(data)
88 mime_dict = mimetypes.read_mime_types(file)
89 eq(mime_dict[".pyunit"], "x-application/x-unittest")
90
91 data = "x-application/x-unittest2 pyunit2\n"
92 file = os.path.join(directory, "sample2.mimetype")
93 with open(file, 'w', encoding="utf-8") as f:
94 f.write(data)
95 mime_dict = mimetypes.read_mime_types(os_helper.FakePath(file))
96 eq(mime_dict[".pyunit2"], "x-application/x-unittest2")
97
98 # bpo-41048: read_mime_types should read the rule file with 'utf-8' encoding.
99 # Not with locale encoding. _bootlocale has been imported because io.open(...)
100 # uses it.
101 data = "application/no-mans-land Fran\u00E7ais"
102 filename = "filename"
103 fp = io.StringIO(data)
104 with unittest.mock.patch.object(mimetypes, 'open',
105 return_value=fp) as mock_open:
106 mime_dict = mimetypes.read_mime_types(filename)
107 mock_open.assert_called_with(filename, encoding='utf-8')
108 eq(mime_dict[".Français"], "application/no-mans-land")
109
110 def test_non_standard_types(self):
111 eq = self.assertEqual
112 # First try strict
113 eq(self.db.guess_file_type('foo.xul', strict=True), (None, None))
114 eq(self.db.guess_extension('image/jpg', strict=True), None)
115 # And then non-strict
116 eq(self.db.guess_file_type('foo.xul', strict=False), ('text/xul', None))
117 eq(self.db.guess_file_type('foo.XUL', strict=False), ('text/xul', None))
118 eq(self.db.guess_file_type('foo.invalid', strict=False), (None, None))
119 eq(self.db.guess_extension('image/jpg', strict=False), '.jpg')
120 eq(self.db.guess_extension('image/JPG', strict=False), '.jpg')
121
122 def test_filename_with_url_delimiters(self):
123 # bpo-38449: URL delimiters cases should be handled also.
124 # They would have different mime types if interpreted as URL as
125 # compared to when interpreted as filename because of the semicolon.
126 eq = self.assertEqual
127 gzip_expected = ('application/x-tar', 'gzip')
128 for name in (
129 ';1.tar.gz',
130 '?1.tar.gz',
131 '#1.tar.gz',
132 '#1#.tar.gz',
133 ';1#.tar.gz',
134 ';&1=123;?.tar.gz',
135 '?k1=v1&k2=v2.tar.gz',
136 ):
137 for prefix in ('', '/', '\\',
138 'c:', 'c:/', 'c:\\', 'c:/d/', 'c:\\d\\',
139 '//share/server/', '\\\\share\\server\\'):
140 path = prefix + name
141 with self.subTest(path=path):
142 eq(self.db.guess_file_type(path), gzip_expected)
143 eq(self.db.guess_type(path), gzip_expected)
144 expected = (None, None) if os.name == 'nt' else gzip_expected
145 for prefix in ('//', '\\\\', '//share/', '\\\\share\\'):
146 path = prefix + name
147 with self.subTest(path=path):
148 eq(self.db.guess_file_type(path), expected)
149 eq(self.db.guess_type(path), expected)
150 eq(self.db.guess_file_type(r" \"\`;b&b&c |.tar.gz"), gzip_expected)
151 eq(self.db.guess_type(r" \"\`;b&b&c |.tar.gz"), gzip_expected)
152
153 eq(self.db.guess_file_type(r'foo/.tar.gz'), (None, 'gzip'))
154 eq(self.db.guess_type(r'foo/.tar.gz'), (None, 'gzip'))
155 expected = (None, 'gzip') if os.name == 'nt' else gzip_expected
156 eq(self.db.guess_file_type(r'foo\.tar.gz'), expected)
157 eq(self.db.guess_type(r'foo\.tar.gz'), expected)
158 eq(self.db.guess_type(r'scheme:foo\.tar.gz'), gzip_expected)
159
160 def test_url(self):
161 result = self.db.guess_type('http://example.com/host.html')
162 result = self.db.guess_type('http://host.html')
163 msg = 'URL only has a host name, not a file'
164 self.assertSequenceEqual(result, (None, None), msg)
165 result = self.db.guess_type('http://example.com/host.html')
166 msg = 'Should be text/html'
167 self.assertSequenceEqual(result, ('text/html', None), msg)
168 result = self.db.guess_type('http://example.com/host.html#x.tar')
169 self.assertSequenceEqual(result, ('text/html', None))
170 result = self.db.guess_type('http://example.com/host.html?q=x.tar')
171 self.assertSequenceEqual(result, ('text/html', None))
172
173 def test_guess_all_types(self):
174 # First try strict. Use a set here for testing the results because if
175 # test_urllib2 is run before test_mimetypes, global state is modified
176 # such that the 'all' set will have more items in it.
177 all = self.db.guess_all_extensions('text/plain', strict=True)
178 self.assertTrue(set(all) >= {'.bat', '.c', '.h', '.ksh', '.pl', '.txt'})
179 self.assertEqual(len(set(all)), len(all)) # no duplicates
180 # And now non-strict
181 all = self.db.guess_all_extensions('image/jpg', strict=False)
182 self.assertEqual(all, ['.jpg'])
183 # And now for no hits
184 all = self.db.guess_all_extensions('image/jpg', strict=True)
185 self.assertEqual(all, [])
186 # And now for type existing in both strict and non-strict mappings.
187 self.db.add_type('test-type', '.strict-ext')
188 self.db.add_type('test-type', '.non-strict-ext', strict=False)
189 all = self.db.guess_all_extensions('test-type', strict=False)
190 self.assertEqual(all, ['.strict-ext', '.non-strict-ext'])
191 all = self.db.guess_all_extensions('test-type')
192 self.assertEqual(all, ['.strict-ext'])
193 # Test that changing the result list does not affect the global state
194 all.append('.no-such-ext')
195 all = self.db.guess_all_extensions('test-type')
196 self.assertNotIn('.no-such-ext', all)
197
198 def test_encoding(self):
199 filename = support.findfile("mime.types")
200 mimes = mimetypes.MimeTypes([filename])
201 exts = mimes.guess_all_extensions('application/vnd.geocube+xml',
202 strict=True)
203 self.assertEqual(exts, ['.g3', '.g\xb3'])
204
205 def test_init_reinitializes(self):
206 # Issue 4936: make sure an init starts clean
207 # First, put some poison into the types table
208 mimetypes.add_type('foo/bar', '.foobar')
209 self.assertEqual(mimetypes.guess_extension('foo/bar'), '.foobar')
210 # Reinitialize
211 mimetypes.init()
212 # Poison should be gone.
213 self.assertEqual(mimetypes.guess_extension('foo/bar'), None)
214
215 @unittest.skipIf(sys.platform.startswith("win"), "Non-Windows only")
216 def test_guess_known_extensions(self):
217 # Issue 37529
218 # The test fails on Windows because Windows adds mime types from the Registry
219 # and that creates some duplicates.
220 from mimetypes import types_map
221 for v in types_map.values():
222 self.assertIsNotNone(mimetypes.guess_extension(v))
223
224 def test_preferred_extension(self):
225 def check_extensions():
226 self.assertEqual(mimetypes.guess_extension('application/octet-stream'), '.bin')
227 self.assertEqual(mimetypes.guess_extension('application/postscript'), '.ps')
228 self.assertEqual(mimetypes.guess_extension('application/vnd.apple.mpegurl'), '.m3u')
229 self.assertEqual(mimetypes.guess_extension('application/vnd.ms-excel'), '.xls')
230 self.assertEqual(mimetypes.guess_extension('application/vnd.ms-powerpoint'), '.ppt')
231 self.assertEqual(mimetypes.guess_extension('application/x-texinfo'), '.texi')
232 self.assertEqual(mimetypes.guess_extension('application/x-troff'), '.roff')
233 self.assertEqual(mimetypes.guess_extension('application/xml'), '.xsl')
234 self.assertEqual(mimetypes.guess_extension('audio/mpeg'), '.mp3')
235 self.assertEqual(mimetypes.guess_extension('image/avif'), '.avif')
236 self.assertEqual(mimetypes.guess_extension('image/webp'), '.webp')
237 self.assertEqual(mimetypes.guess_extension('image/jpeg'), '.jpg')
238 self.assertEqual(mimetypes.guess_extension('image/tiff'), '.tiff')
239 self.assertEqual(mimetypes.guess_extension('message/rfc822'), '.eml')
240 self.assertEqual(mimetypes.guess_extension('text/html'), '.html')
241 self.assertEqual(mimetypes.guess_extension('text/plain'), '.txt')
242 self.assertEqual(mimetypes.guess_extension('text/rtf'), '.rtf')
243 self.assertEqual(mimetypes.guess_extension('text/x-rst'), '.rst')
244 self.assertEqual(mimetypes.guess_extension('video/mpeg'), '.mpeg')
245 self.assertEqual(mimetypes.guess_extension('video/quicktime'), '.mov')
246
247 check_extensions()
248 mimetypes.init()
249 check_extensions()
250
251 def test_init_stability(self):
252 mimetypes.init()
253
254 suffix_map = mimetypes.suffix_map
255 encodings_map = mimetypes.encodings_map
256 types_map = mimetypes.types_map
257 common_types = mimetypes.common_types
258
259 mimetypes.init()
260 self.assertIsNot(suffix_map, mimetypes.suffix_map)
261 self.assertIsNot(encodings_map, mimetypes.encodings_map)
262 self.assertIsNot(types_map, mimetypes.types_map)
263 self.assertIsNot(common_types, mimetypes.common_types)
264 self.assertEqual(suffix_map, mimetypes.suffix_map)
265 self.assertEqual(encodings_map, mimetypes.encodings_map)
266 self.assertEqual(types_map, mimetypes.types_map)
267 self.assertEqual(common_types, mimetypes.common_types)
268
269 def test_path_like_ob(self):
270 filename = "LICENSE.txt"
271 filepath = os_helper.FakePath(filename)
272 filepath_with_abs_dir = os_helper.FakePath('/dir/'+filename)
273 filepath_relative = os_helper.FakePath('../dir/'+filename)
274 path_dir = os_helper.FakePath('./')
275
276 expected = self.db.guess_file_type(filename)
277
278 self.assertEqual(self.db.guess_file_type(filepath), expected)
279 self.assertEqual(self.db.guess_type(filepath), expected)
280 self.assertEqual(self.db.guess_file_type(
281 filepath_with_abs_dir), expected)
282 self.assertEqual(self.db.guess_type(
283 filepath_with_abs_dir), expected)
284 self.assertEqual(self.db.guess_file_type(filepath_relative), expected)
285 self.assertEqual(self.db.guess_type(filepath_relative), expected)
286
287 self.assertEqual(self.db.guess_file_type(path_dir), (None, None))
288 self.assertEqual(self.db.guess_type(path_dir), (None, None))
289
290 def test_bytes_path(self):
291 self.assertEqual(self.db.guess_file_type(b'foo.html'),
292 self.db.guess_file_type('foo.html'))
293 self.assertEqual(self.db.guess_file_type(b'foo.tar.gz'),
294 self.db.guess_file_type('foo.tar.gz'))
295 self.assertEqual(self.db.guess_file_type(b'foo.tgz'),
296 self.db.guess_file_type('foo.tgz'))
297
298 def test_keywords_args_api(self):
299 self.assertEqual(self.db.guess_file_type(
300 path="foo.html", strict=True), ("text/html", None))
301 self.assertEqual(self.db.guess_type(
302 url="scheme:foo.html", strict=True), ("text/html", None))
303 self.assertEqual(self.db.guess_all_extensions(
304 type='image/jpg', strict=True), [])
305 self.assertEqual(self.db.guess_extension(
306 type='image/jpg', strict=False), '.jpg')
307
308
309 @unittest.skipUnless(sys.platform.startswith("win"), "Windows only")
310 class Win32MimeTypesTestCase(unittest.TestCase):
311 def setUp(self):
312 # ensure all entries actually come from the Windows registry
313 self.original_types_map = mimetypes.types_map.copy()
314 mimetypes.types_map.clear()
315 mimetypes.init()
316 self.db = mimetypes.MimeTypes()
317
318 def tearDown(self):
319 # restore default settings
320 mimetypes.types_map.clear()
321 mimetypes.types_map.update(self.original_types_map)
322
323 @unittest.skipIf(win32_edition() in ('NanoServer', 'WindowsCoreHeadless', 'IoTEdgeOS'),
324 "MIME types registry keys unavailable")
325 def test_registry_parsing(self):
326 # the original, minimum contents of the MIME database in the
327 # Windows registry is undocumented AFAIK.
328 # Use file types that should *always* exist:
329 eq = self.assertEqual
330 eq(self.db.guess_type("foo.txt"), ("text/plain", None))
331 eq(self.db.guess_type("image.jpg"), ("image/jpeg", None))
332 eq(self.db.guess_type("image.png"), ("image/png", None))
333
334 @unittest.skipIf(not hasattr(_winapi, "_mimetypes_read_windows_registry"),
335 "read_windows_registry accelerator unavailable")
336 def test_registry_accelerator(self):
337 from_accel = {}
338 from_reg = {}
339 _winapi._mimetypes_read_windows_registry(
340 lambda v, k: from_accel.setdefault(k, set()).add(v)
341 )
342 mimetypes.MimeTypes._read_windows_registry(
343 lambda v, k: from_reg.setdefault(k, set()).add(v)
344 )
345 self.assertEqual(list(from_reg), list(from_accel))
346 for k in from_reg:
347 self.assertEqual(from_reg[k], from_accel[k])
348
349
350 class MiscTestCase(unittest.TestCase):
351 def test__all__(self):
352 support.check__all__(self, mimetypes)
353
354
355 class MimetypesCliTestCase(unittest.TestCase):
356
357 def mimetypes_cmd(self, *args, **kwargs):
358 support.patch(self, sys, "argv", [sys.executable, *args])
359 with support.captured_stdout() as output:
360 mimetypes._main()
361 return output.getvalue().strip()
362
363 def test_help_option(self):
364 support.patch(self, sys, "argv", [sys.executable, "-h"])
365 with support.captured_stdout() as output:
366 with self.assertRaises(SystemExit) as cm:
367 mimetypes._main()
368
369 self.assertIn("Usage: mimetypes.py", output.getvalue())
370 self.assertEqual(cm.exception.code, 0)
371
372 def test_invalid_option(self):
373 support.patch(self, sys, "argv", [sys.executable, "--invalid"])
374 with support.captured_stdout() as output:
375 with self.assertRaises(SystemExit) as cm:
376 mimetypes._main()
377
378 self.assertIn("Usage: mimetypes.py", output.getvalue())
379 self.assertEqual(cm.exception.code, 1)
380
381 def test_guess_extension(self):
382 eq = self.assertEqual
383
384 extension = self.mimetypes_cmd("-l", "-e", "image/jpg")
385 eq(extension, ".jpg")
386
387 extension = self.mimetypes_cmd("-e", "image/jpg")
388 eq(extension, "I don't know anything about type image/jpg")
389
390 extension = self.mimetypes_cmd("-e", "image/jpeg")
391 eq(extension, ".jpg")
392
393 def test_guess_type(self):
394 eq = self.assertEqual
395
396 type_info = self.mimetypes_cmd("-l", "foo.pic")
397 eq(type_info, "type: image/pict encoding: None")
398
399 type_info = self.mimetypes_cmd("foo.pic")
400 eq(type_info, "I don't know anything about type foo.pic")
401
402 if __name__ == "__main__":
403 unittest.main()