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
onyx
backend/tests/unit/onyx/server/features/craft/session/test_md_to_docx.py
.py
"""Unit tests for the Markdown -> DOCX converter.""" import re import zipfile from io import BytesIO from xml.etree import ElementTree from docx import Document from docx.document import Document as DocxDocument from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.oxml.ns import qn from docx.table import _Cell fr...
516
20,583
onyx
backend/tests/unit/onyx/server/features/craft/session/test_snapshot_api.py
.py
"""Unit coverage for on-demand build-session snapshot endpoints.""" from __future__ import annotations import json from types import SimpleNamespace from typing import cast from unittest.mock import MagicMock from uuid import uuid4 import pytest from sqlalchemy.orm import Session from onyx.db.models import Sandbox,...
121
4,017
onyx
backend/tests/unit/onyx/server/features/craft/session/test_session_ready.py
.py
"""Getting a session's runtime up before a turn touches it. The bug these pin: provisioning the sandbox and rebuilding the session workspace used to be separate, so a turn could provision a pod and create an opencode instance for a session directory while the restore endpoint was still writing that directory's config....
164
6,254
onyx
backend/tests/unit/onyx/server/features/craft/session/test_presentation_preview.py
.py
from types import SimpleNamespace from unittest.mock import MagicMock from uuid import uuid4 import pytest from onyx.server.features.build.session.manager import SessionManager @pytest.mark.parametrize("extension", ["ppt", "PPT"]) def test_legacy_powerpoint_preview_runs_the_slide_converter(extension: str) -> None: ...
63
2,257
onyx
backend/tests/unit/onyx/server/features/craft/session/test_sandbox_status_writers.py
.py
"""Pins the invariant that Craft sandbox status transitions live exclusively in the lifecycle module (plus the db layer that implements the mutation). Any new module referencing a sandbox-status mutation helper fails this test and forces a conscious decision: route the transition through ``sandbox_lifecycle`` instead,...
59
2,287
onyx
backend/tests/unit/onyx/server/features/craft/session/test_hidden_workspace_entries.py
.py
from __future__ import annotations import pytest from onyx.server.features.build.sandbox.models import FilesystemEntry from onyx.server.features.build.session.manager import _is_hidden_workspace_entry @pytest.mark.parametrize("name", ["nextjs.log", "nextjs.pid"]) def test_dev_server_runtime_files_are_hidden(name: s...
19
715
onyx
backend/tests/unit/onyx/server/features/craft/session/test_streaming_announce_merge.py
.py
"""Tests for tenant-contextvar propagation in the announce-merge stream.""" from __future__ import annotations from collections.abc import Generator from typing import Any from uuid import uuid4 import pytest from onyx.server.features.build.session import streaming from shared_configs.contextvars import CURRENT_TEN...
52
1,695
onyx
backend/tests/unit/onyx/server/features/craft/session/test_webapp_info.py
.py
from __future__ import annotations from types import SimpleNamespace from unittest.mock import MagicMock, patch from uuid import UUID, uuid4 from onyx.db.enums import SandboxStatus from onyx.server.features.build.sandbox.models import FilesystemEntry from onyx.server.features.build.session.manager import SessionManag...
174
5,240
onyx
backend/tests/unit/onyx/server/features/craft/session/test_messages_background_turn.py
.py
from __future__ import annotations from types import SimpleNamespace from typing import cast from unittest.mock import MagicMock from uuid import UUID, uuid4 import pytest from pydantic import ValidationError from sqlalchemy.orm import Session from onyx.db.models import User from onyx.error_handling.error_codes impo...
469
16,057
onyx
backend/tests/unit/onyx/server/features/craft/session/test_archive_walk.py
.py
from __future__ import annotations from uuid import uuid4 from onyx.server.features.build.sandbox.models import FilesystemEntry from onyx.server.features.build.session.manager import SessionManager from tests.common.craft.stubs import StubSandboxManager def _manager(sandbox_manager: StubSandboxManager) -> SessionMa...
80
2,560
onyx
backend/tests/unit/onyx/server/features/craft/session/test_streaming_state.py
.py
"""BuildStreamingState pure logic tests. Tests for chunk accumulation and finalize semantics — no DB required. """ from __future__ import annotations from typing import Any, cast from uuid import UUID, uuid4 import pytest from onyx.db.models import BuildSession from onyx.server.features.build.packets import Compac...
422
15,430
onyx
backend/tests/unit/onyx/server/features/craft/session/test_prewarm_opencode_session.py
.py
from __future__ import annotations from uuid import UUID, uuid4 import pytest from onyx.db.models import BuildSession, Sandbox from onyx.server.features.build.session.manager import SessionManager class _FakeSandboxManager: def __init__(self, result: str | None) -> None: self.result = result se...
130
4,292
onyx
backend/tests/unit/onyx/server/features/craft/scheduled_tasks/test_executor.py
.py
from onyx.server.features.build.scheduled_tasks.executor import ( SUMMARY_MAX_CHARS, _clip_summary, ) def test_clip_summary_short_text_passthrough() -> None: assert _clip_summary("All done.") == "All done." def test_clip_summary_exactly_max_passthrough() -> None: text = "x" * SUMMARY_MAX_CHARS a...
40
1,208
onyx
backend/tests/unit/onyx/server/features/craft/scheduled_tasks/test_schedule.py
.py
from datetime import datetime, timezone from onyx.server.features.build.scheduled_tasks.schedule import ( compute_next_run_at, next_n_fires, ) def test_compute_next_run_at_uses_utc_cron_fields() -> None: after = datetime(2026, 5, 25, 8, 59, tzinfo=timezone.utc) assert compute_next_run_at("0 9 * * *"...
35
1,003
onyx
backend/tests/unit/onyx/server/features/persona/test_knowledge_sources.py
.py
"""Unit tests for MinimalPersonaSnapshot.from_model knowledge_sources aggregation.""" from unittest.mock import MagicMock, patch from onyx.configs.constants import DocumentSource, FederatedConnectorSource from onyx.server.features.document_set.models import DocumentSetSummary from onyx.server.features.persona.models ...
189
5,875
onyx
backend/tests/unit/onyx/server/features/mcp/test_mcp_ssrf.py
.py
"""Guards the SSRF policy for outbound MCP traffic. Validation is driven by the admin ``SSRF Protection`` setting: at the VALIDATE_* levels internal targets are blocked; setting it to ``DISABLED`` re-opens RFC1918 *and* loopback together, while cloud-metadata/link-local and unspecified stay blocked at every level. The ...
225
9,150
onyx
backend/tests/unit/onyx/server/features/mcp/test_oauth_credentials_resolver.py
.py
"""Unit tests for the MCP OAuth credentials resolver and config builder. These tests cover the fix for the "resubmit unchanged wipes client_info" bug described in `plans/mcp-oauth-resubmit-empty-secret-fix.md`. The resolver mirrors the LLM-provider `api_key_changed` pattern: when the frontend marks a credential field ...
415
17,768
onyx
backend/tests/unit/onyx/server/features/mcp/test_shared_api_token_headers.py
.py
import pytest from onyx.db.enums import ( MCPAuthenticationPerformer, MCPAuthenticationType, MCPTransport, ) from onyx.server.features.mcp.api import ( _build_shared_api_token_config_data, _resolve_auth_template, _resolve_shared_api_token, _resolve_shared_api_token_template, ) from onyx.ser...
199
6,140
onyx
backend/tests/unit/onyx/server/features/mcp/test_mcp_oauth_connect.py
.py
import asyncio from collections.abc import AsyncGenerator, Awaitable, Callable from types import SimpleNamespace from typing import cast from unittest.mock import AsyncMock, MagicMock from uuid import uuid4 import httpx import pytest from onyx.db.enums import ( MCPAuthenticationPerformer, MCPAuthenticationTyp...
454
15,901
onyx
backend/tests/unit/onyx/server/features/mcp/test_template_header_substitution.py
.py
"""MCP templates apply user and automatic substitutions in one pass.""" import pytest from onyx.server.features.mcp.api import _build_headers_from_template from onyx.server.features.mcp.models import MCPAuthTemplate class TestBuildHeadersFromTemplate: def test_user_email_placeholder_alone_is_substituted(self) -...
70
2,611
onyx
backend/tests/unit/onyx/server/features/mcp/test_mcp_oauth_client_metadata_document.py
.py
import pytest from fastapi import FastAPI from fastapi.testclient import TestClient from onyx.server.auth_check import PUBLIC_ENDPOINT_SPECS, is_route_in_spec_list from onyx.server.features.mcp import client_metadata TEST_WEB_DOMAIN = "https://onyx.example.com" METADATA_ROUTE = "/mcp/oauth/client-metadata" def _bui...
61
1,937
onyx
backend/tests/unit/onyx/server/features/mcp/test_per_user_listing_invariants.py
.py
"""Invariants for the API model returned by the per-user MCP server listing endpoints (`GET /api/mcp/servers`, `GET /api/mcp/servers/persona/{id}`). The shared admin connection config row is cross-user state — it's the OAuth `client_info` registry used by every user of a given MCP server. Per-user state (tokens and re...
239
8,902
onyx
backend/tests/unit/onyx/server/features/mcp/test_admin_credentials_resolver.py
.py
"""`_resolve_admin_credentials` is the per-key "changed flag + mask rejector" used when persisting `admin_credentials` for a per-user API_TOKEN MCP server. Mirrors `_resolve_oauth_credentials` (covered in `test_oauth_credentials_resolver.py`).""" import pytest from onyx.server.features.mcp.api import _resolve_admin_c...
141
5,134
onyx
backend/tests/unit/onyx/server/features/mcp/test_mcp_oauth_refresh.py
.py
"""Regression coverage for SSE-transport MCP OAuth refresh: SSE can't use the SDK's httpx.Auth refresh (open stream), so refresh_mcp_oauth_token_if_expired drives OAuthClientProvider's refresh step directly instead. Exercises the real OAuthClientProvider/OAuthContext/OnyxTokenStorage code — client-auth-method branchin...
551
20,458
onyx
backend/tests/unit/onyx/server/features/mcp/test_build_headers.py
.py
"""Header composition across templates, stored values, and generated auth.""" import json import pytest from onyx.db.enums import MCPAuthenticationType from onyx.db.models import MCPConnectionConfig from onyx.server.features.mcp.credentials import ResolvedMCPCredentials from onyx.server.features.mcp.models import MC...
154
5,318
onyx
backend/tests/unit/onyx/server/features/hierarchy/test_user_access_info.py
.py
"""Unit tests for _get_user_access_info helper function. These tests mock all database operations and don't require a real database. """ from unittest.mock import MagicMock, patch from sqlalchemy.orm import Session from onyx.server.features.hierarchy.api import _get_user_access_info def test_get_user_access_info_...
43
1,342
onyx
backend/tests/unit/onyx/server/features/image_generation/test_image_generation_endpoint.py
.py
import asyncio import base64 import json import threading from collections.abc import Iterator from typing import Any from unittest.mock import patch import pytest from fastapi.responses import StreamingResponse from onyx.error_handling.error_codes import OnyxErrorCode from onyx.error_handling.exceptions import OnyxE...
292
10,419
onyx
backend/tests/unit/onyx/hooks/test_api_dependencies.py
.py
"""Unit tests for the hooks feature gate.""" from unittest.mock import patch import pytest from onyx.error_handling.error_codes import OnyxErrorCode from onyx.error_handling.exceptions import OnyxError from onyx.hooks.api_dependencies import require_hook_enabled class TestRequireHookEnabled: def test_raises_wh...
24
875
onyx
backend/tests/unit/onyx/hooks/test_registry.py
.py
import pytest from onyx.db.enums import HookPoint from onyx.hooks import registry as registry_module from onyx.hooks.registry import get_all_specs, get_hook_point_spec, validate_registry def test_registry_covers_all_hook_points() -> None: """Every HookPoint enum member must have a registered spec.""" assert ...
46
1,604
onyx
backend/tests/unit/onyx/hooks/test_base_spec.py
.py
import pytest from pydantic import BaseModel from onyx.db.enums import HookPoint from onyx.hooks.points.base import HookPointSpec def test_init_subclass_raises_for_missing_attrs() -> None: with pytest.raises(TypeError, match="must define class attributes"): class IncompleteSpec(HookPointSpec): ...
20
585
onyx
backend/tests/unit/onyx/hooks/test_models.py
.py
import pytest from pydantic import ValidationError from onyx.db.enums import HookFailStrategy, HookPoint from onyx.hooks.models import HookCreateRequest, HookUpdateRequest def test_hook_update_request_rejects_empty() -> None: # No fields supplied at all with pytest.raises(ValidationError, match="At least one...
85
3,198
onyx
backend/tests/unit/onyx/hooks/test_query_processing_spec.py
.py
from onyx.db.enums import HookFailStrategy, HookPoint from onyx.hooks.points.query_processing import QueryProcessingSpec def test_hook_point_is_query_processing() -> None: assert QueryProcessingSpec().hook_point == HookPoint.QUERY_PROCESSING def test_default_fail_strategy_is_hard() -> None: assert QueryProc...
62
2,261
onyx
backend/tests/unit/onyx/image_gen/test_generation.py
.py
from types import SimpleNamespace from unittest.mock import MagicMock, patch import pytest from onyx.image_gen.exceptions import ImageGenerationNotConfiguredError from onyx.image_gen.generation import ( generate_images_with_default_config, is_image_generation_configured, ) from onyx.image_gen.interfaces impor...
176
6,251
onyx
backend/tests/unit/onyx/image_gen/test_provider_building.py
.py
import json from unittest.mock import patch import pytest from onyx.image_gen.exceptions import ImageProviderCredentialsError from onyx.image_gen.factory import get_image_generation_provider from onyx.image_gen.interfaces import ImageGenerationProviderCredentials, ReferenceImage from onyx.image_gen.providers.azure_im...
386
13,023
onyx
backend/tests/unit/onyx/llm/test_factory.py
.py
from functools import partial from unittest.mock import MagicMock, patch from onyx.chat.incognito import ( BIFROST_DISABLE_CONTENT_LOGGING_HEADER, incognito_llm_extra_headers, incognito_llm_request_policy, ) from onyx.db.enums import IncognitoRecordMode from onyx.llm.constants import LlmProviderNames from ...
349
12,013
onyx
backend/tests/unit/onyx/llm/test_litellm_monkey_patches.py
.py
from datetime import datetime from typing import Any, cast from unittest import mock from litellm.completion_extras.litellm_responses_transformation.transformation import ( LiteLLMResponsesTransformationHandler, OpenAiResponsesToChatCompletionStreamIterator, ) from litellm.litellm_core_utils.litellm_logging im...
379
12,140
onyx
backend/tests/unit/onyx/llm/test_custom_config_mapping.py
.py
from onyx.llm.constants import LlmProviderNames from onyx.llm.custom_config_mapping import ( get_unsupported_custom_config_keys, map_custom_config_to_model_kwargs, ) def test_bedrock_env_format_keys_map_to_kwargs() -> None: mapping = map_custom_config_to_model_kwargs( model_provider=LlmProviderNam...
242
8,282
onyx
backend/tests/unit/onyx/llm/test_model_response.py
.py
from __future__ import annotations from typing import TYPE_CHECKING, cast import pytest from onyx.llm.model_response import ( ChatCompletionDeltaToolCall, FunctionCall, ModelResponse, ModelResponseStream, from_litellm_model_response, from_litellm_model_response_stream, ) if TYPE_CHECKING: ...
366
11,543
onyx
backend/tests/unit/onyx/llm/test_reasoning_effort_mapping.py
.py
from onyx.llm.models import OPENAI_REASONING_EFFORT, ReasoningEffort # Valid OpenAI reasoning effort values per the API documentation # https://platform.openai.com/docs/api-reference/responses VALID_OPENAI_REASONING_EFFORT_VALUES = frozenset( {"none", "minimal", "low", "medium", "high", "xhigh"} ) def test_opena...
60
2,550
onyx
backend/tests/unit/onyx/llm/test_llm_provider_options.py
.py
from datetime import datetime, timezone import pytest from onyx.llm.well_known_providers.auto_update_models import ( LLMProviderRecommendation, LLMRecommendations, ) from onyx.llm.well_known_providers.constants import ( OPENAI_PROVIDER_NAME, VERTEXAI_PROVIDER_NAME, ) from onyx.llm.well_known_providers...
185
6,298
onyx
backend/tests/unit/onyx/llm/test_resolve_provider_and_model.py
.py
"""An override's model_configuration_id must beat name-based resolution — provider display names are not unique, so only the id routes unambiguously.""" from unittest.mock import MagicMock, patch from onyx.llm.factory import _resolve_provider_and_model _FETCH_MC = "onyx.llm.factory.fetch_model_configuration_by_id" _...
75
2,448
onyx
backend/tests/unit/onyx/llm/test_formatting_reenabled.py
.py
from onyx.llm.utils import model_needs_formatting_reenabled def test_gpt_5_exact_match() -> None: """Test that gpt-5 model name exactly matches.""" assert model_needs_formatting_reenabled("gpt-5") is True def test_o3_exact_match() -> None: """Test that o3 model name exactly matches.""" assert model_...
208
8,318
onyx
backend/tests/unit/onyx/llm/test_llm_exception_classification.py
.py
"""Guards classification order in litellm_exception_to_error_msg: ContextWindowExceededError and ContentPolicyViolationError subclass BadRequestError and must be matched first, or context overflow is mislabeled BAD_REQUEST instead of CONTEXT_TOO_LONG. """ from litellm.exceptions import ( APIError, BadRequestEr...
75
2,591
onyx
backend/tests/unit/onyx/llm/test_tracing_wrap.py
.py
# ruff: noqa: ARG002 """Unit tests for `onyx.llm.tracing_wrap`. Cover: - `LLM.__init_subclass__` auto-wraps `invoke` and `stream` on concrete subclasses - Wrapper is idempotent (double-application is a no-op) - Outer-span guard (``_outer_generation_span_active``) skips fallback when an outer ``generation_span`` is a...
658
24,488
onyx
backend/tests/unit/onyx/llm/test_reasoning_param_fallback.py
.py
"""Guards the degrade-and-retry behavior for provider-rejected reasoning params.""" from typing import Any from unittest.mock import patch import pytest from litellm.exceptions import BadRequestError, RateLimitError from onyx.llm.models import ReasoningEffort, UserMessage from onyx.llm.multi_llm import LitellmLLM, L...
175
5,694
onyx
backend/tests/unit/onyx/llm/test_cost.py
.py
"""Unit tests for split input/output cost and admin per-model overrides (SQLite).""" import logging from collections.abc import Generator from typing import cast import pytest from sqlalchemy import Table, create_engine from sqlalchemy.dialects.postgresql import JSONB as PGJSONB from sqlalchemy.dialects.postgresql im...
486
17,055
onyx
backend/tests/unit/onyx/llm/test_bifrost_routing.py
.py
"""Unit tests for Bifrost's two API-mode routing in LitellmLLM. The surface is selected via a `bifrost_api_mode` value persisted in custom_config; the routing difference is the model= string, which drives litellm's completions->responses bridge. These tests lock that mapping down. """ from unittest.mock import patch ...
94
3,710
onyx
backend/tests/unit/onyx/llm/test_model_map.py
.py
from unittest.mock import patch import litellm from onyx.configs.model_configs import GEN_AI_MODEL_FALLBACK_MAX_TOKENS from onyx.llm.constants import LlmProviderNames from onyx.llm.model_capabilities import ( find_model_obj, get_model_map, model_is_reasoning_model, ) def test_partial_match_in_model_map(...
137
4,731
onyx
backend/tests/unit/onyx/llm/test_portkey_routing.py
.py
"""Unit tests for Portkey's three API-mode routing in LitellmLLM. Portkey is a single provider that can target three API surfaces, selected via a `portkey_api_mode` value persisted in custom_config. The routing differences are entirely: custom_llm_provider, the model= string, and whether the base is coerced to end in ...
109
4,416
onyx
backend/tests/unit/onyx/llm/test_reasoning_effort_override.py
.py
"""Guards parsing of user-selectable reasoning-effort override values.""" import pytest from onyx.llm.models import ReasoningEffort, parse_user_selectable_reasoning_effort @pytest.mark.parametrize( ("value", "expected_effort"), [ ("off", ReasoningEffort.OFF), ("low", ReasoningEffort.LOW), ...
36
1,079
onyx
backend/tests/unit/onyx/llm/test_bedrock_token_limit.py
.py
"""Tests for get_bedrock_token_limit function.""" from unittest.mock import patch from onyx.llm.model_capabilities import get_bedrock_token_limit class TestGetBedrockTokenLimit: """Tests for Bedrock token limit lookup.""" def test_parse_from_model_id_suffix_200k(self) -> None: """Test parsing :200k...
133
5,983
onyx
backend/tests/unit/onyx/llm/test_multi_llm_stream_retry.py
.py
from collections.abc import Iterator from unittest.mock import MagicMock, patch import pytest from litellm.exceptions import Timeout as LiteLLMTimeout from onyx.llm.interfaces import LanguageModelInput from onyx.llm.model_response import Delta, ModelResponseStream, StreamingChoice from onyx.llm.models import UserMess...
91
3,079
onyx
backend/tests/unit/onyx/llm/test_model_is_reasoning.py
.py
import litellm import pytest from onyx.llm import model_capabilities from onyx.llm.model_capabilities import model_is_reasoning_model def test_model_is_reasoning_model() -> None: """Test that reasoning models are correctly identified and non-reasoning models are not""" # Models that should be identified as ...
156
5,787
onyx
backend/tests/unit/onyx/llm/test_token_limit_lookups.py
.py
"""Tests for the token-limit lookup helpers in `onyx.llm.model_capabilities`: `llm_max_input_tokens`, `get_llm_max_output_tokens`, and `get_max_input_tokens`.""" from unittest.mock import patch from onyx.configs.model_configs import GEN_AI_MODEL_FALLBACK_MAX_TOKENS from onyx.llm.model_capabilities import ( get_ll...
228
7,678
onyx
backend/tests/unit/onyx/llm/test_true_openai_model.py
.py
from onyx.llm.constants import LlmProviderNames from onyx.llm.model_capabilities import get_model_map, is_true_openai_model class TestIsTrueOpenAIModel: """Tests for the is_true_openai_model function using real LiteLLM model registry.""" def test_real_openai_gpt4(self) -> None: """Test that real Open...
167
7,395
onyx
backend/tests/unit/onyx/llm/test_multi_llm.py
.py
import os import threading import time from collections.abc import Iterator from contextlib import contextmanager from typing import Any from unittest.mock import ANY, MagicMock, patch import litellm import pytest from litellm.types.utils import ChatCompletionDeltaToolCall, Delta from litellm.types.utils import Functi...
3,169
111,046
onyx
backend/tests/unit/onyx/llm/test_request_context.py
.py
import contextvars from onyx.llm.request_context import ( get_llm_mock_response, reset_llm_mock_response, set_llm_mock_response, ) def test_reset_llm_mock_response_same_context() -> None: token = set_llm_mock_response("mock-response") assert get_llm_mock_response() == "mock-response" reset_l...
28
840
onyx
backend/tests/unit/onyx/llm/test_llm_utils_scrub.py
.py
"""Unit tests for `onyx.llm.utils` helpers, focused on the secret-scrubbing behavior that protects `/admin/llm/test` (and `validate_existing_genai_api_key`) from echoing API keys back through error messages. """ from collections.abc import Iterable from typing import Any from onyx.llm.exceptions import ClassifiedLLME...
274
9,063
onyx
backend/tests/unit/onyx/llm/test_trace_request_params.py
.py
"""Guards that generation spans record the requested effort and the kwargs actually sent.""" from typing import Any from unittest.mock import patch from litellm.exceptions import BadRequestError from onyx.llm.models import ReasoningEffort, UserMessage from onyx.llm.multi_llm import LitellmLLM from onyx.tracing.frame...
75
2,450
onyx
backend/tests/unit/onyx/llm/test_model_name_parser.py
.py
""" Unit tests for LiteLLM model name parser. Tests verify that enrichment data is correctly returned from the parser. """ from onyx.llm.constants import LlmProviderNames from onyx.llm.model_name_parser import parse_litellm_model_name def test_bedrock_model_with_enrichment() -> None: """Test parsing a Bedrock m...
59
2,107
onyx
backend/tests/unit/onyx/llm/test_vision_model_selection_logging.py
.py
""" Unit tests for vision model selection logging in get_default_llm_with_vision. Verifies that operators get clear feedback about: 1. Which vision model was selected and why 2. When the default vision model doesn't support image input 3. When no vision-capable model exists at all """ from unittest.mock import MagicM...
129
4,309
onyx
backend/tests/unit/onyx/llm/conftest.py
.py
""" Test configuration for LLM tests. This module loads model metadata enrichments before running tests so that the model_name_parser has access to the enriched data. """ from collections.abc import Generator import pytest from onyx.llm.litellm_singleton.config import load_model_metadata_enrichments from onyx.llm.m...
23
677
onyx
backend/tests/unit/onyx/llm/prompt_cache/test_processor.py
.py
from __future__ import annotations from unittest.mock import patch from onyx.llm.interfaces import LLMConfig from onyx.llm.models import ChatCompletionMessage, SystemMessage, UserMessage from onyx.llm.prompt_cache import processor as processor_module from onyx.llm.prompt_cache.processor import process_with_prompt_cac...
78
2,667
onyx
backend/tests/unit/onyx/tools/test_tool_runner_chat_files.py
.py
""" Unit tests for chat_files handling in tool_runner.py. These tests verify that chat files are properly passed to PythonTool through the PythonToolOverrideKwargs mechanism. """ from unittest.mock import patch import pytest from onyx.db.models import UserFile from onyx.tools.models import ChatFile, PythonToolOverr...
331
12,317
onyx
backend/tests/unit/onyx/tools/test_search_utils.py
.py
"""Unit tests for search utility functions.""" from typing import NamedTuple import pytest from onyx.tools.tool_implementations.search.search_tool import deduplicate_queries from onyx.tools.tool_implementations.search.search_utils import ( weighted_reciprocal_rank_fusion, ) # ===================================...
573
20,565
onyx
backend/tests/unit/onyx/tools/test_python_tool_availability.py
.py
"""Tests for PythonTool availability based on server_enabled flag and health check. Verifies that PythonTool reports itself as unavailable when either: - CODE_INTERPRETER_BASE_URL is not set, or - CodeInterpreterServer.server_enabled is False in the database, or - The Code Interpreter service health check fails. Also...
265
9,783
onyx
backend/tests/unit/onyx/tools/test_file_reader_tool.py
.py
"""Tests for the FileReaderTool. Verifies: - Tool definition schema is well-formed - File ID validation (allowlist, UUID format) - Character range extraction and clamping - Error handling for missing parameters and non-text files - is_available() reflects DISABLE_VECTOR_DB """ from unittest.mock import MagicMock, pat...
236
7,967
onyx
backend/tests/unit/onyx/tools/test_image_generation_reference_resolution.py
.py
"""Tests for ``ImageGenerationTool._resolve_reference_image_file_ids``. The resolver turns the LLM's ``reference_image_file_ids`` argument into a cleaned list of file IDs to hand to ``_load_reference_images``. It trusts the LLM's picks — the LLM can only see file IDs that actually appear in the conversation (via ``[at...
136
5,427
onyx
backend/tests/unit/onyx/tools/test_coding_agent_repo_setup.py
.py
from types import SimpleNamespace from unittest.mock import MagicMock, patch from onyx.tools.fake_tools import coding_agent def test_coding_agent_downloads_and_extracts_repo_with_existing_policy() -> None: client = MagicMock() client.__enter__.return_value = client client.__exit__.return_value = False ...
50
1,799
onyx
backend/tests/unit/onyx/tools/test_tool_runner.py
.py
from onyx.server.query_and_chat.placement import Placement from onyx.tools.models import ToolCallKickoff from onyx.tools.tool_runner import _merge_tool_calls def _make_tool_call( tool_name: str, tool_args: dict, tool_call_id: str = "call_1", turn_index: int = 0, tab_index: int = 0, ) -> ToolCallKi...
310
10,912
onyx
backend/tests/unit/onyx/tools/test_no_vectordb.py
.py
"""Tests for tool availability when DISABLE_VECTOR_DB is True. Verifies that SearchTool is unavailable, OpenURLTool stays available (crawl-only), and FileReaderTool remains available. """ from unittest.mock import MagicMock, patch import pytest from sqlalchemy.orm import Session # ----------------------------------...
76
2,816
onyx
backend/tests/unit/onyx/tools/test_tool_utils.py
.py
import pytest from onyx.llm.constants import LlmProviderNames from onyx.tools.utils import explicit_tool_calling_supported @pytest.mark.parametrize( "model_provider, model_name, expected_result", [ (LlmProviderNames.ANTHROPIC, "claude-4-sonnet-20250514", True), ( "another-provider...
48
1,599
onyx
backend/tests/unit/onyx/tools/test_tool_llm_names.py
.py
"""Guards built-in tool LLM-facing names against OpenAI's reserved function names. OpenAI reserves certain function names for its own model harness and rejects any request whose tools array defines one of them (400 invalid_request_error: "The function name 'python' is reserved for use by this model."), enforced server...
30
1,400
onyx
backend/tests/unit/onyx/tools/test_open_url_web_search_coupling.py
.py
"""Disabling Web Search in chat must cut off open_url's live web access. OpenURLTool is hidden from the chat tool toggles (chat_selectable=False), so the frontend always includes it in allowed_tool_ids. When WebSearchTool is explicitly excluded, the tool stays available but in indexed-only mode: pasted links are still...
102
3,349
onyx
backend/tests/unit/onyx/tools/test_search_llm_json.py
.py
"""Unit tests for the search-result → LLM surface.""" import json import pytest from onyx.configs.constants import DocumentSource from onyx.context.search.models import InferenceChunk, InferenceSection from onyx.context.search.utils import sandbox_filename_for_document from onyx.tools.tool_implementations.utils impo...
305
10,719
onyx
backend/tests/unit/onyx/tools/test_construct_tools_no_vectordb.py
.py
"""Tests for tool construction when DISABLE_VECTOR_DB is True. Verifies that: - SearchTool.is_available() returns False when vector DB is disabled - OpenURLTool.is_available() returns True when vector DB is disabled (crawl-only) - The force-add SearchTool block is suppressed when DISABLE_VECTOR_DB - FileReaderTool.is_...
196
7,125
onyx
backend/tests/unit/onyx/tools/test_search_tool_time_filter_cache.py
.py
from __future__ import annotations from datetime import datetime, timezone from unittest.mock import MagicMock, patch from onyx.secondary_llm_flows.time_filter import ( DocumentTimeField, TimeFilter, decide_time_filter, ) from onyx.tools.tool_implementations.search.search_tool import SearchTool def _mak...
99
2,995
onyx
backend/tests/unit/onyx/tools/test_mcp_tool_schema.py
.py
"""Tests for MCPTool.tool_definition() schema normalization. MCP servers may legally return `inputSchema` values that omit `properties` (e.g. `{"type": "object"}` for zero-arg tools like AWS Knowledge MCP's `aws___list_regions`). Azure OpenAI rejects such schemas with "object schema missing properties", which breaks e...
238
7,941
onyx
backend/tests/unit/onyx/tools/tool_implementations/websearch/test_websearch_utils.py
.py
from pathlib import Path from onyx.tools.tool_implementations.open_url.models import WebContent from onyx.tools.tool_implementations.web_search.utils import ( inference_section_from_internet_page_scrape, ) CONTENT_FILE = Path(__file__).parent / "data" / "tartan.txt" # inference_section_from_internet_page_scrape ...
210
7,243
onyx
backend/tests/unit/onyx/tools/tool_implementations/websearch/test_brave_client.py
.py
from __future__ import annotations from typing import Any, cast import pytest import requests from fastapi import HTTPException import onyx.tools.tool_implementations.web_search.clients.brave_client as brave_module from onyx.tools.tool_implementations.web_search.clients.brave_client import BraveClient class DummyR...
204
6,466
onyx
backend/tests/unit/onyx/tools/tool_implementations/websearch/test_web_search_tool_run.py
.py
from __future__ import annotations from typing import Any, cast from unittest.mock import MagicMock, patch import pytest from onyx.server.query_and_chat.placement import Placement from onyx.tools.models import ToolCallException, WebSearchToolOverrideKwargs from onyx.tools.tool_implementations.web_search.models impor...
162
6,809
onyx
backend/tests/unit/onyx/tools/tool_implementations/websearch/test_web_search_providers.py
.py
import pytest from onyx.tools.tool_implementations.web_search.clients.brave_client import BraveClient from onyx.tools.tool_implementations.web_search.providers import ( build_search_provider_from_config, provider_requires_api_key, ) from shared_configs.enums import WebSearchProviderType def test_provider_req...
119
4,432
onyx
backend/tests/unit/onyx/tools/tool_implementations/open_url/test_onyx_web_crawler.py
.py
from __future__ import annotations import time from collections.abc import Callable from unittest.mock import MagicMock, patch import pytest from pydantic import BaseModel import onyx.tools.tool_implementations.open_url.onyx_web_crawler as crawler_module from onyx.server.security.models import SSRFProtectionLevel fr...
416
14,331
onyx
backend/tests/unit/onyx/tools/tool_implementations/open_url/test_open_url_failure_messages.py
.py
"""Tests for the failure-message construction in `open_url_tool`. When a URL can't be fetched, the LLM-facing message should include each URL's `failure_reason` so the model knows why and won't retry verbatim. """ from __future__ import annotations from onyx.tools.tool_implementations.open_url.models import FailedFe...
133
5,352
onyx
backend/tests/unit/onyx/tools/tool_implementations/open_url/test_url_normalization.py
.py
"""Unit tests for URL normalization module.""" import pytest from onyx.configs.constants import DocumentSource from onyx.tools.tool_implementations.open_url.open_url_tool import _url_lookup_variants from onyx.tools.tool_implementations.open_url.url_normalization import ( _detect_source_type, normalize_url, ...
350
12,930
onyx
backend/tests/unit/onyx/tools/tool_implementations/open_url/test_snippet_matcher.py
.py
from __future__ import annotations import json import unicodedata # used to verify NFC expansion test preconditions from pathlib import Path import pytest from pydantic import BaseModel, field_validator from onyx.tools.tool_implementations.open_url.snippet_matcher import ( find_snippet_in_content, ) """ We wan...
201
6,119
onyx
backend/tests/unit/onyx/tools/tool_implementations/open_url/test_onyx_web_crawler_playwright_fallback.py
.py
"""Tests for OnyxWebCrawler's Playwright fallback on Cloudflare/bot challenges. The fallback is triggered when the fast `requests` path returns a response that looks like a Cloudflare challenge (HTTP 403, or any 4xx with `cf-ray` / `cf-mitigated` headers, or `Server: cloudflare`). On hit, we try a one-shot headless re...
399
15,856
onyx
backend/tests/unit/onyx/tools/tool_implementations/search/test_search_tool_run.py
.py
from __future__ import annotations from typing import Any, cast from unittest.mock import MagicMock, patch from onyx.configs.constants import DocumentSource, MessageType from onyx.context.search.models import BaseFilters from onyx.server.query_and_chat.placement import Placement from onyx.server.query_and_chat.stream...
347
13,504
onyx
backend/tests/unit/onyx/tools/tool_implementations/python/test_code_interpreter_client.py
.py
"""Unit tests for CodeInterpreterClient streaming-to-batch fallback. When the streaming endpoint (/v1/execute/stream) returns 404 — e.g. because the code-interpreter service is an older version that doesn't support streaming — the client should transparently fall back to the batch endpoint (/v1/execute) and convert th...
681
23,831
onyx
backend/tests/unit/onyx/tools/tool_implementations/python/test_python_tool_upload_cache.py
.py
"""Unit tests for PythonTool file-upload caching. Verifies that PythonTool reuses code-interpreter file IDs across multiple run() calls within the same session instead of re-uploading identical content on every agent loop iteration. """ import json from unittest.mock import MagicMock, patch from onyx.tools.models im...
544
19,164
onyx
backend/tests/unit/onyx/tools/tool_implementations/bash/test_bash_tool.py
.py
"""Unit tests for BashTool. Covers: - Happy path: response shape, emitted start + delta packets. - Missing required ``cmd`` parameter raises ToolCallException. - Exception during execute is caught and surfaces as an error result + delta. - stdout/stderr are truncated at CODE_INTERPRETER_MAX_OUTPUT_LENGTH. - Non-zero e...
516
18,479
onyx
backend/tests/unit/onyx/tools/tool_implementations/coding_agent/test_coding_agent_tool.py
.py
"""Unit tests for CodingAgentTool. Coverage is intentionally narrow — the heavy lifting lives in ``run_coding_agent_call`` and ``BashTool``, both tested separately. This file exists to lock in the wiring this Tool wrapper is responsible for. """ from unittest.mock import MagicMock, patch from onyx.tools.tool_impleme...
40
1,346
onyx
backend/tests/unit/onyx/tools/custom/test_custom_tools.py
.py
import unittest.mock import uuid from typing import Any from unittest.mock import patch import pytest from onyx.server.query_and_chat.placement import Placement from onyx.tools.models import DynamicSchemaInfo, ToolResponse from onyx.tools.tool_implementations.custom.custom_tool import ( CustomToolCallSummary, ...
491
19,165
onyx
backend/tests/unit/onyx/onyxbot/test_slack_blocks.py
.py
from datetime import datetime import pytest import pytz import timeago from onyx.configs.constants import DocumentSource from onyx.context.search.models import SavedSearchDoc from onyx.onyxbot.slack.blocks import _build_sources_blocks def _make_saved_doc( updated_at: datetime | None, semantic_identifier: st...
115
3,550
onyx
backend/tests/unit/onyx/onyxbot/test_slack_channel_config.py
.py
from unittest.mock import MagicMock, patch from onyx.db.slack_channel_config import create_slack_channel_persona def test_create_slack_channel_persona_reuses_existing_persona() -> None: db_session = MagicMock() existing_persona = MagicMock() existing_persona.id = 42 db_session.scalar.return_value = e...
32
921
onyx
backend/tests/unit/onyx/onyxbot/test_handle_regular_answer.py
.py
"""Slack answer handling: references, access checks, and usage attribution.""" from collections.abc import Callable from unittest.mock import MagicMock, patch from uuid import uuid4 import pytest from slack_sdk.errors import SlackApiError from onyx.chat.models import ChatBasicResponse from onyx.context.search.models...
658
22,230
onyx
backend/tests/unit/onyx/onyxbot/test_slack_formatting.py
.py
from onyx.connectors.slack.utils import ( _DEFANG_EXEMPT_REGION_PATTERN, _SUBTEAM_MENTION_PATTERN, ) from onyx.onyxbot.slack.blocks import _clean_markdown_link_text from onyx.onyxbot.slack.formatting import ( _RENDERED_SLACK_LINK_PATTERN, _SLACK_LINK_PATTERN, _convert_slack_links_to_markdown, _n...
387
13,157
onyx
backend/tests/unit/onyx/onyxbot/test_slack_gating.py
.py
"""Tests for Slack bot gating and seat limit enforcement.""" from collections.abc import Generator from typing import Any from unittest.mock import MagicMock, patch import pytest from onyx.server.settings.models import ApplicationStatus # --------------------------------------------------------------------------- #...
601
22,140
onyx
backend/tests/unit/onyx/onyxbot/test_slack_icons.py
.py
from pathlib import Path import pytest from onyx.configs.constants import DocumentSource from onyx.onyxbot.slack.icons import ( _DEFAULT_SOURCE_IMAGE_FILENAME, _PUBLIC_SOURCE_IMAGE_BASE_URL, _SOURCE_IMAGE_FILENAMES, source_to_github_img_link, ) SLACK_SUPPORTED_IMAGE_EXTENSIONS = {".png", ".jpg", ".jp...
44
1,295
onyx
backend/tests/unit/onyx/onyxbot/discord/test_cache_manager.py
.py
"""Unit tests for Discord bot cache manager. Tests for DiscordCacheManager class functionality. """ import asyncio import time from unittest.mock import MagicMock, patch import pytest from onyx.onyxbot.discord.cache import DiscordCacheManager, TenantDiscordData class TestCacheInitialization: """Tests for cach...
521
18,177