ci: reduce test runtime while preserving coverage (#6101)

* ci: reduce test runtime while preserving coverage

* test: close cached usage stores before temporary directory cleanup
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-08 13:03:56 +08:00
1 parent 6646f5fbee
commit 29f27dcf5d
5 files changed
+83 -12

No files matched your search

+2
View File
@@ -138,6 +138,8 @@ jobs:
if: needs.changes.outputs.python_required == 'true' if: needs.changes.outputs.python_required == 'true'
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
timeout-minutes: 20 timeout-minutes: 20
env:
PYTEST_ADDOPTS: "-o tmp_path_retention_policy=failed"
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
+27 -5
View File
@@ -8,6 +8,7 @@ import sys
from collections.abc import Iterator from collections.abc import Iterator
from pathlib import Path from pathlib import Path
from threading import Thread from threading import Thread
from uuid import uuid4
import certifi import certifi
import pytest import pytest
@@ -38,8 +39,9 @@ def _isolate_sessions_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> I
Session storage lives under the active runtime data root (outside the workspace, Session storage lives under the active runtime data root (outside the workspace,
per ADR-0001), so without redirection tests would write into the real home. per ADR-0001), so without redirection tests would write into the real home.
""" """
runtime_root = tmp_path.parent / f"{tmp_path.name}-runtime-root" data_root = tmp_path.parent / "session-data" / uuid4().hex
legacy_root = tmp_path.parent / f"{tmp_path.name}-legacy-sessions-root" runtime_root = data_root / "runtime"
legacy_root = data_root / "legacy-sessions"
def runtime_subdir(name: str) -> Path: def runtime_subdir(name: str) -> Path:
path = runtime_root / name path = runtime_root / name
@@ -57,13 +59,33 @@ def _isolate_sessions_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> I
yield yield
@pytest.fixture(autouse=True)
def _isolate_llm_usage_stores(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> Iterator[None]:
from nanobot import llm_usage
stores: dict[Path, llm_usage.LLMUsageStore] = {}
monkeypatch.setattr(llm_usage, "_STORES", stores)
try:
yield
finally:
for store in stores.values():
store.close()
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def _isolate_star_prompt_store( def _isolate_star_prompt_store(
tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None: ) -> None:
"""Keep WebUI completion events out of the user's invitation state and lock.""" """Keep WebUI completion events out of the user's invitation state and lock."""
webui_dir = tmp_path_factory.mktemp("star-prompt-webui") webui_dir = tmp_path.parent / "star-prompt-webui" / uuid4().hex
monkeypatch.setattr("nanobot.webui.star_prompt.get_webui_dir", lambda: webui_dir)
def get_webui_dir() -> Path:
webui_dir.mkdir(parents=True, exist_ok=True)
return webui_dir
monkeypatch.setattr("nanobot.webui.star_prompt.get_webui_dir", get_webui_dir)
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
+10 -6
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
import asyncio import asyncio
from typing import Any from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch from unittest.mock import AsyncMock, MagicMock, call, patch
import httpx import httpx
import pytest import pytest
@@ -464,11 +464,13 @@ class TestFallbackWhenPrimaryRaises:
) )
retry = fb.chat_stream_with_retry if stream else fb.chat_with_retry retry = fb.chat_stream_with_retry if stream else fb.chat_with_retry
result = await retry(messages=[{"role": "user", "content": "hi"}], model="primary-model") with patch("nanobot.providers.base.asyncio.sleep", new_callable=AsyncMock) as sleep:
result = await retry(messages=[{"role": "user", "content": "hi"}], model="primary-model")
assert result.content == "fallback ok" assert result.content == "fallback ok"
assert result.finish_reason == "stop" assert result.finish_reason == "stop"
factory.assert_called_once_with(_fallback("fallback-a")) factory.assert_called_once_with(_fallback("fallback-a"))
assert sleep.await_args_list == [call(1), call(2), call(4)]
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_authentication_exception_message_is_classified(self) -> None: async def test_authentication_exception_message_is_classified(self) -> None:
@@ -911,13 +913,15 @@ class TestFallbackOnPrimaryError:
fallback_model_observer=_observe, fallback_model_observer=_observe,
) )
result = await fb.chat_with_retry( with patch("nanobot.providers.base.asyncio.sleep", new_callable=AsyncMock) as sleep:
messages=[{"role": "user", "content": "hi"}], result = await fb.chat_with_retry(
model="primary-model", messages=[{"role": "user", "content": "hi"}],
) model="primary-model",
)
assert result.content == "fallback ok" assert result.content == "fallback ok"
assert fallback_models == ["fallback-b"] assert fallback_models == ["fallback-b"]
assert sleep.await_args_list == [call(1), call(2), call(4)]
@pytest.mark.asyncio @pytest.mark.asyncio
@pytest.mark.parametrize(("provider_name", "status", "code", "kind", "expected"), [ @pytest.mark.parametrize(("provider_name", "status", "code", "kind", "expected"), [
+12 -1
View File
@@ -45,6 +45,13 @@ from nanobot.webui.metadata import (
runner = CliRunner() runner = CliRunner()
@pytest.fixture(autouse=True)
def mock_webui_bundle(monkeypatch) -> MagicMock:
prepare_bundle = MagicMock()
monkeypatch.setattr(cli_webui, "_prepare_webui_bundle_for_gateway", prepare_bundle)
return prepare_bundle
def _without_rendered_line_breaks(output: str) -> str: def _without_rendered_line_breaks(output: str) -> str:
return "".join(output.splitlines()) return "".join(output.splitlines())
@@ -2861,7 +2868,9 @@ def test_attach_to_background_gateway_checks_owned_sidecar(tmp_path: Path) -> No
) )
def test_webui_foreground_does_not_claim_unmanaged_gateway(monkeypatch, tmp_path: Path) -> None: def test_webui_foreground_does_not_claim_unmanaged_gateway(
monkeypatch, tmp_path: Path, mock_webui_bundle: MagicMock,
) -> None:
config_file = tmp_path / "config.json" config_file = tmp_path / "config.json"
config_file.write_text("{}") config_file.write_text("{}")
_patch_webui_provider_ready(monkeypatch) _patch_webui_provider_ready(monkeypatch)
@@ -2887,6 +2896,8 @@ def test_webui_foreground_does_not_claim_unmanaged_gateway(monkeypatch, tmp_path
assert result.exit_code == 0 assert result.exit_code == 0
assert "controlled by another foreground command" in result.stdout assert "controlled by another foreground command" in result.stdout
mock_webui_bundle.assert_called_once()
assert mock_webui_bundle.call_args.kwargs == {"mode": "auto"}
def test_webui_foreground_refuses_occupied_webui_port(monkeypatch, tmp_path: Path) -> None: def test_webui_foreground_refuses_occupied_webui_port(monkeypatch, tmp_path: Path) -> None:
+32
View File
@@ -0,0 +1,32 @@
import time
from pathlib import Path
import pytest
from nanobot.llm_usage import LLMCallRecord, get_llm_usage_store
from nanobot.session.manager import SessionManager
from nanobot.webui import star_prompt
@pytest.mark.parametrize("_iteration", range(2))
def test_runtime_stores_are_isolated_between_parameter_cases(
tmp_path: Path, _iteration: int,
) -> None:
sessions = SessionManager(tmp_path.parent / "shared-workspace")
session = sessions.get_or_create("websocket:fixture-isolation")
assert session.messages == []
session.add_message("user", "isolated message")
sessions.save(session)
usage = get_llm_usage_store(tmp_path / "usage.sqlite3")
assert usage.recent_calls() == []
usage.record(LLMCallRecord(
started_at_ms=int(time.time() * 1000), duration_ms=1, provider="test", model="test",
source="user", stream=False, finish_reason="stop",
))
assert len(usage.recent_calls()) == 1
state_path = star_prompt.get_webui_dir() / "star-prompt.json"
assert not state_path.exists()
star_prompt.update_star_prompt("completed", turn_id="fixture-isolation")
assert state_path.exists()