Best Python code snippet using autotest_python
test_mimetypes.py
Source:test_mimetypes.py
...25 def setUp(self):26 self.db = mimetypes.MimeTypes()27 def test_default_data(self):28 eq = self.assertEqual29 eq(self.db.guess_type("foo.html"), ("text/html", None))30 eq(self.db.guess_type("foo.HTML"), ("text/html", None))31 eq(self.db.guess_type("foo.tgz"), ("application/x-tar", "gzip"))32 eq(self.db.guess_type("foo.tar.gz"), ("application/x-tar", "gzip"))33 eq(self.db.guess_type("foo.tar.Z"), ("application/x-tar", "compress"))34 eq(self.db.guess_type("foo.tar.bz2"), ("application/x-tar", "bzip2"))35 eq(self.db.guess_type("foo.tar.xz"), ("application/x-tar", "xz"))36 def test_data_urls(self):37 eq = self.assertEqual38 guess_type = self.db.guess_type39 eq(guess_type("data:invalidDataWithoutComma"), (None, None))40 eq(guess_type("data:,thisIsTextPlain"), ("text/plain", None))41 eq(guess_type("data:;base64,thisIsTextPlain"), ("text/plain", None))42 eq(guess_type("data:text/x-foo,thisIsTextXFoo"), ("text/x-foo", None))43 def test_file_parsing(self):44 eq = self.assertEqual45 sio = io.StringIO("x-application/x-unittest pyunit\n")46 self.db.readfp(sio)47 eq(self.db.guess_type("foo.pyunit"),48 ("x-application/x-unittest", None))49 eq(self.db.guess_extension("x-application/x-unittest"), ".pyunit")50 def test_read_mime_types(self):51 eq = self.assertEqual52 # Unreadable file returns None53 self.assertIsNone(mimetypes.read_mime_types("non-existent"))54 with os_helper.temp_dir() as directory:55 data = "x-application/x-unittest pyunit\n"56 file = pathlib.Path(directory, "sample.mimetype")57 file.write_text(data, encoding="utf-8")58 mime_dict = mimetypes.read_mime_types(file)59 eq(mime_dict[".pyunit"], "x-application/x-unittest")60 # bpo-41048: read_mime_types should read the rule file with 'utf-8' encoding.61 # Not with locale encoding. _bootlocale has been imported because io.open(...)62 # uses it.63 data = "application/no-mans-land Fran\u00E7ais"64 filename = "filename"65 fp = io.StringIO(data)66 with unittest.mock.patch.object(mimetypes, 'open',67 return_value=fp) as mock_open:68 mime_dict = mimetypes.read_mime_types(filename)69 mock_open.assert_called_with(filename, encoding='utf-8')70 eq(mime_dict[".Français"], "application/no-mans-land")71 def test_non_standard_types(self):72 eq = self.assertEqual73 # First try strict74 eq(self.db.guess_type('foo.xul', strict=True), (None, None))75 eq(self.db.guess_extension('image/jpg', strict=True), None)76 # And then non-strict77 eq(self.db.guess_type('foo.xul', strict=False), ('text/xul', None))78 eq(self.db.guess_type('foo.XUL', strict=False), ('text/xul', None))79 eq(self.db.guess_type('foo.invalid', strict=False), (None, None))80 eq(self.db.guess_extension('image/jpg', strict=False), '.jpg')81 eq(self.db.guess_extension('image/JPG', strict=False), '.jpg')82 def test_filename_with_url_delimiters(self):83 # bpo-38449: URL delimiters cases should be handled also.84 # They would have different mime types if interpreted as URL as85 # compared to when interpreted as filename because of the semicolon.86 eq = self.assertEqual87 gzip_expected = ('application/x-tar', 'gzip')88 eq(self.db.guess_type(";1.tar.gz"), gzip_expected)89 eq(self.db.guess_type("?1.tar.gz"), gzip_expected)90 eq(self.db.guess_type("#1.tar.gz"), gzip_expected)91 eq(self.db.guess_type("#1#.tar.gz"), gzip_expected)92 eq(self.db.guess_type(";1#.tar.gz"), gzip_expected)93 eq(self.db.guess_type(";&1=123;?.tar.gz"), gzip_expected)94 eq(self.db.guess_type("?k1=v1&k2=v2.tar.gz"), gzip_expected)95 eq(self.db.guess_type(r" \"\`;b&b&c |.tar.gz"), gzip_expected)96 def test_guess_all_types(self):97 eq = self.assertEqual98 unless = self.assertTrue99 # First try strict. Use a set here for testing the results because if100 # test_urllib2 is run before test_mimetypes, global state is modified101 # such that the 'all' set will have more items in it.102 all = set(self.db.guess_all_extensions('text/plain', strict=True))103 unless(all >= set(['.bat', '.c', '.h', '.ksh', '.pl', '.txt']))104 # And now non-strict105 all = self.db.guess_all_extensions('image/jpg', strict=False)106 all.sort()107 eq(all, ['.jpg'])108 # And now for no hits109 all = self.db.guess_all_extensions('image/jpg', strict=True)110 eq(all, [])111 def test_encoding(self):112 getpreferredencoding = locale.getpreferredencoding113 self.addCleanup(setattr, locale, 'getpreferredencoding',114 getpreferredencoding)115 locale.getpreferredencoding = lambda: 'ascii'116 filename = support.findfile("mime.types")117 mimes = mimetypes.MimeTypes([filename])118 exts = mimes.guess_all_extensions('application/vnd.geocube+xml',119 strict=True)120 self.assertEqual(exts, ['.g3', '.g\xb3'])121 def test_init_reinitializes(self):122 # Issue 4936: make sure an init starts clean123 # First, put some poison into the types table124 mimetypes.add_type('foo/bar', '.foobar')125 self.assertEqual(mimetypes.guess_extension('foo/bar'), '.foobar')126 # Reinitialize127 mimetypes.init()128 # Poison should be gone.129 self.assertEqual(mimetypes.guess_extension('foo/bar'), None)130 def test_preferred_extension(self):131 def check_extensions():132 self.assertEqual(mimetypes.guess_extension('application/octet-stream'), '.bin')133 self.assertEqual(mimetypes.guess_extension('application/postscript'), '.ps')134 self.assertEqual(mimetypes.guess_extension('application/vnd.apple.mpegurl'), '.m3u')135 self.assertEqual(mimetypes.guess_extension('application/vnd.ms-excel'), '.xls')136 self.assertEqual(mimetypes.guess_extension('application/vnd.ms-powerpoint'), '.ppt')137 self.assertEqual(mimetypes.guess_extension('application/x-texinfo'), '.texi')138 self.assertEqual(mimetypes.guess_extension('application/x-troff'), '.roff')139 self.assertEqual(mimetypes.guess_extension('application/xml'), '.xsl')140 self.assertEqual(mimetypes.guess_extension('audio/mpeg'), '.mp3')141 self.assertEqual(mimetypes.guess_extension('image/jpeg'), '.jpg')142 self.assertEqual(mimetypes.guess_extension('image/tiff'), '.tiff')143 self.assertEqual(mimetypes.guess_extension('message/rfc822'), '.eml')144 self.assertEqual(mimetypes.guess_extension('text/html'), '.html')145 self.assertEqual(mimetypes.guess_extension('text/plain'), '.txt')146 self.assertEqual(mimetypes.guess_extension('video/mpeg'), '.mpeg')147 self.assertEqual(mimetypes.guess_extension('video/quicktime'), '.mov')148 check_extensions()149 mimetypes.init()150 check_extensions()151 def test_init_stability(self):152 mimetypes.init()153 suffix_map = mimetypes.suffix_map154 encodings_map = mimetypes.encodings_map155 types_map = mimetypes.types_map156 common_types = mimetypes.common_types157 mimetypes.init()158 self.assertIsNot(suffix_map, mimetypes.suffix_map)159 self.assertIsNot(encodings_map, mimetypes.encodings_map)160 self.assertIsNot(types_map, mimetypes.types_map)161 self.assertIsNot(common_types, mimetypes.common_types)162 self.assertEqual(suffix_map, mimetypes.suffix_map)163 self.assertEqual(encodings_map, mimetypes.encodings_map)164 self.assertEqual(types_map, mimetypes.types_map)165 self.assertEqual(common_types, mimetypes.common_types)166 def test_path_like_ob(self):167 filename = "LICENSE.txt"168 filepath = pathlib.Path(filename)169 filepath_with_abs_dir = pathlib.Path('/dir/'+filename)170 filepath_relative = pathlib.Path('../dir/'+filename)171 path_dir = pathlib.Path('./')172 expected = self.db.guess_type(filename)173 self.assertEqual(self.db.guess_type(filepath), expected)174 self.assertEqual(self.db.guess_type(175 filepath_with_abs_dir), expected)176 self.assertEqual(self.db.guess_type(filepath_relative), expected)177 self.assertEqual(self.db.guess_type(path_dir), (None, None))178 def test_keywords_args_api(self):179 self.assertEqual(self.db.guess_type(180 url="foo.html", strict=True), ("text/html", None))181 self.assertEqual(self.db.guess_all_extensions(182 type='image/jpg', strict=True), [])183 self.assertEqual(self.db.guess_extension(184 type='image/jpg', strict=False), '.jpg')185@unittest.skipUnless(sys.platform.startswith("win"), "Windows only")186class Win32MimeTypesTestCase(unittest.TestCase):187 def setUp(self):188 # ensure all entries actually come from the Windows registry189 self.original_types_map = mimetypes.types_map.copy()190 mimetypes.types_map.clear()191 mimetypes.init()192 self.db = mimetypes.MimeTypes()193 def tearDown(self):194 # restore default settings195 mimetypes.types_map.clear()196 mimetypes.types_map.update(self.original_types_map)197 @unittest.skipIf(win32_edition() in ('NanoServer', 'WindowsCoreHeadless', 'IoTEdgeOS'),198 "MIME types registry keys unavailable")199 def test_registry_parsing(self):200 # the original, minimum contents of the MIME database in the201 # Windows registry is undocumented AFAIK.202 # Use file types that should *always* exist:203 eq = self.assertEqual204 eq(self.db.guess_type("foo.txt"), ("text/plain", None))205 eq(self.db.guess_type("image.jpg"), ("image/jpeg", None))206 eq(self.db.guess_type("image.png"), ("image/png", None))207 @unittest.skipIf(not hasattr(_winapi, "_mimetypes_read_windows_registry"),208 "read_windows_registry accelerator unavailable")209 def test_registry_accelerator(self):210 from_accel = {}211 from_reg = {}212 _winapi._mimetypes_read_windows_registry(213 lambda v, k: from_accel.setdefault(k, set()).add(v)214 )215 mimetypes.MimeTypes._read_windows_registry(216 lambda v, k: from_reg.setdefault(k, set()).add(v)217 )218 self.assertEqual(list(from_reg), list(from_accel))219 for k in from_reg:220 self.assertEqual(from_reg[k], from_accel[k])221class MiscTestCase(unittest.TestCase):222 def test__all__(self):223 support.check__all__(self, mimetypes)224class MimetypesCliTestCase(unittest.TestCase):225 def mimetypes_cmd(self, *args, **kwargs):226 support.patch(self, sys, "argv", [sys.executable, *args])227 with support.captured_stdout() as output:228 mimetypes._main()229 return output.getvalue().strip()230 def test_help_option(self):231 support.patch(self, sys, "argv", [sys.executable, "-h"])232 with support.captured_stdout() as output:233 with self.assertRaises(SystemExit) as cm:234 mimetypes._main()235 self.assertIn("Usage: mimetypes.py", output.getvalue())236 self.assertEqual(cm.exception.code, 0)237 def test_invalid_option(self):238 support.patch(self, sys, "argv", [sys.executable, "--invalid"])239 with support.captured_stdout() as output:240 with self.assertRaises(SystemExit) as cm:241 mimetypes._main()242 self.assertIn("Usage: mimetypes.py", output.getvalue())243 self.assertEqual(cm.exception.code, 1)244 def test_guess_extension(self):245 eq = self.assertEqual246 extension = self.mimetypes_cmd("-l", "-e", "image/jpg")247 eq(extension, ".jpg")248 extension = self.mimetypes_cmd("-e", "image/jpg")249 eq(extension, "I don't know anything about type image/jpg")250 extension = self.mimetypes_cmd("-e", "image/jpeg")251 eq(extension, ".jpg")252 def test_guess_type(self):253 eq = self.assertEqual254 type_info = self.mimetypes_cmd("-l", "foo.pic")255 eq(type_info, "type: image/pict encoding: None")256 type_info = self.mimetypes_cmd("foo.pic")257 eq(type_info, "I don't know anything about type foo.pic")258if __name__ == "__main__":...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!