repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
DeepTutor | tests/knowledge/test_document_adder_provider.py | .py | from __future__ import annotations
import asyncio
import json
from pathlib import Path
from deeptutor.knowledge.add_documents import (
DocumentAdder,
RawDocumentRemoval,
remove_raw_document,
)
def _write_provider_version(kb_dir: Path, provider: str) -> None:
version_dir = kb_dir / "version-1"
ve... | 162 | 5,218 |
DeepTutor | tests/knowledge/test_manifest.py | .py | """KB document inventory — the facts retrieval cannot answer.
"How many files are in this knowledge base?" is a question about the
collection, not about passage similarity, so it is answered from disk. These
tests pin the counting rules (what is and isn't a document), the degradations
(remote / agent / unreadable KBs)... | 237 | 9,364 |
DeepTutor | tests/knowledge/test_manager_get_info_status.py | .py | """Tests for KnowledgeBaseManager.get_info() status promotion (issue #418).
When the persisted ``status`` in ``kb_config.json`` is a "live" sentinel
(``processing`` / ``initializing``) but a ready index version already exists on
disk, ``get_info`` must promote the reported status to ``ready`` so the UI does
not show a... | 266 | 9,485 |
DeepTutor | tests/knowledge/test_naming.py | .py | from __future__ import annotations
import pytest
from deeptutor.knowledge.naming import validate_knowledge_base_name
def test_validate_knowledge_base_name_allows_unicode_and_spaces() -> None:
assert validate_knowledge_base_name(" 高等数学 KB ") == "高等数学 KB"
@pytest.mark.parametrize("name", ["bad/name", "bad\\na... | 16 | 576 |
DeepTutor | tests/knowledge/test_progress_tracker.py | .py | from __future__ import annotations
import json
from deeptutor.knowledge.manager import KnowledgeBaseManager
from deeptutor.knowledge.progress_tracker import ProgressStage, ProgressTracker
def test_progress_tracker_persists_snapshot_and_config(tmp_path) -> None:
tracker = ProgressTracker("demo-kb", tmp_path)
... | 59 | 1,712 |
DeepTutor | tests/knowledge/test_manager_delete.py | .py | from __future__ import annotations
import json
from pathlib import Path
import pytest
from deeptutor.knowledge.manager import KnowledgeBaseManager
def _create_kb(manager: KnowledgeBaseManager, name: str) -> Path:
kb_dir = manager.base_dir / name
(kb_dir / "raw").mkdir(parents=True, exist_ok=True)
(kb_d... | 84 | 3,138 |
DeepTutor | tests/knowledge/test_ima_kb.py | .py | """Manager handling of Tencent IMA KBs (``type: ima`` pointers).
An IMA KB is a connection pointer to a library the user keeps in IMA: no on-disk
folder under ``base_dir``, no local index, and deleting it must only drop our
pointer (never touch the user's IMA library). The stored credentials must never
leak into surfa... | 123 | 4,146 |
DeepTutor | tests/core/test_agentic_loop_intermediate.py | .py | """Tests for the optional ``LoopHost.on_intermediate`` hook.
The hook fires after the loop appends an intermediate-label assistant
message; if the host returns a non-empty string it gets injected as
the next iteration's user message. Used by research's ``APPEND`` label
to feed structured "queue mutated" feedback back ... | 478 | 16,109 |
DeepTutor | tests/core/test_labeled_step_think_prelude.py | .py | """Tests for the pre-label ``<think>...</think>`` prelude handling in
:func:`deeptutor.core.agentic.labeled_step.run_labeled_step`.
Reasoning models (Qwen, Deepseek-R1 via certain proxies, …) sometimes
emit a literal ``<think>...</think>`` block *before* the protocol label.
The streaming parser must:
1. Route prelude... | 581 | 21,187 |
DeepTutor | tests/core/test_agentic_client_provider_kwargs.py | .py | from __future__ import annotations
import pytest
from deeptutor.core.agentic import client as agentic_client
from deeptutor.core.agentic.client import (
_NATIVE_ADAPTER_BUILDERS,
_NATIVE_TOOL_BACKENDS,
LLMClientConfig,
_ProviderOpenAIAdapter,
build_completion_kwargs,
build_openai_client,
c... | 405 | 12,487 |
DeepTutor | tests/core/test_turn_event_store.py | .py | from __future__ import annotations
import pytest
from deeptutor.services.session.sqlite_store import SQLiteSessionStore
@pytest.mark.asyncio
async def test_sqlite_store_persists_turns_and_events(tmp_path) -> None:
store = SQLiteSessionStore(tmp_path / "chat_history.db")
session = await store.create_session... | 86 | 2,645 |
DeepTutor | tests/core/test_builtin_tools.py | .py | """Tests for built-in tools and unified tool registry behavior."""
from __future__ import annotations
import sys
import types
from types import SimpleNamespace
from typing import Any
import pytest
from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult
from deeptutor.runtime.reg... | 447 | 16,749 |
DeepTutor | tests/core/test_agentic_messages.py | .py | from __future__ import annotations
from deeptutor.core.agentic.messages import assistant_message_with_tool_calls
def test_assistant_message_with_tool_calls_normalizes_empty_values() -> None:
message = assistant_message_with_tool_calls(
content="",
tool_calls=[{"id": "call-1", "name": "search"}],
... | 40 | 1,240 |
DeepTutor | tests/core/test_stream_bus.py | .py | """Tests for StreamBus async event fan-out."""
from __future__ import annotations
import asyncio
import json
import pytest
from deeptutor.core.stream import StreamEvent, StreamEventType
from deeptutor.core.stream_bus import StreamBus
# ---------------------------------------------------------------------------
# B... | 231 | 6,746 |
DeepTutor | tests/core/test_capabilities_runtime.py | .py | """Runtime tests for built-in capabilities under the unified framework."""
from __future__ import annotations
import asyncio
import sys
import types
from types import SimpleNamespace
from typing import Any
import pytest
from deeptutor.agents.chat.capability import ChatCapability
from deeptutor.agents.question.capab... | 427 | 16,622 |
DeepTutor | tests/core/test_agentic_labels.py | .py | from deeptutor.core.agentic.labels import classify_label, find_inline_labels
_ALLOWED = ("FINISH", "TOOL", "THINK", "PAUSE")
def test_classify_label_accepts_common_wrapper_variants() -> None:
assert classify_label("`FINISH`\nDone", allowed_labels=_ALLOWED) == (
"FINISH",
"Done",
)
assert ... | 65 | 2,064 |
DeepTutor | tests/core/test_prompt_manager.py | .py | #!/usr/bin/env python
"""
Unit tests for the unified PromptManager.
"""
import pytest
from deeptutor.services.prompt import PromptManager, get_prompt_manager
class TestPromptManager:
"""Test cases for PromptManager."""
def setup_method(self):
"""Reset singleton and cache before each test."""
... | 197 | 6,371 |
DeepTutor | tests/core/test_math_animator_capability.py | .py | from __future__ import annotations
import asyncio
from types import SimpleNamespace
import pytest
from deeptutor.agents.math_animator.capability import MathAnimatorCapability
from deeptutor.core.context import UnifiedContext
from deeptutor.core.stream import StreamEvent, StreamEventType
from deeptutor.core.stream_bu... | 122 | 4,537 |
DeepTutor | tests/core/test_labeled_step_finish_usage.py | .py | from __future__ import annotations
import asyncio
from types import SimpleNamespace
from typing import Any
import pytest
import deeptutor.core.agentic.labeled_step as labeled_step_module
from deeptutor.core.agentic.labeled_step import run_labeled_step
from deeptutor.core.agentic.usage import UsageTracker
from deeptu... | 175 | 5,294 |
DeepTutor | tests/core/test_labeled_step_image_fallback.py | .py | """Stage-2 image fallback on the chat agentic path (``run_labeled_step``).
When a model rejects image content and is not in the known-vision allowlist,
the labeled step strips the images in place and retries text-only instead of
hard-failing the turn. Known-vision models keep their images so the real error
propagates.... | 164 | 5,228 |
DeepTutor | tests/core/test_prompt_parity.py | .py | from __future__ import annotations
from pathlib import Path
import re
from typing import Any, Iterable
import yaml
PROJECT_ROOT = Path(__file__).resolve().parents[2]
AGENTS_DIR = PROJECT_ROOT / "deeptutor" / "agents"
# Modules that live outside deeptutor/agents/ but still own prompts.
EXTRA_PROMPT_MODULE_DIRS = (
... | 124 | 4,226 |
DeepTutor | tests/core/test_labeled_step_tool_fallback.py | .py | from __future__ import annotations
import asyncio
from types import SimpleNamespace
from typing import Any
import pytest
from deeptutor.core.agentic.labeled_step import run_labeled_step
from deeptutor.core.stream import StreamEventType
from deeptutor.core.stream_bus import StreamBus
def _chunk(content: str | None ... | 113 | 3,347 |
DeepTutor | tests/core/test_record_streamed_usage.py | .py | """Contract tests for the shared once-per-stream usage recorder.
``record_streamed_usage`` is the single seam used by ``run_labeled_step``,
chat's ``_call_llm``, and the question pipeline's tool summarizer after
PR #617 unified their triplicated post-stream accounting.
"""
from __future__ import annotations
from typ... | 75 | 2,218 |
DeepTutor | tests/core/test_context.py | .py | """Tests for UnifiedContext, Attachment, StreamEvent, and trace helpers."""
from __future__ import annotations
from deeptutor.core.context import Attachment, UnifiedContext
from deeptutor.core.errors import (
ConfigurationError,
DeepTutorError,
EnvironmentConfigError,
LLMContextError,
LLMServiceEr... | 207 | 7,285 |
DeepTutor | tests/core/test_config_manager.py | .py | from pathlib import Path
import pytest
import yaml
from deeptutor.utils.config_manager import ConfigManager
def write_yaml(path: Path, data: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(yaml.safe_dump(data, sort_keys=False), encoding="utf-8")
@pytest.fixture(autouse=True)
... | 95 | 2,703 |
DeepTutor | tests/core/agentic/test_tool_arg_guard.py | .py | """Required-argument guard in front of tool dispatch (issue #779).
Under a large tool surface and long history, providers intermittently emit a
function call whose ``arguments`` is ``{}`` even though the schema marks
fields required. The tool used to be the one to reject it — ``exec`` raised
``exec requires a non-empt... | 261 | 8,984 |
DeepTutor | tests/core/agentic/test_tool_provider_trace.py | .py | """Which provider is running, on every event of a tool call's sub-trace.
This is what lets the activity row say "Using wolfram" or "Running blender"
instead of title-casing a generated name into "Mcp Wolfram Wolframalpha". The
identity is resolved from the tool object here because it is the only place that
knows it; t... | 166 | 5,951 |
DeepTutor | tests/core/agentic/test_tool_dispatch_events.py | .py | """Event payloads emitted by the parallel tool dispatcher.
Two regressions live here:
* Mount poisoning — server-injected private kwargs (``_sandbox_mounts``, a
Mount dataclass, and friends) leaked into the ``tool_call`` event's ``args``
metadata. The event was not JSON-serializable, which silently killed the
W... | 321 | 11,850 |
DeepTutor | tests/scripts/test_docker_compose.py | .py | from __future__ import annotations
import importlib.util
import json
from pathlib import Path
import re
import sys
import yaml
def _load_module():
module_path = Path(__file__).resolve().parents[2] / "scripts" / "docker_compose.py"
spec = importlib.util.spec_from_file_location("docker_compose_under_test", mo... | 208 | 9,236 |
DeepTutor | tests/scripts/test_start_web.py | .py | from __future__ import annotations
import importlib.util
from pathlib import Path
from unittest import mock
def _load_module():
module_path = Path(__file__).resolve().parents[2] / "scripts" / "start_web.py"
spec = importlib.util.spec_from_file_location("start_web_under_test", module_path)
assert spec and... | 31 | 956 |
DeepTutor | tests/scripts/test_update.py | .py | from __future__ import annotations
import importlib.util
from pathlib import Path
import subprocess
import sys
def _load_update_module():
module_path = Path(__file__).resolve().parents[2] / "scripts" / "update.py"
module_name = "update_script_under_test"
sys.modules.pop(module_name, None)
spec = impo... | 125 | 4,072 |
DeepTutor | tests/scripts/test_start_tour.py | .py | from __future__ import annotations
import importlib.util
from pathlib import Path
from unittest import mock
def _load_module():
module_path = Path(__file__).resolve().parents[2] / "scripts" / "start_tour.py"
spec = importlib.util.spec_from_file_location("start_tour_under_test", module_path)
assert spec a... | 31 | 991 |
DeepTutor | tests/scripts/test_cli_kit.py | .py | from __future__ import annotations
import importlib.util
import io
from pathlib import Path
import sys
from unittest import mock
def _load_cli_kit():
module_path = Path(__file__).resolve().parents[2] / "scripts" / "_cli_kit.py"
spec = importlib.util.spec_from_file_location("cli_kit_under_test", module_path)
... | 33 | 975 |
DeepTutor | tests/api/test_imports.py | .py | """Tests for the chat-history import endpoints.
The handlers are exercised directly (no TestClient) with the per-user store
factory monkeypatched to a tmp database, so nothing touches the real chat DB.
"""
from __future__ import annotations
import asyncio
from pathlib import Path
from fastapi import HTTPException
f... | 151 | 5,400 |
DeepTutor | tests/api/test_auth_contextvar.py | .py | """Regression tests for #481 and the auth-dep refactor.
When ``require_auth`` was declared as a sync ``def``, FastAPI dispatched it
through ``anyio.to_thread.run_sync``, which executes the function in a worker
thread under a *copy* of the request context. Any ``ContextVar.set`` inside
that thread is discarded when the... | 199 | 8,252 |
DeepTutor | tests/api/test_space_mcp.py | .py | """The per-user MCP surface: isolation, refusals, and secret hygiene.
This router is auth-gated rather than admin-gated, which is only defensible
because of what it refuses. Each test below pins one of those refusals.
"""
from __future__ import annotations
from pathlib import Path
from typing import Any
from fastap... | 402 | 15,440 |
DeepTutor | tests/api/test_upload_off_event_loop.py | .py | """The upload path must never hold the event loop (issue #777).
Batch-uploading files stalled every other request — chat WebSockets included
— for the whole duration of the batch. Two distinct causes, both pinned here:
* ``_save_uploaded_files`` is blocking end to end (a chunked write of every
uploaded byte, zip ex... | 128 | 4,401 |
DeepTutor | tests/api/test_subagents_router.py | .py | """API tests for the subagents router (detect / connect / list / disconnect).
Built on a standalone app with a fake KB manager and a stubbed detector, so it
exercises the HTTP contract without spawning a real CLI or touching the data
tree (mirrors test_knowledge_router's isolation).
"""
from __future__ import annotat... | 357 | 12,876 |
DeepTutor | tests/api/test_auth_logout_cookie.py | .py | """Regression test for #623.
``Response.delete_cookie()`` defaults ``secure=False``. The logout endpoint
passed only ``samesite=_SAMESITE`` (no ``secure``), so when
``cookie_secure=true`` (``_SAMESITE="none"``) the expiry header became
``SameSite=None`` without ``Secure`` — an invalid combination browsers
reject outri... | 58 | 2,159 |
DeepTutor | tests/api/test_selective_access_log.py | .py | """Tests for the selective_access_log middleware in main.py.
Verifies that non-200 responses are logged with the 5-element args tuple
(client_addr, method, full_path, http_version, status_code) — the shape that
was needed for uvicorn's AccessFormatter in #334 — while 200s stay silent.
The real middleware logs through... | 116 | 3,921 |
DeepTutor | tests/api/test_task_id_manager.py | .py | from datetime import datetime, timedelta
from deeptutor.api.utils.task_id_manager import TaskIDManager
def _manager() -> TaskIDManager:
manager = TaskIDManager()
manager._task_ids = {}
manager._task_metadata = {}
return manager
def test_generate_prunes_expired_completed_tasks() -> None:
manager... | 39 | 1,085 |
DeepTutor | tests/api/test_system_router.py | .py | from __future__ import annotations
from types import SimpleNamespace
import pytest
from deeptutor.api.routers import system as system_router
from deeptutor.runtime.memory_probe import MemorySnapshot, ProcessMemory
def _snapshot(*processes: ProcessMemory, **overrides: object) -> MemorySnapshot:
fields: dict[str... | 141 | 5,043 |
DeepTutor | tests/api/test_mcp_settings_auth.py | .py | """The deployment MCP registry is admin-only, and single-server writes are surgical.
A ``stdio`` server's ``command`` runs on the host as the application user, so
every route that can read or change this registry is administrator-gated. That
gate had no test at all.
"""
from __future__ import annotations
from pathli... | 128 | 4,116 |
DeepTutor | tests/api/test_space_cli_apps.py | .py | """The CLI apps API: who can install, and who can only choose.
The router is auth-gated with ``require_admin`` on two routes rather than on the
whole thing, which is only defensible if those two are genuinely the privileged
half. These tests pin that split, and the rule that keeps *enable* from becoming
a way around t... | 264 | 9,692 |
DeepTutor | tests/api/test_codex_oauth_scope.py | .py | """Who may drive the Codex OAuth lifecycle (issue #781).
These five endpoints act on the *caller's own* credentials — the store, the
model catalog, and the callback route are all resolved from owner scope — so
the administrator gate that used to sit on them was what left ordinary users
unable to use Codex at all: an o... | 139 | 4,930 |
DeepTutor | tests/api/test_voice_routes.py | .py | """Voice router tests — /tts and /stt request/response contracts."""
from __future__ import annotations
import io
from typing import Any
import wave
from fastapi import FastAPI
from fastapi.testclient import TestClient
import pytest
from deeptutor.api.routers import voice as voice_router
from deeptutor.services.voi... | 112 | 3,948 |
DeepTutor | tests/api/test_memory_resolver.py | .py | """GET /api/v1/memory/resolve_entry/{id} → (layer, key).
L3 docs cite L2 entries by their ``m_<ULID>`` entry id. The resolver
turns an L3 footnote click into "which L2 surface do I navigate to".
"""
from __future__ import annotations
import importlib
from pathlib import Path
import pytest
pytest.importorskip("fast... | 83 | 2,784 |
DeepTutor | tests/api/test_cors_settings.py | .py | """Tests for FastAPI CORS settings."""
from __future__ import annotations
from fastapi.testclient import TestClient
from deeptutor.api import main as api_main
def test_cors_allows_remote_http_origins_when_auth_disabled(
monkeypatch,
) -> None:
monkeypatch.delenv("AUTH_ENABLED", raising=False)
monkeypat... | 76 | 2,679 |
DeepTutor | tests/api/test_output_files.py | .py | """Request-scoped regression coverage for generated-output downloads (#790)."""
from __future__ import annotations
from collections.abc import Callable
from pathlib import Path
from fastapi import FastAPI
from fastapi.testclient import TestClient
import pytest
from deeptutor.services.auth import TokenPayload
from d... | 186 | 7,677 |
DeepTutor | tests/api/test_co_writer.py | .py | """Co-Writer backend tests: doc id validation, storage CRUD, history limits."""
from pathlib import Path
from fastapi import HTTPException
import pytest
from deeptutor.api.routers.co_writer import _validate_doc_id
from deeptutor.co_writer import edit_agent
from deeptutor.co_writer.storage import CoWriterStorage
cl... | 142 | 4,997 |
DeepTutor | tests/api/test_knowledge_router.py | .py | from __future__ import annotations
import asyncio
import importlib
import json
from pathlib import Path
import pytest
try:
from fastapi import FastAPI
from fastapi.testclient import TestClient
except Exception: # pragma: no cover - optional dependency in lightweight envs
FastAPI = None
TestClient = ... | 1,227 | 48,028 |
DeepTutor | tests/api/test_tool_options.py | .py | """Contract tests for the configurable-tool surface (``build_tool_options``).
The ``mcp_tools`` rows are what the partner tool picker and the admin grant
editor fold into one checkbox per service, so the provider identity fields are
a UI contract: ``kind`` + ``provider_id`` are the grouping key, ``server`` is
the lega... | 163 | 5,445 |
DeepTutor | tests/api/test_skills_hub_router.py | .py | """API tests for the in-app EduHub skill browser endpoints.
``GET /api/v1/skills/hub/catalog`` and ``/hub/detail`` proxy a hub's public
catalog so the web panel can render it in DeepTutor's own UI (no iframe, no
login). The hub provider is mocked over an ``httpx`` transport.
"""
from __future__ import annotations
im... | 107 | 3,877 |
DeepTutor | tests/api/test_knowledge_zip_upload.py | .py | """Wiring tests for safe ``.zip`` upload handling in the knowledge router.
The deep security guards live in ``tests/utils/test_archive_extractor.py``;
these check that ``_save_uploaded_files`` routes ``.zip`` uploads through the
safe extractor, registers only supported members, and never persists the
archive itself.
"... | 96 | 3,150 |
DeepTutor | tests/api/test_tools_router.py | .py | from __future__ import annotations
import pytest
from deeptutor.api.routers import settings as settings_router
from deeptutor.api.routers import tools as tools_router
from deeptutor.tools.builtin import (
BUILTIN_TOOL_NAMES,
COMING_SOON_TOOL_NAMES,
USER_TOGGLEABLE_TOOL_NAMES,
)
@pytest.mark.asyncio
asyn... | 110 | 4,433 |
DeepTutor | tests/api/test_main_notebook_router.py | .py | """Tests for the main notebook router (/api/v1/notebook).
Verifies that records can only be saved using real notebook UUIDs
(from /api/v1/notebook/list), not question-notebook category integer IDs.
"""
from __future__ import annotations
import asyncio
import importlib
import json
import pytest
pytest.importorskip(... | 162 | 5,501 |
DeepTutor | tests/api/test_unified_ws_turn_runtime.py | .py | from __future__ import annotations
from types import SimpleNamespace
import pytest
from deeptutor.core.stream import StreamEvent, StreamEventType
from deeptutor.services.session.sqlite_store import SQLiteSessionStore
from deeptutor.services.session.turn_runtime import TurnRuntimeManager
async def _noop_async(*_arg... | 923 | 34,686 |
DeepTutor | tests/api/test_sessions_truncation.py | .py | """Tests for oversized event-payload truncation in the session GET response.
Covers ``_truncate_oversized_events`` (introduced via PR #524 and refactored to
operate directly on the store's parsed ``events`` list). The session store
returns each message with an ``events`` list and no ``events_json`` key, so the
helper ... | 85 | 2,803 |
DeepTutor | tests/api/test_partners_channel_schema.py | .py | """Tests for the schema-driven channels endpoint helpers.
Covers:
* ``resolve_config_model``: maps each ``XxxChannel`` to its ``XxxConfig``.
* ``inline_refs``: flattens nested model ``$ref``s (slack ``dm`` subtree).
* ``collect_secret_fields``: only flags **string-typed** secret-looking keys
(so e.g. ``user_token_re... | 192 | 7,186 |
DeepTutor | tests/api/test_question_router.py | .py | from __future__ import annotations
from contextlib import contextmanager
import importlib
from pathlib import Path
import sys
import types
import pytest
FastAPI = pytest.importorskip("fastapi").FastAPI
TestClient = pytest.importorskip("fastapi.testclient").TestClient
@pytest.fixture(autouse=True)
def _cleanup_ques... | 154 | 6,200 |
DeepTutor | tests/api/test_partners_router.py | .py | """API surface tests for /api/v1/partners (create / config / soul / assets)."""
from __future__ import annotations
import base64
import json
from pathlib import Path
import pytest
import yaml
try:
from fastapi import FastAPI
from fastapi.testclient import TestClient
except Exception: # pragma: no cover
... | 393 | 16,770 |
DeepTutor | tests/api/test_notebook_router.py | .py | from __future__ import annotations
import asyncio
import importlib
from pathlib import Path
import pytest
pytest.importorskip("fastapi")
FastAPI = pytest.importorskip("fastapi").FastAPI
TestClient = pytest.importorskip("fastapi.testclient").TestClient
notebook_router = importlib.import_module("deeptutor.api.routers... | 371 | 13,027 |
DeepTutor | tests/api/test_settings_router.py | .py | from __future__ import annotations
from copy import deepcopy
import json
from types import SimpleNamespace
from typing import Any
import pytest
from deeptutor.api.routers import settings as settings_router
from deeptutor.services.codex_auth.contracts import CodexAuthError
from deeptutor.services.config.provider_runt... | 1,344 | 50,087 |
DeepTutor | tests/api/test_codex_oauth_callback.py | .py | from __future__ import annotations
from fastapi import FastAPI
from fastapi.testclient import TestClient
import pytest
from deeptutor.api.routers import auth as auth_router
from deeptutor.services.codex_auth.contracts import CodexAuthError
from deeptutor.services.codex_auth.oauth import oauth_state_matches
class Fa... | 206 | 6,313 |
DeepTutor | tests/api/test_plugins_api_partner.py | .py | """Regression tests for partner-compatible plugin capability streaming."""
from __future__ import annotations
import importlib
import json
import re
from typing import Any
import pytest
try:
from fastapi import FastAPI
from fastapi.testclient import TestClient
except Exception: # pragma: no cover
FastA... | 125 | 4,268 |
DeepTutor | tests/utils/test_archive_extractor.py | .py | """Tests for the safe ZIP extractor (``deeptutor.utils.archive_extractor``).
These lock in the security guards that a naive ``extractall`` lacks: Zip Slip
defusal, extension whitelisting, nested-archive rejection, duplicate handling,
and the zip-bomb size/count/ratio limits.
"""
from __future__ import annotations
fr... | 163 | 5,817 |
DeepTutor | tests/utils/test_document_validator.py | .py | from __future__ import annotations
from deeptutor.services.rag.file_routing import FileTypeRouter
from deeptutor.utils.document_validator import DocumentValidator
def test_validate_upload_safety_preserves_unicode_and_lowercases_extension() -> None:
safe_name = DocumentValidator.validate_upload_safety(
"中... | 55 | 1,704 |
DeepTutor | tests/utils/test_document_extractor.py | .py | """Tests for deeptutor.utils.document_extractor."""
from __future__ import annotations
import base64
import io
from docx import Document as DocxDocument
from openpyxl import Workbook
from pptx import Presentation
from pptx.util import Inches
import pytest
from deeptutor.utils import document_extractor as document_e... | 449 | 16,114 |
DeepTutor | tests/utils/test_circuit_breaker.py | .py | """Tests for the circuit breaker state machine."""
from __future__ import annotations
import time
from unittest.mock import patch
from deeptutor.utils.network.circuit_breaker import (
CircuitBreaker,
alert_callback,
is_call_allowed,
record_call_failure,
record_call_success,
)
# -----------------... | 128 | 4,639 |
DeepTutor | tests/utils/test_json_parser.py | .py | """Tests for robust JSON parsing utilities."""
from __future__ import annotations
import json
import logging
from unittest.mock import patch
import pytest
from deeptutor.utils.json_parser import parse_json_response, safe_json_loads
# ---------------------------------------------------------------------------
# par... | 225 | 8,983 |
DeepTutor | tests/logging/test_loguru_bridge.py | .py | import logging
import pytest
from deeptutor.logging import bind_log_context, capture_process_logs
from deeptutor.logging.loguru_bridge import install_loguru_bridge
def test_loguru_bridge_forwards_to_stdlib_process_capture():
loguru = pytest.importorskip("loguru")
events = []
assert install_loguru_bridg... | 20 | 650 |
DeepTutor | tests/logging/test_process_logs.py | .py | import logging
from deeptutor.logging import ProcessLogEvent, bind_log_context, capture_process_logs
def test_capture_process_logs_emits_structured_event_for_matching_task():
events: list[ProcessLogEvent] = []
logger = logging.getLogger("deeptutor.tests.process")
with bind_log_context(task_id="task-1", ... | 36 | 1,204 |
DeepTutor | tests/logging/test_task_log_stream.py | .py | import json
import logging
import pytest
from deeptutor.api.utils.task_log_stream import (
KnowledgeTaskStreamManager,
capture_task_logs,
get_task_stream_manager,
)
@pytest.mark.asyncio
async def test_knowledge_task_stream_emits_process_log_sse_event():
manager = KnowledgeTaskStreamManager()
man... | 128 | 4,472 |
DeepTutor | tests/logging/test_context.py | .py | from deeptutor.logging import bind_log_context, current_log_context
def test_bind_log_context_is_scoped_and_nested():
assert current_log_context() == {}
with bind_log_context(request_id="req-1", task_id="task-1"):
assert current_log_context() == {"request_id": "req-1", "task_id": "task-1"}
wi... | 18 | 675 |
DeepTutor | tests/logging/test_configure.py | .py | import importlib
import json
import logging
from pathlib import Path
import pytest
from deeptutor.logging import LoggingConfig, bind_log_context
@pytest.fixture(autouse=True)
def _clean_logging_handlers():
configure_module = importlib.import_module("deeptutor.logging.configure")
configure_module._remove_man... | 78 | 2,459 |
DeepTutor | tests/cli/test_codebuddy_login.py | .py | from __future__ import annotations
import sys
from types import SimpleNamespace
import pytest
from deeptutor_cli.provider_cmd import _login_codebuddy
class FakeAuthFlow:
auth_url = "https://codebuddy.example/login"
def __await__(self):
async def _wait():
return SimpleNamespace(
... | 54 | 1,509 |
DeepTutor | tests/cli/test_init_wizard_probe.py | .py | from __future__ import annotations
from io import StringIO
from types import SimpleNamespace
from rich.console import Console
def test_gemini_embedding_fallback_prefers_stable_embedding2() -> None:
from deeptutor_cli.init_wizard import EMBEDDING_FALLBACK_MODELS
# Embedding 2 leads, but 001 stays offered: i... | 319 | 10,111 |
DeepTutor | tests/cli/test_config_cli.py | .py | """CLI config command tests."""
from __future__ import annotations
from types import SimpleNamespace
from typer.testing import CliRunner
from deeptutor_cli.main import app
runner = CliRunner()
def test_config_show_handles_missing_embedding(monkeypatch) -> None:
"""CLI-only defaults skip embedding setup, so c... | 66 | 1,872 |
DeepTutor | tests/cli/test_chat_state_output.py | .py | """Regression tests for literal state values in the interactive chat CLI."""
from __future__ import annotations
from io import StringIO
import pytest
from rich.console import Console
from rich.text import Text
from deeptutor_cli import chat
def _render(monkeypatch: pytest.MonkeyPatch, render, state: chat.ChatStat... | 104 | 3,115 |
DeepTutor | tests/cli/test_kb_cli.py | .py | from __future__ import annotations
from pathlib import Path
from deeptutor_cli.kb import _collect_documents
def test_collect_documents_from_directory_matches_uppercase_extensions(tmp_path: Path) -> None:
docs_dir = tmp_path / "资料"
docs_dir.mkdir()
upper_pdf = docs_dir / "报告.PDF"
upper_pdf.write_byte... | 21 | 620 |
DeepTutor | tests/cli/test_notebook_cli.py | .py | """CLI smoke tests for ``deeptutor notebook`` commands."""
from __future__ import annotations
from pathlib import Path
from typer.testing import CliRunner
from deeptutor_cli.main import app
runner = CliRunner()
class FakeNotebookManager:
"""Fake NotebookManager for CLI testing."""
def __init__(self) -> ... | 237 | 7,312 |
DeepTutor | tests/cli/test_turn_renderer.py | .py | """Tests for the CLI turn-stream renderer against the chat-loop protocol.
The chat agent loop (deeptutor/agents/chat/agent_loop.py) streams every
round's text as ``content`` chunks with ``trace_kind=llm_chunk`` and labels
the round afterwards via a ``call_status`` marker carrying ``call_role``
(``narration`` | ``finis... | 378 | 13,515 |
DeepTutor | tests/cli/test_chat_cli.py | .py | """CLI smoke tests for the standalone ``deeptutor-cli`` package."""
from __future__ import annotations
import json
from typing import Any
import pytest
from typer.testing import CliRunner
from deeptutor.app import DeepTutorApp, TurnRequest
from deeptutor.runtime.bootstrap.builtin_capabilities import BUILTIN_CAPABIL... | 243 | 8,025 |
DeepTutor | tests/cli/test_chat_terminal.py | .py | """POSIX terminal behavior tests for the interactive chat CLI."""
from __future__ import annotations
import os
from pathlib import Path
import select
import subprocess
import sys
import time
import pytest
pty = pytest.importorskip("pty")
termios = pytest.importorskip("termios")
@pytest.mark.skipif(not hasattr(ter... | 74 | 2,178 |
DeepTutor | tests/cli/test_docs_contract.py | .py | """Contracts that keep the public docs aligned with the CLI surface."""
from __future__ import annotations
from pathlib import Path
import re
import shlex
ROOT = Path(__file__).resolve().parents[2]
DOCS_ROOT = ROOT / "site" / "src" / "content" / "docs"
PUBLIC_DOCS = (
ROOT / "README.md",
ROOT / "deeptutor_cl... | 125 | 3,746 |
DeepTutor | tests/cli/test_common.py | .py | """Unit tests for shared CLI helpers."""
from __future__ import annotations
import pytest
from deeptutor_cli.common import parse_json_object
def test_parse_json_object_whitespace_is_empty_dict() -> None:
assert parse_json_object(" ") == {}
def test_parse_json_object_invalid_json_still_errors() -> None:
... | 17 | 413 |
DeepTutor | tests/cli/test_provider_cli.py | .py | from pathlib import Path
import unittest
from typer.testing import CliRunner
from deeptutor_cli import provider_cmd
from deeptutor_cli.main import app
ROOT = Path(__file__).resolve().parents[2]
PROVIDER_CMD = (ROOT / "deeptutor_cli" / "provider_cmd.py").read_text(encoding="utf-8")
CLI_README = (ROOT / "deeptutor_cli... | 131 | 5,390 |
DeepTutor | tests/book/test_runtime_reclaim.py | .py | import asyncio
import pytest
from deeptutor.book import engine as engine_module
from deeptutor.book.engine import BookEngine, _BookRuntime
@pytest.mark.asyncio
async def test_idle_background_runtime_is_released(monkeypatch) -> None:
engine = BookEngine.__new__(BookEngine)
engine._global_lock = asyncio.Lock(... | 26 | 695 |
DeepTutor | tests/book/test_engine_controls.py | .py | from __future__ import annotations
from deeptutor.book.engine import BookEngine
from deeptutor.book.models import Block, BlockStatus, BlockType, Page, PageStatus
def test_force_compile_reset_preserves_user_notes() -> None:
generated = Block(
type=BlockType.CODE,
status=BlockStatus.READY,
... | 96 | 3,092 |
DeepTutor | tests/book/test_spine_synthesizer_llm_call.py | .py | """The spine synthesizer must reach the LLM through its own agent seam.
``_call_json`` is blocking on purpose — nothing consumes a partial spine, and a
reasoning model's ``<think>`` prelude never reaches the parser this way (#707).
But it has to stay on ``BaseAgent.call_llm``: calling the factory directly drops
the tr... | 63 | 2,070 |
DeepTutor | tests/book/test_llm_writer.py | .py | from __future__ import annotations
import pytest
from deeptutor.book.blocks import _llm_writer
@pytest.mark.asyncio
async def test_llm_json_normalizes_array_to_expected_key(monkeypatch: pytest.MonkeyPatch) -> None:
async def fake_llm_text(**_: object) -> str:
return '[{"front": "A", "back": "B"}]'
... | 63 | 2,000 |
DeepTutor | tests/book/test_context.py | .py | from __future__ import annotations
from deeptutor.book.context import build_book_context, normalize_book_references
from deeptutor.book.models import (
Block,
BlockStatus,
BlockType,
Book,
Chapter,
Page,
PageStatus,
Spine,
)
class FakeBookStorage:
def __init__(self) -> None:
... | 160 | 5,645 |
DeepTutor | tests/runtime/test_import_layering.py | .py | """The provider/registry layering must not become mutually dependent.
``deferred_tools`` (registry layer) sanitises provider text through
``providers.text``, so the provider *primitives* sit below the registry.
``providers.view`` composes the registry, so it sits above. Re-exporting
``view`` from ``providers/__init__`... | 36 | 1,312 |
DeepTutor | tests/runtime/test_launcher_allocator_env.py | .py | from deeptutor.runtime.launcher import _apply_single_user_allocator_env
def test_single_user_allocator_defaults_reduce_fragmentation() -> None:
env: dict[str, str] = {}
_apply_single_user_allocator_env(env)
assert env["MALLOC_ARENA_MAX"] == "2"
assert env["MALLOC_TRIM_THRESHOLD_"] == "131072"
def ... | 19 | 583 |
DeepTutor | tests/runtime/test_api_import_memory_boundary.py | .py | from __future__ import annotations
import json
from pathlib import Path
import subprocess
import sys
def test_api_import_keeps_optional_heavy_dependencies_cold() -> None:
repo_root = Path(__file__).resolve().parents[2]
probe = """
import json
import sys
import deeptutor.api.main # noqa: F401
heavy_roots =... | 44 | 812 |
DeepTutor | tests/runtime/test_memory_probe.py | .py | from __future__ import annotations
import os
from pathlib import Path
import sys
import pytest
from deeptutor.runtime import memory_probe
def test_capture_always_measures_at_least_this_process() -> None:
snapshot = memory_probe.capture()
if not snapshot.processes:
pytest.skip("no memory backend on... | 170 | 6,694 |
DeepTutor | tests/runtime/test_run_server_memory_mode.py | .py | from __future__ import annotations
from pathlib import Path
from typing import Any
import pytest
from deeptutor.api import run_server
@pytest.fixture
def uvicorn_kwargs(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> dict[str, Any]:
captured: dict[str, Any] = {}
monkeypatch.setattr(run_server, "get_ru... | 52 | 1,594 |
DeepTutor | tests/runtime/test_orchestrator.py | .py | """Tests for ChatOrchestrator routing and lifecycle."""
from __future__ import annotations
import asyncio
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from deeptutor.core.capability_protocol import BaseCapability, CapabilityManifest
from deeptutor.core.context import UnifiedContext
from deept... | 229 | 7,524 |
DeepTutor | tests/runtime/test_memory_reclaim.py | .py | from __future__ import annotations
import asyncio
import pytest
from deeptutor.runtime import memory_reclaim
@pytest.mark.asyncio
async def test_scheduled_reclaims_are_coalesced(monkeypatch: pytest.MonkeyPatch) -> None:
calls = 0
def _release() -> tuple[int, bool]:
nonlocal calls
calls += ... | 29 | 671 |
DeepTutor | tests/runtime/test_request_contracts_subagent.py | .py | """Regression: the per-turn subagent consult budget must pass chat-config validation.
``subagent_consult_budget`` rides in the request ``config`` (composer stepper)
but isn't part of any capability's public schema. It must be treated as a
runtime-only key, not rejected by ``extra="forbid"`` — otherwise a second turn
w... | 28 | 1,045 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.