|
| 1 | +#!/usr/bin/env python3 -m pytest |
| 2 | +import io |
| 3 | +import json |
| 4 | + |
| 5 | +import pytest |
| 6 | + |
| 7 | +from markitdown import MarkItDown, StreamInfo |
| 8 | +from markitdown._charset_utils import decode_bytes, normalize_charset |
| 9 | + |
| 10 | +# Longer than the 4k prefix that _get_stream_info_guesses sniffs for a charset, |
| 11 | +# so the non-ASCII character below lands outside the sniffed window. |
| 12 | +_PREFIX_PADDING = "word " * 1200 |
| 13 | + |
| 14 | +# Sits beyond _PREFIX_PADDING, and is not representable in ASCII or cp1252-as-ASCII. |
| 15 | +_LATE_CHARACTER = "—" # em dash |
| 16 | + |
| 17 | + |
| 18 | +def _convert_bytes(data: bytes, extension: str) -> str: |
| 19 | + markitdown = MarkItDown() |
| 20 | + return markitdown.convert( |
| 21 | + io.BytesIO(data), stream_info=StreamInfo(extension=extension) |
| 22 | + ).markdown |
| 23 | + |
| 24 | + |
| 25 | +def _convert_declared(data: bytes, extension: str, charset: str) -> str: |
| 26 | + """Convert with a charset declared up front, as a Content-Type header would.""" |
| 27 | + markitdown = MarkItDown() |
| 28 | + return markitdown.convert( |
| 29 | + io.BytesIO(data), stream_info=StreamInfo(extension=extension, charset=charset) |
| 30 | + ).markdown |
| 31 | + |
| 32 | + |
| 33 | +def test_decode_bytes_honors_correct_charset(): |
| 34 | + assert decode_bytes("café".encode("utf-8"), "utf-8") == "café" |
| 35 | + assert decode_bytes("café".encode("cp1252"), "cp1252") == "café" |
| 36 | + |
| 37 | + |
| 38 | +def test_decode_bytes_recovers_from_wrong_charset(): |
| 39 | + """A charset that cannot decode the data must not raise.""" |
| 40 | + assert decode_bytes("café".encode("utf-8"), "ascii") == "café" |
| 41 | + |
| 42 | + |
| 43 | +def test_decode_bytes_recovers_from_unknown_charset(): |
| 44 | + assert decode_bytes(b"plain text", "not-a-real-codec") == "plain text" |
| 45 | + |
| 46 | + |
| 47 | +def test_decode_bytes_without_charset_detects(): |
| 48 | + assert decode_bytes("café".encode("utf-8")) == "café" |
| 49 | + |
| 50 | + |
| 51 | +@pytest.mark.parametrize( |
| 52 | + "data", |
| 53 | + [ |
| 54 | + b"valid ascii tail \xc3\x28", # truncated utf-8 sequence |
| 55 | + b"valid ascii tail \xff\xff\xff", |
| 56 | + b"\xff\xfe\x00 utf-16 byte order mark", |
| 57 | + b"", |
| 58 | + ], |
| 59 | +) |
| 60 | +def test_decode_bytes_never_raises(data): |
| 61 | + """Undecodable bytes degrade to a lossy decode rather than failing the conversion.""" |
| 62 | + assert isinstance(decode_bytes(data, "utf-8"), str) |
| 63 | + assert isinstance(decode_bytes(data), str) |
| 64 | + |
| 65 | + |
| 66 | +def test_decode_bytes_preserves_decodable_text_around_bad_bytes(): |
| 67 | + assert "valid ascii tail" in decode_bytes(b"valid ascii tail \xc3\x28", "utf-8") |
| 68 | + |
| 69 | + |
| 70 | +def test_normalize_charset(): |
| 71 | + assert normalize_charset(None) is None |
| 72 | + assert normalize_charset("UTF8") == normalize_charset("utf-8") |
| 73 | + assert normalize_charset("not-a-real-codec") == "not-a-real-codec" |
| 74 | + |
| 75 | + |
| 76 | +def test_non_ascii_beyond_sniffed_prefix(): |
| 77 | + """ |
| 78 | + Regression: the charset is sniffed from the first 4k of the stream but used |
| 79 | + to decode all of it, so a mostly-ASCII document whose first non-ASCII |
| 80 | + character appears past that window used to fail with a UnicodeDecodeError. |
| 81 | + """ |
| 82 | + content = _PREFIX_PADDING + _LATE_CHARACTER + " tail" |
| 83 | + result = _convert_bytes(content.encode("utf-8"), ".txt") |
| 84 | + assert _LATE_CHARACTER in result |
| 85 | + assert "tail" in result |
| 86 | + |
| 87 | + |
| 88 | +# A charset can also arrive already declared -- from a Content-Type header, or |
| 89 | +# from the caller -- in which case it is trusted without being sniffed at all. |
| 90 | +# These cover each converter that decodes a whole stream with such a charset. |
| 91 | + |
| 92 | + |
| 93 | +def test_declared_charset_too_narrow_plain_text(): |
| 94 | + content = _PREFIX_PADDING + _LATE_CHARACTER |
| 95 | + result = _convert_declared(content.encode("utf-8"), ".txt", "ascii") |
| 96 | + assert _LATE_CHARACTER in result |
| 97 | + |
| 98 | + |
| 99 | +def test_declared_charset_too_narrow_csv(): |
| 100 | + content = "header\n" + _PREFIX_PADDING + "\n" + _LATE_CHARACTER + "\n" |
| 101 | + result = _convert_declared(content.encode("utf-8"), ".csv", "ascii") |
| 102 | + assert _LATE_CHARACTER in result |
| 103 | + |
| 104 | + |
| 105 | +def test_declared_charset_too_narrow_ipynb(): |
| 106 | + notebook = { |
| 107 | + "nbformat": 4, |
| 108 | + "nbformat_minor": 5, |
| 109 | + "metadata": {}, |
| 110 | + "cells": [ |
| 111 | + # Padded so the non-ASCII cell below falls outside the sniffed prefix, |
| 112 | + # leaving the declared charset the only one in play. |
| 113 | + { |
| 114 | + "cell_type": "markdown", |
| 115 | + "metadata": {}, |
| 116 | + "source": [_PREFIX_PADDING], |
| 117 | + }, |
| 118 | + { |
| 119 | + "cell_type": "markdown", |
| 120 | + "metadata": {}, |
| 121 | + "source": [f"late {_LATE_CHARACTER} character"], |
| 122 | + }, |
| 123 | + ], |
| 124 | + } |
| 125 | + data = json.dumps(notebook, ensure_ascii=False).encode("utf-8") |
| 126 | + result = _convert_declared(data, ".ipynb", "ascii") |
| 127 | + assert _LATE_CHARACTER in result |
| 128 | + |
| 129 | + |
| 130 | +def test_pure_ascii_still_round_trips(): |
| 131 | + content = _PREFIX_PADDING + "plain ascii tail" |
| 132 | + result = _convert_bytes(content.encode("ascii"), ".txt") |
| 133 | + assert "plain ascii tail" in result |
| 134 | + |
| 135 | + |
| 136 | +def test_non_utf8_charset_is_not_clobbered(): |
| 137 | + """Widening applies only to an ASCII guess -- other charsets are preserved.""" |
| 138 | + markitdown = MarkItDown() |
| 139 | + content = "テスト " + _PREFIX_PADDING |
| 140 | + stream = io.BytesIO(content.encode("cp932")) |
| 141 | + guesses = markitdown._get_stream_info_guesses( |
| 142 | + stream, base_guess=StreamInfo(extension=".txt") |
| 143 | + ) |
| 144 | + assert normalize_charset(guesses[0].charset) == normalize_charset("cp932") |
| 145 | + assert "テスト" in markitdown.convert(stream, file_extension=".txt").markdown |
0 commit comments