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/skills/test_push.py
.py
from __future__ import annotations import io import zipfile 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 Skill, User from onyx.error_handling.error_codes import OnyxErro...
248
8,174
onyx
backend/tests/unit/onyx/skills/test_skill_patch_unset_sentinel.py
.py
"""Unit tests for SkillPatchRequest intent tracking.""" import pytest from pydantic import ValidationError from onyx.db.enums import SkillSharePermission from onyx.server.features.skill.models import SkillPatchRequest def test_omitted_fields_do_not_count_as_updates() -> None: req = SkillPatchRequest(public_perm...
95
2,966
onyx
backend/tests/unit/onyx/skills/test_validation.py
.py
from __future__ import annotations import io from types import SimpleNamespace from typing import cast from unittest.mock import MagicMock from uuid import uuid4 from onyx.db.file_record import FileRecordNotFoundError from onyx.db.models import Skill from onyx.file_store.file_store import FileStore from onyx.skills.v...
54
1,520
onyx
backend/tests/unit/onyx/skills/test_skill_access.py
.py
from uuid import uuid4 import pytest from onyx.auth.schemas import UserRole from onyx.db.enums import SkillAccessLevel, SkillSharePermission from onyx.db.models import Skill, Skill__User, Skill__UserGroup, User from onyx.error_handling.exceptions import OnyxError from onyx.server.features.skill.api import _ensure_can...
319
8,417
onyx
backend/tests/unit/onyx/skills/test_bundle_files.py
.py
import io import zipfile import pytest from onyx.error_handling.exceptions import OnyxError from onyx.skills.bundle import ( build_single_file_bundle, build_skill_md, inspect_custom_bundle, update_custom_bundle_files, ) def _zip(entries: list[tuple[str, bytes]]) -> bytes: output = io.BytesIO() ...
148
4,604
onyx
backend/tests/unit/onyx/skills/test_content.py
.py
import io import zipfile from pathlib import Path from unittest.mock import Mock import pytest from onyx.db.models import Skill from onyx.file_store.file_store import FileStore from onyx.skills import built_in as built_in_module from onyx.skills.built_in import BuiltInSkillDefinition from onyx.skills.content import (...
71
2,109
onyx
backend/tests/unit/onyx/skills/test_pptx_chart_helper.py
.py
"""Tests for the pptx skill's ``scripts/chart.py`` styling helper. matplotlib is a sandbox dependency, not a backend one, so the whole module is skipped when it isn't importable. The helper isn't on the backend import path either — it's loaded from its on-disk skill location. """ from __future__ import annotations i...
63
2,067
onyx
backend/tests/unit/onyx/file_store/test_store_plaintext.py
.py
"""Tests for store_plaintext caching behavior in file_store.utils.""" from io import BytesIO from unittest.mock import MagicMock, patch from uuid import uuid4 from onyx.file_store.models import ChatFileType from onyx.file_store.utils import load_user_file, store_plaintext _UTILS_MODULE = "onyx.file_store.utils" @p...
131
4,562
onyx
backend/tests/unit/onyx/file_store/test_document_batch_storage.py
.py
"""Tests for FileStoreDocumentBatchStorage.""" from unittest.mock import MagicMock, patch from onyx.file_store.document_batch_storage import FileStoreDocumentBatchStorage from onyx.file_store.file_store import S3BackedFileStore _S3_MODULE = "onyx.file_store.file_store" def _mock_db_session() -> MagicMock: sess...
44
1,620
onyx
backend/tests/unit/onyx/file_store/test_delete_file.py
.py
"""Tests for FileStore.delete_file error_on_missing behavior.""" from unittest.mock import MagicMock, patch import pytest _S3_MODULE = "onyx.file_store.file_store" _PG_MODULE = "onyx.file_store.postgres_file_store" def _mock_db_session() -> MagicMock: session = MagicMock() session.__enter__ = MagicMock(ret...
91
3,210
onyx
backend/tests/unit/onyx/chat/test_stop_signal_checker.py
.py
"""Unit tests for stop_signal_checker and chat_processing_checker. These modules are safety-critical — they control whether a chat stream continues or stops. The tests use a simple in-memory CacheBackend stub so no external services are needed. """ from uuid import uuid4 from onyx.cache.interface import CacheBacken...
170
5,359
onyx
backend/tests/unit/onyx/chat/test_build_file_context.py
.py
"""build_file_context must explain empty files to the model. An image-only PDF (or a file whose worker-side processing hasn't finished) used to be injected as a bare "File: x\n\nEnd of File" block, which led models to invent workarounds (web-searching for the document, guessing contents). """ from onyx.chat.chat_util...
75
2,312
onyx
backend/tests/unit/onyx/chat/test_narration_tool_placement.py
.py
"""Regression test for the "disappearing search step" bug. When the model narrates AND calls a tool in the same LLM cycle (e.g. "Let me search Zendesk first." followed by an internal_search call), the narration streams as the assistant message and the tool call is extracted as a kickoff. Both must NOT share the same (...
119
4,191
onyx
backend/tests/unit/onyx/chat/test_incognito_sweep_selection.py
.py
"""Guards which stale incognito uploads the sweep queues for deletion. Two shapes with different fates: an upload no session ever claimed goes without asking anything, and one a session holds goes only once that session's live context is gone. A session that is still live has its orphan clock restarted so it cannot oc...
77
2,800
onyx
backend/tests/unit/onyx/chat/test_organization_profile_prompt.py
.py
"""Guards the Organization Profile system-prompt block: it renders the resolved directory fields when present and is absent when the profile is empty.""" from unittest.mock import patch from onyx.chat.prompt_utils import build_system_prompt from onyx.db.memory import UserInfo, UserMemoryContext def _context(organiz...
39
1,410
onyx
backend/tests/unit/onyx/chat/test_multi_model_streaming.py
.py
"""Unit tests for multi-model streaming validation and DB helpers. These are pure unit tests — no real database or LLM calls required. The validation logic in handle_multi_model_stream fires before any external calls, so we can trigger it with lightweight mocks. """ import threading import time from collections.abc i...
1,030
40,768
onyx
backend/tests/unit/onyx/chat/test_compression.py
.py
"""Unit tests for chat history compression module.""" from datetime import datetime, timedelta, timezone from unittest.mock import MagicMock, patch from onyx.chat.compression import ( SummaryContent, _build_llm_messages_for_summarization, calculate_total_history_tokens, find_summary_for_branch, ge...
591
20,705
onyx
backend/tests/unit/onyx/chat/test_stream_buffer_unit.py
.py
"""Regression coverage for the chat stream buffer: chunk sequencing and cursor reads, compression roundtrip, size-cap truncation, the done marker's TTL switch, and missing-chunk gaps surfacing as non-replayable instead of broken replays.""" import os import zlib from uuid import UUID, uuid4 import pytest from onyx.c...
218
6,606
onyx
backend/tests/unit/onyx/chat/test_incognito_liveness_predicates.py
.py
"""Guards the split between "never started" and "explicitly ended". A session holds no context until its first message, so absence and teardown look identical in Redis. Anything deciding whether to accept new work must read only the tombstone, or attaching a file before sending the first message is rejected as an ende...
62
1,993
onyx
backend/tests/unit/onyx/chat/test_incognito_record_mode.py
.py
"""Guards the incognito recording policy: which mode permits which sink. The mode enum is the only policy object, so these tests pin the full mode x sink matrix. A behavior change that is not also a deliberate edit here is a policy regression. """ from unittest.mock import MagicMock, patch import pytest from onyx.c...
180
6,956
onyx
backend/tests/unit/onyx/chat/test_citation_utils.py
.py
""" Unit tests for citation_utils module. This module tests the collapse_citations function which renumbers citations in text to use the smallest possible numbers while respecting existing mappings. """ from datetime import datetime from onyx.chat.citation_processor import CitationMapping from onyx.chat.citation_uti...
485
19,401
onyx
backend/tests/unit/onyx/chat/test_process_message_mock_llm.py
.py
from unittest.mock import Mock import pytest from onyx.chat import process_message from onyx.chat.models import AnswerStream, StreamingError from onyx.configs import app_configs from onyx.server.query_and_chat.models import MessageResponseIDInfo, SendMessageRequest def test_mock_llm_response_requires_integration_mo...
61
1,867
onyx
backend/tests/unit/onyx/chat/test_llm_step.py
.py
"""Tests for llm_step.py, specifically sanitization and argument parsing.""" from typing import Any import pytest from onyx.chat import llm_step as llm_step_module from onyx.chat.llm_step import ( _extract_tool_call_kickoffs, _increment_turns, _parse_tool_args_to_dict, _resolve_tool_arguments, _X...
1,113
44,371
onyx
backend/tests/unit/onyx/chat/test_multi_model_types.py
.py
"""Unit tests for multi-model answer generation types. Tests cover: - Placement.model_index serialization - MultiModelMessageResponseIDInfo round-trip - SendMessageRequest.llm_overrides backward compatibility - ChatMessageDetail new fields """ from datetime import datetime, timezone from uuid import uuid4 from onyx....
148
4,884
onyx
backend/tests/unit/onyx/chat/test_save_chat.py
.py
"""Tests for save_chat.py. Covers _extract_referenced_file_descriptors and sanitization in save_chat_turn. """ from unittest.mock import MagicMock from pytest import MonkeyPatch from onyx.chat import save_chat from onyx.chat.save_chat import _extract_referenced_file_descriptors from onyx.file_store.models import Ch...
212
6,380
onyx
backend/tests/unit/onyx/chat/test_llm_loop.py
.py
"""Tests for llm_loop.py, including history construction and empty-response paths.""" from typing import Any from unittest.mock import Mock import pytest from onyx.chat.llm_loop import ( _REFUSAL_FINISH_REASONS, EmptyLLMResponseError, _build_empty_llm_response_error, _try_fallback_tool_extraction, ...
1,450
58,548
onyx
backend/tests/unit/onyx/chat/test_context_files.py
.py
"""Tests for the unified context file extraction logic (Phase 5). Covers: - resolve_context_user_files: precedence rule (custom persona supersedes project) - extract_context_files: all-or-nothing context window fit check - Search filter / search_usage determination in the caller """ from unittest.mock import MagicMoc...
645
25,002
onyx
backend/tests/unit/onyx/chat/test_emitter.py
.py
"""Unit tests for the Emitter class. All tests use the streaming mode (merged_queue required). Emitter has a single code path — no standalone bus. """ import queue from onyx.chat.emitter import Emitter from onyx.server.query_and_chat.placement import Placement from onyx.server.query_and_chat.streaming_models import ...
175
5,867
onyx
backend/tests/unit/onyx/chat/test_argument_delta_streaming.py
.py
from typing import Any from unittest.mock import MagicMock, patch from onyx.chat.tool_call_args_streaming import maybe_emit_argument_delta from onyx.server.query_and_chat.placement import Placement from onyx.server.query_and_chat.streaming_models import ToolCallArgumentDelta from onyx.utils.jsonriver import Parser d...
630
23,231
onyx
backend/tests/unit/onyx/chat/test_chat_utils.py
.py
"""Tests for chat_utils.py, specifically get_custom_agent_prompt.""" from io import BytesIO from typing import cast from unittest.mock import MagicMock, patch from onyx.chat.chat_utils import ( _build_tool_call_response_history_message, _get_or_extract_plaintext, convert_chat_history, get_custom_agent...
351
13,234
onyx
backend/tests/unit/onyx/chat/test_citation_processor.py
.py
""" Unit tests for DynamicCitationProcessor. This module contains comprehensive tests for the DynamicCitationProcessor class, which processes streaming tokens from LLMs to extract citations, remove citation markers from output text, and emit CitationInfo objects. Key features tested: - Dynamic citation mapping update...
2,528
95,206
onyx
backend/tests/unit/onyx/chat/test_process_message.py
.py
import pytest from onyx.chat.process_message import ( _resolve_query_processing_hook_result, remove_answer_citations, ) from onyx.error_handling.error_codes import OnyxErrorCode from onyx.error_handling.exceptions import OnyxError from onyx.hooks.executor import HookSkipped, HookSoftFailed from onyx.hooks.poin...
122
4,550
onyx
backend/tests/unit/onyx/indexing/test_embedder.py
.py
from collections.abc import Generator from unittest.mock import Mock, patch import pytest from onyx.configs.constants import DocumentSource from onyx.connectors.models import Document, TextSection from onyx.indexing.embedder import DefaultIndexingEmbedder from onyx.indexing.models import ChunkEmbedding, DocAwareChunk...
101
3,237
onyx
backend/tests/unit/onyx/indexing/test_document_chunker.py
.py
import io import pytest from chonkie import SentenceChunker from onyx.configs.constants import SECTION_SEPARATOR, DocumentSource from onyx.connectors.models import ( IndexingDocument, Section, SectionType, TabularSection, ) from onyx.indexing.chunking import DocumentChunker from onyx.indexing.chunking...
834
28,625
onyx
backend/tests/unit/onyx/indexing/test_vespa.py
.py
from http import HTTPStatus from typing import Any import httpx import pytest from sqlalchemy.orm import Session from onyx.db.engine.sql_engine import get_sqlalchemy_engine from onyx.document_index.document_index_utils import get_both_index_properties from onyx.document_index.vespa_constants import DOCUMENT_ID_ENDPOI...
96
3,401
onyx
backend/tests/unit/onyx/indexing/test_chunker.py
.py
from typing import Any from unittest.mock import Mock import pytest from onyx.configs.app_configs import USE_CHUNK_SUMMARY, USE_DOCUMENT_SUMMARY from onyx.configs.constants import DocumentSource from onyx.connectors.models import Document, TextSection from onyx.indexing.chunker import Chunker from onyx.indexing.embed...
110
3,608
onyx
backend/tests/unit/onyx/indexing/test_personas_in_chunks.py
.py
"""Tests that persona IDs are correctly propagated through the indexing pipeline. Covers Phase 1 (schema plumbing) and Phase 2 (write at index time) of the unify-assistant-project-files plan. """ from unittest.mock import MagicMock, patch from uuid import uuid4 from onyx.access.models import DocumentAccess from onyx...
194
5,907
onyx
backend/tests/unit/onyx/indexing/test_persistent_indexing_helpers.py
.py
"""Unit tests for the PERSISTENT_INDEXING catch-all helpers in `onyx.indexing.persistent_indexing`.""" from unittest.mock import MagicMock, patch import pytest from onyx.configs.constants import DocumentSource from onyx.connectors.models import Document, TextSection from onyx.indexing.persistent_indexing import ( ...
158
5,227
onyx
backend/tests/unit/onyx/indexing/test_tabular_section_chunker.py
.py
"""End-to-end tests for `TabularChunker.chunk_section`. Each test is structured as: INPUT — the CSV text passed to the chunker + token budget + link EXPECTED — the exact chunk texts the chunker should emit ACT — a single call to `chunk_section` ASSERT — literal equality against the expected c...
1,135
49,837
onyx
backend/tests/unit/onyx/indexing/test_embed_chunks_in_batches.py
.py
"""Unit tests for _embed_chunks_to_store. Tests cover: - Single batch, no failures - Multiple batches, no failures - Failure in a single batch - Cross-batch document failure scrubbing - Later batches skip already-failed docs - Empty input - All chunks fail """ from collections.abc import Callable from u...
391
13,809
onyx
backend/tests/unit/onyx/indexing/test_censoring.py
.py
import os from unittest.mock import MagicMock, patch import pytest from onyx.configs.constants import DocumentSource from onyx.context.search.models import InferenceChunk from onyx.db.models import User from onyx.utils.variable_functionality import fetch_ee_implementation_or_noop _post_query_chunk_censoring = fetch_...
204
7,534
onyx
backend/tests/unit/onyx/indexing/test_indexing_pipeline.py
.py
import random import threading import time from datetime import datetime, timezone from typing import Any, List, cast from unittest.mock import MagicMock, Mock, patch import pytest from onyx.connectors.models import ( Document, DocumentSource, ImageSection, TabularSection, TextSection, ) from onyx...
1,175
41,133
onyx
backend/tests/unit/onyx/indexing/test_document_push.py
.py
"""Unit tests for the config-driven document push (non-EE).""" from collections.abc import Iterator from unittest.mock import MagicMock, patch import httpx import pytest from onyx.indexing.document_push import ( DocumentPushPayload, get_document_push_config, push_document_via_config, ) _MODULE = "onyx.i...
124
4,039
onyx
backend/tests/unit/onyx/indexing/conftest.py
.py
import pytest from onyx.indexing.embedder import DefaultIndexingEmbedder from onyx.indexing.indexing_heartbeat import IndexingHeartbeatInterface class MockHeartbeat(IndexingHeartbeatInterface): def __init__(self) -> None: self.call_count = 0 def should_stop(self) -> bool: return False d...
31
724
onyx
backend/tests/unit/onyx/secondary_llm_flows/test_document_filter.py
.py
from collections.abc import Iterator from contextlib import contextmanager from unittest.mock import MagicMock, patch from onyx.configs.chat_configs import SECONDARY_LLM_FLOW_TIMEOUT_S from onyx.configs.constants import DocumentSource from onyx.context.search.models import ( ContextExpansionType, InferenceChun...
155
4,899
onyx
backend/tests/unit/onyx/secondary_llm_flows/test_chat_session_naming.py
.py
from typing import cast from unittest.mock import MagicMock, patch from uuid import uuid4 from onyx.configs.constants import MessageType from onyx.db.models import ChatMessage from onyx.error_handling.error_codes import OnyxErrorCode from onyx.error_handling.exceptions import OnyxError from onyx.secondary_llm_flows.ch...
66
2,179
onyx
backend/tests/unit/onyx/secondary_llm_flows/test_source_filter.py
.py
from __future__ import annotations from contextlib import nullcontext from unittest.mock import MagicMock, patch from onyx.configs.constants import DocumentSource, MessageType from onyx.llm.models import UserMessage from onyx.secondary_llm_flows.source_filter import SearchCycle, decide_search_scope from onyx.tools.mo...
148
5,122
onyx
backend/tests/unit/onyx/secondary_llm_flows/test_time_filter.py
.py
from __future__ import annotations from contextlib import nullcontext from datetime import datetime, timezone from unittest.mock import MagicMock, patch from onyx.configs.constants import MessageType from onyx.context.search.models import BaseFilters, TimeRange from onyx.llm.models import UserMessage from onyx.second...
245
8,670
onyx
backend/tests/unit/onyx/configs/test_google_embedding_configs.py
.py
import pytest from onyx.configs.embedding_configs import SUPPORTED_EMBEDDING_MODELS @pytest.mark.parametrize( "model_name", ["google/gemini-embedding-2", "google/gemini-embedding-2-preview"], ) def test_supported_embedding_models_include_gemini_embedding_2( model_name: str, ) -> None: gemini_embeddin...
20
630
onyx
backend/tests/unit/onyx/configs/test_sentry.py
.py
from typing import cast from unittest.mock import MagicMock, patch from sentry_sdk.types import Event import onyx.configs.sentry as sentry_module from onyx.configs.sentry import _add_instance_tags def _event(data: dict) -> Event: """Helper to create a Sentry Event from a plain dict for testing.""" return ca...
88
3,219
onyx
backend/tests/unit/onyx/configs/test_idp_claim_map_parsing.py
.py
"""Guards the IDP_PROFILE_CLAIM_MAP env parsing: every ignored shape must warn, since a silently dropped map is invisible misconfiguration.""" import logging from onyx.configs.app_configs import parse_idp_claim_map def test_valid_map_parses() -> None: raw = '{"department": ["dept", "division"], "country": ["c"]...
39
1,254
onyx
backend/tests/unit/onyx/configs/test_sentry_scrubber.py
.py
"""Guards the Sentry credential hardening: 1. ``build_event_scrubber()`` redacts a provider API key nested in a captured ``headers`` dict (e.g. litellm's outbound request, where the key lives under the hyphenated ``x-api-key``) while preserving non-sensitive fields. 2. ``init_sentry()`` actually wires the creden...
76
2,802
onyx
backend/tests/unit/onyx/configs/test_object_storage_credentials.py
.py
from onyx.configs.app_configs import _uses_default_object_storage_credentials def test_default_credentials_detected_against_minio() -> None: # MinIO endpoint set + the well-known default => flagged. assert ( _uses_default_object_storage_credentials( "http://minio:9000", "minioadmin", "mini...
50
1,488
onyx
backend/tests/unit/onyx/configs/test_cohere_embedding_configs.py
.py
from onyx.configs.embedding_configs import SUPPORTED_EMBEDDING_MODELS def test_supported_embedding_models_include_cohere_embed_v4() -> None: cohere_embed_v4_models = [ model for model in SUPPORTED_EMBEDDING_MODELS if model.name == "cohere/embed-v4.0" ] # One FLOAT-precision entry ...
14
488
onyx
backend/tests/unit/onyx/configs/test_postgres_pool_pre_ping.py
.py
import importlib import os from types import ModuleType from unittest.mock import patch def _reload_app_configs() -> ModuleType: """Reload the module so the env var is re-read at import time.""" import onyx.configs.app_configs as module return importlib.reload(module) def test_postgres_pool_pre_ping_de...
36
1,353
onyx
backend/tests/unit/onyx/document_index/test_disabled_document_index.py
.py
"""Tests for DisabledDocumentIndex — verifies all methods raise RuntimeError. This is the safety net for the DISABLE_VECTOR_DB feature. Every method on DisabledDocumentIndex must raise RuntimeError with the standard error message so any accidental vector-DB call is caught immediately. """ import re import pytest fr...
100
3,377
onyx
backend/tests/unit/onyx/document_index/vespa/test_vespa_batch_flush.py
.py
"""Unit tests for VespaDocumentIndex.index(). These tests mock all external I/O (HTTP calls, thread pools) and verify the streaming logic, ID cleaning/mapping, and DocumentInsertionRecord construction. """ from unittest.mock import MagicMock, patch from onyx.access.models import DocumentAccess from onyx.configs.cons...
148
4,796
onyx
backend/tests/unit/onyx/document_index/vespa/shared_utils/test_utils.py
.py
from onyx.utils.text_processing import remove_invalid_unicode_chars def test_remove_invalid_unicode_chars() -> None: """Test that invalid Unicode characters are properly removed.""" # Test removal of illegal XML character 0xFDDB text_with_illegal_char = "Valid text \ufddb more text" sanitized = remove...
47
2,119
onyx
backend/tests/unit/onyx/document_index/opensearch/test_index_pair_secondary_missing.py
.py
"""Unit tests for the missing-doc (404) conversion paths. Pure-Python seams: - `OpenSearchDocumentIndex.update` keeps processing requests past a missing-doc one and reports only the docs that were actually missing (chunk -> doc mapping). - `OpenSearchIndexPair.update` lets PRESENT (primary) write, then converts a ...
146
6,035
onyx
backend/tests/unit/onyx/document_index/opensearch/test_get_doc_chunk_id.py
.py
import pytest from onyx.document_index.interfaces_new import TenantState from onyx.document_index.opensearch.constants import DEFAULT_MAX_CHUNK_SIZE from onyx.document_index.opensearch.schema import get_opensearch_doc_chunk_id from onyx.document_index.opensearch.string_filtering import ( MAX_DOCUMENT_ID_ENCODED_LE...
203
8,550
onyx
backend/tests/unit/onyx/document_index/opensearch/test_opensearch_auth.py
.py
import importlib import os from unittest.mock import MagicMock, patch import pytest from opensearchpy import Urllib3AWSV4SignerAuth import onyx.configs.app_configs as app_configs from onyx.document_index.opensearch.client import OpenSearchClient from onyx.document_index.opensearch.constants import OpenSearchAuthMetho...
85
2,733
onyx
backend/tests/unit/onyx/document_index/opensearch/test_opensearch_tls.py
.py
import importlib import os from unittest.mock import patch import certifi import pytest from onyx.document_index.opensearch.client import OpenSearchClient _OS_TLS_ENV = ( "OPENSEARCH_VERIFY_CERTS", "OPENSEARCH_CA_CERTS", "OPENSEARCH_CLIENT_CERT", "OPENSEARCH_CLIENT_KEY", ) # --- client wiring -----...
78
2,575
onyx
backend/tests/unit/onyx/document_index/opensearch/test_port_copy.py
.py
"""Unit coverage for the reindex-port copier's mid-batch deletion guard. `copy_present_chunks_to_future` re-checks document existence right before the create-only write (after the slow re-embed) so a doc deleted while the batch was being read/embedded is not resurrected into the FUTURE index. """ from unittest.mock i...
251
9,414
onyx
backend/tests/unit/onyx/document_index/opensearch/test_opensearch_batch_flush.py
.py
from unittest.mock import MagicMock, patch from onyx.access.models import DocumentAccess from onyx.configs.constants import DocumentSource from onyx.connectors.models import Document, TextSection from onyx.document_index.interfaces_new import IndexingMetadata, TenantState from onyx.document_index.opensearch.opensearch...
220
7,511
onyx
backend/tests/unit/onyx/document_index/opensearch/test_time_cutoff_filter.py
.py
"""Pins how created_at_range / updated_at_range turn into range clauses and when undated documents are included, via `DocumentQuery._get_search_filters` (a pure DSL builder, no live OpenSearch). Intent-to-range mapping: document_index/FILTER_SEMANTICS.md ("Time filtering"). """ from datetime import datetime, timedelta...
200
8,284
onyx
backend/tests/unit/onyx/document_index/opensearch/test_document_chunk_serialization.py
.py
"""Unit tests for DocumentChunk datetime (de)serialization. `created_at` and `last_updated` are stored in OpenSearch as epoch seconds. These pin that the pydantic model serializes tz-aware datetimes to epoch ints, parses them back to UTC datetimes, and omits the fields entirely when unset. """ from datetime import da...
79
2,549
onyx
backend/tests/unit/onyx/db/test_delete_user.py
.py
from typing import Any from unittest.mock import MagicMock, patch from uuid import UUID, uuid4 from onyx.db.models import ( DocumentSet, DocumentSet__User, Persona, Persona__User, SamlAccount, User__UserGroup, ) from onyx.db.users import delete_user_from_db def _mock_user( user_id: UUID |...
150
4,669
onyx
backend/tests/unit/onyx/db/test_user_usage_reset.py
.py
"""Admin resets clear one user's active enforcement window.""" import datetime import uuid 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 import UUID...
138
4,529
onyx
backend/tests/unit/onyx/db/test_llm_sync.py
.py
"""Tests for LLM provider model sync functionality.""" from unittest.mock import MagicMock, patch import pytest from onyx.db.enums import LLMModelFlowType from onyx.db.llm import sync_model_configurations from onyx.server.manage.llm.models import SyncModelEntry def _make_existing_model(name: str, flow_types: list[...
278
9,526
onyx
backend/tests/unit/onyx/db/test_is_limited_user.py
.py
"""Unit tests for is_limited_user() in onyx.db.users.""" from unittest.mock import MagicMock from onyx.db.enums import AccountType from onyx.db.users import is_limited_user class TestIsLimitedUser: def test_anonymous_user_is_limited(self) -> None: user = MagicMock() user.account_type = AccountTy...
44
1,513
onyx
backend/tests/unit/onyx/db/test_chat_sessions.py
.py
"""Tests for get_chat_sessions_by_user filtering behavior. Verifies that failed chat sessions (those with only SYSTEM messages) are correctly filtered out while preserving recently created sessions, matching the behavior specified in PR #7233. """ from datetime import datetime, timedelta, timezone from unittest.mock ...
223
7,394
onyx
backend/tests/unit/onyx/db/test_index_attempt_errors.py
.py
"""Tests for get_index_attempt_errors_across_connectors.""" from datetime import datetime, timezone from unittest.mock import MagicMock from onyx.db.index_attempt import get_index_attempt_errors_across_connectors from onyx.db.models import IndexAttemptError def _make_error( id: int = 1, cc_pair_id: int = 1,...
86
2,837
onyx
backend/tests/unit/onyx/db/test_projects_upload_task_expiry.py
.py
""" Unit test verifying that the upload API path sends tasks with expires=. The upload_files_to_user_files_with_indexing function must include expires= on every send_task call to prevent phantom task accumulation if the worker is down or slow. """ from unittest.mock import MagicMock, patch from uuid import uuid4 fro...
67
2,090
onyx
backend/tests/unit/onyx/db/test_scim_dal.py
.py
import logging from unittest.mock import MagicMock, patch from uuid import uuid4 import pytest from ee.onyx.db.scim import ScimDAL from onyx.db.models import ScimGroupMapping, ScimToken, ScimUserMapping, User from tests.unit.onyx.db.conftest import model_attrs class TestScimDALTokens: """Tests for ScimDAL token...
236
7,932
onyx
backend/tests/unit/onyx/db/test_dal.py
.py
from unittest.mock import MagicMock, patch import pytest from onyx.db.dal import DAL class TestDALSessionDelegation: """Verify that DAL methods delegate correctly to the underlying session.""" def test_commit(self) -> None: session = MagicMock() dal = DAL(session) dal.commit() ...
110
3,916
onyx
backend/tests/unit/onyx/db/test_voice.py
.py
"""Unit tests for onyx.db.voice module.""" from unittest.mock import MagicMock from uuid import uuid4 import pytest from onyx.db.models import VoiceProvider from onyx.db.voice import ( MAX_VOICE_PLAYBACK_SPEED, MIN_VOICE_PLAYBACK_SPEED, deactivate_stt_provider, deactivate_tts_provider, delete_voi...
557
19,019
onyx
backend/tests/unit/onyx/db/test_email_reconcile.py
.py
"""Guards how a user is moved onto a new address after an IdP rename. The replaced address has to land in `prior_emails`, or the user loses every document whose indexed ACL still names it until its connector re-syncs. """ from types import SimpleNamespace from typing import cast from unittest.mock import MagicMock fr...
149
4,664
onyx
backend/tests/unit/onyx/db/test_external_app_auth_template.py
.py
"""Unit tests for `validate_auth_template`.""" from __future__ import annotations import json from typing import Any import pytest from onyx.db.external_app import resolve_masked_credentials, validate_auth_template from onyx.error_handling.exceptions import OnyxError from onyx.utils.encryption import mask_string fr...
96
2,788
onyx
backend/tests/unit/onyx/db/test_slack_service_account.py
.py
from unittest.mock import MagicMock, patch from onyx.auth.schemas import UserRole from onyx.configs.constants import SLACK_SERVICE_ACCOUNT_EMAIL from onyx.db.enums import AccountType from onyx.db.users import get_or_create_slack_service_account def test_create_slack_service_account() -> None: db_session = MagicM...
34
1,226
onyx
backend/tests/unit/onyx/db/test_usage.py
.py
"""Unit tests for tenant usage tracking and limits.""" from datetime import datetime, timezone from unittest.mock import MagicMock, patch import pytest from onyx.db.usage import ( TenantUsageStats, UsageLimitExceededError, UsageType, check_usage_limit, get_current_window_start, get_or_create_...
336
11,945
onyx
backend/tests/unit/onyx/db/test_user_usage.py
.py
"""Unit tests for the per-user usage ledger. `record_user_usage` is Postgres-only (pg_insert upsert); its unit tests mock the session like tenant usage. Read-path helpers still run against in-memory SQLite seeded with ORM inserts.""" import datetime import sqlite3 from collections.abc import Generator from typing imp...
569
21,290
onyx
backend/tests/unit/onyx/db/test_user_email_alias_release.py
.py
"""Guards that claiming an address revokes it as anyone else's alias. A prior address keeps granting its former holder access to documents whose indexed ACLs still name it. That grant is only safe while the address belongs to nobody else, so every `User` email write has to release it. """ from unittest.mock import Ma...
83
3,039
onyx
backend/tests/unit/onyx/db/test_assign_default_groups.py
.py
""" Unit tests for assign_user_to_default_groups__no_commit in onyx.db.users. Covers: 1. Standard/service-account users get assigned to the correct default group 2. BOT, EXT_PERM_USER, ANONYMOUS account types are skipped 3. Missing default group raises RuntimeError 4. Already-in-group is a no-op 5. IntegrityError race...
176
5,590
onyx
backend/tests/unit/onyx/db/test_persona_display_priority.py
.py
from types import SimpleNamespace from unittest.mock import MagicMock import pytest from onyx.db.persona import update_personas_display_priority def _persona(persona_id: int, display_priority: int) -> SimpleNamespace: return SimpleNamespace(id=persona_id, display_priority=display_priority) def test_update_dis...
58
1,607
onyx
backend/tests/unit/onyx/db/test_chat_message_cleanup.py
.py
"""Regression tests for delete_messages_and_files_from_chat_session. Verifies that user-owned files (those with user_file_id) are never deleted during chat session cleanup — only chat-only files should be removed. """ from unittest.mock import MagicMock, call, patch from uuid import uuid4 from onyx.db.chat import de...
99
2,985
onyx
backend/tests/unit/onyx/db/test_tools.py
.py
from unittest.mock import MagicMock from uuid import uuid4 from onyx.db import tools as tools_mod def test_create_tool_call_no_commit_sanitizes_fields() -> None: mock_session = MagicMock() tool_call = tools_mod.create_tool_call_no_commit( chat_session_id=uuid4(), parent_chat_message_id=1, ...
28
934
onyx
backend/tests/unit/onyx/db/conftest.py
.py
"""Fixtures for unit-testing DAL classes with mocked sessions.""" from typing import Any from unittest.mock import MagicMock import pytest from sqlalchemy.orm import Session from ee.onyx.db.scim import ScimDAL def model_attrs(obj: object) -> dict[str, Any]: """Extract user-set attributes from a SQLAlchemy mode...
32
919
onyx
backend/tests/unit/onyx/db/engine/test_engine_disposal.py
.py
"""Verify that all Postgres connection pools are disposed on app shutdown. Regression test for an observed leak under ``uvicorn --reload``: each worker restart spawned new pools without disposing the prior worker's pools, so Postgres held the orphaned connections until its server-side timeouts kicked them out. After a...
178
7,309
onyx
backend/tests/unit/onyx/db/engine/test_postgres_tcp_keepalives.py
.py
import importlib import os from types import ModuleType from unittest.mock import patch def _reload_app_configs() -> ModuleType: """Reload the module so the env vars are re-read at import time.""" import onyx.configs.app_configs as module return importlib.reload(module) def _reload_sql_engine() -> Modu...
110
4,075
onyx
backend/tests/unit/onyx/db/engine/test_tenant_utils.py
.py
"""Tests for onyx.db.engine.tenant_utils.""" import pytest from onyx.db.engine.tenant_utils import validate_tenant_id class TestValidateTenantId: """Tests for validate_tenant_id - validates tenant ID format for SQL safety.""" @pytest.mark.parametrize( "tenant_id", [ # Standard U...
68
2,677
onyx
backend/tests/unit/onyx/db/engine/test_postgres_ssl.py
.py
import datetime as dt import importlib import os import ssl from types import ModuleType from unittest.mock import patch import certifi import pytest from cryptography import x509 from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import rsa from cryptograph...
379
14,024
onyx
backend/tests/unit/onyx/cache/test_redis_backend.py
.py
from __future__ import annotations import threading from queue import Queue from types import SimpleNamespace from typing import cast from unittest.mock import MagicMock import pytest from redis.exceptions import LockNotOwnedError from redis.lock import Lock as RedisLock from onyx.cache.interface import CacheLockLos...
97
2,890
onyx
backend/tests/unit/onyx/redis/test_redis_mtls.py
.py
import importlib import os from collections.abc import Generator from pathlib import Path from unittest.mock import patch from urllib.parse import quote import pytest import onyx.redis.redis_pool as redis_pool _REDIS_TLS_ENV = ( "REDIS_SSL", "REDIS_SSL_CERTFILE", "REDIS_SSL_KEYFILE", "REDIS_SSL_CA_CE...
170
6,377
onyx
backend/tests/unit/onyx/redis/test_redis_sentinel.py
.py
import importlib import os from collections.abc import Iterator from contextlib import contextmanager from typing import cast from unittest.mock import patch import onyx.redis.redis_pool as redis_pool _SENTINELS = [("s1", 26379), ("s2", 26379)] # --- app Redis (sync + async) connection routing ---------------------...
313
12,037
onyx
backend/tests/unit/background/celery/test_celery_utils.py
.py
"""Unit tests for extract_ids_from_runnable_connector metrics instrumentation.""" from collections.abc import Iterator from unittest.mock import MagicMock import pytest from onyx.background.celery.celery_utils import extract_ids_from_runnable_connector from onyx.connectors.interfaces import SlimConnector from onyx.c...
157
5,812
onyx
backend/tests/unit/server/documents/test_stage_metric_residual.py
.py
"""Unit tests for the BATCH_UNACCOUNTED residual synthesis. ``synthesize_unaccounted`` is a pure function over stage snapshots, so it is tested without a DB. Covers the residual math, the in-span component set, the clamp, and the absent-BATCH_TOTAL case. """ from onyx.db.index_attempt_metrics_models import STAGE_SCOP...
136
4,990
onyx
backend/tests/unit/server/metrics/test_connector_state_metrics.py
.py
"""Unit tests for the DB-snapshot connector state metrics collector.""" from contextlib import nullcontext from datetime import datetime, timedelta, timezone from threading import Event, Thread from unittest.mock import MagicMock import pytest from prometheus_client import CollectorRegistry import onyx.server.metric...
255
7,818
onyx
backend/tests/unit/server/metrics/test_metrics_server.py
.py
"""Tests for the Prometheus metrics server module.""" import socket import urllib.request from collections.abc import Iterator from typing import Any from unittest.mock import MagicMock, patch from wsgiref.simple_server import WSGIServer import pytest from onyx.server.metrics.metrics_server import _DEFAULT_PORTS, st...
283
11,254
onyx
backend/tests/unit/server/metrics/test_celery_task_metrics.py
.py
"""Tests for generic Celery task lifecycle Prometheus metrics.""" import time from collections.abc import Iterator from unittest.mock import MagicMock import pytest from onyx.background.celery.apps.app_base import on_before_task_publish from onyx.server.metrics.celery_task_metrics import ( TASK_COMPLETED, TA...
207
6,461
onyx
backend/tests/unit/server/metrics/test_metrics_auth.py
.py
"""Unit tests for the /metrics bearer-token auth dependency. Auth is required by default; ``DISABLE_METRICS_AUTH`` is the explicit opt-out. """ from unittest.mock import MagicMock import pytest from onyx.error_handling.error_codes import OnyxErrorCode from onyx.error_handling.exceptions import OnyxError from onyx.s...
83
3,323