diff --git a/mathics/eval/import_export/importexport.py b/mathics/eval/import_export/importexport.py index 46be11a10c..eca2f4d644 100644 --- a/mathics/eval/import_export/importexport.py +++ b/mathics/eval/import_export/importexport.py @@ -175,9 +175,20 @@ def eval_ImageExport(expr, path: Optional[str] = None) -> Expression: return Expression(SymbolByteArray, ByteArray(expr_pil.tobytes())) +# MIME types for which mimetypes.guess_extension() depends on the +# platform. For example, without an /etc/mime.types file (as on macOS), +# Python gives ".xsl" for "application/xml". +MIMETYPE_TO_SHORTNAME_OVERRIDE: Final[Dict[str, str]] = { + "application/xml": "XML", + "text/xml": "XML", +} + + def filetype_from_mime_content(mime_content_name: str) -> str: - if mime_content_name in MIMETYPE_TO_SHORTNAME: + if mime_content_name in MIMETYPE_TO_SHORTNAME_OVERRIDE: + short_name = MIMETYPE_TO_SHORTNAME_OVERRIDE[mime_content_name] + elif mime_content_name in MIMETYPE_TO_SHORTNAME: short_name = MIMETYPE_TO_SHORTNAME[mime_content_name] else: # Map MIME type to a standard extension using the stdlib diff --git a/test/builtin/import_export/test_importexport.py b/test/builtin/import_export/test_importexport.py index c016a193e1..bd4149652d 100644 --- a/test/builtin/import_export/test_importexport.py +++ b/test/builtin/import_export/test_importexport.py @@ -401,3 +401,21 @@ def test_inividually(): def test_b64encode(str_expr, msgs, str_expected, fail_msg): """special case""" check_evaluation_as_in_cli(str_expr, str_expected, fail_msg, msgs) + + +@pytest.mark.parametrize( + ("mime_type", "short_name"), + [ + ("application/xml", "XML"), + ("text/xml", "XML"), + ("image/jpeg", "JPG"), + ("image/png", "PNG"), + ], +) +def test_filetype_from_mime_content(mime_type, short_name): + """The short name of a MIME type must not depend on the platform's + mimetypes database (without /etc/mime.types, Python maps + "application/xml" to ".xsl").""" + from mathics.eval.import_export.importexport import filetype_from_mime_content + + assert filetype_from_mime_content(mime_type).lstrip(".") == short_name