[Python-checkins] bpo-39299: Add more tests for mimetypes and its cli. (GH-17949)

Karthikeyan Singaravelan webhook-mailer at python.org
Mon Jan 13 09:39:44 EST 2020


https://github.com/python/cpython/commit/d8efc1495194228c3a4cd472200275d6491d8e2d
commit: d8efc1495194228c3a4cd472200275d6491d8e2d
branch: master
author: Karthikeyan Singaravelan <tir.karthi at gmail.com>
committer: GitHub <noreply at github.com>
date: 2020-01-13T20:09:36+05:30
summary:

bpo-39299: Add more tests for mimetypes and its cli. (GH-17949)

* Add tests for case insensitive check of types and extensions as fallback.
* Add tests for data url with no comma.
* Add tests for read_mime_types.
* Add tests for the mimetypes cli and refactor __main__ code to private function.
* Restore mimetypes.knownfiles value at the end of the test.

files:
M Lib/mimetypes.py
M Lib/test/test_mimetypes.py

diff --git a/Lib/mimetypes.py b/Lib/mimetypes.py
index a09e618d8a584..e972ca2e291a0 100644
--- a/Lib/mimetypes.py
+++ b/Lib/mimetypes.py
@@ -564,7 +564,7 @@ def _default_mime_types():
 _default_mime_types()
 
 
-if __name__ == '__main__':
+def _main():
     import getopt
 
     USAGE = """\
@@ -608,3 +608,7 @@ def usage(code, msg=''):
             guess, encoding = guess_type(gtype, strict)
             if not guess: print("I don't know anything about type", gtype)
             else: print('type:', guess, 'encoding:', encoding)
+
+
+if __name__ == '__main__':
+    _main()
diff --git a/Lib/test/test_mimetypes.py b/Lib/test/test_mimetypes.py
index a5a06b189dec4..9cac6ce0225e1 100644
--- a/Lib/test/test_mimetypes.py
+++ b/Lib/test/test_mimetypes.py
@@ -8,10 +8,20 @@
 from test import support
 from platform import win32_edition
 
-# Tell it we don't know about external files:
-mimetypes.knownfiles = []
-mimetypes.inited = False
-mimetypes._default_mime_types()
+
+def setUpModule():
+    global knownfiles
+    knownfiles = mimetypes.knownfiles
+
+    # Tell it we don't know about external files:
+    mimetypes.knownfiles = []
+    mimetypes.inited = False
+    mimetypes._default_mime_types()
+
+
+def tearDownModule():
+    # Restore knownfiles to its initial state
+    mimetypes.knownfiles = knownfiles
 
 
 class MimeTypesTestCase(unittest.TestCase):
@@ -21,6 +31,7 @@ def setUp(self):
     def test_default_data(self):
         eq = self.assertEqual
         eq(self.db.guess_type("foo.html"), ("text/html", None))
+        eq(self.db.guess_type("foo.HTML"), ("text/html", None))
         eq(self.db.guess_type("foo.tgz"), ("application/x-tar", "gzip"))
         eq(self.db.guess_type("foo.tar.gz"), ("application/x-tar", "gzip"))
         eq(self.db.guess_type("foo.tar.Z"), ("application/x-tar", "compress"))
@@ -30,6 +41,7 @@ def test_default_data(self):
     def test_data_urls(self):
         eq = self.assertEqual
         guess_type = self.db.guess_type
+        eq(guess_type("data:invalidDataWithoutComma"), (None, None))
         eq(guess_type("data:,thisIsTextPlain"), ("text/plain", None))
         eq(guess_type("data:;base64,thisIsTextPlain"), ("text/plain", None))
         eq(guess_type("data:text/x-foo,thisIsTextXFoo"), ("text/x-foo", None))
@@ -42,6 +54,19 @@ def test_file_parsing(self):
            ("x-application/x-unittest", None))
         eq(self.db.guess_extension("x-application/x-unittest"), ".pyunit")
 
+    def test_read_mime_types(self):
+        eq = self.assertEqual
+
+        # Unreadable file returns None
+        self.assertIsNone(mimetypes.read_mime_types("non-existent"))
+
+        with support.temp_dir() as directory:
+            data = "x-application/x-unittest pyunit\n"
+            file = pathlib.Path(directory, "sample.mimetype")
+            file.write_text(data)
+            mime_dict = mimetypes.read_mime_types(file)
+            eq(mime_dict[".pyunit"], "x-application/x-unittest")
+
     def test_non_standard_types(self):
         eq = self.assertEqual
         # First try strict
@@ -49,7 +74,10 @@ def test_non_standard_types(self):
         eq(self.db.guess_extension('image/jpg', strict=True), None)
         # And then non-strict
         eq(self.db.guess_type('foo.xul', strict=False), ('text/xul', None))
+        eq(self.db.guess_type('foo.XUL', strict=False), ('text/xul', None))
+        eq(self.db.guess_type('foo.invalid', strict=False), (None, None))
         eq(self.db.guess_extension('image/jpg', strict=False), '.jpg')
+        eq(self.db.guess_extension('image/JPG', strict=False), '.jpg')
 
     def test_filename_with_url_delimiters(self):
         # bpo-38449: URL delimiters cases should be handled also.
@@ -200,5 +228,53 @@ def test__all__(self):
         support.check__all__(self, mimetypes)
 
 
+class MimetypesCliTestCase(unittest.TestCase):
+
+    def mimetypes_cmd(self, *args, **kwargs):
+        support.patch(self, sys, "argv", [sys.executable, *args])
+        with support.captured_stdout() as output:
+            mimetypes._main()
+            return output.getvalue().strip()
+
+    def test_help_option(self):
+        support.patch(self, sys, "argv", [sys.executable, "-h"])
+        with support.captured_stdout() as output:
+            with self.assertRaises(SystemExit) as cm:
+                mimetypes._main()
+
+        self.assertIn("Usage: mimetypes.py", output.getvalue())
+        self.assertEqual(cm.exception.code, 0)
+
+    def test_invalid_option(self):
+        support.patch(self, sys, "argv", [sys.executable, "--invalid"])
+        with support.captured_stdout() as output:
+            with self.assertRaises(SystemExit) as cm:
+                mimetypes._main()
+
+        self.assertIn("Usage: mimetypes.py", output.getvalue())
+        self.assertEqual(cm.exception.code, 1)
+
+    def test_guess_extension(self):
+        eq = self.assertEqual
+
+        extension = self.mimetypes_cmd("-l", "-e", "image/jpg")
+        eq(extension, ".jpg")
+
+        extension = self.mimetypes_cmd("-e", "image/jpg")
+        eq(extension, "I don't know anything about type image/jpg")
+
+        extension = self.mimetypes_cmd("-e", "image/jpeg")
+        eq(extension, ".jpg")
+
+    def test_guess_type(self):
+        eq = self.assertEqual
+
+        type_info = self.mimetypes_cmd("-l", "foo.pic")
+        eq(type_info, "type: image/pict encoding: None")
+
+        type_info = self.mimetypes_cmd("foo.pic")
+        eq(type_info, "I don't know anything about type foo.pic")
+
+
 if __name__ == "__main__":
     unittest.main()



More information about the Python-checkins mailing list