Debian Codegraph @

lib-python/3/test/test_mimetypes.py

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