refactor: remove redundant comments and docstrings (#6527)

* refactor: remove redundant comments and docstrings

* fix(signal): annotate async context manager as a generator
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-30 13:07:03 +08:00
1 parent cb3ba45317
commit a4d2430140
922 files changed
+406 -7738

No files matched your search

@@ -1,5 +1,3 @@
"""Tests for the Ant Ling provider registration."""
from unittest.mock import patch
from nanobot.config.schema import Config, ProvidersConfig
@@ -76,8 +76,6 @@ async def test_chat_falls_back_to_stream_on_long_request_error() -> None:
assert captured["temperature"] == 0.5
assert captured["reasoning_effort"] == "high"
assert captured["tool_choice"] == "auto"
# The fallback must NOT pass an on_content_delta — chat() callers don't
# expect streaming side-effects.
assert "on_content_delta" not in captured
@@ -100,5 +98,4 @@ async def test_chat_does_not_fall_back_on_unrelated_value_error() -> None:
result = await provider.chat(messages=[{"role": "user", "content": "hi"}])
assert called is False
# Generic ValueError flows through _handle_error and surfaces as an error response.
assert result.finish_reason == "error" or "Error" in (result.content or "")
@@ -1,10 +1,7 @@
"""Tests for AnthropicProvider._merge_consecutive."""
from nanobot.providers.anthropic_provider import AnthropicProvider
class TestMergeConsecutive:
"""Verify role alternation and trailing-assistant stripping."""
def test_basic_alternation(self):
msgs = [
@@ -23,12 +20,10 @@ class TestMergeConsecutive:
{"role": "assistant", "content": "reply"},
]
result = AnthropicProvider._merge_consecutive(msgs)
# Two user messages merged into one, trailing assistant stripped
assert len(result) == 1
assert result[0]["role"] == "user"
def test_trailing_assistant_stripped(self):
"""Anthropic rejects prefill — trailing assistant must be removed."""
msgs = [
{"role": "user", "content": "hello"},
{"role": "assistant", "content": "hi"},
@@ -47,7 +42,6 @@ class TestMergeConsecutive:
{"role": "assistant", "content": "c"},
]
result = AnthropicProvider._merge_consecutive(msgs)
# b+c merged into one assistant, then stripped as trailing
assert len(result) == 3
assert result[-1]["role"] == "user"
assert result[-1]["content"] == "ok"
@@ -79,7 +73,6 @@ class TestMergeConsecutive:
result = AnthropicProvider._merge_consecutive(msgs)
assert len(result) == 1
assert result[0]["role"] == "user"
# "b" was merged into "a"'s block list during the merge pass.
assert result[0]["content"] == [
{"type": "text", "text": "a"},
{"type": "text", "text": "b"},
@@ -1,5 +1,3 @@
"""Anthropic streaming idle timeout should follow the full SSE stream, not text only."""
from __future__ import annotations
import asyncio
@@ -125,7 +123,6 @@ async def test_chat_stream_without_callback_survives_long_active_stream(monkeypa
@pytest.mark.asyncio
async def test_chat_stream_without_callback_still_enforces_idle_timeout(monkeypatch) -> None:
"""A genuinely stalled stream must still be cut off by the idle timeout."""
monkeypatch.setenv("NANOBOT_STREAM_IDLE_TIMEOUT_S", "0.05")
provider = AnthropicProvider(api_key="sk-test")
provider._client = MagicMock()
@@ -152,7 +149,6 @@ async def test_chat_stream_without_callback_still_enforces_idle_timeout(monkeypa
@pytest.mark.asyncio
async def test_chat_stream_calls_on_content_delta_only_for_text_delta() -> None:
"""Thinking deltas must be consumed without invoking on_content_delta."""
provider = AnthropicProvider(api_key="sk-test")
provider._client = MagicMock()
@@ -1,5 +1,3 @@
"""Tests for Anthropic provider thinking / reasoning_effort modes."""
from __future__ import annotations
from unittest.mock import patch
@@ -88,7 +86,6 @@ def test_opus_4_7_high_uses_adaptive_effort() -> None:
def test_opus_4_7_omits_temperature_none() -> None:
"""Without thinking, opus-4-7 must still omit temperature (API rejects it)."""
kw = _build(_make_provider("claude-opus-4-7"), None)
assert "temperature" not in kw
assert "thinking" not in kw
@@ -197,7 +194,6 @@ def test_ordinary_model_sends_temperature() -> None:
def test_reasoning_effort_string_none_does_not_enable_thinking() -> None:
"""reasoning_effort='none' must not enable thinking — treated same as disabled."""
kw = _build(_make_provider(), "none")
assert "thinking" not in kw
assert kw["temperature"] == 0.7
@@ -75,7 +75,6 @@ def test_convert_user_content_coerces_typeless_dict():
def test_convert_user_content_coerces_mixed_typeless():
"""Multiple typeless items and non-dict items are all handled."""
result = AnthropicProvider._convert_user_content([
42,
{"key": "val"},
@@ -108,7 +107,6 @@ def test_convert_assistant_message_repairs_history_tool_arguments():
def test_anthropic_sanitizes_invalid_tool_ids_consistently():
"""Invalid restored IDs must be valid for Anthropic and keep pairs matched."""
blocks = AnthropicProvider._assistant_blocks({
"role": "assistant",
"content": None,
@@ -130,7 +128,6 @@ def test_anthropic_sanitizes_invalid_tool_ids_consistently():
def test_anthropic_sanitized_tool_ids_avoid_simple_collisions():
"""Replacement-only sanitizing would collapse these two ids to call_a."""
blocks = AnthropicProvider._assistant_blocks({
"role": "assistant",
"content": None,
@@ -1,5 +1,3 @@
"""Test Azure OpenAI provider (Responses API via OpenAI SDK)."""
import json
import sys
import time
@@ -16,13 +14,8 @@ from nanobot.providers.azure_openai_provider import (
)
from nanobot.providers.base import LLMResponse, ProviderCallContext
# ---------------------------------------------------------------------------
# Init & validation
# ---------------------------------------------------------------------------
def test_init_creates_sdk_client():
"""Provider creates an AsyncOpenAI client with correct base_url."""
provider = AzureOpenAIProvider(
api_key="test-key",
api_base="https://test-resource.openai.azure.com",
@@ -31,14 +24,11 @@ def test_init_creates_sdk_client():
assert provider.api_key == "test-key"
assert provider.api_base == "https://test-resource.openai.azure.com/"
assert provider.default_model == "gpt-4o-deployment"
# SDK client base_url ends with /openai/v1/
assert str(provider._client.base_url).rstrip("/").endswith("/openai/v1")
# Static-key path must NOT construct an AAD token provider
assert provider._token_provider is None
def test_init_base_url_no_trailing_slash():
"""Trailing slashes are normalised before building base_url."""
provider = AzureOpenAIProvider(
api_key="k", api_base="https://res.openai.azure.com",
)
@@ -58,17 +48,11 @@ def test_init_validation_missing_base():
def test_no_api_version_in_base_url():
"""The /openai/v1/ path should NOT contain an api-version query param."""
provider = AzureOpenAIProvider(api_key="k", api_base="https://res.openai.azure.com")
base = str(provider._client.base_url)
assert "api-version" not in base
# ---------------------------------------------------------------------------
# AAD / DefaultAzureCredential fallback
# ---------------------------------------------------------------------------
def _install_fake_azure_identity(monkeypatch, credential_factory):
"""Install a fake ``azure.identity.aio`` module exposing ``DefaultAzureCredential``."""
azure_mod = sys.modules.get("azure") or SimpleNamespace()
@@ -159,7 +143,6 @@ async def test_aad_token_provider_sends_rotating_bearer_tokens_on_chat_requests(
async def test_explicit_key_sends_bearer_without_constructing_credential(
monkeypatch, azure_wire_requests,
):
"""Explicit api_key wins through chat(), without invoking Azure credentials."""
credential_factory = MagicMock(side_effect=AssertionError(
"DefaultAzureCredential must not be constructed when api_key is set"
))
@@ -180,8 +163,6 @@ async def test_explicit_key_sends_bearer_without_constructing_credential(
def test_init_missing_key_without_azure_identity_raises(monkeypatch):
"""Clear RuntimeError with install hint when azure-identity is missing."""
# Force the import inside _AzureTokenProvider to fail.
real_import = __builtins__["__import__"] if isinstance(__builtins__, dict) else __builtins__.__import__
def fake_import(name, *args, **kwargs):
@@ -196,7 +177,6 @@ def test_init_missing_key_without_azure_identity_raises(monkeypatch):
@pytest.mark.asyncio
async def test_token_provider_returns_credential_token(monkeypatch):
"""Token callback delegates to DefaultAzureCredential.get_token with the AOAI scope."""
access_token = SimpleNamespace(token="token-A", expires_on=time.time() + 3600)
credential_instance = MagicMock()
credential_instance.get_token = AsyncMock(return_value=access_token)
@@ -216,11 +196,6 @@ async def test_token_provider_returns_credential_token(monkeypatch):
assert credential_instance.get_token.await_count == 2
# ---------------------------------------------------------------------------
# _supports_temperature
# ---------------------------------------------------------------------------
def test_supports_temperature_standard_model():
assert AzureOpenAIProvider._supports_temperature("gpt-4o") is True
@@ -236,15 +211,9 @@ def test_supports_temperature_with_reasoning_effort():
def test_supports_temperature_with_reasoning_effort_none_string():
"""reasoning_effort='none' must NOT suppress temperature — it means thinking is off."""
assert AzureOpenAIProvider._supports_temperature("gpt-4o", reasoning_effort="none") is True
# ---------------------------------------------------------------------------
# _build_body — Responses API body construction
# ---------------------------------------------------------------------------
def test_build_body_basic():
provider = AzureOpenAIProvider(
api_key="k", api_base="https://res.openai.azure.com", default_model="gpt-4o",
@@ -259,7 +228,6 @@ def test_build_body_basic():
assert body["store"] is False
assert "reasoning" not in body
assert "include" not in body
# input should contain the converted user message only (system extracted)
assert any(
item.get("role") == "user"
for item in body["input"]
@@ -291,7 +259,6 @@ def test_build_body_enables_server_compaction():
def test_build_body_max_tokens_minimum():
"""max_output_tokens should never be less than 1."""
provider = AzureOpenAIProvider(api_key="k", api_base="https://r.com", default_model="gpt-4o")
body = provider._build_body([{"role": "user", "content": "x"}], None, None, 0, 0.7, None, None)
assert body["max_output_tokens"] == 1
@@ -314,12 +281,10 @@ def test_build_body_with_reasoning():
)
assert body["reasoning"] == {"effort": "medium"}
assert "reasoning.encrypted_content" in body.get("include", [])
# temperature omitted for reasoning models
assert "temperature" not in body
def test_build_body_reasoning_effort_none_string_omits_reasoning():
"""reasoning_effort='none' must not inject a reasoning body and must allow temperature."""
provider = AzureOpenAIProvider(api_key="k", api_base="https://r.com", default_model="gpt-4o")
body = provider._build_body(
[{"role": "user", "content": "hi"}], None, "gpt-4o", 4096, 0.7, "none", None,
@@ -329,7 +294,6 @@ def test_build_body_reasoning_effort_none_string_omits_reasoning():
def test_build_body_image_conversion():
"""image_url content blocks should be converted to input_image."""
provider = AzureOpenAIProvider(api_key="k", api_base="https://r.com", default_model="gpt-4o")
messages = [{
"role": "user",
@@ -348,7 +312,6 @@ def test_build_body_image_conversion():
def test_build_body_sanitizes_single_dict_content_block():
"""Single content dicts should be preserved via shared message sanitization."""
provider = AzureOpenAIProvider(api_key="k", api_base="https://r.com", default_model="gpt-4o")
messages = [{
"role": "user",
@@ -360,11 +323,6 @@ def test_build_body_sanitizes_single_dict_content_block():
assert body["input"][0]["content"] == [{"type": "input_text", "text": "Hi from dict content"}]
# ---------------------------------------------------------------------------
# chat() — non-streaming
# ---------------------------------------------------------------------------
def _make_sdk_response(
content="Hello!", tool_calls=None, status="completed",
usage=None,
@@ -513,7 +471,6 @@ async def test_chat_error_handling():
@pytest.mark.asyncio
async def test_chat_reasoning_param_format():
"""reasoning_effort should be sent as reasoning={effort: ...} not a flat string."""
provider = AzureOpenAIProvider(
api_key="k", api_base="https://test.openai.azure.com", default_model="gpt-5-chat",
)
@@ -530,19 +487,12 @@ async def test_chat_reasoning_param_format():
assert "reasoning_effort" not in call_kwargs
# ---------------------------------------------------------------------------
# chat_stream()
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_chat_stream_success():
"""Streaming should call on_content_delta and return combined response."""
provider = AzureOpenAIProvider(
api_key="test-key", api_base="https://test.openai.azure.com", default_model="gpt-4o",
)
# Build mock SDK stream events
events = []
ev1 = MagicMock(type="response.output_text.delta", delta="Hello")
ev2 = MagicMock(type="response.output_text.delta", delta=" world")
@@ -576,7 +526,6 @@ async def test_chat_stream_success():
@pytest.mark.asyncio
async def test_chat_stream_with_tool_calls():
"""Streaming tool calls should be accumulated correctly."""
provider = AzureOpenAIProvider(
api_key="k", api_base="https://test.openai.azure.com", default_model="gpt-4o",
)
@@ -621,7 +570,6 @@ async def test_chat_stream_with_tool_calls():
@pytest.mark.asyncio
async def test_chat_stream_error():
"""Streaming should return error when SDK raises."""
provider = AzureOpenAIProvider(
api_key="k", api_base="https://test.openai.azure.com", default_model="gpt-4o",
)
@@ -634,11 +582,6 @@ async def test_chat_stream_error():
assert result.finish_reason == "error"
# ---------------------------------------------------------------------------
# get_default_model
# ---------------------------------------------------------------------------
def test_get_default_model():
provider = AzureOpenAIProvider(
api_key="k", api_base="https://r.com", default_model="my-deploy",
-2
View File
@@ -1,5 +1,3 @@
"""Tests for the native AWS Bedrock Converse provider."""
from __future__ import annotations
from typing import Any
-18
View File
@@ -1,5 +1,3 @@
"""Tests for cached token extraction from OpenAI-compatible providers."""
from __future__ import annotations
import pytest
@@ -19,7 +17,6 @@ def _provider() -> OpenAICompatProvider:
return OpenAICompatProvider(api_key="test-key")
# Minimal valid choice so _parse reaches _extract_usage.
_DICT_CHOICE = {"message": {"content": "Hello"}}
@@ -38,10 +35,7 @@ def _sdk_response(usage) -> ChatCompletion:
})
# --- dict-based response (raw JSON / mapping) ---
def test_extract_usage_openai_cached_tokens_dict():
"""prompt_tokens_details.cached_tokens from a dict response."""
p = _provider()
response = {
"choices": [_DICT_CHOICE],
@@ -59,7 +53,6 @@ def test_extract_usage_openai_cached_tokens_dict():
def test_extract_usage_deepseek_cached_tokens_dict():
"""prompt_cache_hit_tokens from a DeepSeek dict response."""
p = _provider()
response = {
"choices": [_DICT_CHOICE],
@@ -77,7 +70,6 @@ def test_extract_usage_deepseek_cached_tokens_dict():
def test_extract_usage_no_cached_tokens_dict():
"""Response without any cache fields preserves an unreported cache count."""
p = _provider()
response = {
"choices": [_DICT_CHOICE],
@@ -94,7 +86,6 @@ def test_extract_usage_no_cached_tokens_dict():
def test_extract_usage_openai_cached_zero_dict():
"""cached_tokens=0 remains distinct from an unreported cache count."""
p = _provider()
response = {
"choices": [_DICT_CHOICE],
@@ -140,11 +131,8 @@ def test_extract_usage_missing_is_none():
assert result.usage is None
# --- object-based response (OpenAI SDK Pydantic model) ---
@pytest.mark.parametrize("cache_read, cache_write", [(1200, None), (0, 0)])
def test_extract_usage_openai_cached_tokens_obj(cache_read, cache_write):
"""SDK prompt token details preserve cache counts, including explicit zero."""
p = _provider()
response = _sdk_response({
"prompt_tokens": 2000,
@@ -179,7 +167,6 @@ def test_extract_usage_preserves_reported_total_and_cache_write_obj():
def test_extract_usage_deepseek_cached_tokens_obj():
"""prompt_cache_hit_tokens from a DeepSeek SDK object response."""
p = _provider()
response = _sdk_response({
"prompt_tokens": 1500,
@@ -193,7 +180,6 @@ def test_extract_usage_deepseek_cached_tokens_obj():
def test_extract_usage_stepfun_top_level_cached_tokens_dict():
"""StepFun/Moonshot: usage.cached_tokens at top level (not nested)."""
p = _provider()
response = {
"choices": [_DICT_CHOICE],
@@ -210,7 +196,6 @@ def test_extract_usage_stepfun_top_level_cached_tokens_dict():
def test_extract_usage_stepfun_top_level_cached_tokens_obj():
"""StepFun/Moonshot: usage.cached_tokens as SDK object attribute."""
p = _provider()
response = _sdk_response({
"prompt_tokens": 591,
@@ -224,7 +209,6 @@ def test_extract_usage_stepfun_top_level_cached_tokens_obj():
def test_extract_usage_priority_nested_over_top_level_dict():
"""When both nested and top-level cached_tokens exist, nested wins."""
p = _provider()
response = {
"choices": [_DICT_CHOICE],
@@ -278,7 +262,6 @@ def test_parse_chunks_preserves_usage_only_chunk(as_sdk: bool) -> None:
def test_anthropic_adds_native_cache_fields_to_logical_input():
"""Anthropic excludes cache reads/writes from its native input_tokens."""
from nanobot.providers.anthropic_provider import AnthropicProvider
usage_obj = FakeUsage(
@@ -304,7 +287,6 @@ def test_anthropic_adds_native_cache_fields_to_logical_input():
def test_anthropic_no_cache_fields():
"""Anthropic response without cache fields preserves unreported counts."""
from nanobot.providers.anthropic_provider import AnthropicProvider
usage_obj = FakeUsage(input_tokens=800, output_tokens=200)
@@ -1,5 +1,3 @@
"""Tests for provider-owned conversation-state lifecycle coordination."""
from __future__ import annotations
from unittest.mock import MagicMock
-2
View File
@@ -1,5 +1,3 @@
"""Tests for OpenAICompatProvider handling custom/direct endpoints."""
from unittest.mock import patch
import pytest
@@ -1,5 +1,3 @@
"""Tests for custom provider thinking_style config passthrough."""
from __future__ import annotations
from nanobot.config.schema import Config, ProviderConfig, ProvidersConfig
@@ -8,7 +6,6 @@ from nanobot.providers.registry import create_dynamic_spec
class TestCustomProviderThinkingStyle:
"""Verify that thinking_style flows from config to ProviderSpec."""
def test_default_thinking_style_is_none(self) -> None:
cfg = ProviderConfig()
@@ -31,12 +28,10 @@ class TestCustomProviderThinkingStyle:
assert spec.thinking_style == "reasoning_split"
def test_provider_config_accepts_camel_case(self) -> None:
"""Config JSON uses camelCase: thinkingStyle."""
cfg = ProviderConfig.model_validate({"thinkingStyle": "thinking_type"})
assert cfg.thinking_style == "thinking_type"
def test_providers_config_custom_has_thinking_style(self) -> None:
"""Full providers config round-trip."""
data = {
"custom": {
"apiKey": "sk-test",
-2
View File
@@ -1,5 +1,3 @@
"""Tests for the Eden AI provider registration."""
from unittest.mock import patch
from nanobot.config.schema import Config, ProvidersConfig
@@ -1,10 +1,7 @@
"""Tests for LLMProvider._enforce_role_alternation."""
from nanobot.providers.base import _SYNTHETIC_USER_CONTENT, LLMProvider
class TestEnforceRoleAlternation:
"""Verify trailing-assistant removal and consecutive same-role merging."""
def test_empty_messages(self):
assert LLMProvider._enforce_role_alternation([]) == []
@@ -184,7 +181,6 @@ class TestEnforceRoleAlternation:
assert "Subagent completed successfully." in result[1]["content"]
def test_trailing_assistant_not_recovered_when_user_message_present(self):
"""Recovery should NOT happen when a user message already exists."""
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi"},
@@ -243,7 +239,6 @@ class TestEnforceRoleAlternation:
non_system = [m for m in result if m["role"] != "system"]
assert non_system[0]["role"] == "user"
assert non_system[0]["content"] == _SYNTHETIC_USER_CONTENT
# The original assistant should follow.
assert non_system[1]["role"] == "assistant"
def test_leading_assistant_with_tool_calls_not_patched(self):
@@ -258,12 +253,10 @@ class TestEnforceRoleAlternation:
]
result = LLMProvider._enforce_role_alternation(msgs)
non_system = [m for m in result if m["role"] != "system"]
# The assistant has tool_calls so it should NOT be patched.
assert non_system[0]["role"] == "assistant"
assert non_system[0].get("tool_calls") is not None
def test_user_after_system_not_patched(self):
"""Normal system→user sequence is not modified."""
msgs = [
{"role": "system", "content": "sys"},
{"role": "user", "content": "hello"},
-30
View File
@@ -1,5 +1,3 @@
"""Tests for provider extra_body config injection into request payloads."""
from __future__ import annotations
from typing import Any
@@ -12,13 +10,8 @@ from nanobot.providers.openai_compat_provider import (
)
from nanobot.providers.registry import find_by_name
# ---------------------------------------------------------------------------
# _deep_merge unit tests
# ---------------------------------------------------------------------------
class TestDeepMerge:
"""Verify recursive dict merge semantics."""
def test_flat_merge(self) -> None:
assert _deep_merge({"a": 1}, {"b": 2}) == {"a": 1, "b": 2}
@@ -56,13 +49,7 @@ class TestDeepMerge:
assert override == {"a": {"y": 2}}
# ---------------------------------------------------------------------------
# Provider construction
# ---------------------------------------------------------------------------
class TestExtraBodyInit:
"""Verify the provider stores extra_body from config."""
def test_default_is_empty(self) -> None:
provider = OpenAICompatProvider(api_key="test")
@@ -78,11 +65,6 @@ class TestExtraBodyInit:
assert provider._extra_body == body
# ---------------------------------------------------------------------------
# _build_kwargs integration
# ---------------------------------------------------------------------------
def _make_provider(extra_body: dict[str, Any] | None = None) -> OpenAICompatProvider:
return OpenAICompatProvider(
api_key="test-key",
@@ -96,7 +78,6 @@ def _simple_messages() -> list[dict[str, Any]]:
class TestBuildKwargsExtraBody:
"""Verify extra_body flows into _build_kwargs output."""
def test_no_extra_body_no_key(self) -> None:
provider = _make_provider()
@@ -143,7 +124,6 @@ class TestBuildKwargsExtraBody:
assert kwargs["extra_body"] == {"custom_param": "value"}
def test_extra_body_merges_with_thinking(self) -> None:
"""Config extra_body should merge with (and override) thinking params."""
from nanobot.providers.registry import ProviderSpec
spec = ProviderSpec(
@@ -164,12 +144,10 @@ class TestBuildKwargsExtraBody:
temperature=0.1, reasoning_effort="high", tool_choice=None,
)
body = kwargs.get("extra_body", {})
# Config param should be present
assert body.get("custom_param") == "value"
assert body["thinking"] == {"type": "enabled"}
def test_guided_json_injection(self) -> None:
"""Real-world use case: vLLM guided decoding."""
schema = {"type": "object", "properties": {"name": {"type": "string"}}}
provider = _make_provider({"guided_json": schema})
kwargs = provider._build_kwargs(
@@ -180,7 +158,6 @@ class TestBuildKwargsExtraBody:
assert kwargs["extra_body"]["guided_json"] == schema
def test_repetition_penalty_injection(self) -> None:
"""Real-world use case: local model sampling param."""
provider = _make_provider({"repetition_penalty": 1.15})
kwargs = provider._build_kwargs(
messages=_simple_messages(),
@@ -191,7 +168,6 @@ class TestBuildKwargsExtraBody:
class TestBuildResponsesBodyExtraBody:
"""Verify extra_body flows into Responses API request bodies."""
def test_responses_extra_body_merges_top_level_fields(self) -> None:
provider = OpenAICompatProvider(
@@ -353,13 +329,7 @@ class TestBuildResponsesBodyExtraBody:
]
# ---------------------------------------------------------------------------
# Schema validation
# ---------------------------------------------------------------------------
class TestSchemaConfig:
"""Verify ProviderConfig accepts extra_body."""
def test_default_is_none(self) -> None:
from nanobot.config.schema import ProviderConfig
@@ -1,5 +1,3 @@
"""Tests for provider extra_query config injection into client defaults."""
from __future__ import annotations
from unittest.mock import MagicMock, patch
@@ -10,7 +8,6 @@ from nanobot.providers.openai_compat_provider import OpenAICompatProvider
class TestExtraQuerySchema:
"""Verify ProviderConfig accepts extra_query."""
def test_default_is_none(self) -> None:
config = ProviderConfig()
@@ -22,7 +19,6 @@ class TestExtraQuerySchema:
class TestExtraQueryInit:
"""Verify the provider stores extra_query from config."""
def test_default_is_empty(self) -> None:
provider = OpenAICompatProvider(api_key="test")
@@ -39,7 +35,6 @@ class TestExtraQueryInit:
class TestExtraQueryBuildClient:
"""Verify extra_query flows into AsyncOpenAI default_query."""
def test_build_client_passes_default_query(self) -> None:
mock_client = MagicMock()
@@ -71,7 +66,6 @@ class TestExtraQueryBuildClient:
class TestProviderSignatureIncludesExtraQuery:
"""Verify provider_signature tracks provider extra_query changes."""
def test_provider_signature_tracks_extra_query(self) -> None:
base = {
@@ -12,7 +12,6 @@ from nanobot.providers import github_copilot_provider as gc
@pytest.mark.asyncio
async def test_concurrent_token_refresh_fetches_once(monkeypatch):
"""A competing caller waits for the in-flight exchange and reuses its token."""
monkeypatch.setattr(gc, "_load_github_token", lambda: SimpleNamespace(access="github-token"))
fetch_count = 0
@@ -48,7 +47,6 @@ async def test_concurrent_token_refresh_fetches_once(monkeypatch):
provider = gc.GitHubCopilotProvider()
async def competing_call():
# No suspension between this signal and entering the token path.
competing_started.set()
return await provider._get_copilot_access_token()
@@ -1,5 +1,3 @@
"""Device authorization exposes its prompt before waiting for browser approval."""
import threading
import time
from types import SimpleNamespace
@@ -1,9 +1,3 @@
"""Regression tests for GitHub Copilot /responses routing.
Covers the Copilot-specific branches added to route GPT-5 / o-series models
through the /responses endpoint without falling back to /chat/completions.
"""
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock, patch
@@ -27,7 +21,6 @@ def _make_copilot_provider() -> OpenAICompatProvider:
def test_should_use_responses_api_allows_github_copilot_non_openai_base():
"""github_copilot bypasses the direct-OpenAI base check and still opts in for GPT-5."""
provider = _make_copilot_provider()
assert provider._should_use_responses_api("github_copilot/gpt-5.4-mini", None) is True
assert provider._should_use_responses_api("github_copilot/gpt-6-astra", None) is True
@@ -35,7 +28,6 @@ def test_should_use_responses_api_allows_github_copilot_non_openai_base():
def test_build_responses_body_strips_github_copilot_prefix():
"""/responses body must send the bare model name; gateway rejects routing prefixes."""
provider = _make_copilot_provider()
body = provider._build_responses_body(
messages=[{"role": "user", "content": "hi"}],
@@ -54,7 +46,6 @@ def test_build_responses_body_strips_github_copilot_prefix():
@pytest.mark.asyncio
async def test_github_copilot_does_not_fall_back_from_responses_error():
"""On /responses failure, github_copilot must re-raise instead of hitting /chat/completions."""
from nanobot.providers.github_copilot_provider import GitHubCopilotProvider
mock_client = MagicMock()
-39
View File
@@ -603,10 +603,6 @@ async def test_minimax_base64_response_uses_detected_mime() -> None:
assert response.images == [f"data:image/jpeg;base64,{raw_b64}"]
# ---------------------------------------------------------------------------
# StepFun (阶跃星辰)
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_stepfun_payload_and_response_with_aspect_ratio() -> None:
fake = FakeClient(FakeResponse({"data": [{"b64_json": RAW_B64}]}))
@@ -672,7 +668,6 @@ async def test_stepfun_uses_explicit_image_size() -> None:
@pytest.mark.asyncio
async def test_stepfun_style_reference_on_1x_model(tmp_path: Path) -> None:
"""step-1x-medium supports style_reference for reference-image generation."""
ref = tmp_path / "ref.png"
ref.write_bytes(PNG_BYTES)
fake = FakeClient(FakeResponse({"data": [{"b64_json": RAW_B64}]}))
@@ -695,7 +690,6 @@ async def test_stepfun_style_reference_on_1x_model(tmp_path: Path) -> None:
@pytest.mark.asyncio
async def test_stepfun_no_style_reference_on_non_1x_model() -> None:
"""step-image-edit-2 does not use style_reference; reference images are ignored."""
fake = FakeClient(FakeResponse({"data": [{"b64_json": RAW_B64}]}))
client = StepFunImageGenerationClient(
api_key="sk-sf-test",
@@ -730,11 +724,6 @@ async def test_stepfun_no_images_raises() -> None:
await client.generate(prompt="draw", model="step-image-edit-2")
# ---------------------------------------------------------------------------
# OpenAI
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_openai_payload_and_response() -> None:
fake = FakeClient(FakeResponse({"data": [{"b64_json": RAW_B64}]}))
@@ -1080,11 +1069,6 @@ async def test_openai_requires_api_key() -> None:
await client.generate(prompt="draw", model="dall-e-3")
# ---------------------------------------------------------------------------
# Custom OpenAI-compatible Images API
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_custom_generate_success() -> None:
fake = FakeClient(FakeResponse({"data": [{"b64_json": RAW_B64}]}))
@@ -1205,11 +1189,6 @@ async def test_custom_generate_http_error() -> None:
await client.generate(prompt="draw", model="custom-image-model")
# ---------------------------------------------------------------------------
# OpenAI Codex (Responses API)
# ---------------------------------------------------------------------------
@pytest.fixture
def codex_oauth(monkeypatch):
import sys
@@ -1358,11 +1337,6 @@ async def test_openai_no_images_raises() -> None:
await client.generate(prompt="draw", model="dall-e-3")
# ---------------------------------------------------------------------------
# Zhipu
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_zhipu_image_generation_payload_and_response() -> None:
fake = FakeClient(FakeResponse({"data": [{"url": "https://cdn.example/image.png"}]}))
@@ -1461,11 +1435,6 @@ async def test_zhipu_image_generation_rejects_reference_images() -> None:
)
# ---------------------------------------------------------------------------
# ModelScope (魔搭) image generation tests
# ---------------------------------------------------------------------------
class ModelScopeFakeClient:
"""Fake httpx client for ModelScope async task pattern.
@@ -1537,7 +1506,6 @@ async def test_modelscope_image_generation_submit_and_poll(
assert response.images[0].startswith("data:image/png;base64,")
assert generated_image_downloads == [("https://cdn.example/image.png", proxy)]
# Verify POST request
post_call = fake.calls[0]
assert post_call["url"] == "https://api-inference.modelscope.cn/v1/images/generations"
assert post_call["headers"]["Authorization"] == "Bearer ms-token"
@@ -1546,7 +1514,6 @@ async def test_modelscope_image_generation_submit_and_poll(
assert body["model"] == "Qwen/Qwen-Image"
assert body["prompt"] == "A golden cat"
# Verify task polling GET
assert "/tasks/abc123" in fake.get_calls[0]["url"]
poll_headers = fake.get_calls[0]["headers"]
assert poll_headers["X-ModelScope-Task-Type"] == "image_generation"
@@ -1637,7 +1604,6 @@ async def test_modelscope_image_generation_missing_task_id() -> None:
@pytest.mark.asyncio
async def test_modelscope_image_generation_with_reference_image() -> None:
"""Reference images are converted to base64 data URLs for image editing models."""
submit = FakeResponse({"task_id": "t1"})
poll = [FakeResponse({"task_status": "SUCCEED", "output_images": ["https://cdn/img.png"]})]
fake = ModelScopeFakeClient(submit, poll)
@@ -1646,7 +1612,6 @@ async def test_modelscope_image_generation_with_reference_image() -> None:
client=fake, # type: ignore[arg-type]
)
# Create a temporary image file
import tempfile
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
f.write(PNG_BYTES)
@@ -1668,7 +1633,6 @@ async def test_modelscope_image_generation_with_reference_image() -> None:
@pytest.mark.asyncio
async def test_modelscope_image_generation_extra_body_passthrough() -> None:
"""Extra body fields like loras are passed through to the API."""
submit = FakeResponse({"task_id": "t1"})
poll = [FakeResponse({"task_status": "SUCCEED", "output_images": ["https://cdn/img.png"]})]
fake = ModelScopeFakeClient(submit, poll)
@@ -1687,12 +1651,10 @@ async def test_modelscope_image_generation_extra_body_passthrough() -> None:
@pytest.mark.asyncio
async def test_modelscope_image_generation_poll_timeout(monkeypatch) -> None:
"""Polling that never reaches SUCCEED/FAILED raises a timeout error."""
monkeypatch.setattr(
"nanobot.providers.image_generation._MODELSCOPE_POLL_MAX_ATTEMPTS", 3
)
submit = FakeResponse({"task_id": "t1"})
# Always PENDING — never resolves.
poll = [FakeResponse({"task_status": "PENDING"})]
fake = ModelScopeFakeClient(submit, poll)
client = ModelScopeImageGenerationClient(
@@ -1703,7 +1665,6 @@ async def test_modelscope_image_generation_poll_timeout(monkeypatch) -> None:
with pytest.raises(ImageGenerationError, match="timed out"):
await client.generate(prompt="test", model="m")
# Should have polled up to the (patched) attempt limit.
assert len(fake.get_calls) == 3
-2
View File
@@ -1,5 +1,3 @@
"""Exercise inline image preparation at provider SDK and HTTP boundaries."""
from __future__ import annotations
import base64
@@ -1,5 +1,3 @@
"""Internal model calls consume active streams and stop when the stream goes idle."""
import asyncio
import json
from collections.abc import AsyncIterator, Awaitable, Callable
-2
View File
@@ -25,13 +25,11 @@ def _response(finish_reason: str, *, with_tool_call: bool = True) -> LLMResponse
class TestShouldExecuteTools:
def test_no_tool_calls_never_executes(self) -> None:
# No tool calls present -> guard must reject regardless of finish_reason.
for reason in ("tool_calls", "stop", "length", "error", "refusal", "content_filter"):
resp = _response(reason, with_tool_call=False)
assert resp.should_execute_tools is False, f"rejected for finish_reason={reason!r}"
def test_tool_calls_with_tool_calls_reason_executes(self) -> None:
# The canonical case: provider explicitly signals tool intent.
resp = _response("tool_calls")
assert resp.has_tool_calls is True
assert resp.should_execute_tools is True
@@ -1,5 +1,3 @@
"""Tests for _is_local_endpoint detection and keepalive configuration."""
from unittest.mock import MagicMock
import pytest
@@ -17,7 +15,6 @@ def _make_spec(is_local: bool = False) -> MagicMock:
class TestIsLocalEndpoint:
"""Test the _is_local_endpoint helper."""
def test_spec_is_local_true(self):
assert _is_local_endpoint(_make_spec(is_local=True), None) is True
@@ -62,11 +59,9 @@ class TestIsLocalEndpoint:
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
class TestLocalKeepaliveConfig:
"""Verify that local endpoints get keepalive_expiry=0."""
async def test_local_spec_disables_keepalive(self):
spec = _make_spec(is_local=True)
@@ -80,7 +75,6 @@ class TestLocalKeepaliveConfig:
assert pool._keepalive_expiry == 0
async def test_lan_ip_disables_keepalive(self):
"""A generic 'openai' spec with a LAN IP should still disable keepalive."""
spec = _make_spec(is_local=False)
spec.env_key = ""
spec.default_api_base = None
@@ -100,5 +94,4 @@ class TestLocalKeepaliveConfig:
)
await provider._ensure_client()
pool = provider._client._client._transport._pool
# Default httpx keepalive is 5.0s
assert pool._keepalive_expiry == 5.0
-5
View File
@@ -1,17 +1,13 @@
"""Tests for the LongCat provider registration."""
from nanobot.config.schema import ProvidersConfig
from nanobot.providers.registry import PROVIDERS, find_by_name
def test_longcat_config_field_exists():
"""ProvidersConfig should have a longcat field."""
config = ProvidersConfig()
assert hasattr(config, "longcat")
def test_longcat_provider_in_registry():
"""LongCat should be registered in the provider registry."""
specs = {s.name: s for s in PROVIDERS}
assert "longcat" in specs
@@ -22,7 +18,6 @@ def test_longcat_provider_in_registry():
def test_find_by_name_longcat():
"""find_by_name should resolve the LongCat provider."""
spec = find_by_name("longcat")
assert spec is not None
@@ -1,17 +1,13 @@
"""Tests for the MiniMax Anthropic provider registration."""
from nanobot.config.schema import ProvidersConfig
from nanobot.providers.registry import PROVIDERS
def test_minimax_anthropic_config_field_exists():
"""ProvidersConfig should expose a minimax_anthropic field."""
config = ProvidersConfig()
assert hasattr(config, "minimax_anthropic")
def test_minimax_anthropic_provider_in_registry():
"""MiniMax Anthropic endpoint should be registered with Anthropic backend."""
specs = {s.name: s for s in PROVIDERS}
assert "minimax_anthropic" in specs
-12
View File
@@ -1,5 +1,3 @@
"""Tests for the Mistral provider registration and reasoning quirks."""
from __future__ import annotations
from unittest.mock import patch
@@ -25,13 +23,11 @@ def _mistral_provider(default_model: str = "mistral-medium-3-5") -> OpenAICompat
def test_mistral_config_field_exists() -> None:
"""ProvidersConfig should have a mistral field."""
config = ProvidersConfig()
assert hasattr(config, "mistral")
def test_mistral_provider_in_registry() -> None:
"""Mistral should be registered in the provider registry."""
specs = {s.name: s for s in PROVIDERS}
assert "mistral" in specs
@@ -41,7 +37,6 @@ def test_mistral_provider_in_registry() -> None:
def test_mistral_keyword_match_covers_model_families() -> None:
"""Codestral, Devstral, Ministral, Magistral models route to the Mistral spec."""
from nanobot.config.schema import Config
for model in (
@@ -101,7 +96,6 @@ def test_mistral_uses_high_reasoning_effort(effort) -> None:
def test_magistral_strips_reasoning_effort() -> None:
"""Magistral reasons implicitly; API rejects reasoning_effort kwarg."""
p = _mistral_provider()
for effort in ("low", "medium", "high", "minimal"):
kwargs = p._build_kwargs(
@@ -117,7 +111,6 @@ def test_magistral_strips_reasoning_effort() -> None:
def test_extract_thinking_content_from_mistral_response() -> None:
"""Thinking blocks should land in reasoning_content, not content."""
p = _mistral_provider()
response = {
"choices": [
@@ -146,7 +139,6 @@ def test_extract_thinking_content_from_mistral_response() -> None:
def test_extract_thinking_content_with_tool_calls() -> None:
"""A response with thinking + tool_calls (no text content) should still parse."""
p = _mistral_provider()
response = {
"choices": [
@@ -185,7 +177,6 @@ def test_extract_thinking_content_with_tool_calls() -> None:
def test_thinking_content_only_for_mistral_spec() -> None:
"""Providers without extract_thinking_blocks should not lift thinking text."""
other_spec = find_by_name("openai")
assert other_spec is not None
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
@@ -218,7 +209,6 @@ def test_thinking_content_only_for_mistral_spec() -> None:
def test_streaming_thinking_chunks_become_reasoning() -> None:
"""Streamed thinking deltas (Mistral shape) feed reasoning_content."""
chunks = [
{
"choices": [
@@ -295,7 +285,6 @@ def test_streaming_thinking_chunks_via_sdk_path() -> None:
def test_mistral_strips_reasoning_content_from_history() -> None:
"""Mistral's request schema 400s on reasoning_content; it must be dropped."""
p = _mistral_provider()
messages = [
{"role": "user", "content": "hi"},
@@ -312,7 +301,6 @@ def test_mistral_strips_reasoning_content_from_history() -> None:
def test_mistral_tool_call_ids_get_normalized() -> None:
"""Non-9-char tool_call IDs should be hashed to 9-char alphanumeric."""
p = _mistral_provider()
messages = [
{"role": "user", "content": "hi"},
+1 -6
View File
@@ -1,5 +1,3 @@
"""Preset API declarations control requests through OpenAI-compatible gateways."""
import asyncio
import json
@@ -76,8 +74,6 @@ async def test_model_override_keeps_request_settings_within_connection(
before = config.model_dump()
model = f"{target}/new-model"
if literal_env_syntax:
# SDK/factory arguments are model IDs, not configuration templates.
# Auto routing of this literal uses the first configured connection.
monkeypatch.setenv("NANOBOT_TEST_CALL_MODEL", "tenant_a/env-model")
model = "${NANOBOT_TEST_CALL_MODEL}"
if entrypoint == "sdk":
@@ -210,7 +206,6 @@ async def test_preset_overrides_isolate_requests_and_preserve_prompt_prefix(bind
await provider._ensure_client()
bind_transport(provider, handler)
signature = provider_signature(config, preset=override)
# Editing the config cannot change a previously constructed provider.
override.extra_body["metadata"]["local"] = "later"
assert signature != provider_signature(config, preset=override)
messages = [{"role": "system", "content": "stable"}, {"role": "user", "content": "hello"}]
@@ -222,7 +217,7 @@ async def test_preset_overrides_isolate_requests_and_preserve_prompt_prefix(bind
changed_body = json.loads(by_route["preset"].content)
assert changed_body.pop("metadata") == {"local": "yes"}
assert base_body.pop("metadata") == {"shared": "yes"}
assert changed_body == base_body # Includes system/history and serialized tool definitions.
assert changed_body == base_body
assert by_route["preset"].headers.get_list("x-route") == ["preset"]
assert all(request.headers["x-keep"] == "yes" for request in requests)
assert by_route["preset"].url.params["route"] == "preset"
@@ -1,5 +1,3 @@
"""Tests for the ModelScope (魔搭) provider registration."""
from unittest.mock import patch
from nanobot.config.schema import Config, ProvidersConfig
@@ -95,7 +93,6 @@ def test_modelscope_strips_prefix_in_request_model() -> None:
tool_choice=None,
)
# strip_model_prefixes removes "modelscope/" → "Qwen/Qwen3.5-35B-A3B"
assert kwargs["model"] == "Qwen/Qwen3.5-35B-A3B"
assert kwargs["max_tokens"] == 1024
assert "max_completion_tokens" not in kwargs
-2
View File
@@ -1,5 +1,3 @@
"""Tests for the Novita AI provider registration."""
from unittest.mock import patch
from nanobot.config.schema import Config, ProvidersConfig
@@ -230,7 +230,6 @@ def test_openai_codex_catalog_uses_account_catalog_and_filters_hidden_models(
request = captured["request"]
assert isinstance(request, httpx.Request)
assert request.url.copy_with(query=None) == httpx.URL(DEFAULT_OPENAI_CODEX_MODELS_URL)
# Assert the release-independent wire version, not the constant used by the request.
assert request.url.params["client_version"] == "99.99.99"
assert request.headers["Authorization"] == "Bearer secret"
assert request.headers["chatgpt-account-id"] == "account-42"
@@ -646,7 +645,6 @@ def test_catalog_retains_safe_error_kind_until_reauthentication(
assert first.error_kind == second.error_kind == expected
assert calls == (2 if with_cache else 1)
assert sentinel not in repr(first) + "".join(logs)
# Same account re-login must bypass both the stale list and negative cache.
failing[0] = False
catalog.invalidate()
recovered = catalog.get(cache_key="same-account")
@@ -121,7 +121,7 @@ async def test_codex_langfuse_disabled_when_env_var_unset(monkeypatch) -> None:
assert result.content == "hello"
assert capture.calls == []
assert find_spec_calls == [] # short-circuited before ever checking the package
assert find_spec_calls == []
@pytest.mark.parametrize(
@@ -253,7 +253,7 @@ async def test_codex_langfuse_generation_ends_on_cancellation(monkeypatch, gener
assert len(generations) == 1
gen = generations[0]
assert gen.end_calls == 1
assert gen.update_calls == [] # no output/usage known - nothing to attach
assert gen.update_calls == []
async def test_codex_langfuse_traces_each_request_during_native_compaction(monkeypatch, generations) -> None:
@@ -408,7 +408,6 @@ async def test_codex_langfuse_traces_the_actual_wire_body_not_the_prenormalized_
async def test_codex_langfuse_records_rejected_compaction_as_error(monkeypatch, generations) -> None:
"""A transport-successful compaction with no usable item must not trace as a success."""
provider = OpenAICodexProvider(default_model="openai-codex/gpt-5.6-sol")
state = build_responses_state(
provider=provider._responses_state_provider(),
@@ -448,7 +447,7 @@ async def test_codex_langfuse_records_rejected_compaction_as_error(monkeypatch,
),
)
assert response.content == "done" # falls back to the uncompacted request
assert response.content == "done"
assert len(generations) == 2
compaction_gen = generations[0]
assert compaction_gen.start_kwargs["name"] == "codex_compaction"
@@ -276,7 +276,6 @@ def test_worker_exit_and_credential_commit_are_distinct(monkeypatch, tmp_path, f
if finish == "cancel":
flow.cancel()
elif finish == "expiry":
# Advance the shared clock used by both the flow and its save guard.
now = time.monotonic() + 10
monkeypatch.setattr(codex_oauth, "time", SimpleNamespace(monotonic=lambda: now))
assert flow.has_pending_work
@@ -356,7 +356,6 @@ async def test_codex_request_marks_rejected_compaction_without_retaining_raw_bod
@pytest.mark.asyncio
async def test_codex_request_honors_stream_idle_timeout_env(monkeypatch) -> None:
"""NANOBOT_STREAM_IDLE_TIMEOUT_S overrides the default Codex stream timeout."""
monkeypatch.setenv("NANOBOT_STREAM_IDLE_TIMEOUT_S", "5")
original_client = httpx.AsyncClient
seen: dict[str, int] = {}
@@ -1,5 +1,3 @@
"""Exercise the Codex provider against local Responses WebSocket and SSE peers."""
from __future__ import annotations
import asyncio
@@ -287,7 +285,6 @@ async def test_gateway_prepares_image_batch_and_preserves_originals(codex_peer,
for path in paths:
image.save(path, "JPEG", quality=95)
originals = [path.read_bytes() for path in paths]
# Each image fits by itself; the combined base64 payload requires preparation.
original_sizes = [4 * ((len(raw) + 2) // 3) for raw in originals]
assert max(original_sizes) < 1_000_000 < sum(original_sizes)
small = tmp_path / "thumbnail.jpg"
@@ -1,11 +1,3 @@
"""Tests for OpenAICompatProvider spec-driven behavior.
Validates that:
- OpenRouter (no strip) keeps model names intact.
- AiHubMix strips provider prefixes declared by its spec.
- Standard providers pass model names through as-is.
"""
from __future__ import annotations
import asyncio
@@ -191,7 +183,6 @@ def _fake_chat_stream_legacy_function_call_chunks():
@pytest.mark.asyncio
async def test_openai_compat_chat_stream_forwards_reasoning_deltas_deepseek_style() -> None:
"""DeepSeek Chat Completions exposes ``delta.reasoning_content`` while streaming."""
mock_chat = AsyncMock(return_value=_fake_chat_stream_reasoning_chunks())
spec = find_by_name("deepseek")
thinking: list[str] = []
@@ -480,7 +471,6 @@ async def test_openrouter_user_headers_override_default_attribution() -> None:
@pytest.mark.asyncio
async def test_openrouter_keeps_model_name_intact() -> None:
"""OpenRouter gateway keeps the full model name (gateway does its own routing)."""
mock_create = AsyncMock(return_value=_fake_chat_response())
spec = find_by_name("openrouter")
@@ -505,7 +495,6 @@ async def test_openrouter_keeps_model_name_intact() -> None:
@pytest.mark.asyncio
async def test_aihubmix_strips_model_prefix() -> None:
"""AiHubMix strips provider prefixes declared by its spec."""
mock_create = AsyncMock(return_value=_fake_chat_response())
spec = find_by_name("aihubmix")
@@ -530,7 +519,6 @@ async def test_aihubmix_strips_model_prefix() -> None:
@pytest.mark.asyncio
async def test_standard_provider_passes_model_through() -> None:
"""Standard provider (e.g. deepseek) passes model name through as-is."""
mock_create = AsyncMock(return_value=_fake_chat_response())
spec = find_by_name("deepseek")
@@ -554,7 +542,6 @@ async def test_standard_provider_passes_model_through() -> None:
@pytest.mark.asyncio
async def test_openai_compat_preserves_extra_content_on_tool_calls() -> None:
"""Gemini extra_content (thought signatures) must survive parse→serialize round-trip."""
mock_create = AsyncMock(return_value=_fake_tool_call_response())
spec = find_by_name("gemini")
@@ -603,7 +590,6 @@ def test_openai_compat_parse_preserves_array_tool_arguments() -> None:
def test_openai_model_passthrough() -> None:
"""OpenAI models pass through unchanged."""
spec = find_by_name("openai")
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
provider = OpenAICompatProvider(
@@ -1361,10 +1347,6 @@ async def test_openai_compat_stream_watchdog_returns_error_on_stall(monkeypatch)
assert "stream stalled" in result.content
# ---------------------------------------------------------------------------
# Provider-specific thinking parameters (extra_body)
# ---------------------------------------------------------------------------
def _build_kwargs_for(provider_name: str, model: str, reasoning_effort=None):
spec = find_by_name(provider_name)
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
@@ -1402,21 +1384,18 @@ def test_dashscope_thinking_enabled_with_reasoning_effort() -> None:
def test_dashscope_thinking_disabled_for_minimal() -> None:
"""'minimal' → wire 'minimum' + thinking off on DashScope."""
kw = _build_kwargs_for("dashscope", "qwen3-plus", reasoning_effort="minimal")
assert kw["reasoning_effort"] == "minimum"
assert kw["extra_body"] == {"enable_thinking": False}
def test_dashscope_thinking_disabled_for_minimum_alias() -> None:
"""Native 'minimum' spelling must also disable thinking, not enable it."""
kw = _build_kwargs_for("dashscope", "qwen3-plus", reasoning_effort="minimum")
assert kw["reasoning_effort"] == "minimum"
assert kw["extra_body"] == {"enable_thinking": False}
def test_non_dashscope_minimal_not_retranslated() -> None:
"""DashScope-specific translation must not leak to other providers."""
kw = _build_kwargs_for("openai", "gpt-5", reasoning_effort="minimal")
assert kw["reasoning_effort"] == "minimal"
@@ -1505,7 +1484,6 @@ def test_byteplus_thinking_disabled_for_minimal() -> None:
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")
assert kw["extra_body"] == {"thinking": {"type": "enabled"}}
@@ -1522,7 +1500,6 @@ def test_deepseek_thinking_enabled() -> None:
def test_deepseek_reasoning_effort_controls(
effort: str | None, wire_effort: str | None, thinking_type: str | None,
) -> None:
"""DeepSeek's minimal alias enables low-effort thinking; none disables it."""
kw = _build_kwargs_for("deepseek", "deepseek-flash", reasoning_effort=effort)
if wire_effort is None:
assert "reasoning_effort" not in kw
@@ -1562,7 +1539,6 @@ def test_deepseek_backfills_reasoning_content_on_legacy_tool_call_messages() ->
def test_backfill_does_not_touch_messages_when_thinking_explicitly_off() -> None:
"""When thinking is explicitly disabled, legacy messages must NOT be altered."""
spec = find_by_name("deepseek")
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
p = OpenAICompatProvider(api_key="k", default_model="deepseek-v4-pro", spec=spec)
@@ -1585,7 +1561,6 @@ def test_backfill_does_not_touch_messages_when_thinking_explicitly_off() -> None
def test_deepseek_v4_backfills_incomplete_reasoning_history_when_effort_implicit() -> None:
"""DeepSeek-V4 reasons natively: backfill even without explicit reasoning_effort."""
spec = find_by_name("deepseek")
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
p = OpenAICompatProvider(api_key="k", default_model="deepseek-v4-pro", spec=spec)
@@ -1618,7 +1593,6 @@ def test_deepseek_v4_backfills_incomplete_reasoning_history_when_effort_implicit
def test_deepseek_flash_backfills_missing_tool_history_reasoning(
model: str, effort: str | None, history_reasoning: str | None,
) -> None:
"""Default thinking rejects tool-call history without reasoning_content."""
provider = OpenAICompatProvider(
api_key="k", default_model=model, spec=find_by_name("deepseek"),
)
@@ -1694,7 +1668,6 @@ def test_deepseek_chat_keeps_tool_history_when_effort_implicit() -> None:
def test_deepseek_coerces_list_content_to_string() -> None:
"""DeepSeek chat endpoint expects message.content to be a string."""
spec = find_by_name("deepseek")
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
p = OpenAICompatProvider(api_key="k", default_model="deepseek-chat", spec=spec)
@@ -1731,7 +1704,6 @@ def test_deepseek_coerces_list_content_to_string() -> None:
def test_deepseek_vision_preserves_multimodal_content(
model: str, prefixed: bool, with_text: bool, responses: bool,
) -> None:
"""DeepSeek vision models must preserve images on both API surfaces."""
if prefixed:
model = f"deepseek/{model}"
spec = find_by_name("deepseek")
@@ -1789,7 +1761,6 @@ def test_deepseek_pro_remains_text_only(responses: bool) -> None:
def test_non_deepseek_keeps_list_content() -> None:
"""Only DeepSeek should force string content; OpenAI-compatible providers keep blocks."""
spec = find_by_name("openai")
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
p = OpenAICompatProvider(api_key="k", default_model="gpt-4o", spec=spec)
@@ -1813,7 +1784,6 @@ def test_non_deepseek_keeps_list_content() -> None:
def test_openai_no_thinking_extra_body() -> None:
"""Non-thinking providers should never get extra_body for thinking."""
kw = _build_kwargs_for("openai", "gpt-4o", reasoning_effort="medium")
assert "extra_body" not in kw
@@ -1867,7 +1837,6 @@ def kimi_k3_model(request: pytest.FixtureRequest) -> str:
def test_kimi_k3_uses_native_defaults(kimi_k3_model: str) -> None:
"""K3 omits fixed sampling params and uses the non-deprecated token limit field."""
kw = _build_kwargs_for("moonshot", kimi_k3_model, reasoning_effort=None)
assert "temperature" not in kw
@@ -1879,7 +1848,6 @@ def test_kimi_k3_uses_native_defaults(kimi_k3_model: str) -> None:
@pytest.mark.parametrize("effort", ["low", "high", "max"])
def test_kimi_k3_preserves_supported_reasoning_effort(kimi_k3_model: str, effort: str) -> None:
"""K3 uses top-level reasoning_effort, never the K2.x thinking body."""
kw = _build_kwargs_for("moonshot", kimi_k3_model, reasoning_effort=effort)
assert kw["reasoning_effort"] == effort
@@ -1888,7 +1856,6 @@ def test_kimi_k3_preserves_supported_reasoning_effort(kimi_k3_model: str, effort
def test_kimi_k3_normalizes_legacy_enabled_reasoning_effort(kimi_k3_model: str) -> None:
"""Switching a K2.x preset to K3 must not send unsupported effort values."""
kw = _build_kwargs_for("moonshot", kimi_k3_model, reasoning_effort="medium")
assert kw["reasoning_effort"] == "max"
@@ -1897,7 +1864,6 @@ def test_kimi_k3_normalizes_legacy_enabled_reasoning_effort(kimi_k3_model: str)
@pytest.mark.parametrize("effort", ["none", "minimal"])
def test_kimi_k3_omits_disabled_reasoning_effort(kimi_k3_model: str, effort: str) -> None:
"""K3 cannot disable reasoning, so disabled effort falls back to its default."""
kw = _build_kwargs_for("moonshot", kimi_k3_model, reasoning_effort=effort)
assert "reasoning_effort" not in kw
@@ -1923,7 +1889,6 @@ def test_openrouter_kimi_thinking_mapping(model, effort) -> None:
"thinking": {"type": "enabled"},
"reasoning": {"effort": effort},
}
# Even via OR, reasoning_effort wire kwarg is dropped for kimi models
assert "reasoning_effort" not in kw
@@ -1935,7 +1900,6 @@ def test_kimi_k27_code_thinking_none_omits_disabled() -> None:
def test_kimi_k27_code_thinking_none_with_openrouter_prefix_omits_disabled() -> None:
"""OpenRouter-routed Kimi K2.7 Code should not request disabled thinking."""
kw = _build_kwargs_for("openrouter", "moonshotai/kimi-k2.7-code", reasoning_effort="none")
assert "extra_body" not in kw
assert "reasoning_effort" not in kw
@@ -1946,35 +1910,26 @@ def test_kimi_k27_code_thinking_none_with_openrouter_prefix_omits_disabled() ->
def test_moonshot_kimi_k25_k26_omit_temperature(
model: str, reasoning_effort: str | None,
) -> None:
"""Moonshot chooses the valid temperature from the K2.5/K2.6 thinking mode."""
kw = _build_kwargs_for("moonshot", model, reasoning_effort=reasoning_effort)
assert "temperature" not in kw
def test_moonshot_kimi_k27_code_temperature_override() -> None:
"""Moonshot registry should force temperature 1.0 for Kimi K2.7 Code."""
kw = _build_kwargs_for("moonshot", "kimi-k2.7-code", reasoning_effort=None)
assert kw["temperature"] == 1.0
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")
assert "extra_body" not in kw
def test_kimi_k2_thinking_series_no_thinking_injection() -> None:
"""kimi-k2-thinking series models must NOT receive extra_body.thinking."""
kw = _build_kwargs_for("moonshot", "kimi-k2-thinking", reasoning_effort="high")
assert "extra_body" not in kw
# ---------------------------------------------------------------------------
# reasoning_effort="none" — treated as thinking disabled
# ---------------------------------------------------------------------------
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")
assert kw.get("extra_body") == {"enable_thinking": False}
assert "reasoning_effort" not in kw
@@ -1996,7 +1951,6 @@ def test_qwen_thinking_disabled_via_model_level_mapping() -> None:
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")
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
p = OpenAICompatProvider(api_key="k", default_model="deepseek-v4-pro", spec=spec)
+2 -52
View File
@@ -1,5 +1,3 @@
"""Tests for the shared openai_responses converters and parsers."""
import json
from io import StringIO
from types import SimpleNamespace
@@ -62,10 +60,6 @@ async def test_sdk_tool_alias_survives_capture_and_next_request_replay():
assert items[0]["async"] is True
assert "async_" not in items[0]
# ======================================================================
# converters - split_tool_call_id
# ======================================================================
class TestSplitToolCallId:
def test_plain_id(self):
@@ -87,11 +81,6 @@ class TestSplitToolCallId:
assert split_tool_call_id(42) == ("call_0", None)
# ======================================================================
# converters - convert_user_message
# ======================================================================
class TestConvertUserMessage:
def test_string_content(self):
result = convert_user_message("hello")
@@ -131,7 +120,6 @@ class TestConvertUserMessage:
assert result["content"] == [{"type": "input_text", "text": ""}]
def test_meta_fields_not_leaked(self):
"""_meta on content blocks must never appear in converted output."""
result = convert_user_message([
{"type": "text", "text": "hi", "_meta": {"path": "/tmp/x"}},
])
@@ -142,11 +130,6 @@ class TestConvertUserMessage:
assert result["content"] == [{"type": "input_text", "text": ""}]
# ======================================================================
# converters - convert_messages
# ======================================================================
class TestConvertMessages:
def test_system_extracted_as_instructions(self):
msgs = [
@@ -275,7 +258,6 @@ class TestConvertMessages:
assert items[1]["call_id"] == "call_1"
def test_assistant_with_tool_calls_no_id(self):
"""Fallback call IDs still work when tool_call.id is missing."""
_, items = convert_messages([{
"role": "assistant",
"content": None,
@@ -360,7 +342,6 @@ class TestConvertMessages:
assert items[0]["output"] == json.dumps(content, ensure_ascii=False)
def test_non_standard_keys_not_leaked(self):
"""Extra keys on messages must not appear in converted items."""
_, items = convert_messages([{
"role": "user",
"content": "hi",
@@ -372,7 +353,6 @@ class TestConvertMessages:
assert "_meta" not in str(item)
def test_full_conversation_roundtrip(self):
"""System + user + assistant(tool_call) + tool -> correct structure."""
msgs = [
{"role": "system", "content": "Be concise."},
{"role": "user", "content": "Weather in SF?"},
@@ -387,17 +367,12 @@ class TestConvertMessages:
]
instructions, items = convert_messages(msgs)
assert instructions == "Be concise."
assert len(items) == 3 # user, function_call, function_call_output
assert len(items) == 3
assert items[0]["role"] == "user"
assert items[1]["type"] == "function_call"
assert items[2]["type"] == "function_call_output"
# ======================================================================
# converters - convert_tools
# ======================================================================
class TestConvertTools:
def test_standard_function_tool(self):
tools = [{"type": "function", "function": {
@@ -440,7 +415,6 @@ class TestConvertTools:
assert convert_tools(tools) == []
def test_tool_without_function_wrapper(self):
"""Direct dict without type=function wrapper."""
tools = [{"name": "f1", "description": "d", "parameters": {}}]
result = convert_tools(tools)
assert result[0]["name"] == "f1"
@@ -459,11 +433,6 @@ class TestConvertTools:
assert len(convert_tools(tools)) == 2
# ======================================================================
# parsing - map_finish_reason
# ======================================================================
class TestMapFinishReason:
def test_completed(self):
assert map_finish_reason("completed") == "stop"
@@ -495,11 +464,6 @@ class TestMapFinishReason:
assert is_replayable_finish_reason(finish_reason) is False
# ======================================================================
# parsing - parse_response_output
# ======================================================================
class TestParseResponseOutput:
def test_text_response(self):
resp = {
@@ -562,7 +526,6 @@ class TestParseResponseOutput:
assert result.provider_state is not None
def test_malformed_tool_arguments_logged(self):
"""Malformed JSON arguments should log a warning and remain non-object."""
resp = {
"output": [{
"type": "function_call",
@@ -669,7 +632,6 @@ class TestParseResponseOutput:
assert result.provider_state is None
def test_sdk_model_object(self):
"""parse_response_output should handle SDK objects with model_dump()."""
mock = MagicMock()
mock.model_dump.return_value = {
"output": [{"type": "message", "role": "assistant",
@@ -1040,19 +1002,13 @@ class TestResponsesConversationState:
assert instructions == "You are KITT."
assert replayed is True
reasoning_items = [item for item in items if item.get("type") == "reasoning"]
assert len(reasoning_items) == 2 # one replayed, one converted delta
assert len(reasoning_items) == 2
assert isinstance(reasoning_items[0]["content"], list)
# Stored replay items keep their original block type.
assert reasoning_items[0]["content"][0]["type"] == "output_text"
assert isinstance(reasoning_items[1]["content"], list)
assert reasoning_items[1]["content"][0]["type"] == "reasoning_text"
# ======================================================================
# parsing - consume_sse
# ======================================================================
class _SseResponse:
def __init__(self, events: list[dict]):
self._events = events
@@ -1670,11 +1626,6 @@ class TestConsumeSse:
assert type(tool_calls[0].arguments) is type(arguments)
# ======================================================================
# parsing - consume_sdk_stream
# ======================================================================
class TestConsumeSdkStream:
@pytest.mark.asyncio
@pytest.mark.parametrize("event_type", ["response.output_text.delta", "response.refusal.delta"])
@@ -2205,7 +2156,6 @@ class TestConsumeSdkStream:
@pytest.mark.asyncio
async def test_malformed_tool_args_logged(self):
"""Malformed JSON in streaming tool args should log a warning and remain non-object."""
item_added = MagicMock(type="function_call", call_id="c1", id="fc1", arguments="")
item_added.name = "f"
ev1 = MagicMock(type="response.output_item.added", item=item_added)
@@ -1,5 +1,3 @@
"""Tests for the OpenCode Zen and OpenCode Go provider registrations."""
import asyncio
import hashlib
import json
@@ -194,7 +192,6 @@ def test_opencode_affinity_matches_hostname(base, enabled):
@pytest.mark.parametrize("stream", [False, True])
@pytest.mark.parametrize("configured_header", [None, "x-opencode-session", "X-OpenCode-Session"])
async def test_opencode_wire_affinity(monkeypatch, api_type, stream, configured_header):
"""Exercise SDK header encoding/merging through the public provider entrypoints."""
from openai import AsyncOpenAI
from nanobot.providers import openai_compat_provider
@@ -1,5 +1,3 @@
"""Tests for the OrcaRouter provider registration."""
from unittest.mock import patch
from nanobot.config.schema import Config, ProvidersConfig
@@ -1,5 +1,3 @@
"""Provider credentials must not leak through process-global os.environ."""
from __future__ import annotations
import os
@@ -9,7 +7,6 @@ from nanobot.providers.registry import find_by_name
def test_provider_init_does_not_mutate_shared_env_keys(monkeypatch) -> None:
"""Multi-provider setups must not overwrite or pin each other's keys."""
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
monkeypatch.delenv("OPENROUTER_API_KEY", raising=False)
@@ -85,10 +85,10 @@ def test_anthropic_handle_error_marks_connection_kind() -> None:
@pytest.mark.parametrize("expected, kwargs", [
(True, {"error_status_code": 402}), # HTTP 402
(True, {"error_type": "insufficient_quota"}), # billing token
(True, {"content": "429 You exceeded your current quota"}), # text marker
(False, {"error_status_code": 429, "error_type": "rate_limit_exceeded"}), # plain rate limit
(True, {"error_status_code": 402}),
(True, {"error_type": "insufficient_quota"}),
(True, {"content": "429 You exceeded your current quota"}),
(False, {"error_status_code": 429, "error_type": "rate_limit_exceeded"}),
])
def test_is_arrearage_response(expected: bool, kwargs: dict) -> None:
response = LLMResponse(finish_reason="error", **{"content": "boom", **kwargs})
-18
View File
@@ -404,7 +404,6 @@ async def test_chat_stream_with_retry_retries_timeout_in_new_stream_segment(
@pytest.mark.asyncio
async def test_chat_with_retry_uses_provider_generation_defaults() -> None:
"""When callers omit generation params, provider.generation defaults are used."""
provider = ScriptedProvider([LLMResponse(content="ok")])
provider.generation = GenerationSettings(temperature=0.2, max_tokens=321, reasoning_effort="high")
@@ -417,7 +416,6 @@ async def test_chat_with_retry_uses_provider_generation_defaults() -> None:
@pytest.mark.asyncio
async def test_chat_with_retry_explicit_override_beats_defaults() -> None:
"""Explicit kwargs should override provider.generation defaults."""
provider = ScriptedProvider([LLMResponse(content="ok")])
provider.generation = GenerationSettings(temperature=0.2, max_tokens=321, reasoning_effort="high")
@@ -433,10 +431,6 @@ async def test_chat_with_retry_explicit_override_beats_defaults() -> None:
assert provider.last_kwargs["reasoning_effort"] == "low"
# ---------------------------------------------------------------------------
# Image fallback tests
@pytest.mark.asyncio
@pytest.mark.parametrize("error", [
LLMResponse(content="unauthorized", finish_reason="error", error_status_code=401),
@@ -465,8 +459,6 @@ async def test_account_failure_does_not_retry_without_images(error: LLMResponse)
assert LLMProvider.public_error_kind(response) in {"authentication", "billing"}
# ---------------------------------------------------------------------------
_IMAGE_MSG = [
{"role": "user", "content": [
{"type": "text", "text": "describe this"},
@@ -484,7 +476,6 @@ _IMAGE_MSG_NO_META = [
@pytest.mark.asyncio
async def test_non_transient_error_with_images_retries_without_images() -> None:
"""Any non-transient error retries once with images stripped when images are present."""
provider = ScriptedProvider([
LLMResponse(content="API调用参数有误,请检查文档", finish_reason="error"),
LLMResponse(content="ok, no image"),
@@ -504,7 +495,6 @@ async def test_non_transient_error_with_images_retries_without_images() -> None:
@pytest.mark.asyncio
async def test_successful_image_retry_mutates_original_messages_in_place() -> None:
"""Successful no-image retry should update the caller's message history."""
provider = ScriptedProvider([
LLMResponse(content="model does not support images", finish_reason="error"),
LLMResponse(content="ok, no image"),
@@ -603,7 +593,6 @@ async def test_image_retry_discards_provider_state_with_images(
@pytest.mark.asyncio
async def test_non_transient_error_without_images_no_retry() -> None:
"""Non-transient errors without image content are returned immediately."""
provider = ScriptedProvider([
LLMResponse(content="401 unauthorized", finish_reason="error"),
])
@@ -618,7 +607,6 @@ async def test_non_transient_error_without_images_no_retry() -> None:
@pytest.mark.asyncio
async def test_image_fallback_returns_error_on_second_failure() -> None:
"""If the image-stripped retry also fails, return that error."""
provider = ScriptedProvider([
LLMResponse(content="some model error", finish_reason="error"),
LLMResponse(content="still failing", finish_reason="error"),
@@ -633,7 +621,6 @@ async def test_image_fallback_returns_error_on_second_failure() -> None:
@pytest.mark.asyncio
async def test_image_fallback_without_meta_uses_default_placeholder() -> None:
"""When _meta is absent, fallback placeholder is non-descriptive."""
provider = ScriptedProvider([
LLMResponse(content="error", finish_reason="error"),
LLMResponse(content="ok"),
@@ -959,15 +946,12 @@ async def test_chat_with_retry_normalizes_explicit_none_max_tokens() -> None:
)
assert response.content == "ok"
# Generation settings default to 4096 / 0.7; explicit None should
# have been replaced before reaching chat().
assert provider.last_kwargs["max_tokens"] == 4096
assert provider.last_kwargs["temperature"] == 0.7
@pytest.mark.asyncio
async def test_chat_with_retry_retries_zhipu_1302_rate_limit(monkeypatch) -> None:
"""ZhiPu returns code 1302 with Chinese rate-limit text instead of HTTP 429."""
provider = ScriptedProvider([
LLMResponse(
content='Error: {\'code\': \'1302\', \'message\': \'您的账户已达到速率限制,请您控制请求频率\'}',
@@ -991,7 +975,6 @@ async def test_chat_with_retry_retries_zhipu_1302_rate_limit(monkeypatch) -> Non
@pytest.mark.asyncio
async def test_chat_with_retry_retries_zhipu_1302_with_429_status(monkeypatch) -> None:
"""ZhiPu 1302 error with HTTP 429 status should also retry."""
provider = ScriptedProvider([
LLMResponse(
content='Error: {\'code\': \'1302\', \'message\': \'您的账户已达到速率限制,请您控制请求频率\'}',
@@ -1017,7 +1000,6 @@ async def test_chat_with_retry_retries_zhipu_1302_with_429_status(monkeypatch) -
@pytest.mark.asyncio
async def test_chat_stream_with_retry_normalizes_explicit_none_max_tokens() -> None:
"""chat_stream_with_retry must apply the same None-guard as chat_with_retry."""
provider = ScriptedProvider([LLMResponse(content="ok")])
response = await provider.chat_stream_with_retry(
@@ -1,5 +1,3 @@
"""Shared tool-argument parsing policy tests."""
from nanobot.providers.base import (
parse_tool_arguments,
tool_arguments_json_for_replay,
-2
View File
@@ -1,5 +1,3 @@
"""Tests for lazy provider exports from nanobot.providers."""
from __future__ import annotations
import importlib
-5
View File
@@ -1,5 +1,3 @@
"""Tests for proxy environment variable handling in OpenAICompatProvider."""
from unittest.mock import MagicMock
import httpx
@@ -16,7 +14,6 @@ def _make_spec(is_local: bool = False) -> MagicMock:
class TestLocalEndpointProxyDisabled:
"""Local endpoints must bypass proxy to avoid routing LAN traffic through it."""
@pytest.mark.parametrize("api_base,is_local", [
("http://localhost:11434/v1", True),
@@ -37,7 +34,6 @@ class TestLocalEndpointProxyDisabled:
class TestCloudEndpointProxyEnabled:
"""Cloud endpoints must respect proxy env vars for corporate/VPN proxies."""
async def test_cloud_respects_trust_env(self):
spec = _make_spec(is_local=False)
@@ -48,7 +44,6 @@ class TestCloudEndpointProxyEnabled:
)
await provider._ensure_client()
client = provider._client._client
# trust_env should be True so httpx reads HTTP_PROXY etc.
assert client._trust_env is True
async def test_explicit_provider_proxy_overrides_env(self, monkeypatch):
-22
View File
@@ -1,9 +1,3 @@
"""Tests for reasoning_content extraction in OpenAICompatProvider.
Covers non-streaming (_parse) and streaming (_parse_chunks) paths for
providers that return a reasoning_content field (e.g. MiMo, DeepSeek-R1).
"""
from unittest.mock import patch
from openai.types.chat import ChatCompletion, ChatCompletionChunk
@@ -11,11 +5,8 @@ from openai.types.chat import ChatCompletion, ChatCompletionChunk
from nanobot.providers.openai_compat_provider import OpenAICompatProvider
from nanobot.utils.helpers import build_assistant_message
# ── _parse: non-streaming ─────────────────────────────────────────────────
def test_parse_dict_extracts_reasoning_content() -> None:
"""reasoning_content at message level is surfaced in LLMResponse."""
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
provider = OpenAICompatProvider()
@@ -37,7 +28,6 @@ def test_parse_dict_extracts_reasoning_content() -> None:
def test_parse_dict_reasoning_content_none_when_absent() -> None:
"""reasoning_content is None when the response doesn't include it."""
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
provider = OpenAICompatProvider()
@@ -80,7 +70,6 @@ def test_parse_dict_reasoning_content_empty_string_preserved() -> None:
def test_parse_sdk_reasoning_content_empty_string_preserved() -> None:
"""SDK response objects preserve reasoning_content=\"\"."""
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
provider = OpenAICompatProvider()
@@ -103,7 +92,6 @@ def test_parse_sdk_reasoning_content_empty_string_preserved() -> None:
def test_tool_call_history_preserves_empty_reasoning_content_after_sanitize() -> None:
"""Empty reasoning_content survives the tool-call history round trip."""
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
provider = OpenAICompatProvider()
@@ -137,11 +125,7 @@ def test_tool_call_history_preserves_empty_reasoning_content_after_sanitize() ->
assert sanitized[1]["reasoning_content"] == ""
# ── _parse_chunks: streaming dict branch ─────────────────────────────────
def test_parse_chunks_dict_accumulates_reasoning_content() -> None:
"""reasoning_content deltas in dict chunks are joined into one string."""
chunks = [
{
"choices": [{
@@ -170,7 +154,6 @@ def test_parse_chunks_dict_accumulates_reasoning_content() -> None:
def test_parse_chunks_dict_reasoning_content_none_when_absent() -> None:
"""reasoning_content is None when no chunk contains it."""
chunks = [
{"choices": [{"finish_reason": "stop", "delta": {"content": "hi"}}]},
]
@@ -181,9 +164,6 @@ def test_parse_chunks_dict_reasoning_content_none_when_absent() -> None:
assert result.reasoning_content is None
# ── _parse_chunks: streaming SDK objects ──────────────────────────────────
def _make_reasoning_chunk(
reasoning: str | None, content: str | None, finish: str | None,
) -> ChatCompletionChunk:
@@ -201,7 +181,6 @@ def _make_reasoning_chunk(
def test_parse_chunks_sdk_accumulates_reasoning_content() -> None:
"""reasoning_content on SDK delta objects is joined across chunks."""
chunks = [
_make_reasoning_chunk("Think… ", None, None),
_make_reasoning_chunk("Done.", None, None),
@@ -215,7 +194,6 @@ def test_parse_chunks_sdk_accumulates_reasoning_content() -> None:
def test_parse_chunks_sdk_reasoning_content_none_when_absent() -> None:
"""reasoning_content is None when SDK deltas carry no reasoning_content."""
chunks = [_make_reasoning_chunk(None, "hello", "stop")]
result = OpenAICompatProvider._parse_chunks(chunks)
@@ -1,5 +1,3 @@
"""Exercise Responses adapters through real SDK requests to a local endpoint."""
from __future__ import annotations
import json
@@ -1,5 +1,3 @@
"""Tests for Responses API circuit breaker in OpenAICompatProvider."""
import time
import pytest
@@ -156,7 +154,6 @@ def test_probe_after_interval(provider, monkeypatch):
provider._record_responses_failure("gpt-5", None)
assert provider._should_use_responses_api("gpt-5", None) is False
# Fast-forward past the probe interval
key = "gpt-5:"
provider._responses_tripped_at[key] = time.monotonic() - _RESPONSES_PROBE_INTERVAL_S - 1
assert provider._should_use_responses_api("gpt-5", None) is True
@@ -181,11 +178,6 @@ def test_reasoning_effort_key_is_case_insensitive(provider):
assert provider._should_use_responses_api("o3", "high") is False
# ======================================================================
# _should_fallback_from_responses_error
# ======================================================================
class _FakeAPIError(Exception):
def __init__(self, status_code, body):
super().__init__(str(body))
@@ -214,9 +206,7 @@ def test_legacy_compatibility_markers_still_trigger_fallback():
assert OpenAICompatProvider._should_fallback_from_responses_error(err) is True
# ======================================================================
# DeepSeek Responses wire shape (PR #5214 root cause)
# ======================================================================
def _deepseek_provider(provider):
@@ -316,9 +306,8 @@ def test_deepseek_replay_body_keeps_reasoning_content_as_array(provider):
)
reasoning_items = [item for item in body["input"] if item.get("type") == "reasoning"]
assert len(reasoning_items) == 2 # one replayed from state, one converted
assert len(reasoning_items) == 2
assert isinstance(reasoning_items[0]["content"], list)
# Stored replay items keep their original block type.
assert reasoning_items[0]["content"][0]["type"] == "output_text"
assert isinstance(reasoning_items[1]["content"], list)
assert reasoning_items[1]["content"][0]["type"] == "reasoning_text"
@@ -1,5 +1,3 @@
"""Responses terminal events must not depend on the transport reaching EOF."""
import asyncio
import json
from contextlib import asynccontextmanager
+5 -11
View File
@@ -27,19 +27,17 @@ from nanobot.utils.helpers import (
class TestSanitizeSurrogates:
def test_paired_surrogates_reconstructed_to_emoji(self):
# \uD83E\uDD16 is the UTF-16 surrogate pair for 🤖 (U+1F916).
raw = "hello \ud83e\udd16 world"
cleaned = sanitize_surrogates(raw)
assert cleaned == "hello 🤖 world"
cleaned.encode("utf-8") # must not raise
cleaned.encode("utf-8")
def test_lone_surrogate_replaced_with_fffd(self):
raw = "hello \ud83e world" # lone high surrogate
raw = "hello \ud83e world"
cleaned = sanitize_surrogates(raw)
assert "\ud83e" not in cleaned
# replacement char U+FFFD substitutes the unpaired surrogate
assert "\ufffd" in cleaned
cleaned.encode("utf-8") # must not raise
cleaned.encode("utf-8")
def test_normal_text_returned_unchanged_identity(self):
raw = "plain ascii + 中文 + 🤖"
@@ -54,7 +52,6 @@ class TestSanitizeSurrogatesDeep:
def test_clean_input_returns_same_object(self):
payload = {"role": "user", "content": [{"type": "text", "text": "hi 🤖"}]}
result = sanitize_surrogates_deep(payload)
# No allocation on clean input: same object identity.
assert result is payload
def test_lone_surrogate_in_nested_content_cleaned(self):
@@ -66,11 +63,10 @@ class TestSanitizeSurrogatesDeep:
],
}
cleaned = sanitize_surrogates_deep(dirty)
assert cleaned is not dirty # rebuilt
assert cleaned is not dirty
first = cleaned["content"][0]["text"]
assert "\ud83e" not in first
assert cleaned["content"][1]["text"] == "normal 🤖"
# Full payload must be UTF-8 encodable.
import json
json.dumps(cleaned, ensure_ascii=False).encode("utf-8")
@@ -87,7 +83,6 @@ class TestSanitizeSurrogatesDeep:
"\ud83e clean",
)
cleaned = sanitize_surrogates_deep(dirty)
# tuple preserved as tuple
assert isinstance(cleaned, tuple)
assert "\ud83e" not in cleaned[0]["k"]
assert cleaned[1][1] == "🤖"
@@ -108,7 +103,7 @@ class TestProviderSanitizeEmptyContent:
result = LLMProvider._sanitize_empty_content(messages)
text = result[0]["content"]
assert "\ud83e" not in text
text.encode("utf-8") # would raise pre-fix
text.encode("utf-8")
def test_lone_surrogate_in_content_block_scrubbed(self):
messages = [
@@ -156,7 +151,6 @@ class TestProviderSanitizeEmptyContent:
},
]
cleaned = LLMProvider._sanitize_empty_content(messages)
# This is the operation that previously raised UnicodeEncodeError.
json.dumps({"model": "x", "messages": cleaned}, ensure_ascii=False).encode("utf-8")
assert cleaned[0]["content"] == "You are a 🐱 assistant."
assert cleaned[1]["content"] == "🤖 fixed?"
-2
View File
@@ -1,5 +1,3 @@
"""Tests for the Skywork provider registration."""
from unittest.mock import patch
from nanobot.config.schema import Config, ProvidersConfig
+2 -43
View File
@@ -1,5 +1,3 @@
"""Tests for StepFun ASR SSE transcription provider."""
from __future__ import annotations
import asyncio
@@ -27,11 +25,6 @@ def audio_file(tmp_path: Path) -> Path:
return p
# ---------------------------------------------------------------------------
# Defaults and base normalization
# ---------------------------------------------------------------------------
def test_stepfun_defaults() -> None:
provider = StepFunTranscriptionProvider(api_key="sk-test")
assert provider.api_url == "https://api.stepfun.com/v1/audio/asr/sse"
@@ -59,11 +52,6 @@ def test_stepfun_custom_model() -> None:
assert provider.model == "stepaudio-2-asr-pro"
# ---------------------------------------------------------------------------
# Short-circuit: missing key / missing file
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_missing_api_key_short_circuits(audio_file: Path) -> None:
with patch.dict("os.environ", {}, clear=True):
@@ -83,14 +71,8 @@ async def test_missing_file_short_circuits(audio_file: Path) -> None:
stream_mock.assert_not_called()
# ---------------------------------------------------------------------------
# SSE stream parsing: happy path
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_sse_delta_then_done(audio_file: Path) -> None:
"""Simulates the real SSE event sequence: delta(s) -> text.done."""
events = [
{"type": "transcript.text.delta", "session_id": "s1", "text": "你"},
{"type": "transcript.text.delta", "session_id": "s1", "text": "你好"},
@@ -109,7 +91,6 @@ async def test_sse_delta_then_done(audio_file: Path) -> None:
@pytest.mark.asyncio
async def test_sse_only_done_event(audio_file: Path) -> None:
"""Single transcript.text.done event without deltas."""
events = [
{"type": "transcript.text.done", "session_id": "s1", "text": "hello world"},
]
@@ -126,7 +107,6 @@ async def test_sse_only_done_event(audio_file: Path) -> None:
@pytest.mark.asyncio
async def test_sse_error_event(audio_file: Path) -> None:
"""Error event in SSE stream returns "" immediately."""
events = [
{"type": "error", "session_id": "s1", "message": "audio too short"},
]
@@ -146,13 +126,12 @@ async def test_sse_error_event(audio_file: Path) -> None:
@pytest.mark.asyncio
async def test_sse_ignores_non_data_lines(audio_file: Path) -> None:
"""Empty lines and lines without 'data:' prefix are ignored."""
events = [
{"type": "transcript.text.done", "session_id": "s1", "text": "result"},
]
raw_lines = [
"", # empty line
"event: session.start", # non-data event
"",
"event: session.start",
f"data: {json.dumps(events[0])}",
]
@@ -167,7 +146,6 @@ async def test_sse_ignores_non_data_lines(audio_file: Path) -> None:
@pytest.mark.asyncio
async def test_sse_malformed_json_skipped(audio_file: Path) -> None:
"""Malformed JSON in data lines are skipped gracefully."""
events = [
{"type": "transcript.text.done", "session_id": "s1", "text": "ok"},
]
@@ -185,11 +163,6 @@ async def test_sse_malformed_json_skipped(audio_file: Path) -> None:
assert result == "ok"
# ---------------------------------------------------------------------------
# Retry contract
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
@pytest.mark.parametrize(
"scenario,expected",
@@ -252,7 +225,6 @@ async def test_sse_closes_each_attempt_before_backoff(monkeypatch, audio_file, s
@pytest.mark.asyncio
async def test_gives_up_after_max_retries(audio_file: Path) -> None:
"""Persistent 503 returns "" after all retries exhausted."""
stream_cm = _make_stream_cm(503, [])
provider = StepFunTranscriptionProvider(api_key="sk-test")
@@ -267,7 +239,6 @@ async def test_gives_up_after_max_retries(audio_file: Path) -> None:
@pytest.mark.asyncio
async def test_sse_empty_text_done_returns_empty(audio_file: Path) -> None:
"""Empty text in transcript.text.done should return "" immediately, not retry."""
events = [
{"type": "transcript.text.done", "session_id": "s1", "text": ""},
]
@@ -302,7 +273,6 @@ async def test_non_retryable_status_returns_empty(audio_file: Path, status: int)
@pytest.mark.asyncio
async def test_retries_on_connect_error(audio_file: Path) -> None:
"""Network-level transient errors are retried."""
success_lines = [
f"data: {json.dumps({'type': 'transcript.text.done', 'session_id': 's1', 'text': 'ok'})}",
]
@@ -336,7 +306,6 @@ async def test_unread_503_socket_closes_before_backoff(monkeypatch, audio_file,
bodies.append(json.loads(await reader.readexactly(int(headers[b"Content-Length"]))))
first = len(bodies) == 1
if first:
# The body never finishes: the retry must close it without reading EOF.
writer.write(b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 1000000\r\n\r\nunread")
else:
payload = b'data: {"type":"transcript.text.done","text":"socket-ok"}\n\n'
@@ -395,11 +364,6 @@ async def test_unread_503_socket_closes_before_backoff(monkeypatch, audio_file,
await asyncio.wait_for(asyncio.gather(*pending, return_exceptions=True), timeout=5)
# ---------------------------------------------------------------------------
# Registry integration
# ---------------------------------------------------------------------------
def test_stepfun_in_registry() -> None:
assert "stepfun" in transcription_provider_names()
spec = get_transcription_provider("stepfun")
@@ -428,11 +392,6 @@ def test_config_resolves_stepfun() -> None:
assert resolved.configured is True
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _make_stream_cm(status: int, lines: list[str]) -> MagicMock:
"""Build a mock for `AsyncClient.stream` that yields *lines* as SSE."""
-34
View File
@@ -24,11 +24,7 @@ _STEPFUN_SPEC = ProviderSpec(
)
# ── _parse: dict branch ─────────────────────────────────────────────────────
def test_parse_dict_stepfun_reasoning_fallback() -> None:
"""When content is None and reasoning exists, content falls back to reasoning."""
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
provider = OpenAICompatProvider(spec=_STEPFUN_SPEC)
@@ -45,12 +41,10 @@ def test_parse_dict_stepfun_reasoning_fallback() -> None:
result = provider._parse(response)
assert result.content == "Let me think... The answer is 42."
# reasoning_content should also be populated from reasoning
assert result.reasoning_content == "Let me think... The answer is 42."
def test_parse_dict_stepfun_reasoning_priority() -> None:
"""reasoning_content field takes priority over reasoning when both present."""
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
provider = OpenAICompatProvider(spec=_STEPFUN_SPEC)
@@ -68,13 +62,9 @@ def test_parse_dict_stepfun_reasoning_priority() -> None:
result = provider._parse(response)
assert result.content == "informal thinking"
# reasoning_content uses the dedicated field, not reasoning
assert result.reasoning_content == "formal reasoning content"
# ── _parse: SDK objects ────────────────────────────────────────────────────
def _make_sdk_response(content, reasoning=None, reasoning_content=None) -> ChatCompletion:
return ChatCompletion.model_validate({
"id": "chatcmpl-stepfun",
@@ -95,7 +85,6 @@ def _make_sdk_response(content, reasoning=None, reasoning_content=None) -> ChatC
def test_parse_sdk_stepfun_reasoning_fallback() -> None:
"""SDK branch: content falls back to msg.reasoning when content is None."""
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
provider = OpenAICompatProvider(spec=_STEPFUN_SPEC)
@@ -108,7 +97,6 @@ def test_parse_sdk_stepfun_reasoning_fallback() -> None:
def test_parse_sdk_stepfun_reasoning_priority() -> None:
"""reasoning_content field takes priority over reasoning in SDK branch."""
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
provider = OpenAICompatProvider(spec=_STEPFUN_SPEC)
@@ -124,11 +112,7 @@ def test_parse_sdk_stepfun_reasoning_priority() -> None:
assert result.reasoning_content == "formal reasoning"
# ── _parse_chunks: streaming dict branch ────────────────────────────────────
def test_parse_chunks_dict_stepfun_reasoning_fallback() -> None:
"""Streaming dict: reasoning field used when reasoning_content is absent."""
chunks = [
{
"choices": [{
@@ -156,11 +140,7 @@ def test_parse_chunks_dict_stepfun_reasoning_fallback() -> None:
assert result.reasoning_content == "Thinking step 1... step 2."
# ── Regression: normal models unaffected ────────────────────────────────────
def test_parse_dict_normal_model_with_reasoning_content_unaffected() -> None:
"""Models that use reasoning_content (e.g. DeepSeek-R1) are not affected."""
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
provider = OpenAICompatProvider()
@@ -181,7 +161,6 @@ def test_parse_dict_normal_model_with_reasoning_content_unaffected() -> None:
def test_parse_dict_standard_model_no_reasoning_unaffected() -> None:
"""Standard models (no reasoning fields at all) work exactly as before."""
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
provider = OpenAICompatProvider()
@@ -199,7 +178,6 @@ def test_parse_dict_standard_model_no_reasoning_unaffected() -> None:
def test_parse_chunks_dict_reasoning_precedence() -> None:
"""reasoning_content takes precedence over reasoning in dict chunks."""
chunks = [
{
"choices": [{
@@ -224,9 +202,6 @@ def test_parse_chunks_dict_reasoning_precedence() -> None:
assert result.reasoning_content == "formal: "
# ── _parse_chunks: streaming SDK objects ───────────────────────────────────
def _make_sdk_chunk(
reasoning_content=None, reasoning=None, content=None, finish=None,
) -> ChatCompletionChunk:
@@ -248,7 +223,6 @@ def _make_sdk_chunk(
def test_parse_chunks_sdk_stepfun_reasoning_fallback() -> None:
"""SDK streaming: reasoning field used when reasoning_content is None."""
chunks = [
_make_sdk_chunk(reasoning="Thinking... ", content=None, finish=None),
_make_sdk_chunk(reasoning=None, content="answer", finish="stop"),
@@ -261,7 +235,6 @@ def test_parse_chunks_sdk_stepfun_reasoning_fallback() -> None:
def test_parse_chunks_sdk_reasoning_precedence() -> None:
"""reasoning_content takes precedence over reasoning in SDK chunks."""
chunks = [
_make_sdk_chunk(reasoning_content="formal: ", reasoning="informal: ", content=None),
_make_sdk_chunk(reasoning_content=None, reasoning=None, content="result", finish="stop"),
@@ -272,11 +245,7 @@ def test_parse_chunks_sdk_reasoning_precedence() -> None:
assert result.reasoning_content == "formal: "
# ── Regression: non-StepFun providers must NOT promote reasoning to content ─
def test_parse_dict_non_stepfun_no_reasoning_as_content() -> None:
"""Providers without reasoning_as_content flag must not treat reasoning as content."""
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
provider = OpenAICompatProvider()
@@ -292,14 +261,11 @@ def test_parse_dict_non_stepfun_no_reasoning_as_content() -> None:
result = provider._parse(response)
# content stays None — reasoning is NOT promoted
assert result.content is None
# reasoning still goes to reasoning_content for display as thinking
assert result.reasoning_content == "internal thought process that should NOT be shown to user"
def test_parse_sdk_non_stepfun_no_reasoning_as_content() -> None:
"""SDK branch: providers without flag must not treat reasoning as content."""
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI"):
provider = OpenAICompatProvider()
@@ -8,13 +8,8 @@ from __future__ import annotations
from nanobot.providers.base import LLMProvider
# ---------------------------------------------------------------------------
# _strip_image_content (returns new list)
# ---------------------------------------------------------------------------
class TestStripImageContent:
"""Tests for the non-mutating _strip_image_content method."""
def test_replaces_image_url_with_nondescriptive_placeholder(self):
messages = [
@@ -37,10 +32,8 @@ class TestStripImageContent:
assert content[0] == {"type": "text", "text": "What is this?"}
assert content[1]["type"] == "text"
placeholder = content[1]["text"]
# Must NOT leak the file path
assert "/tmp/screenshot.png" not in placeholder
assert "screenshot" not in placeholder
# Must clearly indicate the image was not delivered
assert "not delivered" in placeholder.lower()
def test_returns_none_when_no_images(self):
@@ -71,7 +64,6 @@ class TestStripImageContent:
result = LLMProvider._strip_image_content(messages)
assert result is not None
content = result[0]["content"]
# text + 2 placeholders
assert len(content) == 3
for block in content[1:]:
assert block["type"] == "text"
@@ -113,20 +105,12 @@ class TestStripImageContent:
]
result = LLMProvider._strip_image_content(messages)
assert result is not None
# system and assistant messages unchanged
assert result[0]["content"] == "You are helpful."
assert result[2]["content"] == "Hi there!"
# user message has image replaced
assert result[1]["content"][0]["type"] == "text"
# ---------------------------------------------------------------------------
# _strip_image_content_inplace (mutates in place)
# ---------------------------------------------------------------------------
class TestStripImageContentInplace:
"""Tests for the mutating _strip_image_content_inplace method."""
def test_replaces_image_url_with_nondescriptive_placeholder(self):
messages = [
@@ -167,6 +151,5 @@ class TestStripImageContentInplace:
]
messages = [{"role": "user", "content": original_content}]
LLMProvider._strip_image_content_inplace(messages)
# The original list was mutated
assert original_content[1]["type"] == "text"
assert "/img.png" not in original_content[1]["text"]
+4 -63
View File
@@ -1,5 +1,3 @@
"""Tests for transcription retry behavior on transient errors (B10)."""
from __future__ import annotations
import asyncio
@@ -160,9 +158,6 @@ def test_resolver_supports_siliconflow_transcription_api_key_env() -> None:
def test_resolver_interpolates_env_ref_in_api_key() -> None:
# load_config() does not interpolate ${VAR}; the transcription path receives
# the raw config, so an env reference in the key must be resolved here rather
# than sent verbatim to the provider (which yields a 401).
config = Config()
config.transcription.provider = "groq"
config.providers.groq.api_key = "${MY_GROQ_KEY}"
@@ -181,8 +176,6 @@ def test_resolver_env_ref_missing_var_degrades_to_not_configured() -> None:
with patch.dict(os.environ, {}, clear=True):
resolved = resolve_transcription_config(config)
# Unresolved reference degrades to a falsy key rather than the literal
# "${...}" string, so the config reports itself as not configured.
assert resolved.api_key == ""
assert resolved.configured is False
@@ -415,11 +408,6 @@ def test_resolver_keeps_enabled_and_limits_on_effective_config() -> None:
assert resolved.max_upload_mb == 12
# ---------------------------------------------------------------------------
# OpenAI provider — retry on transient HTTP + network errors
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
@pytest.mark.parametrize("outcome", [_response(401), _response(501), httpx.LocalProtocolError("bad")])
async def test_openai_does_not_retry_terminal_errors(audio_file: Path, outcome) -> None:
@@ -442,16 +430,10 @@ async def test_openai_gives_up_after_max_attempts(audio_file: Path, outcome) ->
with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", sleep):
result = await provider.transcribe(audio_file)
assert result == ""
# 4 attempts total (initial + 3 retries) with 3 sleeps between them.
assert post.await_count == 4
assert [call.args[0] for call in sleep.await_args_list] == [1.0, 2.0, 4.0]
# ---------------------------------------------------------------------------
# Groq provider — same semantics (both go through the shared helper)
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_groq_retries_on_5xx_then_succeeds(audio_file: Path) -> None:
provider = GroqTranscriptionProvider(api_key="gsk-test")
@@ -472,14 +454,8 @@ async def test_groq_does_not_retry_on_auth_error(audio_file: Path) -> None:
assert post.await_count == 1
# ---------------------------------------------------------------------------
# Regression: missing file / missing key must still short-circuit
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_openai_missing_api_key_short_circuits(audio_file: Path) -> None:
"""Missing API key short-circuits before any HTTP call, even when the file exists."""
with patch.dict("os.environ", {}, clear=True):
provider = OpenAITranscriptionProvider(api_key=None)
post = AsyncMock()
@@ -499,7 +475,6 @@ async def test_openai_missing_file_short_circuits() -> None:
@pytest.mark.asyncio
async def test_returns_empty_when_file_unreadable(audio_file: Path) -> None:
"""Existing file that cannot be read (PermissionError/OSError): "" with no HTTP attempt."""
provider = OpenAITranscriptionProvider(api_key="sk-test")
post = AsyncMock()
with patch("pathlib.Path.read_bytes", side_effect=PermissionError("denied")), patch(
@@ -510,11 +485,6 @@ async def test_returns_empty_when_file_unreadable(audio_file: Path) -> None:
assert post.await_count == 0
# ---------------------------------------------------------------------------
# language: forwarded through the helper to the multipart body, on every attempt
# ---------------------------------------------------------------------------
@pytest.mark.parametrize(
"provider_cls,language",
[(OpenAITranscriptionProvider, "en"), (GroqTranscriptionProvider, "ko")],
@@ -524,7 +494,6 @@ async def test_returns_empty_when_file_unreadable(audio_file: Path) -> None:
async def test_provider_forwards_language_in_multipart(
audio_file: Path, provider_cls: type, language: str
) -> None:
"""When ``language`` is set, the helper sends it as a multipart field."""
provider = provider_cls(api_key="k", language=language)
post = AsyncMock(return_value=_response(200, {"text": "ok"}))
with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", AsyncMock()):
@@ -544,7 +513,6 @@ async def test_provider_forwards_language_in_multipart(
async def test_provider_omits_language_when_unset(
audio_file: Path, provider_cls: type
) -> None:
"""When ``language`` is None, no ``language`` field is sent."""
provider = provider_cls(api_key="k")
post = AsyncMock(return_value=_response(200, {"text": "ok"}))
with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", AsyncMock()):
@@ -611,14 +579,8 @@ async def test_json_retry_shares_budget_and_rebuilds_cached_audio(audio_file: Pa
assert call.kwargs["timeout"] == 60.0
# ---------------------------------------------------------------------------
# Malformed / unexpected response bodies must short-circuit, not escape
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_returns_empty_on_malformed_json_body(audio_file: Path) -> None:
"""200 with invalid JSON: log and return "" immediately (no retry, no exception)."""
provider = OpenAITranscriptionProvider(api_key="sk-test")
post = AsyncMock(return_value=_raw_response(200, b"<html>not json</html>"))
with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", AsyncMock()):
@@ -629,7 +591,6 @@ async def test_returns_empty_on_malformed_json_body(audio_file: Path) -> None:
@pytest.mark.asyncio
async def test_returns_empty_on_non_dict_json_body(audio_file: Path) -> None:
"""200 with a JSON array (not dict): no AttributeError leak; return "" immediately."""
provider = OpenAITranscriptionProvider(api_key="sk-test")
post = AsyncMock(return_value=_raw_response(200, b"[]"))
with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", AsyncMock()):
@@ -638,16 +599,6 @@ async def test_returns_empty_on_non_dict_json_body(audio_file: Path) -> None:
assert post.await_count == 1
# ---------------------------------------------------------------------------
# Pin the full advertised retry contract: all retryable statuses + exceptions
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Configurable model: forwarded to the multipart "model" field on all providers
# ---------------------------------------------------------------------------
@pytest.mark.parametrize(
"provider_cls,default_model",
[(OpenAITranscriptionProvider, "whisper-1"), (GroqTranscriptionProvider, "whisper-large-v3")],
@@ -672,17 +623,12 @@ async def test_multipart_provider_sends_configured_model(audio_file: Path, provi
assert post.await_args_list[0].kwargs["files"]["model"] == (None, "my-stt-model")
# ---------------------------------------------------------------------------
# OpenRouter provider — JSON body with base64 audio + configurable STT model
# ---------------------------------------------------------------------------
def test_audio_format_maps_known_extensions() -> None:
assert _audio_format(Path("v.oga")) == "ogg" # Telegram voice notes
assert _audio_format(Path("v.oga")) == "ogg"
assert _audio_format(Path("v.opus")) == "ogg"
assert _audio_format(Path("v.mp4")) == "m4a"
assert _audio_format(Path("v.mp3")) == "mp3"
assert _audio_format(Path("v.wav")) == "wav" # passthrough for unknown
assert _audio_format(Path("v.wav")) == "wav"
def test_openrouter_defaults_and_chat_base_normalization() -> None:
@@ -690,14 +636,12 @@ def test_openrouter_defaults_and_chat_base_normalization() -> None:
assert default.api_url == "https://openrouter.ai/api/v1/audio/transcriptions"
assert default.model == "openai/whisper-1"
# A chat-style base (what users copy from provider config) gets the path appended.
chat_base = OpenRouterTranscriptionProvider(api_key="k", api_base="https://openrouter.ai/api/v1")
assert chat_base.api_url == "https://openrouter.ai/api/v1/audio/transcriptions"
@pytest.mark.asyncio
async def test_openrouter_sends_json_base64_body(audio_file: Path) -> None:
"""OpenRouter gets a JSON body with base64 audio + format — never multipart."""
provider = OpenRouterTranscriptionProvider(
api_key="k", model="nvidia/parakeet-tdt-0.6b-v3", language="en"
)
@@ -705,11 +649,11 @@ async def test_openrouter_sends_json_base64_body(audio_file: Path) -> None:
with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", AsyncMock()):
assert await provider.transcribe(audio_file) == "hi"
call = post.await_args_list[0].kwargs
assert "files" not in call # not multipart
assert "files" not in call
body = call["json"]
assert body["model"] == "nvidia/parakeet-tdt-0.6b-v3"
assert body["language"] == "en"
assert body["input_audio"]["format"] == "ogg" # .ogg fixture
assert body["input_audio"]["format"] == "ogg"
assert base64.b64decode(body["input_audio"]["data"]) == audio_file.read_bytes()
@@ -1024,9 +968,7 @@ async def test_transcription_cancellation_releases_client(monkeypatch, audio_fil
await client.aclose()
# ---------------------------------------------------------------------------
# apiBase normalization (#3637): a chat-style base must not be POSTed verbatim
# ---------------------------------------------------------------------------
def test_resolve_transcription_url_falls_back_to_default() -> None:
@@ -1040,7 +982,6 @@ def test_resolve_transcription_url_appends_path_to_chat_style_base() -> None:
_resolve_transcription_url("https://api.groq.com/openai/v1", "https://x/audio/transcriptions")
== "https://api.groq.com/openai/v1/audio/transcriptions"
)
# Trailing slash must not produce a doubled separator.
assert (
_resolve_transcription_url("https://api.groq.com/openai/v1/", "https://x/audio/transcriptions")
== "https://api.groq.com/openai/v1/audio/transcriptions"
@@ -60,19 +60,12 @@ def _simple_messages() -> list[dict[str, Any]]:
return [{"role": "user", "content": "hello"}]
# ---------------------------------------------------------------------------
# Registry
# ---------------------------------------------------------------------------
def test_xiaomi_mimo_config_field_exists():
"""ProvidersConfig should expose a xiaomi_mimo field."""
config = ProvidersConfig()
assert hasattr(config, "xiaomi_mimo")
def test_xiaomi_mimo_uses_thinking_type_style():
"""MiMo hosted API uses {"thinking": {"type": ...}}, the thinking_type style."""
spec = _mimo_spec()
assert spec.thinking_style == "thinking_type"
assert spec.backend == "openai_compat"
@@ -80,33 +73,23 @@ def test_xiaomi_mimo_uses_thinking_type_style():
def test_openrouter_declares_gateway_reasoning_style():
"""OpenRouter uses its own reasoning.effort field for routed thinking models."""
spec = _openrouter_spec()
assert spec.thinking_style == ""
assert spec.gateway_reasoning_style == "reasoning_effort"
# ---------------------------------------------------------------------------
# _build_kwargs wire-format
# ---------------------------------------------------------------------------
def test_mimo_reasoning_effort_none_disables_thinking():
"""reasoning_effort="none" should send thinking.type="disabled"."""
provider = _mimo_provider()
kwargs = provider._build_kwargs(
messages=_simple_messages(),
tools=None, model=None, max_tokens=100,
temperature=0.7, reasoning_effort="none", tool_choice=None,
)
# reasoning_effort itself must NOT be sent when value is "none"
assert "reasoning_effort" not in kwargs
# The disable signal must be in extra_body
assert kwargs["extra_body"] == {"thinking": {"type": "disabled"}}
def test_mimo_reasoning_effort_medium_enables_thinking():
"""reasoning_effort="medium" should send thinking.type="enabled"."""
provider = _mimo_provider()
kwargs = provider._build_kwargs(
messages=_simple_messages(),
@@ -118,7 +101,6 @@ def test_mimo_reasoning_effort_medium_enables_thinking():
def test_mimo_reasoning_effort_low_enables_thinking():
"""Any non-none/minimal effort enables thinking."""
provider = _mimo_provider()
kwargs = provider._build_kwargs(
messages=_simple_messages(),
@@ -145,11 +127,6 @@ def test_mimo_reasoning_effort_unset_preserves_provider_default():
assert "extra_body" not in kwargs
# ---------------------------------------------------------------------------
# Gateway path: MiMo routed through OpenRouter (no spec.thinking_style)
# ---------------------------------------------------------------------------
def test_mimo_via_openrouter_reasoning_effort_none_disables_thinking():
"""OpenRouter routes MiMo as "xiaomi/mimo-v2.5-pro" and does NOT forward
extra_body.thinking to upstream, so a disable signal must also reach OR