test: consolidate repetitive cases across the suite

This commit is contained in:
chengyongru authored and chengyongru committed 2026-09-25 14:28:21 +08:00
1 parent c406024b59
commit 6eccc2859a
31 files changed
+745 -1315

No files matched your search

@@ -990,8 +990,22 @@ async def test_read_media_bytes_follows_safe_redirect_when_explicitly_enabled()
@pytest.mark.asyncio
async def test_read_media_bytes_blocks_cross_host_redirect_without_allowlist() -> None:
"""Redirect opt-in should not allow arbitrary cross-host redirects by default."""
@pytest.mark.parametrize(
"response_body, redirect_url",
[
pytest.param(
b'cross-host media',
"https://example.org/final.txt",
id="cross_host_redirect_without_allowlist",
),
pytest.param(
b'internal secret',
"http://127.0.0.1/metadata",
id="private_redirect_even_when_redirects_enabled",
),
],
)
async def test_read_media_bytes_blocks_untrusted_redirects(response_body, redirect_url) -> None:
channel = DingTalkChannel(
DingTalkConfig(
client_id="app",
@@ -1005,14 +1019,14 @@ async def test_read_media_bytes_blocks_cross_host_redirect_without_allowlist() -
responses=[
_FakeResponse(
302,
headers={"location": "https://example.org/final.txt"},
headers={"location": redirect_url},
url="https://example.com/redirect.txt",
),
_FakeResponse(
200,
content=b"cross-host media",
content=response_body,
headers={"content-type": "text/plain"},
url="https://example.org/final.txt",
url=redirect_url,
),
]
)
@@ -1061,40 +1075,6 @@ async def test_read_media_bytes_allows_cross_host_redirect_when_allowlisted() ->
]
@pytest.mark.asyncio
async def test_read_media_bytes_blocks_private_redirect_even_when_redirects_enabled() -> None:
"""Redirect opt-in must still validate each hop before fetching it."""
channel = DingTalkChannel(
DingTalkConfig(
client_id="app",
client_secret="secret",
allow_from=["*"],
allow_remote_media_redirects=True,
),
MessageBus(),
)
channel._http = _FakeHttp(
responses=[
_FakeResponse(
302,
headers={"location": "http://127.0.0.1/metadata"},
url="https://example.com/redirect.txt",
),
_FakeResponse(
200,
content=b"internal secret",
headers={"content-type": "text/plain"},
url="http://127.0.0.1/metadata",
),
]
)
data, filename, content_type = await channel._read_media_bytes("https://example.com/redirect.txt")
assert (data, filename, content_type) == (None, None, None)
assert [call["url"] for call in channel._http.calls] == ["https://example.com/redirect.txt"]
def test_normalize_upload_payload_zips_html_attachment() -> None:
channel = DingTalkChannel(
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"]),
@@ -1111,43 +1111,34 @@ def test_email_with_partial_auth_rejected(monkeypatch) -> None:
assert len(items) == 0, "Email with dkim=fail should be rejected"
def test_forged_authentication_results_cannot_override_trusted_failure(monkeypatch) -> None:
@pytest.mark.parametrize(
"subject, forged_auth_results",
[
pytest.param(
"Forged authentication",
"mx.attacker.example; spf=pass smtp.mailfrom=owner@example.com; dkim=pass header.d=example.com",
id="forged_authentication_results_cannot_override_trusted_failure",
),
pytest.param(
"Forged trusted producer",
"mx.receiver.example; spf=pass smtp.mailfrom=owner@example.com; dkim=pass header.d=example.com",
id="duplicate_header_with_trusted_id_is_rejected",
),
],
)
def test_forged_authentication_results_cannot_override_trusted_failure(
monkeypatch,
subject,
forged_auth_results,
) -> None:
raw = _make_raw_email(
from_addr="owner@example.com",
subject="Forged authentication",
subject=subject,
body="Malicious payload",
auth_results=[
"mx.receiver.example; spf=fail smtp.mailfrom=attacker.example; "
"dkim=fail header.d=attacker.example",
"mx.attacker.example; spf=pass smtp.mailfrom=owner@example.com; "
"dkim=pass header.d=example.com",
],
)
fake = _make_fake_imap(raw)
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda _h, _p: fake)
cfg = _make_config(
allow_from=["owner@example.com"],
verify_dkim=True,
verify_spf=True,
trusted_authserv_ids=["mx.receiver.example"],
)
channel = EmailChannel(cfg, MessageBus())
items, _ = channel._fetch_new_messages()
assert items == []
def test_duplicate_header_with_trusted_id_is_rejected(monkeypatch) -> None:
raw = _make_raw_email(
from_addr="owner@example.com",
subject="Forged trusted producer",
body="Malicious payload",
auth_results=[
"mx.receiver.example; spf=fail smtp.mailfrom=attacker.example; "
"dkim=fail header.d=attacker.example",
"mx.receiver.example; spf=pass smtp.mailfrom=owner@example.com; "
"dkim=pass header.d=example.com",
forged_auth_results,
],
)
fake = _make_fake_imap(raw)
@@ -121,12 +121,40 @@ async def test_tool_hint_multiple_tools_in_one_message(mock_feishu_channel):
@mark.asyncio
async def test_tool_hint_new_format_basic(mock_feishu_channel):
"""New format hints (read path, grep "pattern") should parse correctly."""
@pytest.mark.parametrize(
"content, first_hint, second_hint",
[
pytest.param(
"read src/main.py, grep \"TODO\"",
"read src/main.py",
"grep \"TODO\"",
id="new_format_basic",
),
pytest.param(
"grep \"hello, world\", $ echo test",
"grep \"hello, world\"",
"$ echo test",
id="new_format_with_comma_in_quotes",
),
pytest.param(
"read path × 3, grep \"pattern\"",
"× 3",
"grep \"pattern\"",
id="new_format_with_folding",
),
pytest.param(
"web_search(\"foo, bar\"), read_file(\"/path/to/file\")",
"web_search(\"foo, bar\")",
"read_file(\"/path/to/file\")",
id="keeps_commas_inside_arguments",
),
],
)
async def test_tool_hint_preserves_arguments(mock_feishu_channel, content, first_hint, second_hint):
msg = OutboundMessage(
channel="feishu",
chat_id="oc_123456",
content='read src/main.py, grep "TODO"',
content=content,
event=ProgressEvent(tool_hint=True),
)
@@ -135,46 +163,8 @@ async def test_tool_hint_new_format_basic(mock_feishu_channel):
card = _get_tool_hint_card(mock_send)
md = card["elements"][0]["content"]
assert "read src/main.py" in md
assert 'grep "TODO"' in md
@mark.asyncio
async def test_tool_hint_new_format_with_comma_in_quotes(mock_feishu_channel):
"""Commas inside quoted arguments must not cause incorrect line splits."""
msg = OutboundMessage(
channel="feishu",
chat_id="oc_123456",
content='grep "hello, world", $ echo test',
event=ProgressEvent(tool_hint=True),
)
with patch.object(mock_feishu_channel, '_send_message_sync') as mock_send:
await mock_feishu_channel.send(msg)
card = _get_tool_hint_card(mock_send)
md = card["elements"][0]["content"]
assert 'grep "hello, world"' in md
assert "$ echo test" in md
@mark.asyncio
async def test_tool_hint_new_format_with_folding(mock_feishu_channel):
"""Folded calls (× N) should display correctly."""
msg = OutboundMessage(
channel="feishu",
chat_id="oc_123456",
content='read path × 3, grep "pattern"',
event=ProgressEvent(tool_hint=True),
)
with patch.object(mock_feishu_channel, '_send_message_sync') as mock_send:
await mock_feishu_channel.send(msg)
card = _get_tool_hint_card(mock_send)
md = card["elements"][0]["content"]
assert "\u00d7 3" in md
assert 'grep "pattern"' in md
assert first_hint in md
assert second_hint in md
@mark.asyncio
@@ -193,22 +183,3 @@ async def test_tool_hint_new_format_mcp(mock_feishu_channel):
card = _get_tool_hint_card(mock_send)
md = card["elements"][0]["content"]
assert "4_5v::analyze_image" in md
@mark.asyncio
async def test_tool_hint_keeps_commas_inside_arguments(mock_feishu_channel):
"""Commas inside a single tool argument must not be split onto a new line."""
msg = OutboundMessage(
channel="feishu",
chat_id="oc_123456",
content='web_search("foo, bar"), read_file("/path/to/file")',
event=ProgressEvent(tool_hint=True),
)
with patch.object(mock_feishu_channel, '_send_message_sync') as mock_send:
await mock_feishu_channel.send(msg)
card = _get_tool_hint_card(mock_send)
md = card["elements"][0]["content"]
assert 'web_search("foo, bar")' in md
assert 'read_file("/path/to/file")' in md
@@ -508,17 +508,18 @@ class TestIsAllowed:
ch = _make_channel(dm_enabled=False, group_enabled=False)
assert ch.is_allowed("+19995550001") is False
def test_allows_wildcard(self):
ch = _make_channel(dm_policy="allowlist", dm_allow_from=["*"])
assert ch.is_allowed("+19995550001|some-uuid") is True
def test_allows_composite_sender_against_split_allowlist(self):
"""Composite sender_id, single-id allow_from — must match either part."""
ch = _make_channel(
dm_policy="allowlist",
dm_allow_from=["+19995550001"],
)
assert ch.is_allowed("+19995550001|1872ba20-uuid") is True
@pytest.mark.parametrize(
"expected, sender_id, allowed_id",
[
pytest.param(True, "+19995550001|some-uuid", "*", id="wildcard"),
pytest.param(True, "+19995550001|1872ba20-uuid", "+19995550001", id="phone"),
pytest.param(True, "+19995550001|1872ba20-uuid", "1872ba20-uuid", id="uuid"),
pytest.param(False, "+19995550001|1872ba20-uuid", "+12223334444", id="unknown"),
],
)
def test_allowlist_matches_sender_identifiers(self, expected, sender_id, allowed_id):
ch = _make_channel(dm_policy="allowlist", dm_allow_from=[allowed_id])
assert ch.is_allowed(sender_id) is expected
def test_allows_composite_sender_against_composite_allowlist_entry(self):
"""Backward compat: pipe-joined composite allowlist entries still match."""
@@ -526,14 +527,6 @@ class TestIsAllowed:
ch = _make_channel(dm_policy="allowlist", dm_allow_from=[composite])
assert ch.is_allowed(composite) is True
def test_allows_when_only_uuid_part_is_listed(self):
ch = _make_channel(dm_policy="allowlist", dm_allow_from=["1872ba20-uuid"])
assert ch.is_allowed("+19995550001|1872ba20-uuid") is True
def test_denies_when_no_part_matches(self):
ch = _make_channel(dm_policy="allowlist", dm_allow_from=["+12223334444"])
assert ch.is_allowed("+19995550001|1872ba20-uuid") is False
def test_allowlist_union_includes_group_ids(self):
"""allow_from is the union of dm.allow_from and group.allow_from."""
ch = _make_channel(
@@ -1,5 +1,7 @@
"""Unit tests for the Signal markdown → plain text + textStyle converter."""
import pytest
from nanobot.channels.signal.runtime import _markdown_to_signal, _partition_styles
from nanobot.utils.helpers import split_message
@@ -36,46 +38,49 @@ def utf16_styles_for(plain: str, text_styles: list[str]) -> dict[str, list[str]]
# ---------------------------------------------------------------------------
def test_empty():
plain, styles = _markdown_to_signal("")
assert plain == ""
@pytest.mark.parametrize(
"markdown, expected_plain",
[
pytest.param("", "", id="empty"),
pytest.param("hello world", "hello world", id="plain_text"),
pytest.param("> some quote", "some quote", id="blockquote_strips_marker"),
pytest.param(
"[Click here](https://example.com)",
"Click here (https://example.com)",
id="link_text_differs_from_url",
),
pytest.param(
"[https://example.com](https://example.com)",
"https://example.com",
id="link_text_equals_url",
),
pytest.param("**bold", "**bold", id="unclosed_bold_falls_through_as_plain"),
pytest.param("use `grep", "use `grep", id="unclosed_inline_code_falls_through_as_plain"),
],
)
def test_markdown_without_styles(markdown, expected_plain):
plain, styles = _markdown_to_signal(markdown)
assert plain == expected_plain
assert styles == []
def test_plain_text():
plain, styles = _markdown_to_signal("hello world")
assert plain == "hello world"
assert styles == []
def test_bold_stars():
plain, styles = _markdown_to_signal("say **hello** now")
assert plain == "say hello now"
assert styles_for(plain, styles) == {"hello": ["BOLD"]}
def test_bold_underscores():
plain, styles = _markdown_to_signal("say __hello__ now")
assert plain == "say hello now"
assert styles_for(plain, styles) == {"hello": ["BOLD"]}
def test_italic_star():
plain, styles = _markdown_to_signal("say *hello* now")
assert plain == "say hello now"
assert styles_for(plain, styles) == {"hello": ["ITALIC"]}
def test_italic_underscore():
plain, styles = _markdown_to_signal("say _hello_ now")
assert plain == "say hello now"
assert styles_for(plain, styles) == {"hello": ["ITALIC"]}
def test_strikethrough():
plain, styles = _markdown_to_signal("say ~~hello~~ now")
assert plain == "say hello now"
assert styles_for(plain, styles) == {"hello": ["STRIKETHROUGH"]}
@pytest.mark.parametrize(
"markdown, expected_plain, styled_text, style",
[
pytest.param("say **hello** now", "say hello now", "hello", "BOLD", id="bold_stars"),
pytest.param("say __hello__ now", "say hello now", "hello", "BOLD", id="bold_underscores"),
pytest.param("say *hello* now", "say hello now", "hello", "ITALIC", id="italic_star"),
pytest.param("say _hello_ now", "say hello now", "hello", "ITALIC", id="italic_underscore"),
pytest.param("say ~~hello~~ now", "say hello now", "hello", "STRIKETHROUGH", id="strikethrough"),
pytest.param("run `ls -la` here", "run ls -la here", "ls -la", "MONOSPACE", id="inline_code"),
pytest.param("# My Title", "My Title", "My Title", "BOLD", id="header_becomes_bold"),
pytest.param("## Sub-section", "Sub-section", "Sub-section", "BOLD", id="h2_becomes_bold"),
],
)
def test_markdown_style_mapping(markdown, expected_plain, styled_text, style):
plain, styles = _markdown_to_signal(markdown)
assert plain == expected_plain
assert styles_for(plain, styles) == {styled_text: [style]}
# ---------------------------------------------------------------------------
@@ -83,12 +88,6 @@ def test_strikethrough():
# ---------------------------------------------------------------------------
def test_inline_code():
plain, styles = _markdown_to_signal("run `ls -la` here")
assert plain == "run ls -la here"
assert styles_for(plain, styles) == {"ls -la": ["MONOSPACE"]}
def test_code_block():
plain, styles = _markdown_to_signal("```\nprint('hi')\n```")
assert "print('hi')" in plain
@@ -120,34 +119,6 @@ def test_inline_code_not_processed_further():
assert "BOLD" not in entry
# ---------------------------------------------------------------------------
# Headers
# ---------------------------------------------------------------------------
def test_header_becomes_bold():
plain, styles = _markdown_to_signal("# My Title")
assert plain == "My Title"
assert styles_for(plain, styles) == {"My Title": ["BOLD"]}
def test_h2_becomes_bold():
plain, styles = _markdown_to_signal("## Sub-section")
assert plain == "Sub-section"
assert styles_for(plain, styles) == {"Sub-section": ["BOLD"]}
# ---------------------------------------------------------------------------
# Blockquotes
# ---------------------------------------------------------------------------
def test_blockquote_strips_marker():
plain, styles = _markdown_to_signal("> some quote")
assert plain == "some quote"
assert styles == []
# ---------------------------------------------------------------------------
# Lists
# ---------------------------------------------------------------------------
@@ -174,18 +145,6 @@ def test_numbered_list():
# ---------------------------------------------------------------------------
def test_link_text_differs_from_url():
plain, styles = _markdown_to_signal("[Click here](https://example.com)")
assert plain == "Click here (https://example.com)"
assert styles == []
def test_link_text_equals_url():
plain, styles = _markdown_to_signal("[https://example.com](https://example.com)")
assert plain == "https://example.com"
assert styles == []
def test_link_text_equals_url_without_scheme():
plain, styles = _markdown_to_signal("[example.com](https://example.com)")
assert plain == "https://example.com"
@@ -280,47 +239,21 @@ def assert_within_utf16_bounds(plain: str, styles: list[str]) -> None:
assert start + length <= limit, f"range {entry} exceeds utf-16 length {limit} of {plain!r}"
def test_bold_with_emoji_inside():
plain, styles = _markdown_to_signal("**hi 🎉 bye**")
assert plain == "hi 🎉 bye"
assert utf16_styles_for(plain, styles) == {"hi 🎉 bye": ["BOLD"]}
assert_within_utf16_bounds(plain, styles)
def test_italic_with_trailing_emoji():
plain, styles = _markdown_to_signal("*bye 🎉*")
assert plain == "bye 🎉"
assert utf16_styles_for(plain, styles) == {"bye 🎉": ["ITALIC"]}
assert_within_utf16_bounds(plain, styles)
def test_bold_after_emoji_prefix():
plain, styles = _markdown_to_signal("🎉 **bold**")
assert plain == "🎉 bold"
assert utf16_styles_for(plain, styles) == {"bold": ["BOLD"]}
assert_within_utf16_bounds(plain, styles)
def test_bold_after_and_inside_emoji():
plain, styles = _markdown_to_signal("🎉 **a 🎊 b**")
assert plain == "🎉 a 🎊 b"
assert utf16_styles_for(plain, styles) == {"a 🎊 b": ["BOLD"]}
assert_within_utf16_bounds(plain, styles)
def test_supplementary_cjk_in_bold():
"""Non-BMP CJK (U+20BB7) proves the bug is UTF-16, not emoji-specific."""
plain, styles = _markdown_to_signal("**𠮷野家**")
assert plain == "𠮷野家"
assert utf16_styles_for(plain, styles) == {"𠮷野家": ["BOLD"]}
assert_within_utf16_bounds(plain, styles)
def test_zwj_emoji_in_bold():
"""ZWJ family sequence = multiple surrogate pairs + BMP ZWJs."""
plain, styles = _markdown_to_signal("**hi 👨‍👩‍👧 bye**")
assert plain == "hi 👨‍👩‍👧 bye"
assert utf16_styles_for(plain, styles) == {"hi 👨‍👩‍👧 bye": ["BOLD"]}
@pytest.mark.parametrize(
"markdown, expected_plain, styled_text, style",
[
pytest.param("**hi 🎉 bye**", "hi 🎉 bye", "hi 🎉 bye", "BOLD", id="bold_with_emoji_inside"),
pytest.param("*bye 🎉*", "bye 🎉", "bye 🎉", "ITALIC", id="italic_with_trailing_emoji"),
pytest.param("🎉 **bold**", "🎉 bold", "bold", "BOLD", id="bold_after_emoji_prefix"),
pytest.param("🎉 **a 🎊 b**", "🎉 a 🎊 b", "a 🎊 b", "BOLD", id="bold_after_and_inside_emoji"),
pytest.param("**𠮷野家**", "𠮷野家", "𠮷野家", "BOLD", id="supplementary_cjk_in_bold"),
pytest.param("**hi 👨‍👩‍👧 bye**", "hi 👨‍👩‍👧 bye", "hi 👨‍👩‍👧 bye", "BOLD", id="zwj_emoji_in_bold"),
],
)
def test_style_offsets_use_utf16(markdown, expected_plain, styled_text, style):
plain, styles = _markdown_to_signal(markdown)
assert plain == expected_plain
assert utf16_styles_for(plain, styles) == {styled_text: [style]}
assert_within_utf16_bounds(plain, styles)
@@ -494,20 +427,6 @@ def test_bold_and_italic_adjacent_no_separator():
assert sd.get("italic") == ["ITALIC"]
def test_unclosed_bold_falls_through_as_plain():
"""An unmatched `**` opener round-trips as literal text with no style."""
plain, styles = _markdown_to_signal("**bold")
assert plain == "**bold"
assert styles == []
def test_unclosed_inline_code_falls_through_as_plain():
"""An unmatched backtick round-trips as literal text with no style."""
plain, styles = _markdown_to_signal("use `grep")
assert plain == "use `grep"
assert styles == []
def test_inline_code_inside_blockquote():
"""Blockquote prefix is stripped; inline code becomes MONOSPACE."""
plain, styles = _markdown_to_signal("> use `grep`")
@@ -518,35 +518,21 @@ async def test_message_rejected_on_svg_mime(tmp_path) -> None:
@pytest.mark.asyncio
async def test_message_rejected_on_malformed_data_url(tmp_path) -> None:
@pytest.mark.parametrize(
"data_url",
[
pytest.param("http://evil.example/image.png", id="malformed_data_url"),
pytest.param("data:image/png;base64,not-valid-base64!!!", id="broken_base64"),
],
)
async def test_message_rejects_invalid_media_data_url(tmp_path, data_url) -> None:
channel = _make_channel()
mock_conn = AsyncMock()
envelope = {
"type": "message",
"chat_id": "abc123",
"content": "nope",
"media": [{"data_url": "http://evil.example/image.png"}],
}
with patch(
"nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path
):
await channel._dispatch_envelope(mock_conn, "client-1", envelope)
channel._handle_message.assert_not_awaited()
err = json.loads(mock_conn.send.call_args[0][0])
assert err["reason"] == "decode"
@pytest.mark.asyncio
async def test_message_rejected_on_broken_base64(tmp_path) -> None:
channel = _make_channel()
mock_conn = AsyncMock()
envelope = {
"type": "message",
"chat_id": "abc123",
"content": "nope",
"media": [{"data_url": "data:image/png;base64,not-valid-base64!!!"}],
"media": [{"data_url": data_url}],
}
with patch(