|
| 1 | +"""Protocol-level tests for decoding a page by the charset its HTML declares (#5199). |
| 2 | +
|
| 3 | +httpx decodes a body by the Content-Type header's charset and falls back to |
| 4 | +UTF-8 without one, so a legacy-encoded page that names its charset only in a |
| 5 | +``<meta charset>`` or ``<meta http-equiv="Content-Type">`` tag came back |
| 6 | +garbled. ``decode_page`` now scans the head of an HTML (or untyped) body for |
| 7 | +that declaration when the header names none. These tests drive the real |
| 8 | +server through an MCP client with HTTP served by ``harness.FakeWeb``, and pin |
| 9 | +both the fix and its edges: the header and a byte order mark still win, a |
| 10 | +declaration on a non-HTML body or past the first 1024 bytes is ignored, and an |
| 11 | +unknown or unusable declared charset falls back to the old decoding. |
| 12 | +
|
| 13 | +Most cases fetch with ``raw: true`` so the decoded text reaches the client |
| 14 | +untouched by HTML extraction; one case goes through extraction to show the |
| 15 | +Markdown is right too. |
| 16 | +""" |
| 17 | + |
| 18 | +from __future__ import annotations |
| 19 | + |
| 20 | +from typing import Any |
| 21 | + |
| 22 | +import httpx |
| 23 | +import pytest |
| 24 | +from mcp import ClientSession |
| 25 | +from mcp.types import CallToolResult |
| 26 | + |
| 27 | +from .harness import FakeWeb, connect |
| 28 | + |
| 29 | +PAGE = "https://example.com/page" |
| 30 | +ROBOTS = "https://example.com/robots.txt" |
| 31 | + |
| 32 | +JAPANESE = "日本語のページです" |
| 33 | +RUSSIAN = "Привет, мир" |
| 34 | +KOREAN = "안녕하세요 세계" |
| 35 | +CHINESE = "你好,世界" |
| 36 | + |
| 37 | + |
| 38 | +def text_of(result: CallToolResult) -> str: |
| 39 | + assert not result.is_error, result |
| 40 | + data = result.model_dump(by_alias=True, mode="json", exclude_none=True) |
| 41 | + assert len(data["content"]) == 1 |
| 42 | + return data["content"][0]["text"] |
| 43 | + |
| 44 | + |
| 45 | +def page(body: bytes, content_type: str | None = "text/html") -> httpx.Response: |
| 46 | + headers = {} if content_type is None else {"content-type": content_type} |
| 47 | + return httpx.Response(200, content=body, headers=headers) |
| 48 | + |
| 49 | + |
| 50 | +async def fetch(web: FakeWeb, response: httpx.Response, **arguments: Any) -> str: |
| 51 | + web.add(ROBOTS, httpx.Response(404)) |
| 52 | + web.add(PAGE, response) |
| 53 | + async with connect() as (session, _): |
| 54 | + assert isinstance(session, ClientSession) |
| 55 | + result = await session.call_tool("fetch", {"url": PAGE, **arguments}) |
| 56 | + return text_of(result) |
| 57 | + |
| 58 | + |
| 59 | +def document(meta: str, text: str) -> str: |
| 60 | + return f"<html><head>{meta}<title>t</title></head><body><p>{text}</p></body></html>" |
| 61 | + |
| 62 | + |
| 63 | +@pytest.mark.parametrize( |
| 64 | + ("meta", "encoding", "text"), |
| 65 | + [ |
| 66 | + ('<meta charset="Shift_JIS">', "shift_jis", JAPANESE), |
| 67 | + ("<meta charset=windows-1251>", "cp1251", RUSSIAN), |
| 68 | + ("<META CHARSET='euc-kr'>", "euc_kr", KOREAN), |
| 69 | + ('<meta charset="GBK" />', "gbk", CHINESE), |
| 70 | + ( |
| 71 | + '<meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">', |
| 72 | + "shift_jis", |
| 73 | + JAPANESE, |
| 74 | + ), |
| 75 | + ( |
| 76 | + "<meta http-equiv='content-type' content='text/html;charset=windows-1251'>", |
| 77 | + "cp1251", |
| 78 | + RUSSIAN, |
| 79 | + ), |
| 80 | + ], |
| 81 | +) |
| 82 | +async def test_a_charset_declared_only_in_the_html_is_honored( |
| 83 | + web: FakeWeb, meta: str, encoding: str, text: str |
| 84 | +) -> None: |
| 85 | + body = document(meta, text).encode(encoding) |
| 86 | + assert text in await fetch(web, page(body), raw=True) |
| 87 | + |
| 88 | + |
| 89 | +async def test_a_declared_charset_is_honored_without_a_content_type_header( |
| 90 | + web: FakeWeb, |
| 91 | +) -> None: |
| 92 | + body = document('<meta charset="Shift_JIS">', JAPANESE).encode("shift_jis") |
| 93 | + assert JAPANESE in await fetch(web, page(body, content_type=None), raw=True) |
| 94 | + |
| 95 | + |
| 96 | +async def test_xhtml_content_type_is_scanned(web: FakeWeb) -> None: |
| 97 | + body = document('<meta charset="windows-1251">', RUSSIAN).encode("cp1251") |
| 98 | + response = page(body, content_type="application/xhtml+xml") |
| 99 | + assert RUSSIAN in await fetch(web, response, raw=True) |
| 100 | + |
| 101 | + |
| 102 | +async def test_the_extracted_markdown_is_decoded_too( |
| 103 | + web: FakeWeb, python_readability: None |
| 104 | +) -> None: |
| 105 | + body = document('<meta charset="Shift_JIS">', JAPANESE).encode("shift_jis") |
| 106 | + assert JAPANESE in await fetch(web, page(body)) |
| 107 | + |
| 108 | + |
| 109 | +async def test_a_header_charset_wins_over_the_html_declaration(web: FakeWeb) -> None: |
| 110 | + # The page lies in its meta tag; the header is right, and wins. |
| 111 | + body = document('<meta charset="Shift_JIS">', RUSSIAN).encode("cp1251") |
| 112 | + response = page(body, content_type="text/html; charset=windows-1251") |
| 113 | + assert RUSSIAN in await fetch(web, response, raw=True) |
| 114 | + |
| 115 | + |
| 116 | +async def test_a_byte_order_mark_wins_over_the_html_declaration( |
| 117 | + web: FakeWeb, |
| 118 | +) -> None: |
| 119 | + body = b"\xef\xbb\xbf" + document('<meta charset="Shift_JIS">', JAPANESE).encode( |
| 120 | + "utf-8" |
| 121 | + ) |
| 122 | + assert JAPANESE in await fetch(web, page(body), raw=True) |
| 123 | + |
| 124 | + |
| 125 | +async def test_a_declaration_on_a_non_html_body_is_ignored(web: FakeWeb) -> None: |
| 126 | + # A text/plain body is UTF-8 by default; a meta-like string in it is text. |
| 127 | + body = document('<meta charset="windows-1251">', JAPANESE).encode("utf-8") |
| 128 | + assert JAPANESE in await fetch(web, page(body, content_type="text/plain")) |
| 129 | + |
| 130 | + |
| 131 | +async def test_a_declaration_past_the_first_1024_bytes_is_ignored( |
| 132 | + web: FakeWeb, |
| 133 | +) -> None: |
| 134 | + padding = "<!-- " + "x" * 1100 + " -->" |
| 135 | + body = ( |
| 136 | + f"<html><head>{padding}<meta charset=windows-1251></head>" |
| 137 | + f"<body><p>{JAPANESE}</p></body></html>" |
| 138 | + ).encode("utf-8") |
| 139 | + assert JAPANESE in await fetch(web, page(body), raw=True) |
| 140 | + |
| 141 | + |
| 142 | +async def test_a_page_with_no_declaration_is_decoded_as_utf8(web: FakeWeb) -> None: |
| 143 | + body = document("", JAPANESE).encode("utf-8") |
| 144 | + assert JAPANESE in await fetch(web, page(body), raw=True) |
| 145 | + |
| 146 | + |
| 147 | +@pytest.mark.parametrize( |
| 148 | + "declared", |
| 149 | + [ |
| 150 | + # Unknown to Python. |
| 151 | + "no-such-charset", |
| 152 | + "x-user-defined", |
| 153 | + # Known codecs that are not text encodings, or refuse to decode. |
| 154 | + "base64", |
| 155 | + "rot13", |
| 156 | + "undefined", |
| 157 | + # Text codecs that are not web encodings. |
| 158 | + "unicode_escape", |
| 159 | + "raw_unicode_escape", |
| 160 | + "idna", |
| 161 | + "punycode", |
| 162 | + ], |
| 163 | +) |
| 164 | +async def test_an_unusable_declared_charset_falls_back_to_the_old_decoding( |
| 165 | + web: FakeWeb, declared: str |
| 166 | +) -> None: |
| 167 | + body = document(f'<meta charset="{declared}">', JAPANESE + " \\u0041").encode( |
| 168 | + "utf-8" |
| 169 | + ) |
| 170 | + text = await fetch(web, page(body), raw=True) |
| 171 | + assert JAPANESE + " \\u0041" in text |
| 172 | + |
| 173 | + |
| 174 | +@pytest.mark.parametrize("declared", ["utf-16", "UTF-16LE", "utf-32"]) |
| 175 | +async def test_a_utf16_or_utf32_declaration_is_read_as_utf8( |
| 176 | + web: FakeWeb, declared: str |
| 177 | +) -> None: |
| 178 | + body = document(f'<meta charset="{declared}">', JAPANESE).encode("utf-8") |
| 179 | + assert JAPANESE in await fetch(web, page(body), raw=True) |
0 commit comments