From 29f27dcf5d65d492aa376753ea9b9419a4f46517 Mon Sep 17 00:00:00 2001 From: chengyongru <61816729+chengyongru@users.noreply.github.com> Date: Thu, 8 Oct 2026 13:03:56 +0800 Subject: [PATCH] ci: reduce test runtime while preserving coverage (#6101) * ci: reduce test runtime while preserving coverage * test: close cached usage stores before temporary directory cleanup --- .github/workflows/ci.yml | 2 ++ conftest.py | 32 ++++++++++++++++++++++++----- tests/agent/test_runner_fallback.py | 16 +++++++++------ tests/cli/test_commands.py | 13 +++++++++++- tests/test_fixture_isolation.py | 32 +++++++++++++++++++++++++++++ 5 files changed, 83 insertions(+), 12 deletions(-) create mode 100644 tests/test_fixture_isolation.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 629740f6f..8b2c7f94d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -138,6 +138,8 @@ jobs: if: needs.changes.outputs.python_required == 'true' runs-on: ${{ matrix.os }} timeout-minutes: 20 + env: + PYTEST_ADDOPTS: "-o tmp_path_retention_policy=failed" strategy: fail-fast: false matrix: diff --git a/conftest.py b/conftest.py index 66bda8be9..1db713017 100644 --- a/conftest.py +++ b/conftest.py @@ -8,6 +8,7 @@ import sys from collections.abc import Iterator from pathlib import Path from threading import Thread +from uuid import uuid4 import certifi 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, per ADR-0001), so without redirection tests would write into the real home. """ - runtime_root = tmp_path.parent / f"{tmp_path.name}-runtime-root" - legacy_root = tmp_path.parent / f"{tmp_path.name}-legacy-sessions-root" + data_root = tmp_path.parent / "session-data" / uuid4().hex + runtime_root = data_root / "runtime" + legacy_root = data_root / "legacy-sessions" def runtime_subdir(name: str) -> Path: path = runtime_root / name @@ -57,13 +59,33 @@ def _isolate_sessions_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> I 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) def _isolate_star_prompt_store( - tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch + tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: """Keep WebUI completion events out of the user's invitation state and lock.""" - webui_dir = tmp_path_factory.mktemp("star-prompt-webui") - monkeypatch.setattr("nanobot.webui.star_prompt.get_webui_dir", lambda: webui_dir) + webui_dir = tmp_path.parent / "star-prompt-webui" / uuid4().hex + + 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) diff --git a/tests/agent/test_runner_fallback.py b/tests/agent/test_runner_fallback.py index 5bdf0ef02..f8b0ba2bb 100644 --- a/tests/agent/test_runner_fallback.py +++ b/tests/agent/test_runner_fallback.py @@ -4,7 +4,7 @@ from __future__ import annotations import asyncio from typing import Any -from unittest.mock import AsyncMock, MagicMock, patch +from unittest.mock import AsyncMock, MagicMock, call, patch import httpx import pytest @@ -464,11 +464,13 @@ class TestFallbackWhenPrimaryRaises: ) 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.finish_reason == "stop" factory.assert_called_once_with(_fallback("fallback-a")) + assert sleep.await_args_list == [call(1), call(2), call(4)] @pytest.mark.asyncio async def test_authentication_exception_message_is_classified(self) -> None: @@ -911,13 +913,15 @@ class TestFallbackOnPrimaryError: fallback_model_observer=_observe, ) - result = await fb.chat_with_retry( - messages=[{"role": "user", "content": "hi"}], - model="primary-model", - ) + with patch("nanobot.providers.base.asyncio.sleep", new_callable=AsyncMock) as sleep: + result = await fb.chat_with_retry( + messages=[{"role": "user", "content": "hi"}], + model="primary-model", + ) assert result.content == "fallback ok" assert fallback_models == ["fallback-b"] + assert sleep.await_args_list == [call(1), call(2), call(4)] @pytest.mark.asyncio @pytest.mark.parametrize(("provider_name", "status", "code", "kind", "expected"), [ diff --git a/tests/cli/test_commands.py b/tests/cli/test_commands.py index 8b93b1299..b34fa3aaf 100644 --- a/tests/cli/test_commands.py +++ b/tests/cli/test_commands.py @@ -45,6 +45,13 @@ from nanobot.webui.metadata import ( 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: 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.write_text("{}") _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 "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: diff --git a/tests/test_fixture_isolation.py b/tests/test_fixture_isolation.py new file mode 100644 index 000000000..fb82ddfc4 --- /dev/null +++ b/tests/test_fixture_isolation.py @@ -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()