From 80d91087a231831dd24c4e17f8b8bbd1e83cee1e Mon Sep 17 00:00:00 2001 From: Vitaliy <160263432+vitalivo@users.noreply.github.com> Date: Sat, 12 Sep 2026 17:39:03 +0300 Subject: [PATCH] Decode binary file contents before detecting frontmatter --- frontmatter/__init__.py | 1 - tests/unit_test.py | 23 +++++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/frontmatter/__init__.py b/frontmatter/__init__.py index 04f4029..bb24b83 100644 --- a/frontmatter/__init__.py +++ b/frontmatter/__init__.py @@ -169,7 +169,6 @@ def load( else: raise ValueError(f"Cannot open filename using type {type(fd)}") - handler = handler or detect_format(text, handlers) return loads(text, encoding, handler, **defaults) diff --git a/tests/unit_test.py b/tests/unit_test.py index 188fb4c..dab28c9 100644 --- a/tests/unit_test.py +++ b/tests/unit_test.py @@ -2,6 +2,7 @@ # -*- coding: utf-8 -*- import os +from io import BytesIO, StringIO import shutil import tempfile import textwrap @@ -27,6 +28,28 @@ class FrontmatterTest(unittest.TestCase): maxDiff = None + def test_load_binary_stream(self): + text = "---\ntitle: Café\n---\nBonjour" + for encoding in ("utf-8", "utf-16"): + with self.subTest(encoding=encoding): + post = frontmatter.load(BytesIO(text.encode(encoding)), encoding=encoding) + self.assertEqual(post.metadata, {"title": "Café"}) + self.assertEqual(post.content, "Bonjour") + self.assertIsInstance(post.handler, YAMLHandler) + + post = frontmatter.load(StringIO(text)) + self.assertEqual(post.metadata, {"title": "Café"}) + self.assertEqual(post.content, "Bonjour") + + def test_load_binary_file(self): + with tempfile.TemporaryFile("w+b") as stream: + stream.write(b'{\n"title": "Hello"\n}\nBody') + stream.seek(0) + post = frontmatter.load(stream, author="Ada") + self.assertEqual(post.metadata, {"title": "Hello", "author": "Ada"}) + self.assertEqual(post.content, "Body") + self.assertIsInstance(post.handler, JSONHandler) + def test_with_markdown_content(self): "Parse frontmatter and only the frontmatter" post = frontmatter.load("tests/yaml/hello-markdown.md")