Debian Codegraph @

Lib/test/test_mimetypes.py

raw
1 import io
2 import mimetypes
3 import os
4 import shlex
5 import sys
6 import unittest.mock
7 from platform import win32_edition
8 from test import support
9 from test.support import cpython_only, force_not_colorized, os_helper, requires_subprocess
10 from test.support.import_helper import ensure_lazy_imports
11 from test.support.script_helper import assert_python_ok, assert_python_failure
12
13 try:
14 import _winapi
15 except ImportError:
16 _winapi = None
17
18
19 def setUpModule():
20 global knownfiles
21 knownfiles = mimetypes.knownfiles
22
23 # Tell it we don't know about external files:
24 mimetypes.knownfiles = []
25 mimetypes.inited = False
26 mimetypes._default_mime_types()
27
28
29 def tearDownModule():
30 # Restore knownfiles to its initial state
31 mimetypes.knownfiles = knownfiles
32
33
34 class MimeTypesTestCase(unittest.TestCase):
35 def setUp(self):
36 self.db = mimetypes.MimeTypes()
37
38 def test_case_sensitivity(self):
39 eq = self.assertEqual
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.HTML"), ("text/html", None))
43 eq(self.db.guess_type("scheme:foobar.HTML"), ("text/html", None))
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.TGZ"), ("application/x-tar", "gzip"))
47 eq(self.db.guess_type("scheme:foobar.TGZ"), ("application/x-tar", "gzip"))
48 eq(self.db.guess_file_type("foobar.tar.Z"), ("application/x-tar", "compress"))
49 eq(self.db.guess_type("scheme:foobar.tar.Z"), ("application/x-tar", "compress"))
50 eq(self.db.guess_file_type("foobar.tar.z"), (None, None))
51 eq(self.db.guess_type("scheme:foobar.tar.z"), (None, None))
52
53 def test_default_data(self):
54 eq = self.assertEqual
55 eq(self.db.guess_file_type("foo.html"), ("text/html", None))
56 eq(self.db.guess_file_type("foo.HTML"), ("text/html", None))
57 eq(self.db.guess_file_type("foo.tgz"), ("application/x-tar", "gzip"))
58 eq(self.db.guess_file_type("foo.tar.gz"), ("application/x-tar", "gzip"))
59 eq(self.db.guess_file_type("foo.tar.Z"), ("application/x-tar", "compress"))
60 eq(self.db.guess_file_type("foo.tar.bz2"), ("application/x-tar", "bzip2"))
61 eq(self.db.guess_file_type("foo.tar.xz"), ("application/x-tar", "xz"))
62
63 def test_data_urls(self):
64 eq = self.assertEqual
65 guess_type = self.db.guess_type
66 eq(guess_type("data:invalidDataWithoutComma"), (None, None))
67 eq(guess_type("data:,thisIsTextPlain"), ("text/plain", None))
68 eq(guess_type("data:;base64,thisIsTextPlain"), ("text/plain", None))
69 eq(guess_type("data:text/x-foo,thisIsTextXFoo"), ("text/x-foo", None))
70
71 def test_file_parsing(self):
72 eq = self.assertEqual
73 sio = io.StringIO("x-application/x-unittest pyunit\n")
74 self.db.readfp(sio)
75 eq(self.db.guess_file_type("foo.pyunit"),
76 ("x-application/x-unittest", None))
77 eq(self.db.guess_extension("x-application/x-unittest"), ".pyunit")
78
79 def test_read_mime_types(self):
80 eq = self.assertEqual
81
82 # Unreadable file returns None
83 self.assertIsNone(mimetypes.read_mime_types("non-existent"))
84
85 with os_helper.temp_dir() as directory:
86 data = "x-application/x-unittest pyunit\n"
87 file = os.path.join(directory, "sample.mimetype")
88 with open(file, 'w', encoding="utf-8") as f:
89 f.write(data)
90 mime_dict = mimetypes.read_mime_types(file)
91 eq(mime_dict[".pyunit"], "x-application/x-unittest")
92
93 data = "x-application/x-unittest2 pyunit2\n"
94 file = os.path.join(directory, "sample2.mimetype")
95 with open(file, 'w', encoding="utf-8") as f:
96 f.write(data)
97 mime_dict = mimetypes.read_mime_types(os_helper.FakePath(file))
98 eq(mime_dict[".pyunit2"], "x-application/x-unittest2")
99
100 # bpo-41048: read_mime_types should read the rule file with 'utf-8' encoding.
101 # Not with locale encoding. _bootlocale has been imported because io.open(...)
102 # uses it.
103 data = "application/no-mans-land Fran\u00E7ais"
104 filename = "filename"
105 fp = io.StringIO(data)
106 with unittest.mock.patch.object(mimetypes, 'open',
107 return_value=fp) as mock_open:
108 mime_dict = mimetypes.read_mime_types(filename)
109 mock_open.assert_called_with(filename, encoding='utf-8')
110 eq(mime_dict[".Français"], "application/no-mans-land")
111
112 def test_non_standard_types(self):
113 eq = self.assertEqual
114 # First try strict
115 eq(self.db.guess_file_type('foo.xul', strict=True), (None, None))
116 eq(self.db.guess_extension('image/jpg', strict=True), None)
117 # And then non-strict
118 eq(self.db.guess_file_type('foo.xul', strict=False), ('text/xul', None))
119 eq(self.db.guess_file_type('foo.XUL', strict=False), ('text/xul', None))
120 eq(self.db.guess_file_type('foo.invalid', strict=False), (None, None))
121 eq(self.db.guess_extension('image/jpg', strict=False), '.jpg')
122 eq(self.db.guess_extension('image/JPG', strict=False), '.jpg')
123
124 def test_filename_with_url_delimiters(self):
125 # bpo-38449: URL delimiters cases should be handled also.
126 # They would have different mime types if interpreted as URL as
127 # compared to when interpreted as filename because of the semicolon.
128 eq = self.assertEqual
129 gzip_expected = ('application/x-tar', 'gzip')
130 for name in (
131 ';1.tar.gz',
132 '?1.tar.gz',
133 '#1.tar.gz',
134 '#1#.tar.gz',
135 ';1#.tar.gz',
136 ';&1=123;?.tar.gz',
137 '?k1=v1&k2=v2.tar.gz',
138 ):
139 for prefix in ('', '/', '\\',
140 'c:', 'c:/', 'c:\\', 'c:/d/', 'c:\\d\\',
141 '//share/server/', '\\\\share\\server\\'):
142 path = prefix + name
143 with self.subTest(path=path):
144 eq(self.db.guess_file_type(path), gzip_expected)
145 eq(self.db.guess_type(path), gzip_expected)
146 expected = (None, None) if os.name == 'nt' else gzip_expected
147 for prefix in ('//', '\\\\', '//share/', '\\\\share\\'):
148 path = prefix + name
149 with self.subTest(path=path):
150 eq(self.db.guess_file_type(path), expected)
151 eq(self.db.guess_type(path), expected)
152 eq(self.db.guess_file_type(r" \"\`;b&b&c |.tar.gz"), gzip_expected)
153 eq(self.db.guess_type(r" \"\`;b&b&c |.tar.gz"), gzip_expected)
154
155 eq(self.db.guess_file_type(r'foo/.tar.gz'), (None, 'gzip'))
156 eq(self.db.guess_type(r'foo/.tar.gz'), (None, 'gzip'))
157 expected = (None, 'gzip') if os.name == 'nt' else gzip_expected
158 eq(self.db.guess_file_type(r'foo\.tar.gz'), expected)
159 eq(self.db.guess_type(r'foo\.tar.gz'), expected)
160 eq(self.db.guess_type(r'scheme:foo\.tar.gz'), gzip_expected)
161
162 def test_url(self):
163 result = self.db.guess_type('http://example.com/host.html')
164 result = self.db.guess_type('http://host.html')
165 msg = 'URL only has a host name, not a file'
166 self.assertSequenceEqual(result, (None, None), msg)
167 result = self.db.guess_type('http://example.com/host.html')
168 msg = 'Should be text/html'
169 self.assertSequenceEqual(result, ('text/html', None), msg)
170 result = self.db.guess_type('http://example.com/host.html#x.tar')
171 self.assertSequenceEqual(result, ('text/html', None))
172 result = self.db.guess_type('http://example.com/host.html?q=x.tar')
173 self.assertSequenceEqual(result, ('text/html', None))
174
175 def test_guess_all_types(self):
176 # First try strict. Use a set here for testing the results because if
177 # test_urllib2 is run before test_mimetypes, global state is modified
178 # such that the 'all' set will have more items in it.
179 all = self.db.guess_all_extensions('text/plain', strict=True)
180 self.assertTrue(set(all) >= {'.bat', '.c', '.h', '.ksh', '.pl', '.txt'})
181 self.assertEqual(len(set(all)), len(all)) # no duplicates
182 # And now non-strict
183 all = self.db.guess_all_extensions('image/jpg', strict=False)
184 self.assertEqual(all, ['.jpg'])
185 # And now for no hits
186 all = self.db.guess_all_extensions('image/jpg', strict=True)
187 self.assertEqual(all, [])
188 # And now for type existing in both strict and non-strict mappings.
189 self.db.add_type('test-type', '.strict-ext')
190 self.db.add_type('test-type', '.non-strict-ext', strict=False)
191 all = self.db.guess_all_extensions('test-type', strict=False)
192 self.assertEqual(all, ['.strict-ext', '.non-strict-ext'])
193 all = self.db.guess_all_extensions('test-type')
194 self.assertEqual(all, ['.strict-ext'])
195 # Test that changing the result list does not affect the global state
196 all.append('.no-such-ext')
197 all = self.db.guess_all_extensions('test-type')
198 self.assertNotIn('.no-such-ext', all)
199
200 def test_encoding(self):
201 filename = support.findfile("mime.types")
202 mimes = mimetypes.MimeTypes([filename])
203 exts = mimes.guess_all_extensions('application/vnd.geocube+xml',
204 strict=True)
205 self.assertEqual(exts, ['.g3', '.g\xb3'])
206
207 def test_init_reinitializes(self):
208 # Issue 4936: make sure an init starts clean
209 # First, put some poison into the types table
210 mimetypes.add_type('foo/bar', '.foobar')
211 self.assertEqual(mimetypes.guess_extension('foo/bar'), '.foobar')
212 # Reinitialize
213 mimetypes.init()
214 # Poison should be gone.
215 self.assertEqual(mimetypes.guess_extension('foo/bar'), None)
216
217 @unittest.skipIf(sys.platform.startswith("win"), "Non-Windows only")
218 def test_guess_known_extensions(self):
219 # Issue 37529
220 # The test fails on Windows because Windows adds mime types from the Registry
221 # and that creates some duplicates.
222 from mimetypes import types_map
223 for v in types_map.values():
224 self.assertIsNotNone(mimetypes.guess_extension(v))
225
226 def test_preferred_extension(self):
227 def check_extensions():
228 for mime_type, ext in (
229 ("application/epub+zip", ".epub"),
230 ("application/octet-stream", ".bin"),
231 ("application/gzip", ".gz"),
232 ("application/ogg", ".ogx"),
233 ("application/postscript", ".ps"),
234 ("application/vnd.apple.mpegurl", ".m3u"),
235 ("application/vnd.ms-excel", ".xls"),
236 ("application/vnd.ms-fontobject", ".eot"),
237 ("application/vnd.ms-powerpoint", ".ppt"),
238 ("application/vnd.oasis.opendocument.graphics", ".odg"),
239 ("application/vnd.oasis.opendocument.presentation", ".odp"),
240 ("application/vnd.oasis.opendocument.spreadsheet", ".ods"),
241 ("application/vnd.oasis.opendocument.text", ".odt"),
242 ("application/vnd.openxmlformats-officedocument.presentationml.presentation", ".pptx"),
243 ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".xlsx"),
244 ("application/vnd.openxmlformats-officedocument.wordprocessingml.document", ".docx"),
245 ("application/vnd.rar", ".rar"),
246 ("application/x-7z-compressed", ".7z"),
247 ("application/x-debian-package", ".deb"),
248 ("application/x-httpd-php", ".php"),
249 ("application/x-rpm", ".rpm"),
250 ("application/x-texinfo", ".texi"),
251 ("application/x-troff", ".roff"),
252 ("application/xml", ".xsl"),
253 ("application/yaml", ".yaml"),
254 ("audio/flac", ".flac"),
255 ("audio/matroska", ".mka"),
256 ("audio/mp4", ".m4a"),
257 ("audio/mpeg", ".mp3"),
258 ("audio/ogg", ".ogg"),
259 ("audio/vnd.wave", ".wav"),
260 ("audio/webm", ".weba"),
261 ("font/otf", ".otf"),
262 ("font/ttf", ".ttf"),
263 ("font/woff", ".woff"),
264 ("font/woff2", ".woff2"),
265 ("image/avif", ".avif"),
266 ("image/emf", ".emf"),
267 ("image/fits", ".fits"),
268 ("image/g3fax", ".g3"),
269 ("image/jp2", ".jp2"),
270 ("image/jpeg", ".jpg"),
271 ("image/jpm", ".jpm"),
272 ("image/t38", ".t38"),
273 ("image/tiff", ".tiff"),
274 ("image/tiff-fx", ".tfx"),
275 ("image/webp", ".webp"),
276 ("image/wmf", ".wmf"),
277 ("message/rfc822", ".eml"),
278 ("model/gltf+json", ".gltf"),
279 ("model/gltf-binary", ".glb"),
280 ("model/stl", ".stl"),
281 ("text/html", ".html"),
282 ("text/plain", ".txt"),
283 ("text/rtf", ".rtf"),
284 ("text/x-rst", ".rst"),
285 ("video/matroska", ".mkv"),
286 ("video/matroska-3d", ".mk3d"),
287 ("video/mpeg", ".mpeg"),
288 ("video/ogg", ".ogv"),
289 ("video/quicktime", ".mov"),
290 ("video/vnd.avi", ".avi"),
291 ("video/x-m4v", ".m4v"),
292 ("video/x-ms-wmv", ".wmv"),
293 ):
294 with self.subTest(mime_type=mime_type, ext=ext):
295 self.assertEqual(mimetypes.guess_extension(mime_type), ext)
296
297 check_extensions()
298 mimetypes.init()
299 check_extensions()
300
301 def test_guess_file_type(self):
302 def check_file_type():
303 for mime_type, ext in (
304 ("application/yaml", ".yaml"),
305 ("application/yaml", ".yml"),
306 ("audio/mpeg", ".mp2"),
307 ("audio/mpeg", ".mp3"),
308 ("video/mpeg", ".m1v"),
309 ("video/mpeg", ".mpe"),
310 ("video/mpeg", ".mpeg"),
311 ("video/mpeg", ".mpg"),
312 ):
313 with self.subTest(mime_type=mime_type, ext=ext):
314 result, _ = mimetypes.guess_file_type(f"filename{ext}")
315 self.assertEqual(result, mime_type)
316
317 check_file_type()
318 mimetypes.init()
319 check_file_type()
320
321 def test_init_stability(self):
322 mimetypes.init()
323
324 suffix_map = mimetypes.suffix_map
325 encodings_map = mimetypes.encodings_map
326 types_map = mimetypes.types_map
327 common_types = mimetypes.common_types
328
329 mimetypes.init()
330 self.assertIsNot(suffix_map, mimetypes.suffix_map)
331 self.assertIsNot(encodings_map, mimetypes.encodings_map)
332 self.assertIsNot(types_map, mimetypes.types_map)
333 self.assertIsNot(common_types, mimetypes.common_types)
334 self.assertEqual(suffix_map, mimetypes.suffix_map)
335 self.assertEqual(encodings_map, mimetypes.encodings_map)
336 self.assertEqual(types_map, mimetypes.types_map)
337 self.assertEqual(common_types, mimetypes.common_types)
338
339 def test_path_like_ob(self):
340 filename = "LICENSE.txt"
341 filepath = os_helper.FakePath(filename)
342 filepath_with_abs_dir = os_helper.FakePath('/dir/'+filename)
343 filepath_relative = os_helper.FakePath('../dir/'+filename)
344 path_dir = os_helper.FakePath('./')
345
346 expected = self.db.guess_file_type(filename)
347
348 self.assertEqual(self.db.guess_file_type(filepath), expected)
349 self.assertEqual(self.db.guess_type(filepath), expected)
350 self.assertEqual(self.db.guess_file_type(
351 filepath_with_abs_dir), expected)
352 self.assertEqual(self.db.guess_type(
353 filepath_with_abs_dir), expected)
354 self.assertEqual(self.db.guess_file_type(filepath_relative), expected)
355 self.assertEqual(self.db.guess_type(filepath_relative), expected)
356
357 self.assertEqual(self.db.guess_file_type(path_dir), (None, None))
358 self.assertEqual(self.db.guess_type(path_dir), (None, None))
359
360 def test_bytes_path(self):
361 self.assertEqual(self.db.guess_file_type(b'foo.html'),
362 self.db.guess_file_type('foo.html'))
363 self.assertEqual(self.db.guess_file_type(b'foo.tar.gz'),
364 self.db.guess_file_type('foo.tar.gz'))
365 self.assertEqual(self.db.guess_file_type(b'foo.tgz'),
366 self.db.guess_file_type('foo.tgz'))
367
368 def test_keywords_args_api(self):
369 self.assertEqual(self.db.guess_file_type(
370 path="foo.html", strict=True), ("text/html", None))
371 self.assertEqual(self.db.guess_type(
372 url="scheme:foo.html", strict=True), ("text/html", None))
373 self.assertEqual(self.db.guess_all_extensions(
374 type='image/jpg', strict=True), [])
375 self.assertEqual(self.db.guess_extension(
376 type='image/jpg', strict=False), '.jpg')
377
378 def test_added_types_are_used(self):
379 mimetypes.add_type('testing/default-type', '')
380 mime_type, _ = mimetypes.guess_type('')
381 self.assertEqual(mime_type, 'testing/default-type')
382
383 mime_type, _ = mimetypes.guess_type('test.myext')
384 self.assertEqual(mime_type, None)
385
386 mimetypes.add_type('testing/type', '.myext')
387 mime_type, _ = mimetypes.guess_type('test.myext')
388 self.assertEqual(mime_type, 'testing/type')
389
390 def test_add_type_with_undotted_extension_deprecated(self):
391 with self.assertWarns(DeprecationWarning):
392 mimetypes.add_type("testing/type", "undotted")
393
394
395 @unittest.skipUnless(sys.platform.startswith("win"), "Windows only")
396 class Win32MimeTypesTestCase(unittest.TestCase):
397 def setUp(self):
398 # ensure all entries actually come from the Windows registry
399 self.original_types_map = mimetypes.types_map.copy()
400 mimetypes.types_map.clear()
401 mimetypes.init()
402 self.db = mimetypes.MimeTypes()
403
404 def tearDown(self):
405 # restore default settings
406 mimetypes.types_map.clear()
407 mimetypes.types_map.update(self.original_types_map)
408
409 @unittest.skipIf(win32_edition() in ('NanoServer', 'WindowsCoreHeadless', 'IoTEdgeOS'),
410 "MIME types registry keys unavailable")
411 def test_registry_parsing(self):
412 # the original, minimum contents of the MIME database in the
413 # Windows registry is undocumented AFAIK.
414 # Use file types that should *always* exist:
415 eq = self.assertEqual
416 eq(self.db.guess_type("foo.txt"), ("text/plain", None))
417 eq(self.db.guess_type("image.jpg"), ("image/jpeg", None))
418 eq(self.db.guess_type("image.png"), ("image/png", None))
419
420 @unittest.skipIf(not hasattr(_winapi, "_mimetypes_read_windows_registry"),
421 "read_windows_registry accelerator unavailable")
422 def test_registry_accelerator(self):
423 from_accel = {}
424 from_reg = {}
425 _winapi._mimetypes_read_windows_registry(
426 lambda v, k: from_accel.setdefault(k, set()).add(v)
427 )
428 mimetypes.MimeTypes._read_windows_registry(
429 lambda v, k: from_reg.setdefault(k, set()).add(v)
430 )
431 self.assertEqual(list(from_reg), list(from_accel))
432 for k in from_reg:
433 self.assertEqual(from_reg[k], from_accel[k])
434
435
436 class MiscTestCase(unittest.TestCase):
437 def test__all__(self):
438 support.check__all__(self, mimetypes)
439
440 @cpython_only
441 def test_lazy_import(self):
442 ensure_lazy_imports("mimetypes", {"os", "posixpath", "urllib.parse", "argparse"})
443
444
445 class CommandLineTest(unittest.TestCase):
446 @force_not_colorized
447 def test_parse_args(self):
448 args, help_text = mimetypes._parse_args("-h")
449 self.assertTrue(help_text.startswith("usage: "))
450
451 args, help_text = mimetypes._parse_args("--invalid")
452 self.assertTrue(help_text.startswith("usage: "))
453
454 args, _ = mimetypes._parse_args(shlex.split("-l -e image/jpg"))
455 self.assertTrue(args.extension)
456 self.assertTrue(args.lenient)
457 self.assertEqual(args.type, ["image/jpg"])
458
459 args, _ = mimetypes._parse_args(shlex.split("-e image/jpg"))
460 self.assertTrue(args.extension)
461 self.assertFalse(args.lenient)
462 self.assertEqual(args.type, ["image/jpg"])
463
464 args, _ = mimetypes._parse_args(shlex.split("-l foo.webp"))
465 self.assertFalse(args.extension)
466 self.assertTrue(args.lenient)
467 self.assertEqual(args.type, ["foo.webp"])
468
469 args, _ = mimetypes._parse_args(shlex.split("foo.pic"))
470 self.assertFalse(args.extension)
471 self.assertFalse(args.lenient)
472 self.assertEqual(args.type, ["foo.pic"])
473
474 def test_multiple_inputs(self):
475 result = "\n".join(mimetypes._main(shlex.split("foo.pdf foo.png")))
476 self.assertEqual(
477 result,
478 "type: application/pdf encoding: None\n"
479 "type: image/png encoding: None"
480 )
481
482 def test_multiple_inputs_error(self):
483 result = "\n".join(mimetypes._main(shlex.split("foo.pdf foo.bar_ext")))
484 self.assertEqual(
485 result,
486 "type: application/pdf encoding: None\n"
487 "error: media type unknown for foo.bar_ext"
488 )
489
490
491 def test_invocation(self):
492 for command, expected in [
493 ("-l -e image/jpg", ".jpg"),
494 ("-e image/jpeg", ".jpg"),
495 ("-l foo.webp", "type: image/webp encoding: None"),
496 ]:
497 result = "\n".join(mimetypes._main(shlex.split(command)))
498 self.assertEqual(result, expected)
499
500 def test_invocation_error(self):
501 for command, expected in [
502 ("-e image/jpg", "error: unknown type image/jpg"),
503 ("foo.bar_ext", "error: media type unknown for foo.bar_ext"),
504 ]:
505 with self.subTest(command=command):
506 result = "\n".join(mimetypes._main(shlex.split(command)))
507 self.assertEqual(result, expected)
508
509
510 @requires_subprocess()
511 class CommandLineSubprocessTest(unittest.TestCase):
512 def test_help(self):
513 rc, stdout, stderr = assert_python_ok('-m', 'mimetypes', '--help')
514 self.assertIn(b'mimetypes', stdout)
515 self.assertIn(b'--extension', stdout)
516 self.assertIn(b'--lenient', stdout)
517
518 def test_type_lookup(self):
519 rc, stdout, stderr = assert_python_ok('-m', 'mimetypes', 'foo.pdf')
520 self.assertEqual(stdout.strip(), b'type: application/pdf encoding: None')
521 self.assertEqual(stderr, b'')
522
523 def test_type_lookup_unknown(self):
524 rc, stdout, stderr = assert_python_failure('-m', 'mimetypes', 'foo.unknownext12345')
525 self.assertEqual(stdout.strip(), b'error: media type unknown for foo.unknownext12345')
526 self.assertEqual(stderr, b'')
527
528 def test_extension_flag(self):
529 rc, stdout, stderr = assert_python_ok('-m', 'mimetypes', '-e', 'image/jpeg')
530 self.assertEqual(stdout.strip(), b'.jpg')
531 self.assertEqual(stderr, b'')
532
533 def test_extension_flag_unknown(self):
534 rc, stdout, stderr = assert_python_failure('-m', 'mimetypes', '-e', 'image/unknowntype12345')
535 self.assertEqual(stdout.strip(), b'error: unknown type image/unknowntype12345')
536 self.assertEqual(stderr, b'')
537
538 def test_lenient_flag(self):
539 rc, stdout, stderr = assert_python_ok('-m', 'mimetypes', '-e', '--lenient', 'text/xul')
540 self.assertIn(b'.xul', stdout)
541 self.assertEqual(stderr, b'')
542
543 def test_multiple_inputs(self):
544 rc, stdout, stderr = assert_python_ok('-m', 'mimetypes', 'foo.pdf', 'foo.png')
545 self.assertIn(b'type: application/pdf encoding: None', stdout)
546 self.assertIn(b'type: image/png encoding: None', stdout)
547 self.assertEqual(stderr, b'')
548
549 def test_multiple_inputs_with_error(self):
550 rc, stdout, stderr = assert_python_failure(
551 '-m', 'mimetypes', 'foo.pdf', 'foo.unknownext12345'
552 )
553 self.assertIn(b'type: application/pdf encoding: None', stdout)
554 self.assertIn(b'error: media type unknown for foo.unknownext12345', stdout)
555 self.assertEqual(stderr, b'')
556
557 @force_not_colorized
558 def test_unknown_flag(self):
559 rc, stdout, stderr = assert_python_failure('-m', 'mimetypes', '--unknown-flag', 'foo.pdf')
560 self.assertEqual(stdout, b'')
561 self.assertIn(b'error: unrecognized arguments: --unknown-flag', stderr)
562
563
564 if __name__ == "__main__":
565 unittest.main()