CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.
Python agent-frameworkagent-harnessagent-runtimeagentic-aiai-agentsai-frameworkanthropicharnessharness-engineeringharness-frameworklanggraphlanggraph-alternativellmmcpopenaipi-agentpi-agent-corepythonpython-agent
test(coverage): exercise defensive error paths in capability + catalog + anthropic
xf gong4a1bade7c92d
diff --git a/tests/providers/test_anthropic_capability.py b/tests/providers/test_anthropic_capability.pyindex ed3792b..49966ea 100644--- a/tests/providers/test_anthropic_capability.py+++ b/tests/providers/test_anthropic_capability.py@@ -272,3 +272,78 @@ async def test_capability_honors_opts_thinking_budgets_override():assert payload["thinking"]["budget_tokens"] == 12288# max_tokens must accommodate the new budget.assert payload["max_tokens"] >= 12288 + 512 # min_output_tokens floor+++async def test_capability_disables_thinking_when_budget_reduced_to_zero() -> None:+ """When max_tokens floor is below min_output_tokens (1024), the clamp reduces+ budget to 0 and the provider must fall back to thinking.type=disabled."""+ custom = CapabilityDescriptor(+ reasoning_on_payload={"thinking": {"type": "enabled"}},+ reasoning_level=ReasoningLevelSpec(+ path="thinking.budget_tokens",+ kind="int_budget",+ level_budgets={"high": 16384},+ ),+ )+ p = AnthropicProvider(api_key="x", capability=custom)+ # context_window=512 leaves no room for any budget at all.+ m = Model(+ id="claude-tiny-test",+ provider="anthropic",+ context_window=512,+ max_tokens=512,+ reasoning=True,+ temperature=1.0,+ )+ captured: dict[str, Any] = {}++ async def listener(kw: dict[str, Any], model: Model) -> None:+ captured.update(kw)++ p._request_listeners.append(listener)++ class _FakeStream:+ response = None++ async def __aenter__(self) -> "_FakeStream":+ return self++ async def __aexit__(self, *a: Any) -> bool:+ return False++ def __aiter__(self) -> Any:+ async def gen() -> Any:+ return+ yield # pragma: no cover - generator marker++ return gen()++ async def get_final_message(self) -> Any:+ from anthropic.types import Message++ return Message.model_construct(+ id="m_test",+ model="claude-tiny-test",+ role="assistant",+ content=[],+ stop_reason="end_turn",+ stop_sequence=None,+ type="message",+ usage={"input_tokens": 1, "output_tokens": 1},+ )++ def fake_stream(**kw: Any) -> _FakeStream:+ return _FakeStream()++ p._client.messages.stream = fake_stream # type: ignore[attr-defined]++ s = await p.stream(+ model=m,+ messages=[UserMessage(content=[TextContent(text="hi")])],+ options=StreamOptions(thinking="high"),+ )+ async for _ in s:+ pass+ await s.result()+ assert captured["thinking"] == {"type": "disabled"}diff --git a/tests/test_capability.py b/tests/test_capability.pyindex c8e57cf..d5dfa2d 100644--- a/tests/test_capability.py+++ b/tests/test_capability.py@@ -2,6 +2,7 @@ from cubepi.providers.capability import (CapabilityDescriptor,ReasoningLevelSpec,TemperatureSpec,+ _resolve_level_value,apply_temperature,merge_capability_payload,write_reasoning_level,@@ -271,3 +272,58 @@ def test_reasoning_level_path_must_be_non_empty():kind="int_budget",level_budgets={"low": 4000},)+++def test_apply_temperature_fixed_raises_on_bypassed_validator():+ """Defensive guard: if validator is bypassed and fixed_value is None, raise."""+ import pytest++ # model_construct bypasses validation.+ spec = TemperatureSpec.model_construct(mode="fixed", fixed_value=None)+ with pytest.raises(RuntimeError, match="validator was bypassed"):+ apply_temperature({}, spec)+++def test_resolve_level_int_budget_raises_on_bypassed_validator():+ import pytest++ spec = ReasoningLevelSpec.model_construct(+ path="thinking.budget_tokens",+ kind="int_budget",+ level_budgets=None,+ )+ with pytest.raises(RuntimeError, match="validator was bypassed"):+ _resolve_level_value(spec, "medium")+++def test_resolve_level_effort_raises_on_bypassed_validator():+ import pytest++ spec = ReasoningLevelSpec.model_construct(+ path="reasoning_effort",+ kind="effort",+ level_to_effort=None,+ )+ with pytest.raises(RuntimeError, match="validator was bypassed"):+ _resolve_level_value(spec, "medium")+++def test_resolve_level_enum_raises_on_bypassed_validator():+ import pytest++ spec = ReasoningLevelSpec.model_construct(+ path="extra_body.thinking.type",+ kind="enum",+ level_to_enum=None,+ )+ with pytest.raises(RuntimeError, match="validator was bypassed"):+ _resolve_level_value(spec, "medium")+++def test_resolve_level_unknown_kind_returns_none():+ """Defensive fall-through: a bogus kind (model_construct bypass) returns None."""+ spec = ReasoningLevelSpec.model_construct(+ path="whatever",+ kind="something-bogus", # not a valid Literal value+ )+ assert _resolve_level_value(spec, "medium") is Nonediff --git a/tests/test_catalog.py b/tests/test_catalog.pyindex c8a5195..48109e3 100644--- a/tests/test_catalog.py+++ b/tests/test_catalog.py@@ -1,5 +1,6 @@import pytest+import cubepi.providers.catalog as catalog_modulefrom cubepi.providers.catalog import get_provider_preset, list_provider_presetsfrom cubepi.providers.catalog.types import (AuthSpec,@@ -69,7 +70,7 @@ def test_list_provider_presets_returns_all_entries():def test_every_preset_parses_into_typed_model():presets = list_provider_presets()- assert len(presets) == 20+ assert len(presets) == 22valid_apis = WireApi.__args__for p in presets:assert p.api in valid_apis, p.slug@@ -96,3 +97,73 @@ def test_openrouter_has_model_capability_overrides():over = p.model_capability_overrides["deepseek/deepseek-r1"]assert over.reasoning_level is not Noneassert over.reasoning_level.kind == "effort"+++def test_load_raises_when_yaml_is_not_a_list(tmp_path, monkeypatch):+ """Defensive: if providers.yaml is a dict at top level instead of list, raise."""+ bad = tmp_path / "providers.yaml"+ bad.write_text("not-a-list: just-a-string\n", encoding="utf-8")+ monkeypatch.setattr(catalog_module, "_DATA_FILE", bad)+ catalog_module._load.cache_clear()++ with pytest.raises(ValueError, match="top-level list"):+ catalog_module._load()++ catalog_module._load.cache_clear() # restore for other tests+++def test_load_wraps_per_entry_validation_error(tmp_path, monkeypatch):+ """Per-entry pydantic failures are re-raised with the entry index."""+ bad = tmp_path / "providers.yaml"+ # entry #0 has a required field missing (no `api`, no `base_url`, etc.)+ bad.write_text(+ "- slug: broken\n"+ " display_name: Broken\n"+ " short_name: B\n"+ " category: custom\n"+ " description: missing api/base_url/auth/capability\n",+ encoding="utf-8",+ )+ monkeypatch.setattr(catalog_module, "_DATA_FILE", bad)+ catalog_module._load.cache_clear()++ with pytest.raises(ValueError, match=r"providers\.yaml entry #0"):+ catalog_module._load()++ catalog_module._load.cache_clear()+++def test_load_rejects_duplicate_slug(tmp_path, monkeypatch):+ """Two presets sharing the same slug fail the loader."""+ # Two minimal-valid entries with the same slug.+ bad = tmp_path / "providers.yaml"+ bad.write_text(+ "- slug: dup\n"+ " display_name: D1\n"+ " short_name: D\n"+ " category: custom\n"+ " description: first\n"+ " api: openai-completions\n"+ ' base_url: ""\n'+ " auth: { mode: api_key }\n"+ " capability: {}\n"+ " default_models: []\n"+ "- slug: dup\n"+ " display_name: D2\n"+ " short_name: D\n"+ " category: custom\n"+ " description: second\n"+ " api: openai-completions\n"+ ' base_url: ""\n'+ " auth: { mode: api_key }\n"+ " capability: {}\n"+ " default_models: []\n",+ encoding="utf-8",+ )+ monkeypatch.setattr(catalog_module, "_DATA_FILE", bad)+ catalog_module._load.cache_clear()++ with pytest.raises(ValueError, match="duplicate slug"):+ catalog_module._load()++ catalog_module._load.cache_clear()