test: consolidate repetitive cases across the suite
This commit is contained in:
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(
|
||||
|
||||
@@ -465,39 +465,20 @@ async def test_loop_stream_filter_handles_think_only_prefix_without_crashing(tmp
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_loop_stream_filter_hides_partial_trailing_think_prefix(tmp_path):
|
||||
@pytest.mark.parametrize(
|
||||
"first_delta, second_delta",
|
||||
[
|
||||
pytest.param("Hello <thin", "k>hidden</think>World", id="partial_trailing_think_prefix"),
|
||||
pytest.param("Hello <think>", "hidden</think>World", id="complete_trailing_think_tag"),
|
||||
],
|
||||
)
|
||||
async def test_loop_stream_filter_hides_split_think_tags(tmp_path, first_delta, second_delta):
|
||||
loop = _make_loop(tmp_path)
|
||||
deltas: list[str] = []
|
||||
|
||||
async def chat_stream_with_retry(*, on_content_delta, **kwargs):
|
||||
await on_content_delta("Hello <thin")
|
||||
await on_content_delta("k>hidden</think>World")
|
||||
return LLMResponse(content="Hello <think>hidden</think>World", tool_calls=[], usage=None)
|
||||
|
||||
loop.provider.chat_stream_with_retry = chat_stream_with_retry
|
||||
|
||||
async def on_stream(delta: str) -> None:
|
||||
deltas.append(delta)
|
||||
|
||||
result = await loop._run_agent_loop(
|
||||
TranscriptInput(history=[], current_message=None),
|
||||
runtime=loop.llm_runtime(),
|
||||
events=output_events(on_stream=on_stream),
|
||||
streaming=True,
|
||||
)
|
||||
|
||||
assert result.final_content == "Hello World"
|
||||
assert deltas == ["Hello", " World"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_loop_stream_filter_hides_complete_trailing_think_tag(tmp_path):
|
||||
loop = _make_loop(tmp_path)
|
||||
deltas: list[str] = []
|
||||
|
||||
async def chat_stream_with_retry(*, on_content_delta, **kwargs):
|
||||
await on_content_delta("Hello <think>")
|
||||
await on_content_delta("hidden</think>World")
|
||||
await on_content_delta(first_delta)
|
||||
await on_content_delta(second_delta)
|
||||
return LLMResponse(content="Hello <think>hidden</think>World", tool_calls=[], usage=None)
|
||||
|
||||
loop.provider.chat_stream_with_retry = chat_stream_with_retry
|
||||
|
||||
@@ -71,33 +71,24 @@ class TestHistoryWithCursor:
|
||||
cursor = store.append_history("event 3")
|
||||
assert cursor == 3
|
||||
|
||||
def test_append_history_strips_thinking_content(self, store):
|
||||
"""`strip_think` must run before persistence — well-formed thinking
|
||||
blocks shouldn't land in history."""
|
||||
cursor = store.append_history("<think>reasoning</think>final answer")
|
||||
@pytest.mark.parametrize(
|
||||
"input_text, expected_content",
|
||||
[
|
||||
pytest.param(
|
||||
"<think>reasoning</think>final answer",
|
||||
"final answer",
|
||||
id="strips_thinking_content",
|
||||
),
|
||||
pytest.param("<think>nothing user-facing</think>", "", id="drops_pure_leak_content"),
|
||||
pytest.param("<channel|>", "", id="drops_malformed_leak_prefix"),
|
||||
],
|
||||
)
|
||||
def test_append_history_sanitizes_thinking(self, store, input_text, expected_content):
|
||||
cursor = store.append_history(input_text)
|
||||
content = store.read_file(store.history_file)
|
||||
data = json.loads(content)
|
||||
assert data["cursor"] == cursor
|
||||
assert data["content"] == "final answer"
|
||||
|
||||
def test_append_history_drops_pure_leak_content(self, store):
|
||||
"""Regression: entries that strip down to empty (pure template-token
|
||||
leak) must NOT fall back to the raw leak. Persisting the raw text
|
||||
would re-pollute context via consolidation / replay, undoing the
|
||||
protection `strip_think` provides."""
|
||||
cursor = store.append_history("<think>nothing user-facing</think>")
|
||||
content = store.read_file(store.history_file)
|
||||
data = json.loads(content)
|
||||
assert data["cursor"] == cursor
|
||||
assert data["content"] == ""
|
||||
|
||||
def test_append_history_drops_malformed_leak_prefix(self, store):
|
||||
"""Channel-marker / malformed opening leaks should not survive."""
|
||||
cursor = store.append_history("<channel|>")
|
||||
content = store.read_file(store.history_file)
|
||||
data = json.loads(content)
|
||||
assert data["cursor"] == cursor
|
||||
assert data["content"] == ""
|
||||
assert data["content"] == expected_content
|
||||
|
||||
def test_read_unprocessed_history(self, store):
|
||||
store.append_history("event 1")
|
||||
|
||||
@@ -8,6 +8,7 @@ from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, cast
|
||||
|
||||
import pytest
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from nanobot.cli import onboard as onboard_wizard
|
||||
@@ -240,32 +241,20 @@ class TestGetFieldDisplayName:
|
||||
name = _get_field_display_name("user_name", field_info)
|
||||
assert name == "User Name"
|
||||
|
||||
def test_adds_url_suffix(self):
|
||||
@pytest.mark.parametrize(
|
||||
"field_name, suffix, prefix",
|
||||
[
|
||||
pytest.param("api_url", "Url", "Api", id="url_suffix"),
|
||||
pytest.param("file_path", "Path", "File", id="path_suffix"),
|
||||
pytest.param("user_id", "Id", "User", id="id_suffix"),
|
||||
pytest.param("api_key", "Key", "Api", id="key_suffix"),
|
||||
pytest.param("auth_token", "Token", "Auth", id="token_suffix"),
|
||||
],
|
||||
)
|
||||
def test_title_cases_field_name_parts(self, field_name, suffix, prefix):
|
||||
field_info = SimpleNamespace(description=None)
|
||||
name = _get_field_display_name("api_url", field_info)
|
||||
# Title case: "Api Url"
|
||||
assert "Url" in name and "Api" in name
|
||||
|
||||
def test_adds_path_suffix(self):
|
||||
field_info = SimpleNamespace(description=None)
|
||||
name = _get_field_display_name("file_path", field_info)
|
||||
assert "Path" in name and "File" in name
|
||||
|
||||
def test_adds_id_suffix(self):
|
||||
field_info = SimpleNamespace(description=None)
|
||||
name = _get_field_display_name("user_id", field_info)
|
||||
# Title case: "User Id"
|
||||
assert "Id" in name and "User" in name
|
||||
|
||||
def test_adds_key_suffix(self):
|
||||
field_info = SimpleNamespace(description=None)
|
||||
name = _get_field_display_name("api_key", field_info)
|
||||
assert "Key" in name and "Api" in name
|
||||
|
||||
def test_adds_token_suffix(self):
|
||||
field_info = SimpleNamespace(description=None)
|
||||
name = _get_field_display_name("auth_token", field_info)
|
||||
assert "Token" in name and "Auth" in name
|
||||
name = _get_field_display_name(field_name, field_info)
|
||||
assert suffix in name and prefix in name
|
||||
|
||||
def test_adds_seconds_suffix(self):
|
||||
field_info = SimpleNamespace(description=None)
|
||||
@@ -462,9 +451,16 @@ class TestConfigurePydanticModelDrafts:
|
||||
onboard_wizard, "_input_with_existing", lambda *_args, **_kwargs: text_value
|
||||
)
|
||||
|
||||
def test_back_commits_section_draft(self, monkeypatch):
|
||||
@pytest.mark.parametrize(
|
||||
"exit_action",
|
||||
[
|
||||
pytest.param("back", id="back_commits_section_draft"),
|
||||
pytest.param("done", id="completing_section_returns_updated_draft"),
|
||||
],
|
||||
)
|
||||
def test_leaving_section_commits_draft(self, monkeypatch, exit_action):
|
||||
model = _SimpleDraftModel()
|
||||
self._patch_prompt_helpers(monkeypatch, ["first", "back"])
|
||||
self._patch_prompt_helpers(monkeypatch, ["first", exit_action])
|
||||
|
||||
result = _configure_pydantic_model(model, "Simple")
|
||||
|
||||
@@ -482,31 +478,16 @@ class TestConfigurePydanticModelDrafts:
|
||||
assert result is None
|
||||
assert model.api_key == ""
|
||||
|
||||
def test_completing_section_returns_updated_draft(self, monkeypatch):
|
||||
model = _SimpleDraftModel()
|
||||
self._patch_prompt_helpers(monkeypatch, ["first", "done"])
|
||||
|
||||
result = _configure_pydantic_model(model, "Simple")
|
||||
|
||||
assert result is not None
|
||||
updated = cast(_SimpleDraftModel, result)
|
||||
assert updated.api_key == "secret"
|
||||
assert model.api_key == ""
|
||||
|
||||
def test_nested_section_back_commits_nested_edits(self, monkeypatch):
|
||||
@pytest.mark.parametrize(
|
||||
"exit_action",
|
||||
[
|
||||
pytest.param("back", id="back_commits_nested_edits"),
|
||||
pytest.param("done", id="done_commits_nested_edits"),
|
||||
],
|
||||
)
|
||||
def test_leaving_nested_section_commits_edits(self, monkeypatch, exit_action):
|
||||
model = _OuterDraftModel()
|
||||
self._patch_prompt_helpers(monkeypatch, ["first", "first", "back", "done"])
|
||||
|
||||
result = _configure_pydantic_model(model, "Outer")
|
||||
|
||||
assert result is not None
|
||||
updated = cast(_OuterDraftModel, result)
|
||||
assert updated.nested.api_key == "secret"
|
||||
assert model.nested.api_key == ""
|
||||
|
||||
def test_nested_section_done_commits_nested_edits(self, monkeypatch):
|
||||
model = _OuterDraftModel()
|
||||
self._patch_prompt_helpers(monkeypatch, ["first", "first", "done", "done"])
|
||||
self._patch_prompt_helpers(monkeypatch, ["first", "first", exit_action, "done"])
|
||||
|
||||
result = _configure_pydantic_model(model, "Outer")
|
||||
|
||||
|
||||
@@ -481,24 +481,17 @@ class TestModifyOpen:
|
||||
assert tool._runtime_control.snapshot().workspace == "/new/path"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_modify_pending_queues_blocked(self):
|
||||
"""_pending_queues controls message routing — must be blocked."""
|
||||
@pytest.mark.parametrize(
|
||||
"key",
|
||||
[
|
||||
pytest.param("_pending_queues", id="pending_queues_blocked"),
|
||||
pytest.param("_session_locks", id="session_locks_blocked"),
|
||||
pytest.param("_active_tasks", id="active_tasks_blocked"),
|
||||
],
|
||||
)
|
||||
async def test_modify_runtime_coordination_state_blocked(self, key):
|
||||
tool = _make_tool()
|
||||
result = await tool.execute(action="set", key="_pending_queues", value={})
|
||||
assert "protected" in result
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_modify_session_locks_blocked(self):
|
||||
"""_session_locks controls session isolation — must be blocked."""
|
||||
tool = _make_tool()
|
||||
result = await tool.execute(action="set", key="_session_locks", value={})
|
||||
assert "protected" in result
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_modify_active_tasks_blocked(self):
|
||||
"""_active_tasks tracks running tasks — must be blocked."""
|
||||
tool = _make_tool()
|
||||
result = await tool.execute(action="set", key="_active_tasks", value={})
|
||||
result = await tool.execute(action="set", key=key, value={})
|
||||
assert "protected" in result
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
+56
-77
@@ -583,6 +583,22 @@ def test_provider_logout_openai_codex_removes_local_oauth_files(tmp_path, monkey
|
||||
assert "Logged out from OpenAI Codex" in result.stdout
|
||||
|
||||
|
||||
def test_provider_logout_github_copilot_removes_local_oauth_files(tmp_path, monkeypatch):
|
||||
token_path = tmp_path / "auth" / "github-copilot.json"
|
||||
lock_path = token_path.with_suffix(".lock")
|
||||
token_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
token_path.write_text("{}", encoding="utf-8")
|
||||
lock_path.write_text("", encoding="utf-8")
|
||||
monkeypatch.setenv("OAUTH_CLI_KIT_TOKEN_PATH", str(token_path))
|
||||
|
||||
result = runner.invoke(app, ["provider", "logout", "github-copilot"])
|
||||
|
||||
assert result.exit_code == 0
|
||||
assert not token_path.exists()
|
||||
assert not lock_path.exists()
|
||||
assert "Logged out from GitHub Copilot" in result.stdout
|
||||
|
||||
|
||||
def test_provider_logout_openai_codex_succeeds_when_no_local_oauth_file(monkeypatch, tmp_path):
|
||||
token_path = tmp_path / "auth" / "codex.json"
|
||||
monkeypatch.setenv("OAUTH_CLI_KIT_TOKEN_PATH", str(token_path))
|
||||
@@ -634,22 +650,6 @@ def test_provider_logout_xai_grok_uses_explicit_config_path(tmp_path, monkeypatc
|
||||
assert "Using config:" in result.stdout
|
||||
|
||||
|
||||
def test_provider_logout_github_copilot_removes_local_oauth_files(tmp_path, monkeypatch):
|
||||
token_path = tmp_path / "auth" / "github-copilot.json"
|
||||
lock_path = token_path.with_suffix(".lock")
|
||||
token_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
token_path.write_text("{}", encoding="utf-8")
|
||||
lock_path.write_text("", encoding="utf-8")
|
||||
monkeypatch.setenv("OAUTH_CLI_KIT_TOKEN_PATH", str(token_path))
|
||||
|
||||
result = runner.invoke(app, ["provider", "logout", "github-copilot"])
|
||||
|
||||
assert result.exit_code == 0
|
||||
assert not token_path.exists()
|
||||
assert not lock_path.exists()
|
||||
assert "Logged out from GitHub Copilot" in result.stdout
|
||||
|
||||
|
||||
def test_provider_logout_github_copilot_succeeds_when_no_local_oauth_file(monkeypatch, tmp_path):
|
||||
token_path = tmp_path / "auth" / "github-copilot.json"
|
||||
monkeypatch.setenv("OAUTH_CLI_KIT_TOKEN_PATH", str(token_path))
|
||||
@@ -1000,48 +1000,43 @@ def test_config_accepts_camel_case_explicit_provider_name_for_coding_plan():
|
||||
assert config.get_api_base() == "https://ark.cn-beijing.volces.com/api/coding/v3"
|
||||
|
||||
|
||||
def test_config_accepts_lm_studio_without_api_key_and_uses_default_localhost_api_base():
|
||||
@pytest.mark.parametrize(
|
||||
"provider_name, api_base, config_key",
|
||||
[
|
||||
pytest.param(
|
||||
"lm_studio",
|
||||
"http://localhost:1234/v1",
|
||||
"lmStudio",
|
||||
id="lm_studio_without_api_key_and_uses_default_localhost_api_base",
|
||||
),
|
||||
pytest.param(
|
||||
"atomic_chat",
|
||||
"http://localhost:1337/v1",
|
||||
"atomicChat",
|
||||
id="atomic_chat_without_api_key_and_uses_default_localhost_api_base",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_local_provider_defaults_without_api_key(provider_name, api_base, config_key):
|
||||
config = Config.model_validate(
|
||||
{
|
||||
"agents": {
|
||||
"defaults": {
|
||||
"provider": "lm_studio",
|
||||
"provider": provider_name,
|
||||
"model": "local-model",
|
||||
}
|
||||
},
|
||||
"providers": {
|
||||
"lmStudio": {
|
||||
config_key: {
|
||||
"apiKey": None,
|
||||
}
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
assert config.get_provider_name() == "lm_studio"
|
||||
assert config.get_provider_name() == provider_name
|
||||
assert config.get_api_key() is None
|
||||
assert config.get_api_base() == "http://localhost:1234/v1"
|
||||
|
||||
|
||||
def test_config_accepts_atomic_chat_without_api_key_and_uses_default_localhost_api_base():
|
||||
config = Config.model_validate(
|
||||
{
|
||||
"agents": {
|
||||
"defaults": {
|
||||
"provider": "atomic_chat",
|
||||
"model": "local-model",
|
||||
}
|
||||
},
|
||||
"providers": {
|
||||
"atomicChat": {
|
||||
"apiKey": None,
|
||||
}
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
assert config.get_provider_name() == "atomic_chat"
|
||||
assert config.get_api_key() is None
|
||||
assert config.get_api_base() == "http://localhost:1337/v1"
|
||||
assert config.get_api_base() == api_base
|
||||
|
||||
|
||||
def test_find_by_name_accepts_camel_case_and_hyphen_aliases():
|
||||
@@ -1441,44 +1436,28 @@ def test_make_provider_strips_dynamic_custom_route_prefix_from_request_model():
|
||||
assert body["model"] == "gpt-4o-mini"
|
||||
|
||||
|
||||
def test_make_provider_preserves_namespaced_model_for_forced_dynamic_provider():
|
||||
@pytest.mark.parametrize(
|
||||
"provider_name, model",
|
||||
[
|
||||
pytest.param(
|
||||
"my-company-api",
|
||||
"openai/gpt-4o-mini",
|
||||
id="preserves_namespaced_model_for_forced_dynamic_provider",
|
||||
),
|
||||
pytest.param(
|
||||
"auto",
|
||||
"my-company-api/openai/gpt-4o-mini",
|
||||
id="strips_dynamic_custom_route_prefix_once",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_make_provider_preserves_dynamic_provider_model_namespace(provider_name, model):
|
||||
config = Config.model_validate(
|
||||
{
|
||||
"agents": {
|
||||
"defaults": {
|
||||
"provider": "my-company-api",
|
||||
"model": "openai/gpt-4o-mini",
|
||||
}
|
||||
},
|
||||
"providers": {
|
||||
"my-company-api": {
|
||||
"apiBase": "https://example.com/v1",
|
||||
}
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
provider = make_provider(config)
|
||||
kwargs = provider._build_kwargs(
|
||||
messages=[{"role": "user", "content": "hi"}],
|
||||
tools=None,
|
||||
model=None,
|
||||
max_tokens=16,
|
||||
temperature=0.1,
|
||||
reasoning_effort=None,
|
||||
tool_choice=None,
|
||||
)
|
||||
|
||||
assert kwargs["model"] == "openai/gpt-4o-mini"
|
||||
|
||||
|
||||
def test_make_provider_strips_dynamic_custom_route_prefix_once():
|
||||
config = Config.model_validate(
|
||||
{
|
||||
"agents": {
|
||||
"defaults": {
|
||||
"provider": "auto",
|
||||
"model": "my-company-api/openai/gpt-4o-mini",
|
||||
"provider": provider_name,
|
||||
"model": model,
|
||||
}
|
||||
},
|
||||
"providers": {
|
||||
|
||||
@@ -34,11 +34,17 @@ async def test_interactive_retry_wait_is_rendered_as_progress_even_when_progress
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reasoning_displayed_when_show_reasoning_enabled():
|
||||
"""Reasoning content should be displayed when show_reasoning is True."""
|
||||
@pytest.mark.parametrize(
|
||||
"send_progress",
|
||||
[
|
||||
pytest.param(True, id="displayed_when_show_reasoning_enabled"),
|
||||
pytest.param(False, id="shown_when_send_progress_disabled"),
|
||||
],
|
||||
)
|
||||
async def test_reasoning_display_is_independent_of_send_progress(send_progress):
|
||||
calls: list[str] = []
|
||||
channels_config = SimpleNamespace(
|
||||
send_progress=True, send_tool_hints=False, show_reasoning=True,
|
||||
send_progress=send_progress, send_tool_hints=False, show_reasoning=True,
|
||||
)
|
||||
msg = SimpleNamespace(
|
||||
content="Let me think about this...",
|
||||
@@ -183,27 +189,3 @@ async def test_non_reasoning_progress_not_affected_by_show_reasoning():
|
||||
|
||||
assert handled is True
|
||||
assert calls == ["working on it..."]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reasoning_shown_when_send_progress_disabled():
|
||||
"""Reasoning display is governed by `show_reasoning` alone, independent
|
||||
of `send_progress` — the two knobs are orthogonal."""
|
||||
calls: list[str] = []
|
||||
channels_config = SimpleNamespace(
|
||||
send_progress=False, send_tool_hints=False, show_reasoning=True,
|
||||
)
|
||||
msg = SimpleNamespace(
|
||||
content="Let me think about this...",
|
||||
event=ProgressEvent(content="Let me think about this...", reasoning=True),
|
||||
metadata={},
|
||||
)
|
||||
|
||||
with patch(
|
||||
"nanobot.cli.terminal._print_cli_reasoning",
|
||||
side_effect=lambda t, th, r=None: calls.append(t),
|
||||
):
|
||||
handled = await terminal._maybe_print_interactive_progress(msg, None, channels_config)
|
||||
|
||||
assert handled is True
|
||||
assert calls == ["Let me think about this..."]
|
||||
@@ -1,10 +1,19 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.cli.webui_support import _prepare_webui_bundle_for_gateway
|
||||
from nanobot.config.schema import Config
|
||||
|
||||
|
||||
def test_source_checkout_preserves_warn_only_gateway_startup(monkeypatch) -> None:
|
||||
@pytest.mark.parametrize(
|
||||
"mode",
|
||||
[
|
||||
pytest.param("warn", id="source_checkout_preserves_warn_only_gateway_startup"),
|
||||
pytest.param("skip", id="skip_mode_does_not_build_the_source_webui_bundle"),
|
||||
],
|
||||
)
|
||||
def test_source_checkout_respects_webui_build_mode(monkeypatch, mode) -> None:
|
||||
modes: list[str] = []
|
||||
monkeypatch.setattr(
|
||||
"nanobot.cli.webui_support.inspect_webui_bundle",
|
||||
@@ -16,23 +25,6 @@ def test_source_checkout_preserves_warn_only_gateway_startup(monkeypatch) -> Non
|
||||
lambda **kwargs: modes.append(kwargs["mode"]),
|
||||
)
|
||||
|
||||
_prepare_webui_bundle_for_gateway(Config(), mode="warn")
|
||||
_prepare_webui_bundle_for_gateway(Config(), mode=mode)
|
||||
|
||||
assert modes == ["warn"]
|
||||
|
||||
|
||||
def test_skip_mode_does_not_build_the_source_webui_bundle(monkeypatch) -> None:
|
||||
modes: list[str] = []
|
||||
monkeypatch.setattr(
|
||||
"nanobot.cli.webui_support.inspect_webui_bundle",
|
||||
lambda: SimpleNamespace(source_available=True),
|
||||
)
|
||||
monkeypatch.setattr("nanobot.cli.webui_support._webui_channel_enabled", lambda _config: True)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.cli.webui_support.ensure_webui_bundle",
|
||||
lambda **kwargs: modes.append(kwargs["mode"]),
|
||||
)
|
||||
|
||||
_prepare_webui_bundle_for_gateway(Config(), mode="skip")
|
||||
|
||||
assert modes == ["skip"]
|
||||
assert modes == [mode]
|
||||
@@ -385,15 +385,22 @@ def test_resolve_preset_rejects_unknown_named_preset() -> None:
|
||||
Config().resolve_preset("missing")
|
||||
|
||||
|
||||
def test_match_provider_uses_preset_model() -> None:
|
||||
@pytest.mark.parametrize(
|
||||
"provider_name, model",
|
||||
[
|
||||
pytest.param("openai", "openai/gpt-4.1", id="model"),
|
||||
pytest.param("anthropic", "anthropic/claude-opus-4-5", id="provider_when_forced"),
|
||||
],
|
||||
)
|
||||
def test_match_provider_uses_model_preset(provider_name, model) -> None:
|
||||
config = Config.model_validate({
|
||||
"providers": {
|
||||
"openai": {"apiKey": "sk-test"},
|
||||
provider_name: {"apiKey": "sk-test"},
|
||||
},
|
||||
"model_presets": {
|
||||
"fast": {
|
||||
"model": "openai/gpt-4.1",
|
||||
"provider": "openai",
|
||||
"model": model,
|
||||
"provider": provider_name,
|
||||
}
|
||||
},
|
||||
"agents": {
|
||||
@@ -403,28 +410,7 @@ def test_match_provider_uses_preset_model() -> None:
|
||||
},
|
||||
})
|
||||
name = config.get_provider_name()
|
||||
assert name == "openai"
|
||||
|
||||
|
||||
def test_match_provider_uses_preset_provider_when_forced() -> None:
|
||||
config = Config.model_validate({
|
||||
"providers": {
|
||||
"anthropic": {"apiKey": "sk-test"},
|
||||
},
|
||||
"model_presets": {
|
||||
"fast": {
|
||||
"model": "anthropic/claude-opus-4-5",
|
||||
"provider": "anthropic",
|
||||
}
|
||||
},
|
||||
"agents": {
|
||||
"defaults": {
|
||||
"modelPreset": "fast",
|
||||
}
|
||||
},
|
||||
})
|
||||
name = config.get_provider_name()
|
||||
assert name == "anthropic"
|
||||
assert name == provider_name
|
||||
|
||||
|
||||
def test_match_provider_routes_forced_novita_model_api_models() -> None:
|
||||
|
||||
@@ -45,34 +45,20 @@ def test_format_timing_cron_without_tz(tmp_path) -> None:
|
||||
assert tool._format_timing(s) == "cron: */5 * * * *"
|
||||
|
||||
|
||||
def test_format_timing_every_hours(tmp_path) -> None:
|
||||
@pytest.mark.parametrize(
|
||||
"expected, every_ms",
|
||||
[
|
||||
pytest.param("every 2h", 7200000, id="hours"),
|
||||
pytest.param("every 30m", 1800000, id="minutes"),
|
||||
pytest.param("every 30s", 30000, id="seconds"),
|
||||
pytest.param("every 90s", 90000, id="non_minute_seconds"),
|
||||
pytest.param("every 200ms", 200, id="milliseconds"),
|
||||
],
|
||||
)
|
||||
def test_format_timing_every_interval(tmp_path, expected, every_ms) -> None:
|
||||
tool = _make_tool(tmp_path)
|
||||
s = CronSchedule(kind="every", every_ms=7_200_000)
|
||||
assert tool._format_timing(s) == "every 2h"
|
||||
|
||||
|
||||
def test_format_timing_every_minutes(tmp_path) -> None:
|
||||
tool = _make_tool(tmp_path)
|
||||
s = CronSchedule(kind="every", every_ms=1_800_000)
|
||||
assert tool._format_timing(s) == "every 30m"
|
||||
|
||||
|
||||
def test_format_timing_every_seconds(tmp_path) -> None:
|
||||
tool = _make_tool(tmp_path)
|
||||
s = CronSchedule(kind="every", every_ms=30_000)
|
||||
assert tool._format_timing(s) == "every 30s"
|
||||
|
||||
|
||||
def test_format_timing_every_non_minute_seconds(tmp_path) -> None:
|
||||
tool = _make_tool(tmp_path)
|
||||
s = CronSchedule(kind="every", every_ms=90_000)
|
||||
assert tool._format_timing(s) == "every 90s"
|
||||
|
||||
|
||||
def test_format_timing_every_milliseconds(tmp_path) -> None:
|
||||
tool = _make_tool(tmp_path)
|
||||
s = CronSchedule(kind="every", every_ms=200)
|
||||
assert tool._format_timing(s) == "every 200ms"
|
||||
s = CronSchedule(kind="every", every_ms=every_ms)
|
||||
assert tool._format_timing(s) == expected
|
||||
|
||||
|
||||
def test_format_timing_at(tmp_path) -> None:
|
||||
|
||||
+14
-23
@@ -164,13 +164,20 @@ class TestHandlePairingCommand:
|
||||
assert "123" in reply
|
||||
assert store.is_approved("telegram", "123") is True
|
||||
|
||||
def test_approve_invalid(self) -> None:
|
||||
reply = store.handle_pairing_command("telegram", "approve BAD-CODE")
|
||||
assert "Invalid or expired" in reply
|
||||
|
||||
def test_approve_no_arg(self) -> None:
|
||||
reply = store.handle_pairing_command("telegram", "approve")
|
||||
assert "Usage:" in reply
|
||||
@pytest.mark.parametrize(
|
||||
"command, expected",
|
||||
[
|
||||
pytest.param("approve BAD-CODE", "Invalid or expired", id="approve_invalid"),
|
||||
pytest.param("approve", "Usage:", id="approve_no_arg"),
|
||||
pytest.param("deny BAD-CODE", "not found", id="deny_unknown"),
|
||||
pytest.param("revoke 999", "was not in the approved list", id="revoke_unknown"),
|
||||
pytest.param("revoke", "Usage:", id="revoke_no_arg"),
|
||||
pytest.param("foo", "Unknown pairing command", id="unknown_subcommand"),
|
||||
],
|
||||
)
|
||||
def test_pairing_command_errors(self, command, expected) -> None:
|
||||
reply = store.handle_pairing_command("telegram", command)
|
||||
assert expected in reply
|
||||
|
||||
def test_deny(self) -> None:
|
||||
code = store.generate_code("telegram", "123")
|
||||
@@ -178,10 +185,6 @@ class TestHandlePairingCommand:
|
||||
assert "Denied" in reply
|
||||
assert store.approve_code(code) is None
|
||||
|
||||
def test_deny_unknown(self) -> None:
|
||||
reply = store.handle_pairing_command("telegram", "deny BAD-CODE")
|
||||
assert "not found" in reply
|
||||
|
||||
def test_revoke_current_channel(self) -> None:
|
||||
code = store.generate_code("telegram", "123")
|
||||
store.approve_code(code)
|
||||
@@ -197,18 +200,6 @@ class TestHandlePairingCommand:
|
||||
assert "Revoked" in reply
|
||||
assert store.is_approved("discord", "456") is False
|
||||
|
||||
def test_revoke_unknown(self) -> None:
|
||||
reply = store.handle_pairing_command("telegram", "revoke 999")
|
||||
assert "was not in the approved list" in reply
|
||||
|
||||
def test_revoke_no_arg(self) -> None:
|
||||
reply = store.handle_pairing_command("telegram", "revoke")
|
||||
assert "Usage:" in reply
|
||||
|
||||
def test_unknown_subcommand(self) -> None:
|
||||
reply = store.handle_pairing_command("telegram", "foo")
|
||||
assert "Unknown pairing command" in reply
|
||||
|
||||
def test_default_to_list(self) -> None:
|
||||
store.generate_code("telegram", "123")
|
||||
reply = store.handle_pairing_command("telegram", "")
|
||||
|
||||
@@ -99,8 +99,16 @@ def test_opus_4_8_omits_temperature_adaptive() -> None:
|
||||
assert "temperature" not in kw
|
||||
|
||||
|
||||
def test_opus_4_8_high_uses_adaptive_effort() -> None:
|
||||
kw = _build(_make_provider("claude-opus-4-8"), "high", max_tokens=4096)
|
||||
@pytest.mark.parametrize(
|
||||
"model",
|
||||
[
|
||||
pytest.param("claude-opus-4-8", id="opus_4_8_high_uses_adaptive_effort"),
|
||||
pytest.param("claude-fable-5", id="fable_high_uses_adaptive_effort"),
|
||||
pytest.param("claude-sonnet-5", id="sonnet_5_high_uses_adaptive_effort"),
|
||||
],
|
||||
)
|
||||
def test_adaptive_models_use_high_effort(model) -> None:
|
||||
kw = _build(_make_provider(model), "high", max_tokens=4096)
|
||||
assert "temperature" not in kw
|
||||
assert kw["thinking"] == {"type": "adaptive"}
|
||||
assert kw["output_config"] == {"effort": "high"}
|
||||
@@ -116,13 +124,6 @@ def test_fable_omits_temperature_adaptive() -> None:
|
||||
assert "temperature" not in kw
|
||||
|
||||
|
||||
def test_fable_high_uses_adaptive_effort() -> None:
|
||||
kw = _build(_make_provider("claude-fable-5"), "high", max_tokens=4096)
|
||||
assert "temperature" not in kw
|
||||
assert kw["thinking"] == {"type": "adaptive"}
|
||||
assert kw["output_config"] == {"effort": "high"}
|
||||
|
||||
|
||||
def test_fable_omits_temperature_none() -> None:
|
||||
kw = _build(_make_provider("claude-fable-5"), None)
|
||||
assert "temperature" not in kw
|
||||
@@ -134,13 +135,6 @@ def test_sonnet_5_omits_temperature_adaptive() -> None:
|
||||
assert kw["thinking"] == {"type": "adaptive"}
|
||||
|
||||
|
||||
def test_sonnet_5_high_uses_adaptive_effort() -> None:
|
||||
kw = _build(_make_provider("claude-sonnet-5"), "high", max_tokens=4096)
|
||||
assert "temperature" not in kw
|
||||
assert kw["thinking"] == {"type": "adaptive"}
|
||||
assert kw["output_config"] == {"effort": "high"}
|
||||
|
||||
|
||||
def test_sonnet_5_omits_temperature_none() -> None:
|
||||
kw = _build(_make_provider("anthropic/claude-sonnet-5"), "none")
|
||||
assert "temperature" not in kw
|
||||
|
||||
@@ -469,35 +469,26 @@ async def test_gemini_flash_forwards_aspect_ratio_and_image_size() -> None:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_gemini_flash_2_5_drops_image_size() -> None:
|
||||
@pytest.mark.parametrize(
|
||||
"aspect_ratio, model",
|
||||
[
|
||||
pytest.param("4:3", "gemini-2.5-flash-image", id="5_drops_image_size"),
|
||||
pytest.param("16:9", "gemini-2.0-flash-preview-image-generation", id="0_drops_image_size"),
|
||||
],
|
||||
)
|
||||
async def test_gemini_flash_omits_unsupported_image_size(aspect_ratio, model) -> None:
|
||||
fake = FakeClient(_gemini_flash_image_response())
|
||||
client = GeminiImageGenerationClient(api_key="AIza-test", client=fake) # type: ignore[arg-type]
|
||||
|
||||
await client.generate(
|
||||
prompt="draw a cat",
|
||||
model="gemini-2.5-flash-image",
|
||||
aspect_ratio="4:3",
|
||||
model=model,
|
||||
aspect_ratio=aspect_ratio,
|
||||
image_size="1K",
|
||||
)
|
||||
|
||||
image_config = fake.calls[0]["json"]["generationConfig"]["imageConfig"]
|
||||
assert image_config == {"aspectRatio": "4:3"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_gemini_flash_2_0_drops_image_size() -> None:
|
||||
fake = FakeClient(_gemini_flash_image_response())
|
||||
client = GeminiImageGenerationClient(api_key="AIza-test", client=fake) # type: ignore[arg-type]
|
||||
|
||||
await client.generate(
|
||||
prompt="draw a cat",
|
||||
model="gemini-2.0-flash-preview-image-generation",
|
||||
aspect_ratio="16:9",
|
||||
image_size="1K",
|
||||
)
|
||||
|
||||
image_config = fake.calls[0]["json"]["generationConfig"]["imageConfig"]
|
||||
assert image_config == {"aspectRatio": "16:9"}
|
||||
assert image_config == {"aspectRatio": aspect_ratio}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -876,15 +867,27 @@ async def test_openai_multiple_images() -> None:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_openai_aspect_ratio_to_size() -> None:
|
||||
@pytest.mark.parametrize(
|
||||
"expected_size, model, aspect_ratio",
|
||||
[
|
||||
pytest.param("1024x1024", "dall-e-3", "1:1", id="aspect_ratio_to_size"),
|
||||
pytest.param("1024x1024", "dall-e-2", "16:9", id="dalle2_uses_square_size_for_non_square_ratios"),
|
||||
pytest.param("1536x1024", "gpt-image-1", "16:9", id="gpt_image_uses_supported_landscape_size"),
|
||||
],
|
||||
)
|
||||
async def test_openai_aspect_ratio_uses_model_supported_size(
|
||||
expected_size,
|
||||
model,
|
||||
aspect_ratio,
|
||||
) -> None:
|
||||
fake = FakeClient(FakeResponse({"data": [{"b64_json": RAW_B64}]}))
|
||||
client = OpenAIImageGenerationClient(
|
||||
api_key="sk-openai-test",
|
||||
client=fake, # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
await client.generate(prompt="draw", model="dall-e-3", aspect_ratio="1:1")
|
||||
assert fake.calls[0]["json"]["size"] == "1024x1024"
|
||||
await client.generate(prompt="draw", model=model, aspect_ratio=aspect_ratio)
|
||||
assert fake.calls[0]["json"]["size"] == expected_size
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -902,32 +905,6 @@ async def test_openai_dalle3_uses_supported_orientation_sizes() -> None:
|
||||
assert fake.calls[1]["json"]["size"] == "1792x1024"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_openai_dalle2_uses_square_size_for_non_square_ratios() -> None:
|
||||
fake = FakeClient(FakeResponse({"data": [{"b64_json": RAW_B64}]}))
|
||||
client = OpenAIImageGenerationClient(
|
||||
api_key="sk-openai-test",
|
||||
client=fake, # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
await client.generate(prompt="draw", model="dall-e-2", aspect_ratio="16:9")
|
||||
|
||||
assert fake.calls[0]["json"]["size"] == "1024x1024"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_openai_gpt_image_uses_supported_landscape_size() -> None:
|
||||
fake = FakeClient(FakeResponse({"data": [{"b64_json": RAW_B64}]}))
|
||||
client = OpenAIImageGenerationClient(
|
||||
api_key="sk-openai-test",
|
||||
client=fake, # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
await client.generate(prompt="draw", model="gpt-image-1", aspect_ratio="16:9")
|
||||
|
||||
assert fake.calls[0]["json"]["size"] == "1536x1024"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_openai_gpt_image_uses_supported_orientation_sizes() -> None:
|
||||
fake = FakeClient(FakeResponse({"data": [{"b64_json": RAW_B64}]}))
|
||||
@@ -1098,7 +1075,14 @@ async def test_openai_default_size_when_no_aspect_ratio() -> None:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_openai_ignores_explicit_size_unsupported_by_model_family() -> None:
|
||||
@pytest.mark.parametrize(
|
||||
"expected_size, image_size",
|
||||
[
|
||||
pytest.param("1792x1024", "1536x1024", id="ignores_explicit_size_unsupported_by_model_family"),
|
||||
pytest.param("1024x1024", "1024x1024", id="uses_explicit_image_size"),
|
||||
],
|
||||
)
|
||||
async def test_openai_validates_explicit_size_for_model_family(expected_size, image_size) -> None:
|
||||
fake = FakeClient(FakeResponse({"data": [{"b64_json": RAW_B64}]}))
|
||||
client = OpenAIImageGenerationClient(
|
||||
api_key="sk-openai-test",
|
||||
@@ -1109,30 +1093,11 @@ async def test_openai_ignores_explicit_size_unsupported_by_model_family() -> Non
|
||||
prompt="draw",
|
||||
model="dall-e-3",
|
||||
aspect_ratio="16:9",
|
||||
image_size="1536x1024",
|
||||
image_size=image_size,
|
||||
)
|
||||
|
||||
body = fake.calls[0]["json"]
|
||||
assert body["size"] == "1792x1024"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_openai_uses_explicit_image_size() -> None:
|
||||
fake = FakeClient(FakeResponse({"data": [{"b64_json": RAW_B64}]}))
|
||||
client = OpenAIImageGenerationClient(
|
||||
api_key="sk-openai-test",
|
||||
client=fake, # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
await client.generate(
|
||||
prompt="draw",
|
||||
model="dall-e-3",
|
||||
aspect_ratio="16:9",
|
||||
image_size="1024x1024",
|
||||
)
|
||||
|
||||
body = fake.calls[0]["json"]
|
||||
assert body["size"] == "1024x1024"
|
||||
assert body["size"] == expected_size
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -1180,7 +1145,14 @@ async def test_custom_generate_success() -> None:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_custom_generate_preserves_provider_size_hint() -> None:
|
||||
@pytest.mark.parametrize(
|
||||
"expected_size, image_size",
|
||||
[
|
||||
pytest.param("2K", "2K", id="preserves_provider_size_hint"),
|
||||
pytest.param("1024x1024", "1K", id="maps_one_k_to_openai_dimension"),
|
||||
],
|
||||
)
|
||||
async def test_custom_generate_maps_size_hint(expected_size, image_size) -> None:
|
||||
fake = FakeClient(FakeResponse({"data": [{"b64_json": RAW_B64}]}))
|
||||
client = CustomImageGenerationClient(
|
||||
api_key="sk-custom-test",
|
||||
@@ -1191,28 +1163,10 @@ async def test_custom_generate_preserves_provider_size_hint() -> None:
|
||||
await client.generate(
|
||||
prompt="a cat on the moon",
|
||||
model="custom-image-model",
|
||||
image_size="2K",
|
||||
image_size=image_size,
|
||||
)
|
||||
|
||||
assert fake.calls[0]["json"]["size"] == "2K"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_custom_generate_maps_one_k_to_openai_dimension() -> None:
|
||||
fake = FakeClient(FakeResponse({"data": [{"b64_json": RAW_B64}]}))
|
||||
client = CustomImageGenerationClient(
|
||||
api_key="sk-custom-test",
|
||||
api_base="https://custom.example/v1",
|
||||
client=fake, # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
await client.generate(
|
||||
prompt="a cat on the moon",
|
||||
model="custom-image-model",
|
||||
image_size="1K",
|
||||
)
|
||||
|
||||
assert fake.calls[0]["json"]["size"] == "1024x1024"
|
||||
assert fake.calls[0]["json"]["size"] == expected_size
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -1426,8 +1426,32 @@ def test_non_dashscope_minimal_not_retranslated() -> None:
|
||||
assert kw["reasoning_effort"] == "minimal"
|
||||
|
||||
|
||||
def test_dashscope_no_extra_body_when_reasoning_effort_none() -> None:
|
||||
kw = _build_kwargs_for("dashscope", "qwen-turbo", reasoning_effort=None)
|
||||
@pytest.mark.parametrize(
|
||||
"provider_name, model",
|
||||
[
|
||||
pytest.param("dashscope", "qwen-turbo", id="dashscope_no_extra_body_when_reasoning_effort_none"),
|
||||
pytest.param("minimax", "MiniMax-M2.7", id="minimax_no_extra_body_when_reasoning_effort_none"),
|
||||
pytest.param(
|
||||
"byteplus",
|
||||
"doubao-seed-2-0-pro",
|
||||
id="byteplus_no_extra_body_when_reasoning_effort_none",
|
||||
),
|
||||
pytest.param("deepseek", "deepseek-chat", id="deepseek_no_extra_body_when_reasoning_effort_none"),
|
||||
pytest.param("moonshot", "kimi-k2.5", id="kimi_k25_no_extra_body_when_reasoning_effort_none"),
|
||||
pytest.param(
|
||||
"openrouter",
|
||||
"moonshotai/kimi-k2.5",
|
||||
id="kimi_k25_thinking_disabled_with_openrouter_prefix",
|
||||
),
|
||||
pytest.param(
|
||||
"openrouter",
|
||||
"qwen/qwen3.6-flash",
|
||||
id="qwen_no_extra_body_when_reasoning_effort_omitted",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_provider_omits_extra_body_without_reasoning_effort(provider_name, model) -> None:
|
||||
kw = _build_kwargs_for(provider_name, model, reasoning_effort=None)
|
||||
assert "extra_body" not in kw
|
||||
|
||||
|
||||
@@ -1441,11 +1465,6 @@ def test_minimax_reasoning_split_disabled_for_minimal() -> None:
|
||||
assert kw["extra_body"] == {"reasoning_split": False}
|
||||
|
||||
|
||||
def test_minimax_no_extra_body_when_reasoning_effort_none() -> None:
|
||||
kw = _build_kwargs_for("minimax", "MiniMax-M2.7", reasoning_effort=None)
|
||||
assert "extra_body" not in kw
|
||||
|
||||
|
||||
def test_volcengine_thinking_enabled() -> None:
|
||||
kw = _build_kwargs_for("volcengine", "doubao-seed-2-0-pro", reasoning_effort="high")
|
||||
assert kw["extra_body"] == {"thinking": {"type": "enabled"}}
|
||||
@@ -1468,11 +1487,6 @@ def test_byteplus_thinking_disabled_for_minimal() -> None:
|
||||
assert kw["extra_body"] == {"thinking": {"type": "disabled"}}
|
||||
|
||||
|
||||
def test_byteplus_no_extra_body_when_reasoning_effort_none() -> None:
|
||||
kw = _build_kwargs_for("byteplus", "doubao-seed-2-0-pro", reasoning_effort=None)
|
||||
assert "extra_body" not in kw
|
||||
|
||||
|
||||
def test_deepseek_thinking_enabled() -> None:
|
||||
"""DeepSeek V4 requires extra_body.thinking when reasoning_effort is set."""
|
||||
kw = _build_kwargs_for("deepseek", "deepseek-v4-pro", reasoning_effort="high")
|
||||
@@ -1485,12 +1499,6 @@ def test_deepseek_thinking_disabled_for_minimal() -> None:
|
||||
assert kw["extra_body"] == {"thinking": {"type": "disabled"}}
|
||||
|
||||
|
||||
def test_deepseek_no_extra_body_when_reasoning_effort_none() -> None:
|
||||
"""Without reasoning_effort the thinking param must not be injected."""
|
||||
kw = _build_kwargs_for("deepseek", "deepseek-chat", reasoning_effort=None)
|
||||
assert "extra_body" not in kw
|
||||
|
||||
|
||||
def test_deepseek_backfills_reasoning_content_on_legacy_tool_call_messages() -> None:
|
||||
"""Session messages from before thinking mode was enabled may have assistant
|
||||
messages with tool_calls but no reasoning_content. DeepSeek V4 rejects these
|
||||
@@ -1753,27 +1761,49 @@ def test_openai_no_thinking_extra_body() -> None:
|
||||
assert "extra_body" not in kw
|
||||
|
||||
|
||||
def test_kimi_k25_thinking_enabled() -> None:
|
||||
"""kimi-k2.5 with reasoning_effort set should opt in to thinking."""
|
||||
kw = _build_kwargs_for("moonshot", "kimi-k2.5", reasoning_effort="medium")
|
||||
assert kw.get("extra_body") == {"thinking": {"type": "enabled"}}
|
||||
@pytest.mark.parametrize(
|
||||
"provider_name, model, effort, thinking_type",
|
||||
[
|
||||
pytest.param("moonshot", "kimi-k2.5", "medium", "enabled", id="kimi_k25_thinking_enabled"),
|
||||
pytest.param(
|
||||
"moonshot",
|
||||
"kimi-k2.5",
|
||||
"minimal",
|
||||
"disabled",
|
||||
id="kimi_k25_thinking_disabled_for_minimal",
|
||||
),
|
||||
pytest.param("moonshot", "kimi-k2.6", "medium", "enabled", id="kimi_k26_thinking_enabled"),
|
||||
pytest.param("moonshot", "kimi-k2.7-code", "medium", "enabled", id="kimi_k27_code_thinking_enabled"),
|
||||
pytest.param(
|
||||
"moonshot",
|
||||
"k2.6-code-preview",
|
||||
"high",
|
||||
"enabled",
|
||||
id="kimi_k26_code_preview_thinking_enabled",
|
||||
),
|
||||
pytest.param(
|
||||
"deepseek",
|
||||
"deepseek-v4-pro",
|
||||
"none",
|
||||
"disabled",
|
||||
id="deepseek_thinking_disabled_for_none_string",
|
||||
),
|
||||
pytest.param(
|
||||
"moonshot",
|
||||
"kimi-k2.5",
|
||||
"none",
|
||||
"disabled",
|
||||
id="kimi_k25_thinking_disabled_for_none_string",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_provider_thinking_type_mapping(provider_name, model, effort, thinking_type) -> None:
|
||||
kw = _build_kwargs_for(provider_name, model, reasoning_effort=effort)
|
||||
assert kw.get("extra_body") == {"thinking": {"type": thinking_type}}
|
||||
# Moonshot rejects both 'reasoning_effort' and 'thinking' (#3939)
|
||||
assert "reasoning_effort" not in kw
|
||||
|
||||
|
||||
def test_kimi_k25_thinking_disabled_for_minimal() -> None:
|
||||
"""reasoning_effort='minimal' maps to thinking disabled for kimi-k2.5."""
|
||||
kw = _build_kwargs_for("moonshot", "kimi-k2.5", reasoning_effort="minimal")
|
||||
assert kw.get("extra_body") == {"thinking": {"type": "disabled"}}
|
||||
assert "reasoning_effort" not in kw
|
||||
|
||||
|
||||
def test_kimi_k25_no_extra_body_when_reasoning_effort_none() -> None:
|
||||
"""Without reasoning_effort the thinking param must not be injected."""
|
||||
kw = _build_kwargs_for("moonshot", "kimi-k2.5", reasoning_effort=None)
|
||||
assert "extra_body" not in kw
|
||||
|
||||
|
||||
def test_kimi_k3_uses_native_defaults() -> None:
|
||||
"""K3 omits fixed sampling params and uses the non-deprecated token limit field."""
|
||||
kw = _build_kwargs_for("moonshot", "kimi-k3", reasoning_effort=None)
|
||||
@@ -1811,56 +1841,28 @@ def test_kimi_k3_omits_disabled_reasoning_effort() -> None:
|
||||
assert "extra_body" not in kw
|
||||
|
||||
|
||||
def test_kimi_k25_thinking_enabled_with_openrouter_prefix() -> None:
|
||||
"""OpenRouter-style model names like moonshotai/kimi-k2.5 must trigger thinking.
|
||||
|
||||
OR drops upstream-provider `thinking` fields, so the same intent also has
|
||||
to go through OR's `reasoning.effort` shape (#3851 follow-up).
|
||||
"""
|
||||
kw = _build_kwargs_for("openrouter", "moonshotai/kimi-k2.5", reasoning_effort="medium")
|
||||
@pytest.mark.parametrize(
|
||||
"model, effort",
|
||||
[
|
||||
pytest.param("moonshotai/kimi-k2.5", "medium", id="k25_thinking_enabled_with_openrouter_prefix"),
|
||||
pytest.param("moonshotai/kimi-k2.6", "medium", id="k26_thinking_enabled_with_openrouter_prefix"),
|
||||
pytest.param(
|
||||
"moonshotai/kimi-k2.7-code",
|
||||
"high",
|
||||
id="k27_code_thinking_enabled_with_openrouter_prefix",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_openrouter_kimi_thinking_mapping(model, effort) -> None:
|
||||
kw = _build_kwargs_for("openrouter", model, reasoning_effort=effort)
|
||||
assert kw.get("extra_body") == {
|
||||
"thinking": {"type": "enabled"},
|
||||
"reasoning": {"effort": "medium"},
|
||||
"reasoning": {"effort": effort},
|
||||
}
|
||||
# Even via OR, reasoning_effort wire kwarg is dropped for kimi models
|
||||
assert "reasoning_effort" not in kw
|
||||
|
||||
|
||||
def test_kimi_k26_thinking_enabled() -> None:
|
||||
"""kimi-k2.6 with reasoning_effort set should opt in to thinking."""
|
||||
kw = _build_kwargs_for("moonshot", "kimi-k2.6", reasoning_effort="medium")
|
||||
assert kw.get("extra_body") == {"thinking": {"type": "enabled"}}
|
||||
assert "reasoning_effort" not in kw
|
||||
|
||||
|
||||
def test_kimi_k26_thinking_enabled_with_openrouter_prefix() -> None:
|
||||
"""OpenRouter-style names like moonshotai/kimi-k2.6 must trigger thinking
|
||||
via both upstream `thinking` and OR's `reasoning.effort`."""
|
||||
kw = _build_kwargs_for("openrouter", "moonshotai/kimi-k2.6", reasoning_effort="medium")
|
||||
assert kw.get("extra_body") == {
|
||||
"thinking": {"type": "enabled"},
|
||||
"reasoning": {"effort": "medium"},
|
||||
}
|
||||
assert "reasoning_effort" not in kw
|
||||
|
||||
|
||||
def test_kimi_k27_code_thinking_enabled() -> None:
|
||||
"""Kimi K2.7 Code supports native thinking controls."""
|
||||
kw = _build_kwargs_for("moonshot", "kimi-k2.7-code", reasoning_effort="medium")
|
||||
assert kw.get("extra_body") == {"thinking": {"type": "enabled"}}
|
||||
assert "reasoning_effort" not in kw
|
||||
|
||||
|
||||
def test_kimi_k27_code_thinking_enabled_with_openrouter_prefix() -> None:
|
||||
"""OpenRouter-routed Kimi K2.7 Code should carry both thinking shapes."""
|
||||
kw = _build_kwargs_for("openrouter", "moonshotai/kimi-k2.7-code", reasoning_effort="high")
|
||||
assert kw.get("extra_body") == {
|
||||
"thinking": {"type": "enabled"},
|
||||
"reasoning": {"effort": "high"},
|
||||
}
|
||||
assert "reasoning_effort" not in kw
|
||||
|
||||
|
||||
def test_kimi_k27_code_thinking_none_omits_disabled() -> None:
|
||||
"""Kimi K2.7 Code is always-thinking; disabled thinking is invalid upstream."""
|
||||
kw = _build_kwargs_for("moonshot", "kimi-k2.7-code", reasoning_effort="none")
|
||||
@@ -1891,19 +1893,6 @@ def test_moonshot_kimi_k27_code_temperature_override() -> None:
|
||||
assert kw["temperature"] == 1.0
|
||||
|
||||
|
||||
def test_kimi_k25_thinking_disabled_with_openrouter_prefix() -> None:
|
||||
"""OpenRouter names must NOT trigger thinking without reasoning_effort."""
|
||||
kw = _build_kwargs_for("openrouter", "moonshotai/kimi-k2.5", reasoning_effort=None)
|
||||
assert "extra_body" not in kw
|
||||
|
||||
|
||||
def test_kimi_k26_code_preview_thinking_enabled() -> None:
|
||||
"""k2.6-code-preview also supports thinking; should behave like k2.5."""
|
||||
kw = _build_kwargs_for("moonshot", "k2.6-code-preview", reasoning_effort="high")
|
||||
assert kw.get("extra_body") == {"thinking": {"type": "enabled"}}
|
||||
assert "reasoning_effort" not in kw
|
||||
|
||||
|
||||
def test_kimi_k2_series_no_thinking_injection() -> None:
|
||||
"""kimi-k2 (non-thinking) models must NOT receive extra_body.thinking."""
|
||||
kw = _build_kwargs_for("moonshot", "kimi-k2", reasoning_effort="high")
|
||||
@@ -1920,20 +1909,6 @@ def test_kimi_k2_thinking_series_no_thinking_injection() -> None:
|
||||
# reasoning_effort="none" — treated as thinking disabled
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_deepseek_thinking_disabled_for_none_string() -> None:
|
||||
"""reasoning_effort='none' must send thinking.type=disabled and skip reasoning_effort field."""
|
||||
kw = _build_kwargs_for("deepseek", "deepseek-v4-pro", reasoning_effort="none")
|
||||
assert kw.get("extra_body") == {"thinking": {"type": "disabled"}}
|
||||
assert "reasoning_effort" not in kw
|
||||
|
||||
|
||||
def test_kimi_k25_thinking_disabled_for_none_string() -> None:
|
||||
"""reasoning_effort='none' maps to thinking disabled for kimi-k2.5."""
|
||||
kw = _build_kwargs_for("moonshot", "kimi-k2.5", reasoning_effort="none")
|
||||
assert kw.get("extra_body") == {"thinking": {"type": "disabled"}}
|
||||
assert "reasoning_effort" not in kw
|
||||
|
||||
|
||||
def test_dashscope_thinking_disabled_for_none_string() -> None:
|
||||
"""reasoning_effort='none' disables thinking and must not emit reasoning_effort on DashScope."""
|
||||
kw = _build_kwargs_for("dashscope", "qwen3.6-plus", reasoning_effort="none")
|
||||
@@ -1956,13 +1931,6 @@ def test_qwen_thinking_disabled_via_model_level_mapping() -> None:
|
||||
assert kw["extra_body"] == {"enable_thinking": False, "reasoning": {"effort": "none"}}
|
||||
|
||||
|
||||
def test_qwen_no_extra_body_when_reasoning_effort_omitted() -> None:
|
||||
"""Without reasoning_effort the model-level mapping must not inject extra_body
|
||||
on its own — the provider default applies."""
|
||||
kw = _build_kwargs_for("openrouter", "qwen/qwen3.6-flash", reasoning_effort=None)
|
||||
assert "extra_body" not in kw
|
||||
|
||||
|
||||
def test_deepseek_no_backfill_when_reasoning_effort_none_string() -> None:
|
||||
"""reasoning_effort='none' must NOT trigger reasoning_content backfill (thinking inactive)."""
|
||||
spec = find_by_name("deepseek")
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.providers.openai_compat_provider import (
|
||||
OpenAICompatProvider,
|
||||
_is_local_endpoint,
|
||||
@@ -26,62 +28,43 @@ class TestIsLocalEndpoint:
|
||||
def test_no_spec_no_base(self):
|
||||
assert _is_local_endpoint(None, None) is False
|
||||
|
||||
def test_localhost(self):
|
||||
assert _is_local_endpoint(None, "http://localhost:1234/v1") is True
|
||||
|
||||
def test_localhost_https(self):
|
||||
assert _is_local_endpoint(None, "https://localhost:8080/v1") is True
|
||||
|
||||
def test_loopback_127(self):
|
||||
assert _is_local_endpoint(None, "http://127.0.0.1:11434/v1") is True
|
||||
|
||||
def test_private_192_168(self):
|
||||
assert _is_local_endpoint(None, "http://192.168.8.188:1234/v1") is True
|
||||
|
||||
def test_private_10(self):
|
||||
assert _is_local_endpoint(None, "http://10.0.0.5:8000/v1") is True
|
||||
|
||||
def test_private_172_16(self):
|
||||
assert _is_local_endpoint(None, "http://172.16.0.1:1234/v1") is True
|
||||
|
||||
def test_private_172_31(self):
|
||||
assert _is_local_endpoint(None, "http://172.31.255.255:1234/v1") is True
|
||||
|
||||
def test_not_private_172_32(self):
|
||||
assert _is_local_endpoint(None, "http://172.32.0.1:1234/v1") is False
|
||||
|
||||
def test_docker_internal(self):
|
||||
assert _is_local_endpoint(None, "http://host.docker.internal:11434/v1") is True
|
||||
|
||||
def test_ipv6_loopback(self):
|
||||
assert _is_local_endpoint(None, "http://[::1]:1234/v1") is True
|
||||
|
||||
def test_public_api(self):
|
||||
assert _is_local_endpoint(None, "https://api.openai.com/v1") is False
|
||||
|
||||
def test_openrouter(self):
|
||||
assert _is_local_endpoint(None, "https://openrouter.ai/api/v1") is False
|
||||
@pytest.mark.parametrize(
|
||||
"expected, api_base",
|
||||
[
|
||||
pytest.param(True, "http://localhost:1234/v1", id="localhost"),
|
||||
pytest.param(True, "https://localhost:8080/v1", id="localhost_https"),
|
||||
pytest.param(True, "http://127.0.0.1:11434/v1", id="loopback_127"),
|
||||
pytest.param(True, "http://192.168.8.188:1234/v1", id="private_192_168"),
|
||||
pytest.param(True, "http://10.0.0.5:8000/v1", id="private_10"),
|
||||
pytest.param(True, "http://172.16.0.1:1234/v1", id="private_172_16"),
|
||||
pytest.param(True, "http://172.31.255.255:1234/v1", id="private_172_31"),
|
||||
pytest.param(False, "http://172.32.0.1:1234/v1", id="not_private_172_32"),
|
||||
pytest.param(True, "http://host.docker.internal:11434/v1", id="docker_internal"),
|
||||
pytest.param(True, "http://[::1]:1234/v1", id="ipv6_loopback"),
|
||||
pytest.param(False, "https://api.openai.com/v1", id="public_api"),
|
||||
pytest.param(False, "https://openrouter.ai/api/v1", id="openrouter"),
|
||||
pytest.param(True, "http://LOCALHOST:1234/v1", id="case_insensitive"),
|
||||
pytest.param(True, "http://192.168.1.1:8080/v1/", id="trailing_slash"),
|
||||
pytest.param(
|
||||
False,
|
||||
"https://notlocalhost.example/v1",
|
||||
id="public_hostname_containing_localhost_is_not_local",
|
||||
),
|
||||
pytest.param(
|
||||
False,
|
||||
"https://api10.example.com/v1",
|
||||
id="public_hostname_containing_private_ip_prefix_is_not_local",
|
||||
),
|
||||
pytest.param(True, "192.168.1.1:8080/v1", id="url_without_scheme"),
|
||||
],
|
||||
)
|
||||
def test_endpoint_locality(self, expected, api_base):
|
||||
assert _is_local_endpoint(None, api_base) is expected
|
||||
|
||||
def test_spec_overrides_public_url(self):
|
||||
"""spec.is_local=True takes precedence even with a public-looking URL."""
|
||||
assert _is_local_endpoint(_make_spec(is_local=True), "https://api.example.com/v1") is True
|
||||
|
||||
def test_case_insensitive(self):
|
||||
assert _is_local_endpoint(None, "http://LOCALHOST:1234/v1") is True
|
||||
|
||||
def test_trailing_slash(self):
|
||||
assert _is_local_endpoint(None, "http://192.168.1.1:8080/v1/") is True
|
||||
|
||||
def test_public_hostname_containing_localhost_is_not_local(self):
|
||||
assert _is_local_endpoint(None, "https://notlocalhost.example/v1") is False
|
||||
|
||||
def test_public_hostname_containing_private_ip_prefix_is_not_local(self):
|
||||
assert _is_local_endpoint(None, "https://api10.example.com/v1") is False
|
||||
|
||||
def test_url_without_scheme(self):
|
||||
assert _is_local_endpoint(None, "192.168.1.1:8080/v1") is True
|
||||
|
||||
|
||||
class TestLocalKeepaliveConfig:
|
||||
"""Verify that local endpoints get keepalive_expiry=0."""
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.config.schema import ProvidersConfig
|
||||
from nanobot.providers.openai_compat_provider import OpenAICompatProvider
|
||||
from nanobot.providers.registry import PROVIDERS, find_by_name
|
||||
@@ -54,37 +56,35 @@ def test_mistral_keyword_match_covers_model_families() -> None:
|
||||
assert config.get_provider_name(model) == "mistral", model
|
||||
|
||||
|
||||
def test_reasoning_effort_low_remaps_to_none_omitted() -> None:
|
||||
"""Mistral rejects low/medium efforts: low should map to "none" (omitted)."""
|
||||
@pytest.mark.parametrize(
|
||||
"model, effort",
|
||||
[
|
||||
pytest.param("mistral-medium-3-5", "low", id="low_remaps_to_none_omitted"),
|
||||
pytest.param("mistral-vibe-cli-latest", "minimal", id="minimal_remaps_to_none_omitted"),
|
||||
],
|
||||
)
|
||||
def test_mistral_omits_low_reasoning_effort(model, effort) -> None:
|
||||
p = _mistral_provider()
|
||||
kwargs = p._build_kwargs(
|
||||
messages=[{"role": "user", "content": "hi"}],
|
||||
tools=None,
|
||||
model="mistral-medium-3-5",
|
||||
model=model,
|
||||
max_tokens=64,
|
||||
temperature=0.5,
|
||||
reasoning_effort="low",
|
||||
reasoning_effort=effort,
|
||||
tool_choice=None,
|
||||
)
|
||||
assert "reasoning_effort" not in kwargs
|
||||
|
||||
|
||||
def test_reasoning_effort_minimal_remaps_to_none_omitted() -> None:
|
||||
p = _mistral_provider()
|
||||
kwargs = p._build_kwargs(
|
||||
messages=[{"role": "user", "content": "hi"}],
|
||||
tools=None,
|
||||
model="mistral-vibe-cli-latest",
|
||||
max_tokens=64,
|
||||
temperature=0.5,
|
||||
reasoning_effort="minimal",
|
||||
tool_choice=None,
|
||||
)
|
||||
assert "reasoning_effort" not in kwargs
|
||||
|
||||
|
||||
def test_reasoning_effort_medium_remaps_to_high() -> None:
|
||||
"""Mistral has no 'medium' tier: bump up to 'high'."""
|
||||
@pytest.mark.parametrize(
|
||||
"effort",
|
||||
[
|
||||
pytest.param("medium", id="medium_remaps_to_high"),
|
||||
pytest.param("high", id="high_passes_through"),
|
||||
],
|
||||
)
|
||||
def test_mistral_uses_high_reasoning_effort(effort) -> None:
|
||||
p = _mistral_provider()
|
||||
kwargs = p._build_kwargs(
|
||||
messages=[{"role": "user", "content": "hi"}],
|
||||
@@ -92,21 +92,7 @@ def test_reasoning_effort_medium_remaps_to_high() -> None:
|
||||
model="mistral-medium-3-5",
|
||||
max_tokens=64,
|
||||
temperature=0.5,
|
||||
reasoning_effort="medium",
|
||||
tool_choice=None,
|
||||
)
|
||||
assert kwargs["reasoning_effort"] == "high"
|
||||
|
||||
|
||||
def test_reasoning_effort_high_passes_through() -> None:
|
||||
p = _mistral_provider()
|
||||
kwargs = p._build_kwargs(
|
||||
messages=[{"role": "user", "content": "hi"}],
|
||||
tools=None,
|
||||
model="mistral-medium-3-5",
|
||||
max_tokens=64,
|
||||
temperature=0.5,
|
||||
reasoning_effort="high",
|
||||
reasoning_effort=effort,
|
||||
tool_choice=None,
|
||||
)
|
||||
assert kwargs["reasoning_effort"] == "high"
|
||||
|
||||
@@ -20,6 +20,8 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.config.schema import ProvidersConfig
|
||||
from nanobot.providers.openai_compat_provider import OpenAICompatProvider
|
||||
from nanobot.providers.registry import PROVIDERS
|
||||
@@ -183,10 +185,15 @@ def test_mimo_via_openrouter_reasoning_effort_medium_enables_thinking():
|
||||
}
|
||||
|
||||
|
||||
def test_mimo_via_openrouter_bare_slug_also_matches():
|
||||
"""Bare "mimo-v2.5-pro" (no publisher prefix) must also match the
|
||||
allowlist, since gateways sometimes accept either form."""
|
||||
provider = _openrouter_provider("mimo-v2.5-pro")
|
||||
@pytest.mark.parametrize(
|
||||
"model",
|
||||
[
|
||||
pytest.param("mimo-v2.5-pro", id="mimo_via_openrouter_bare_slug_also_matches"),
|
||||
pytest.param("moonshotai/kimi-k2.5", id="kimi_via_openrouter_also_injects_reasoning_effort"),
|
||||
],
|
||||
)
|
||||
def test_openrouter_thinking_allowlist_accepts_model_slugs(model):
|
||||
provider = _openrouter_provider(model)
|
||||
kwargs = provider._build_kwargs(
|
||||
messages=_simple_messages(),
|
||||
tools=None, model=None, max_tokens=100,
|
||||
@@ -198,40 +205,18 @@ def test_mimo_via_openrouter_bare_slug_also_matches():
|
||||
}
|
||||
|
||||
|
||||
def test_mimo_flash_via_openrouter_does_not_inject_thinking():
|
||||
"""mimo-v2-flash has no thinking mode per Xiaomi docs; the allowlist
|
||||
excludes it, so neither the upstream `thinking` field nor OR's
|
||||
`reasoning.effort` should be injected on the gateway path."""
|
||||
provider = _openrouter_provider("xiaomi/mimo-v2-flash")
|
||||
@pytest.mark.parametrize(
|
||||
"model",
|
||||
[
|
||||
pytest.param("xiaomi/mimo-v2-flash", id="mimo_flash_via_openrouter_does_not_inject_thinking"),
|
||||
pytest.param("openai/gpt-4o", id="non_mimo_model_via_openrouter_unaffected"),
|
||||
],
|
||||
)
|
||||
def test_openrouter_non_thinking_models_omit_extra_body(model):
|
||||
provider = _openrouter_provider(model)
|
||||
kwargs = provider._build_kwargs(
|
||||
messages=_simple_messages(),
|
||||
tools=None, model=None, max_tokens=100,
|
||||
temperature=0.7, reasoning_effort="none", tool_choice=None,
|
||||
)
|
||||
assert "extra_body" not in kwargs
|
||||
|
||||
|
||||
def test_non_mimo_model_via_openrouter_unaffected():
|
||||
"""Sanity: a non-MiMo, non-Kimi model through OpenRouter is untouched."""
|
||||
provider = _openrouter_provider("openai/gpt-4o")
|
||||
kwargs = provider._build_kwargs(
|
||||
messages=_simple_messages(),
|
||||
tools=None, model=None, max_tokens=100,
|
||||
temperature=0.7, reasoning_effort="none", tool_choice=None,
|
||||
)
|
||||
assert "extra_body" not in kwargs
|
||||
|
||||
|
||||
def test_kimi_via_openrouter_also_injects_reasoning_effort():
|
||||
"""Kimi has the same gateway problem as MiMo: OR drops the upstream
|
||||
`thinking` field. The same OR-reasoning injection should fire."""
|
||||
provider = _openrouter_provider("moonshotai/kimi-k2.5")
|
||||
kwargs = provider._build_kwargs(
|
||||
messages=_simple_messages(),
|
||||
tools=None, model=None, max_tokens=100,
|
||||
temperature=0.7, reasoning_effort="none", tool_choice=None,
|
||||
)
|
||||
assert kwargs["extra_body"] == {
|
||||
"thinking": {"type": "disabled"},
|
||||
"reasoning": {"effort": "none"},
|
||||
}
|
||||
@@ -2,6 +2,8 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.agent.tools.apply_patch import ApplyPatchTool
|
||||
|
||||
|
||||
@@ -89,7 +91,14 @@ def test_apply_patch_edits_add_to_existing_file(tmp_path):
|
||||
)
|
||||
|
||||
|
||||
def test_apply_patch_edits_add_to_existing_file_without_final_newline(tmp_path):
|
||||
@pytest.mark.parametrize(
|
||||
"new_text",
|
||||
[
|
||||
pytest.param("beta", id="without_final_newline"),
|
||||
pytest.param("\nbeta", id="respects_leading_newline"),
|
||||
],
|
||||
)
|
||||
def test_apply_patch_add_separates_existing_file_without_final_newline(tmp_path, new_text):
|
||||
target = tmp_path / "notes.txt"
|
||||
target.write_text("alpha", encoding="utf-8")
|
||||
tool = ApplyPatchTool(workspace=tmp_path)
|
||||
@@ -100,7 +109,7 @@ def test_apply_patch_edits_add_to_existing_file_without_final_newline(tmp_path):
|
||||
{
|
||||
"path": "notes.txt",
|
||||
"action": "add",
|
||||
"new_text": "beta",
|
||||
"new_text": new_text,
|
||||
}
|
||||
]
|
||||
)
|
||||
@@ -131,27 +140,6 @@ def test_apply_patch_edits_add_to_existing_crlf_file_without_final_newline(tmp_p
|
||||
assert target.read_bytes() == b"alpha\r\nbravo\r\ncharlie\r\n"
|
||||
|
||||
|
||||
def test_apply_patch_edits_add_to_existing_file_respects_leading_newline(tmp_path):
|
||||
target = tmp_path / "notes.txt"
|
||||
target.write_text("alpha", encoding="utf-8")
|
||||
tool = ApplyPatchTool(workspace=tmp_path)
|
||||
|
||||
result = asyncio.run(
|
||||
tool.execute(
|
||||
edits=[
|
||||
{
|
||||
"path": "notes.txt",
|
||||
"action": "add",
|
||||
"new_text": "\nbeta",
|
||||
}
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
assert "update notes.txt" in result
|
||||
assert target.read_text(encoding="utf-8") == "alpha\nbeta\n"
|
||||
|
||||
|
||||
def test_apply_patch_rejects_delete_action(tmp_path):
|
||||
target = tmp_path / "utils.py"
|
||||
target.write_text("def unused():\n pass\ndef used():\n return 1\n")
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.agent.tools.shell import ExecTool
|
||||
|
||||
|
||||
@@ -13,19 +15,84 @@ def test_deny_patterns_block_rm_rf():
|
||||
assert "deny pattern filter" in result.lower()
|
||||
|
||||
|
||||
def test_allow_patterns_bypass_deny():
|
||||
"""allow_patterns take priority: matching command skips deny check."""
|
||||
tool = ExecTool(allow_patterns=[r"rm\s+-rf\s+/tmp/.*"])
|
||||
result = tool._guard_command("rm -rf /tmp/build", "/tmp")
|
||||
@pytest.mark.parametrize(
|
||||
"command, allow_pattern",
|
||||
[
|
||||
pytest.param("rm -rf /tmp/build", "rm\\s+-rf\\s+/tmp/.*", id="allow_patterns_bypass_deny"),
|
||||
pytest.param(
|
||||
"echo allowlisted 2>&1",
|
||||
"echo\\s+allowlisted\\s+2>&1",
|
||||
id="guard_allow_patterns_keep_fd_redirection_ampersand",
|
||||
),
|
||||
pytest.param(
|
||||
"rm -rf /tmp/build",
|
||||
"rm\\s+-rf\\s+/tmp/build",
|
||||
id="allow_patterns_fullmatch_allows_exact_command",
|
||||
),
|
||||
pytest.param(
|
||||
"echo allowlisted",
|
||||
"\\becho\\s+allowlisted\\b",
|
||||
id="guard_allow_patterns_allow_single_matching_segment",
|
||||
),
|
||||
pytest.param(
|
||||
"echo allowlisted",
|
||||
"^echo\\s+allowlisted$",
|
||||
id="guard_allow_patterns_keep_fullmatch_style_compatibility",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_allow_patterns_accept_matching_commands(command, allow_pattern):
|
||||
tool = ExecTool(allow_patterns=[allow_pattern])
|
||||
result = tool._guard_command(command, "/tmp")
|
||||
assert result is None
|
||||
|
||||
|
||||
def test_allow_patterns_must_match_to_bypass():
|
||||
"""Non-matching allow_patterns do NOT bypass deny."""
|
||||
tool = ExecTool(allow_patterns=[r"rm\s+-rf\s+/opt/"])
|
||||
result = tool._guard_command("rm -rf /tmp/build", "/tmp")
|
||||
@pytest.mark.parametrize(
|
||||
"command, reason, allow_pattern",
|
||||
[
|
||||
pytest.param(
|
||||
"rm -rf /tmp/build",
|
||||
"deny pattern filter",
|
||||
"rm\\s+-rf\\s+/opt/",
|
||||
id="allow_patterns_must_match_to_bypass",
|
||||
),
|
||||
pytest.param(
|
||||
"echo allowlisted && touch /tmp/evil",
|
||||
"allowlist",
|
||||
"\\becho\\s+allowlisted\\b",
|
||||
id="guard_allow_patterns_block_non_matching_chained_segment",
|
||||
),
|
||||
pytest.param(
|
||||
"echo allowlisted & touch /tmp/evil",
|
||||
"allowlist",
|
||||
"echo\\s+allowlisted.*",
|
||||
id="guard_allow_patterns_block_single_ampersand_chained_segment",
|
||||
),
|
||||
pytest.param(
|
||||
"echo allowlisted\ntouch /tmp/evil",
|
||||
"allowlist",
|
||||
"echo\\s+allowlisted\\s*.*",
|
||||
id="guard_allow_patterns_block_newline_chained_segment",
|
||||
),
|
||||
pytest.param(
|
||||
"echo allowlisted\nrm -rf /",
|
||||
"deny pattern filter",
|
||||
"echo\\s+allowlisted\\s*.*",
|
||||
id="guard_newline_chained_segment_still_hits_deny_patterns",
|
||||
),
|
||||
pytest.param(
|
||||
"echo allowlisted &",
|
||||
"allowlist",
|
||||
"echo\\s+allowlisted",
|
||||
id="guard_allow_patterns_preserve_trailing_background_operator",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_allow_patterns_do_not_bypass_rejected_commands(command, reason, allow_pattern):
|
||||
tool = ExecTool(allow_patterns=[allow_pattern])
|
||||
result = tool._guard_command(command, "/tmp")
|
||||
assert result is not None
|
||||
assert "deny pattern filter" in result.lower()
|
||||
assert reason in result.lower()
|
||||
|
||||
|
||||
def test_extra_deny_patterns_from_config():
|
||||
@@ -58,42 +125,6 @@ def test_allow_patterns_is_whitelist_only():
|
||||
assert "allowlist" in result.lower()
|
||||
|
||||
|
||||
def test_guard_allow_patterns_block_non_matching_chained_segment():
|
||||
"""Every top-level shell segment must match an allow pattern."""
|
||||
tool = ExecTool(allow_patterns=[r"\becho\s+allowlisted\b"])
|
||||
|
||||
result = tool._guard_command("echo allowlisted && touch /tmp/evil", "/tmp")
|
||||
assert result is not None
|
||||
assert "allowlist" in result.lower()
|
||||
|
||||
|
||||
def test_guard_allow_patterns_block_single_ampersand_chained_segment():
|
||||
"""A backgrounded command is also a top-level shell segment."""
|
||||
tool = ExecTool(allow_patterns=[r"echo\s+allowlisted.*"])
|
||||
|
||||
result = tool._guard_command("echo allowlisted & touch /tmp/evil", "/tmp")
|
||||
assert result is not None
|
||||
assert "allowlist" in result.lower()
|
||||
|
||||
|
||||
def test_guard_allow_patterns_block_newline_chained_segment():
|
||||
"""A newline separates commands, so each line must match on its own."""
|
||||
tool = ExecTool(allow_patterns=[r"echo\s+allowlisted\s*.*"])
|
||||
|
||||
result = tool._guard_command("echo allowlisted\ntouch /tmp/evil", "/tmp")
|
||||
assert result is not None
|
||||
assert "allowlist" in result.lower()
|
||||
|
||||
|
||||
def test_guard_newline_chained_segment_still_hits_deny_patterns():
|
||||
"""An allowlisted first line does not exempt a denied later line."""
|
||||
tool = ExecTool(allow_patterns=[r"echo\s+allowlisted\s*.*"])
|
||||
|
||||
result = tool._guard_command("echo allowlisted\nrm -rf /", "/tmp")
|
||||
assert result is not None
|
||||
assert "deny pattern filter" in result.lower()
|
||||
|
||||
|
||||
def test_split_shell_segments_keep_line_continuation_intact():
|
||||
"""A backslash-escaped newline continues one command, not a new segment."""
|
||||
assert ExecTool._split_shell_segments("echo allowlisted \\\nextra") == [
|
||||
@@ -101,23 +132,6 @@ def test_split_shell_segments_keep_line_continuation_intact():
|
||||
]
|
||||
|
||||
|
||||
def test_guard_allow_patterns_preserve_trailing_background_operator():
|
||||
tool = ExecTool(allow_patterns=[r"echo\s+allowlisted"])
|
||||
|
||||
result = tool._guard_command("echo allowlisted &", "/tmp")
|
||||
|
||||
assert result is not None
|
||||
assert "allowlist" in result.lower()
|
||||
|
||||
|
||||
def test_guard_allow_patterns_keep_fd_redirection_ampersand():
|
||||
tool = ExecTool(allow_patterns=[r"echo\s+allowlisted\s+2>&1"])
|
||||
|
||||
result = tool._guard_command("echo allowlisted 2>&1", "/tmp")
|
||||
|
||||
assert result is None
|
||||
|
||||
|
||||
def test_deny_patterns_search_original_command_with_quoted_hash():
|
||||
"""Deny checks must still inspect text after a quoted hash."""
|
||||
tool = ExecTool(deny_patterns=[r"\brm\s+-rf\s+/"])
|
||||
@@ -126,21 +140,6 @@ def test_deny_patterns_search_original_command_with_quoted_hash():
|
||||
assert "deny pattern filter" in result.lower()
|
||||
|
||||
|
||||
def test_allow_patterns_fullmatch_allows_exact_command():
|
||||
"""A full-command allow pattern can still exempt an exact denied command."""
|
||||
tool = ExecTool(allow_patterns=[r"rm\s+-rf\s+/tmp/build"])
|
||||
result = tool._guard_command("rm -rf /tmp/build", "/tmp")
|
||||
assert result is None
|
||||
|
||||
|
||||
def test_guard_allow_patterns_allow_single_matching_segment():
|
||||
tool = ExecTool(allow_patterns=[r"\becho\s+allowlisted\b"])
|
||||
|
||||
result = tool._guard_command("echo allowlisted", "/tmp")
|
||||
|
||||
assert result is None
|
||||
|
||||
|
||||
def test_guard_allow_patterns_allow_multiple_matching_segments():
|
||||
tool = ExecTool(
|
||||
allow_patterns=[
|
||||
@@ -152,11 +151,3 @@ def test_guard_allow_patterns_allow_multiple_matching_segments():
|
||||
result = tool._guard_command("echo allowlisted && echo also_allowed", "/tmp")
|
||||
|
||||
assert result is None
|
||||
|
||||
|
||||
def test_guard_allow_patterns_keep_fullmatch_style_compatibility():
|
||||
tool = ExecTool(allow_patterns=[r"^echo\s+allowlisted$"])
|
||||
|
||||
result = tool._guard_command("echo allowlisted", "/tmp")
|
||||
|
||||
assert result is None
|
||||
@@ -762,13 +762,22 @@ def _make_fake_session(tool_names: list[str]) -> SimpleNamespace:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_connect_mcp_servers_enabled_tools_supports_raw_names(
|
||||
fake_mcp_runtime: dict[str, object | None],
|
||||
@pytest.mark.parametrize(
|
||||
"enabled_tool",
|
||||
[
|
||||
pytest.param("demo", id="raw_names"),
|
||||
pytest.param("mcp_test_demo", id="wrapped_names"),
|
||||
],
|
||||
)
|
||||
async def test_connect_mcp_servers_enabled_tools_accepts_raw_and_wrapped_names(
|
||||
fake_mcp_runtime: dict[str,
|
||||
object | None],
|
||||
enabled_tool,
|
||||
) -> None:
|
||||
fake_mcp_runtime["session"] = _make_fake_session(["demo", "other"])
|
||||
registry = ToolRegistry()
|
||||
stacks = await connect_mcp_servers(
|
||||
{"test": MCPServerConfig(command="fake", enabled_tools=["demo"])},
|
||||
{"test": MCPServerConfig(command="fake", enabled_tools=[enabled_tool])},
|
||||
registry,
|
||||
)
|
||||
for stack in stacks.values():
|
||||
@@ -793,22 +802,6 @@ async def test_connect_mcp_servers_enabled_tools_defaults_to_all(
|
||||
assert registry.tool_names == ["mcp_test_demo", "mcp_test_other"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_connect_mcp_servers_enabled_tools_supports_wrapped_names(
|
||||
fake_mcp_runtime: dict[str, object | None],
|
||||
) -> None:
|
||||
fake_mcp_runtime["session"] = _make_fake_session(["demo", "other"])
|
||||
registry = ToolRegistry()
|
||||
stacks = await connect_mcp_servers(
|
||||
{"test": MCPServerConfig(command="fake", enabled_tools=["mcp_test_demo"])},
|
||||
registry,
|
||||
)
|
||||
for stack in stacks.values():
|
||||
await stack.aclose()
|
||||
|
||||
assert registry.tool_names == ["mcp_test_demo"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_connect_mcp_servers_enabled_tools_supports_limited_wrapped_names(
|
||||
fake_mcp_runtime: dict[str, object | None],
|
||||
|
||||
@@ -343,18 +343,18 @@ def test_exec_guard_blocks_home_path_outside_workspace(tmp_path) -> None:
|
||||
assert "hard policy boundary" in error
|
||||
|
||||
|
||||
def test_exec_guard_blocks_bare_tilde_cwd_escape(tmp_path) -> None:
|
||||
@pytest.mark.parametrize(
|
||||
"command",
|
||||
[
|
||||
pytest.param("cd ~ && cat secret.txt", id="bare_tilde_cwd_escape"),
|
||||
pytest.param("cat ~root/.bashrc", id="named_user_home_path"),
|
||||
pytest.param("cat --config=~/.nanobot/config.json", id="equals_home_path_outside_workspace"),
|
||||
pytest.param("cat --config=~root/.bashrc", id="equals_named_user_home_path"),
|
||||
],
|
||||
)
|
||||
def test_exec_guard_blocks_home_paths_outside_workspace(tmp_path, command) -> None:
|
||||
tool = ExecTool(restrict_to_workspace=True)
|
||||
error = tool._guard_command("cd ~ && cat secret.txt", str(tmp_path))
|
||||
assert error is not None
|
||||
assert error.startswith(
|
||||
"Error: Command blocked by safety guard (path outside working dir)"
|
||||
)
|
||||
|
||||
|
||||
def test_exec_guard_blocks_named_user_home_path(tmp_path) -> None:
|
||||
tool = ExecTool(restrict_to_workspace=True)
|
||||
error = tool._guard_command("cat ~root/.bashrc", str(tmp_path))
|
||||
error = tool._guard_command(command, str(tmp_path))
|
||||
assert error is not None
|
||||
assert error.startswith(
|
||||
"Error: Command blocked by safety guard (path outside working dir)"
|
||||
@@ -385,24 +385,6 @@ def test_exec_guard_allows_current_directory_tilde(tmp_path) -> None:
|
||||
assert tool._guard_command("cat ~+/file.txt", str(tmp_path)) is None
|
||||
|
||||
|
||||
def test_exec_guard_blocks_equals_home_path_outside_workspace(tmp_path) -> None:
|
||||
tool = ExecTool(restrict_to_workspace=True)
|
||||
error = tool._guard_command("cat --config=~/.nanobot/config.json", str(tmp_path))
|
||||
assert error is not None
|
||||
assert error.startswith(
|
||||
"Error: Command blocked by safety guard (path outside working dir)"
|
||||
)
|
||||
|
||||
|
||||
def test_exec_guard_blocks_equals_named_user_home_path(tmp_path) -> None:
|
||||
tool = ExecTool(restrict_to_workspace=True)
|
||||
error = tool._guard_command("cat --config=~root/.bashrc", str(tmp_path))
|
||||
assert error is not None
|
||||
assert error.startswith(
|
||||
"Error: Command blocked by safety guard (path outside working dir)"
|
||||
)
|
||||
|
||||
|
||||
def test_exec_guard_blocks_quoted_home_path_outside_workspace(tmp_path) -> None:
|
||||
tool = ExecTool(restrict_to_workspace=True)
|
||||
error = tool._guard_command('cat "~/.nanobot/config.json"', str(tmp_path))
|
||||
|
||||
@@ -71,13 +71,6 @@ def test_clean_url_passes_validation():
|
||||
assert is_valid
|
||||
|
||||
|
||||
def test_backtick_url_produces_empty_scheme_in_urlparse():
|
||||
from urllib.parse import urlparse
|
||||
p = urlparse("`https://example.com/page`")
|
||||
assert p.scheme == ""
|
||||
assert p.netloc == ""
|
||||
|
||||
|
||||
# --- WebFetchTool.execute integration tests ---
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -103,27 +96,17 @@ async def test_execute_accepts_cleanable_http_urls(url):
|
||||
# --- startswith guard tests ---
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_execute_rejects_non_http_url_after_cleaning():
|
||||
@pytest.mark.parametrize(
|
||||
"url",
|
||||
[
|
||||
pytest.param("ftp://example.com/file", id="non_http_url_after_cleaning"),
|
||||
pytest.param("`not a url at all`", id="garbage_after_cleaning"),
|
||||
pytest.param("`example.com/page`", id="bare_domain_after_cleaning"),
|
||||
],
|
||||
)
|
||||
async def test_execute_rejects_invalid_url_after_cleaning(url):
|
||||
tool = WebFetchTool()
|
||||
result = await tool.execute(url="ftp://example.com/file")
|
||||
data = json.loads(result)
|
||||
assert "error" in data
|
||||
assert "URL validation failed" in data["error"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_execute_rejects_garbage_after_cleaning():
|
||||
tool = WebFetchTool()
|
||||
result = await tool.execute(url="`not a url at all`")
|
||||
data = json.loads(result)
|
||||
assert "error" in data
|
||||
assert "URL validation failed" in data["error"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_execute_rejects_bare_domain_after_cleaning():
|
||||
tool = WebFetchTool()
|
||||
result = await tool.execute(url="`example.com/page`")
|
||||
result = await tool.execute(url=url)
|
||||
data = json.loads(result)
|
||||
assert "error" in data
|
||||
assert "URL validation failed" in data["error"]
|
||||
@@ -42,11 +42,26 @@ def test_brave_with_api_key_remains_concurrency_safe():
|
||||
assert tool.concurrency_safe is True
|
||||
|
||||
|
||||
def test_brave_without_api_key_is_treated_as_duckduckgo_for_concurrency(monkeypatch):
|
||||
monkeypatch.delenv("BRAVE_API_KEY", raising=False)
|
||||
tool = _tool(provider="brave", api_key="")
|
||||
assert tool.exclusive is True
|
||||
assert tool.concurrency_safe is False
|
||||
@pytest.mark.parametrize(
|
||||
"env_key, expected_exclusive, expected_safe, provider",
|
||||
[
|
||||
pytest.param("BRAVE_API_KEY", True, False, "brave", id="brave-fallback"),
|
||||
pytest.param("KEENABLE_API_KEY", False, True, "keenable", id="keenable"),
|
||||
pytest.param("SERPER_API_KEY", True, False, "serper", id="serper-fallback"),
|
||||
pytest.param("ANYSEARCH_API_KEY", False, True, "anysearch", id="anysearch"),
|
||||
],
|
||||
)
|
||||
def test_search_concurrency_without_api_key(
|
||||
monkeypatch,
|
||||
env_key,
|
||||
expected_exclusive,
|
||||
expected_safe,
|
||||
provider,
|
||||
):
|
||||
monkeypatch.delenv(env_key, raising=False)
|
||||
tool = _tool(provider=provider, api_key="")
|
||||
assert tool.exclusive is expected_exclusive
|
||||
assert tool.concurrency_safe is expected_safe
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -132,13 +147,6 @@ async def test_tavily_search(monkeypatch):
|
||||
assert "https://openclaw.io" in result
|
||||
|
||||
|
||||
def test_keenable_without_api_key_is_concurrency_safe(monkeypatch):
|
||||
monkeypatch.delenv("KEENABLE_API_KEY", raising=False)
|
||||
tool = _tool(provider="keenable", api_key="")
|
||||
assert tool.exclusive is False
|
||||
assert tool.concurrency_safe is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_keenable_search(monkeypatch):
|
||||
async def mock_post(self, url, **kw):
|
||||
@@ -202,14 +210,6 @@ async def test_keenable_search_http_error(monkeypatch):
|
||||
assert "Error: Keenable search failed (401)" in result
|
||||
|
||||
|
||||
def test_serper_without_api_key_is_treated_as_duckduckgo(monkeypatch):
|
||||
# Serper requires a key; without one we fall back to DuckDuckGo for concurrency.
|
||||
monkeypatch.delenv("SERPER_API_KEY", raising=False)
|
||||
tool = _tool(provider="serper", api_key="")
|
||||
assert tool.exclusive is True
|
||||
assert tool.concurrency_safe is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_serper_search(monkeypatch):
|
||||
async def mock_post(self, url, **kw):
|
||||
@@ -287,15 +287,6 @@ async def test_serper_search_rate_limited(monkeypatch):
|
||||
assert is_tool_error_result(result)
|
||||
|
||||
|
||||
def test_anysearch_remains_concurrency_safe_without_api_key(monkeypatch):
|
||||
# Unlike keyed providers, AnySearch works without a key (anonymous quota),
|
||||
# so it must never be treated as exclusive/serialized.
|
||||
monkeypatch.delenv("ANYSEARCH_API_KEY", raising=False)
|
||||
tool = _tool(provider="anysearch", api_key="")
|
||||
assert tool.exclusive is False
|
||||
assert tool.concurrency_safe is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_anysearch_search(monkeypatch):
|
||||
async def mock_post(self, url, **kw):
|
||||
@@ -575,7 +566,15 @@ async def test_duckduckgo_search_passes_proxy(monkeypatch):
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_brave_fallback_to_duckduckgo_when_no_key(monkeypatch):
|
||||
@pytest.mark.parametrize(
|
||||
"env_key, provider",
|
||||
[
|
||||
pytest.param("BRAVE_API_KEY", "brave", id="brave_fallback_to_duckduckgo_when_no_key"),
|
||||
pytest.param("KAGI_API_KEY", "kagi", id="kagi_fallback_to_duckduckgo_when_no_key"),
|
||||
pytest.param("EXA_API_KEY", "exa", id="exa_fallback_to_duckduckgo_when_no_key"),
|
||||
],
|
||||
)
|
||||
async def test_provider_falls_back_to_duckduckgo_without_key(monkeypatch, env_key, provider):
|
||||
class MockDDGS:
|
||||
def __init__(self, **kw):
|
||||
pass
|
||||
@@ -584,9 +583,9 @@ async def test_brave_fallback_to_duckduckgo_when_no_key(monkeypatch):
|
||||
return [{"title": "Fallback", "href": "https://ddg.example", "body": "DuckDuckGo fallback"}]
|
||||
|
||||
monkeypatch.setattr("ddgs.DDGS", MockDDGS)
|
||||
monkeypatch.delenv("BRAVE_API_KEY", raising=False)
|
||||
monkeypatch.delenv(env_key, raising=False)
|
||||
|
||||
tool = _tool(provider="brave", api_key="")
|
||||
tool = _tool(provider=provider, api_key="")
|
||||
result = await tool.execute(query="test")
|
||||
assert "Fallback" in result
|
||||
|
||||
@@ -768,40 +767,6 @@ async def test_jina_422_falls_back_to_duckduckgo(monkeypatch):
|
||||
assert "DuckDuckGo fallback" in result
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_kagi_fallback_to_duckduckgo_when_no_key(monkeypatch):
|
||||
class MockDDGS:
|
||||
def __init__(self, **kw):
|
||||
pass
|
||||
|
||||
def text(self, query, max_results=5):
|
||||
return [{"title": "Fallback", "href": "https://ddg.example", "body": "DuckDuckGo fallback"}]
|
||||
|
||||
monkeypatch.setattr("ddgs.DDGS", MockDDGS)
|
||||
monkeypatch.delenv("KAGI_API_KEY", raising=False)
|
||||
|
||||
tool = _tool(provider="kagi", api_key="")
|
||||
result = await tool.execute(query="test")
|
||||
assert "Fallback" in result
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_exa_fallback_to_duckduckgo_when_no_key(monkeypatch):
|
||||
class MockDDGS:
|
||||
def __init__(self, **kw):
|
||||
pass
|
||||
|
||||
def text(self, query, max_results=5):
|
||||
return [{"title": "Fallback", "href": "https://ddg.example", "body": "DuckDuckGo fallback"}]
|
||||
|
||||
monkeypatch.setattr("ddgs.DDGS", MockDDGS)
|
||||
monkeypatch.delenv("EXA_API_KEY", raising=False)
|
||||
|
||||
tool = _tool(provider="exa", api_key="")
|
||||
result = await tool.execute(query="test")
|
||||
assert "Fallback" in result
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_jina_search_uses_path_encoded_query(monkeypatch):
|
||||
calls = {}
|
||||
|
||||
@@ -398,9 +398,19 @@ def test_create_model_configuration_rejects_dynamic_custom_provider_without_api_
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"label, provider_name, model",
|
||||
[
|
||||
pytest.param("Deep", "openai", "openai/gpt-4.1", id="unconfigured_provider"),
|
||||
pytest.param("Azure", "azure_openai", "my-deployment", id="azure_openai_without_base"),
|
||||
],
|
||||
)
|
||||
def test_create_model_configuration_rejects_unconfigured_provider(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
label,
|
||||
provider_name,
|
||||
model,
|
||||
) -> None:
|
||||
config_path = tmp_path / "config.json"
|
||||
save_config(Config(), config_path)
|
||||
@@ -409,9 +419,9 @@ def test_create_model_configuration_rejects_unconfigured_provider(
|
||||
with pytest.raises(WebUISettingsError, match="provider is not configured"):
|
||||
create_model_configuration(
|
||||
{
|
||||
"label": ["Deep"],
|
||||
"provider": ["openai"],
|
||||
"model": ["openai/gpt-4.1"],
|
||||
"label": [label],
|
||||
"provider": [provider_name],
|
||||
"model": [model],
|
||||
}
|
||||
)
|
||||
|
||||
@@ -1870,14 +1880,31 @@ def test_openai_codex_remote_login_uses_headless_dependency_mode(
|
||||
assert captured["cancelled"] is True
|
||||
|
||||
|
||||
def test_openai_codex_oauth_login_reports_missing_oauth_cli_kit(
|
||||
@pytest.mark.parametrize(
|
||||
"module_name, provider",
|
||||
[
|
||||
pytest.param(
|
||||
"nanobot.providers.openai_codex_oauth",
|
||||
"openai-codex",
|
||||
id="openai_codex_oauth_login_reports_missing_oauth_cli_kit",
|
||||
),
|
||||
pytest.param(
|
||||
"nanobot.providers.github_copilot_oauth",
|
||||
"github-copilot",
|
||||
id="github_copilot_oauth_login_reports_missing_oauth_cli_kit",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_oauth_login_reports_missing_oauth_cli_kit(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
oauth_flows: WebUIOAuthFlowRegistry,
|
||||
module_name,
|
||||
provider,
|
||||
) -> None:
|
||||
real_import = builtins.__import__
|
||||
|
||||
def fake_import(name, *args, **kwargs):
|
||||
if name == "nanobot.providers.openai_codex_oauth":
|
||||
if name == module_name:
|
||||
raise ImportError("missing")
|
||||
return real_import(name, *args, **kwargs)
|
||||
|
||||
@@ -1885,32 +1912,7 @@ def test_openai_codex_oauth_login_reports_missing_oauth_cli_kit(
|
||||
|
||||
with pytest.raises(WebUISettingsError) as exc:
|
||||
login_oauth_provider(
|
||||
{"provider": ["openai-codex"]},
|
||||
oauth_flows=oauth_flows,
|
||||
)
|
||||
|
||||
assert str(exc.value) == (
|
||||
"This nanobot installation is missing the required oauth-cli-kit package. "
|
||||
"Reinstall or upgrade nanobot-ai using the same installation method."
|
||||
)
|
||||
|
||||
|
||||
def test_github_copilot_oauth_login_reports_missing_oauth_cli_kit(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
oauth_flows: WebUIOAuthFlowRegistry,
|
||||
) -> None:
|
||||
real_import = builtins.__import__
|
||||
|
||||
def fake_import(name, *args, **kwargs):
|
||||
if name == "nanobot.providers.github_copilot_oauth":
|
||||
raise ImportError("missing")
|
||||
return real_import(name, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(builtins, "__import__", fake_import)
|
||||
|
||||
with pytest.raises(WebUISettingsError) as exc:
|
||||
login_oauth_provider(
|
||||
{"provider": ["github-copilot"]},
|
||||
{"provider": [provider]},
|
||||
oauth_flows=oauth_flows,
|
||||
)
|
||||
|
||||
@@ -2550,25 +2552,6 @@ def test_create_model_configuration_accepts_azure_openai_aad_mode(
|
||||
assert saved.model_presets["azure-aad"].model == "my-deployment"
|
||||
|
||||
|
||||
def test_create_model_configuration_rejects_azure_openai_without_base(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""azure_openai without api_base must still be rejected as not configured."""
|
||||
config_path = tmp_path / "config.json"
|
||||
save_config(Config(), config_path)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
|
||||
with pytest.raises(WebUISettingsError, match="provider is not configured"):
|
||||
create_model_configuration(
|
||||
{
|
||||
"label": ["Azure"],
|
||||
"provider": ["azure_openai"],
|
||||
"model": ["my-deployment"],
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_azure_openai_spec_no_longer_requires_api_key() -> None:
|
||||
"""Contract guard: api_key is optional for azure_openai (AAD fallback)."""
|
||||
from nanobot.webui.settings_api import _provider_requires_api_key
|
||||
|
||||
@@ -223,10 +223,13 @@ describe("MarkdownTextRenderer", () => {
|
||||
expect(screen.getByText("src/**/*.json").tagName).toBe("CODE");
|
||||
});
|
||||
|
||||
it("does not wrap complete fenced code blocks in an extra pre", () => {
|
||||
it.each([
|
||||
["complete", "\n```"],
|
||||
["streaming", ""],
|
||||
])("renders a %s fenced code block in one shell", (_state, closingFence) => {
|
||||
const { container } = render(
|
||||
<MarkdownTextRenderer highlightCode={false}>
|
||||
{"当前目录:\n\n```text\n/Users/renxubin/.nanobot/workspace\n```"}
|
||||
{"当前目录:\n\n```text\n/Users/renxubin/.nanobot/workspace" + closingFence}
|
||||
</MarkdownTextRenderer>,
|
||||
);
|
||||
|
||||
@@ -248,17 +251,6 @@ describe("MarkdownTextRenderer", () => {
|
||||
expect(container.querySelectorAll("pre")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("keeps streaming unfinished fenced code blocks to a single shell", () => {
|
||||
const { container } = render(
|
||||
<MarkdownTextRenderer highlightCode={false}>
|
||||
{"当前目录:\n\n```text\n/Users/renxubin/.nanobot/workspace"}
|
||||
</MarkdownTextRenderer>,
|
||||
);
|
||||
|
||||
expect(screen.getByText("/Users/renxubin/.nanobot/workspace")).toBeInTheDocument();
|
||||
expect(container.querySelectorAll("pre")).toHaveLength(1);
|
||||
expect(container.querySelector("pre div")).toBeNull();
|
||||
});
|
||||
|
||||
it("renders markdown images as inline previews", () => {
|
||||
render(<MarkdownTextRenderer></MarkdownTextRenderer>);
|
||||
|
||||
@@ -2787,44 +2787,25 @@ describe("useNanobotStream", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps assistant html media as a file attachment", () => {
|
||||
it.each([
|
||||
{ name: "index.html", kind: "file", url: "/api/media/sig/html" },
|
||||
{ name: "growth.svg", kind: "image", url: "/api/media/sig/svg" },
|
||||
])("classifies assistant $name media as $kind", ({ name, kind, url }) => {
|
||||
const fake = fakeClient();
|
||||
const { result } = renderHook(() => useNanobotStream("chat-html-media", EMPTY_MESSAGES), {
|
||||
const { result } = renderHook(() => useNanobotStream("chat-media", EMPTY_MESSAGES), {
|
||||
wrapper: wrap(fake.client),
|
||||
});
|
||||
|
||||
act(() => {
|
||||
fake.emit("chat-html-media", {
|
||||
fake.emit("chat-media", {
|
||||
event: "message",
|
||||
chat_id: "chat-html-media",
|
||||
text: "file ready",
|
||||
media_urls: [{ url: "/api/media/sig/html", name: "index.html" }],
|
||||
chat_id: "chat-media",
|
||||
text: "media ready",
|
||||
media_urls: [{ url, name }],
|
||||
});
|
||||
});
|
||||
|
||||
expect(result.current.messages[0].media).toEqual([
|
||||
{ kind: "file", url: "/api/media/sig/html", name: "index.html" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("infers assistant svg media as an image attachment", () => {
|
||||
const fake = fakeClient();
|
||||
const { result } = renderHook(() => useNanobotStream("chat-svg-media", EMPTY_MESSAGES), {
|
||||
wrapper: wrap(fake.client),
|
||||
});
|
||||
|
||||
act(() => {
|
||||
fake.emit("chat-svg-media", {
|
||||
event: "message",
|
||||
chat_id: "chat-svg-media",
|
||||
text: "chart ready",
|
||||
media_urls: [{ url: "/api/media/sig/svg", name: "growth.svg" }],
|
||||
});
|
||||
});
|
||||
|
||||
expect(result.current.messages[0].media).toEqual([
|
||||
{ kind: "image", url: "/api/media/sig/svg", name: "growth.svg" },
|
||||
]);
|
||||
expect(result.current.messages[0].media).toEqual([{ kind, url, name }]);
|
||||
});
|
||||
|
||||
it("corrects explicit image media when the name is a non-image file", () => {
|
||||
|
||||
Reference in new issue
Block a user