plone / Products.MimetypesRegistry

Provide a persistent registry of mimetypes for Plone
1 stars 7 forks source link

MimeTypesRegistry.classify() fails with a bytes data #39

Open fdiary opened 1 month ago

fdiary commented 1 month ago

Hello,

https://github.com/plone/Products.MimetypesRegistry/blob/fe06e9f554b58c03b2dc69f1b1eda5630f5265a9/Products/MimetypesRegistry/MimeTypesRegistry.py#L322-L325

Here, the code assume data is str but it can be bytes.

I'd like to propose the following change.

diff --git a/Products/MimetypesRegistry/MimeTypesRegistry.py b/Products/MimetypesRegistry/MimeTypesRegistry.py
index 1f5c4b5..438f439 100644
--- a/Products/MimetypesRegistry/MimeTypesRegistry.py
+++ b/Products/MimetypesRegistry/MimeTypesRegistry.py
@@ -322,7 +322,8 @@ class MimeTypesRegistry(UniqueObject, ActionProviderBase, Folder):
                 failed = "text/x-unknown-content-type"
                 filename = filename or ""
                 data = data or ""
-                data = data.encode()
+                if isinstance(data, str):
+                    data = data.encode()
                 ct, enc = guess_content_type(filename, data, None)
                 if ct == failed:
                     ct = "text/plain"
diff --git a/Products/MimetypesRegistry/tests/test_mimetypes.py b/Products/MimetypesRegistry/tests/test_mimetypes.py
index 1f55056..d0e7a40 100644
--- a/Products/MimetypesRegistry/tests/test_mimetypes.py
+++ b/Products/MimetypesRegistry/tests/test_mimetypes.py
@@ -73,6 +73,10 @@ class TestMimeTypesclass(unittest.TestCase):
         mt = reg.classify("baz", filename="xxx")
         self.assertTrue(isinstance(mt, application_octet_stream), str(mt))

+        # test binary data
+        mt = reg.classify(b"\x01")
+        self.assertTrue(isinstance(mt, application_octet_stream), str(mt))
+
     def testExtension(self):
         reg = self.registry
         data = "<foo>bar</foo>"
gforcada commented 1 month ago

@fdiary thanks for the patch. Would you mind creating a PR for it? Did you sign the contributors agreement?

fdiary commented 1 month ago

@gforcada thanks for your comment. I just posted a PR #40. I already signed the agreement on March 31th 2021.