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/external_dependency_unit/craft/conftest.py
.py
"""Fixtures for build mode tests.""" from __future__ import annotations import hashlib import io import zipfile from collections.abc import Callable, Generator, Iterable from datetime import datetime, timezone from typing import Any from uuid import UUID, uuid4 import pytest from fastapi_users.password import Passwo...
373
12,155
onyx
backend/tests/external_dependency_unit/search_settings/test_index_swap_workflow.py
.py
"""Workflow-level test for the INSTANT index swap. When `check_and_perform_index_swap` runs against an `INSTANT` switchover, it calls `delete_all_documents_for_connector_credential_pair` for each cc_pair. This test exercises that full workflow end-to-end and asserts that the attached `Document.file_id`s are also reape...
193
6,873
onyx
backend/tests/external_dependency_unit/search_settings/test_search_settings.py
.py
"""Tests that search settings with contextual RAG are properly propagated to the indexing pipeline's LLM configuration.""" from unittest.mock import MagicMock, patch import pytest from sqlalchemy.orm import Session from onyx.context.search.models import ( SavedSearchSettings, SearchSettingsCreationRequest, )...
617
22,531
onyx
backend/tests/external_dependency_unit/auth/test_mobile_oauth_registration.py
.py
"""Regression guard: the mobile Google OAuth surface must register whenever env Google OAuth credentials are configured. get_application() reads OAUTH_ENABLED and the client credentials as module globals at call time, so monkeypatching boots the OAuth-enabled surface in-process. Building the app also runs check_router...
32
1,250
onyx
backend/tests/external_dependency_unit/auth/test_mobile_sso_bridge.py
.py
"""External-dependency-unit tests for the mobile SSO bridge on the shared OAuth router (`get_oauth_router`), the highest-blast-radius change in the mobile-auth work — it edits code that web Google login also runs. Uses a stub OAuth client + mocked strategy/backend (à la `test_oidc_pkce.py`), but a REAL Redis (the one-...
318
11,702
onyx
backend/tests/external_dependency_unit/auth/test_oidc_multi_live_idp.py
.py
"""Live-IdP coverage for the DB-backed multi-provider OIDC login against a real OIDC server. Two providers run on one instance, so these guard the parts that only break in a real authorization-code flow: discovery, code exchange, userinfo and session issuance end to end, the per-provider gates that reject a login (emai...
393
15,385
onyx
backend/tests/external_dependency_unit/auth/test_mobile_sso_code_store.py
.py
"""External-dependency-unit tests for the mobile SSO one-time code store. Runs against a real Redis. Pins the security contract that protects the custom-scheme deep link: single-use redemption, a short TTL, and PKCE (S256) binding so a hijacked code is useless without the matching verifier. """ import asyncio import ...
120
4,623
onyx
backend/tests/external_dependency_unit/auth/test_sso_login_discovery.py
.py
"""Guard the cloud SSO discovery contract. Discovery runs before the visitor has authenticated, so it must answer only about workspaces the address already belongs to, must not accept an invitation on their behalf, and must not distinguish "no such workspace" from "workspace without SSO" in what it returns. """ from ...
201
7,456
onyx
backend/tests/external_dependency_unit/auth/test_session_rejection_contract.py
.py
""" The strategy's classification must survive the fastapi-users plumbing (which collapses invalid tokens to None) and land as an error_code in the /me 403 body. The classification matrix lives in test_session_token_strategy.py. """ import json import secrets from datetime import datetime, timedelta, timezone from typ...
82
2,824
onyx
backend/tests/external_dependency_unit/auth/test_sso_admin_api.py
.py
"""Guard the SSO admin API contract: secrets never persist masked, config merges stay partial, conflicting or missing providers are reported, and only provider types the deployment can actually route are configurable. The API must never persist masked secrets as real config values. """ from collections.abc import Gen...
646
22,797
onyx
backend/tests/external_dependency_unit/auth/test_jwt_passthrough.py
.py
""" External-IdP JWT passthrough tests (JWT_PUBLIC_KEY_URL): a real HTTP endpoint serves the verification key (JWKS and PEM), RS256 bearer tokens flow through the production _check_for_saml_and_jwt path against real Postgres. This is deployed customer surface (gateways / Entra minting JWTs for Onyx APIs) with no other...
274
8,842
onyx
backend/tests/external_dependency_unit/auth/test_session_token_strategy.py
.py
""" Redis session-token tests: embedded expiry, grace TTL, tombstones, and rejection classification. Real Redis + Postgres, strategy called directly. The request-level 403 contract lives in test_session_rejection_contract.py. """ import contextvars import json import secrets from datetime import datetime, timedelta, t...
342
11,787
onyx
backend/tests/external_dependency_unit/auth/conftest.py
.py
from collections.abc import Generator import pytest import onyx.db.engine.async_sql_engine as async_sql_engine @pytest.fixture(autouse=True) def null_pool_async_engine( monkeypatch: pytest.MonkeyPatch, ) -> Generator[None, None, None]: # Pooled asyncpg connections bind to the creating loop; NullPool keeps t...
19
631
onyx
backend/tests/external_dependency_unit/craft_helm/test_pod_spec.py
.py
"""Pod spec invariants for the Kubernetes sandbox pod. The pod has one app container — `sandbox` (agent) — plus a native Kubernetes sidecar implemented as a restartable init container named `sidecar`. They share a single image with different entrypoints. The asymmetries between them carry the security model: - `san...
659
24,923
onyx
backend/tests/external_dependency_unit/craft_helm/test_sandbox_image_prepuller.py
.py
"""Invariants for the sandbox image-prepull DaemonSet. The DaemonSet keeps the sandbox image resident on every node in the sandbox pool so a user's first sandbox there doesn't pay the pull. Four properties make it work: - It references the same image as the sandbox pods. A drifted tag pins layers nobody uses wh...
375
15,389
onyx
backend/tests/external_dependency_unit/natural_language_processing/test_query_embedding_cache.py
.py
"""Tests for the query embedding cache module against a real cache backend.""" from unittest.mock import patch from uuid import uuid4 from prometheus_client import REGISTRY from redis.exceptions import RedisError from onyx.cache.factory import get_cache_backend from onyx.natural_language_processing.query_embedding_c...
258
7,216
onyx
backend/tests/external_dependency_unit/natural_language_processing/test_get_query_embeddings.py
.py
"""Tests that the cache is wired correctly into ``get_query_embeddings``.""" from unittest.mock import MagicMock, patch from uuid import uuid4 from sqlalchemy.orm import Session from onyx.context.search.utils import get_query_embeddings from onyx.db.search_settings import get_current_search_settings from onyx.natura...
163
5,614
onyx
backend/tests/external_dependency_unit/natural_language_processing/conftest.py
.py
import struct import pytest @pytest.fixture(scope="function") def test_embedding() -> list[float]: # Each value is narrowed to float32 then back to float64 so it survives the # cache's float32 packing exactly — tests can assert with `==` instead of # tolerating rounding via pytest.approx. raw = [0.5,...
13
433
onyx
backend/tests/external_dependency_unit/voice/test_openai_streaming.py
.py
"""Live regression tests for OpenAI STT against the GA Realtime API. Skipped via `@pytest.mark.secrets(TestSecret.OPENAI_API_KEY)` when the key is absent. Single short API call each, so safe to run on every PR. """ import asyncio import math import struct import pytest from onyx.voice.providers.openai import ( ...
114
3,949
onyx
backend/tests/external_dependency_unit/connectors/test_gmail_multi_credential.py
.py
"""Creating a Gmail credential preserves existing Gmail credential rows.""" from collections.abc import Generator from dataclasses import dataclass, field from uuid import UUID, uuid4 import pytest from sqlalchemy import select from sqlalchemy.orm import Session from onyx.auth.schemas import UserRole from onyx.confi...
115
3,802
onyx
backend/tests/external_dependency_unit/connectors/google_drive/test_google_drive_hierarchy_walker.py
.py
"""Regression tests for hierarchy-node walker mis-parenting bugs in the Google Drive connector. Both tests drive `_get_new_ancestors_for_files` directly with a stubbed `_get_folder_metadata`, then replay the resulting nodes through the real `ConnectorRunner.run` (via a tiny test-only `CheckpointedConnector` that just ...
550
20,617
onyx
backend/tests/external_dependency_unit/connectors/google_drive/test_google_drive_group_sync.py
.py
from collections.abc import Generator from unittest.mock import Mock, patch from sqlalchemy import select from sqlalchemy.orm import Session from ee.onyx.background.celery.tasks.external_group_syncing.tasks import ( _perform_external_group_sync, ) from ee.onyx.db.external_perm import ExternalUserGroup from onyx.a...
556
22,262
onyx
backend/tests/external_dependency_unit/connectors/confluence/test_confluence_group_sync.py
.py
from typing import Any from sqlalchemy.orm import Session from ee.onyx.external_permissions.confluence.group_sync import confluence_group_sync from onyx.configs.constants import DocumentSource from onyx.connectors.models import InputType from onyx.db.enums import AccessType, ConnectorCredentialPairStatus from onyx.db...
160
5,001
onyx
backend/tests/external_dependency_unit/connectors/confluence/conftest.py
.py
import os from typing import Any import pytest @pytest.fixture def confluence_connector_config() -> dict[str, Any]: url_base = os.environ.get("CONFLUENCE_TEST_SPACE_URL") space_key = os.environ.get("CONFLUENCE_SPACE_KEY") page_id = os.environ.get("CONFLUENCE_PAGE_ID") is_cloud = os.environ.get("CONFL...
36
1,040
onyx
backend/tests/external_dependency_unit/connectors/jira/test_jira_group_sync.py
.py
from typing import Any import pytest from sqlalchemy.orm import Session from ee.onyx.external_permissions.jira.group_sync import jira_group_sync from onyx.configs.constants import DocumentSource from onyx.connectors.models import InputType from onyx.db.enums import AccessType, ConnectorCredentialPairStatus from onyx....
153
4,956
onyx
backend/tests/external_dependency_unit/connectors/jira/test_jira_doc_sync.py
.py
from typing import Any import pytest from pydantic import BaseModel from sqlalchemy.orm import Session from ee.onyx.external_permissions.jira.doc_sync import jira_doc_sync from onyx.access.models import DocExternalAccess from onyx.configs.constants import DocumentSource from onyx.connectors.models import InputType fr...
227
8,067
onyx
backend/tests/external_dependency_unit/connectors/jira/conftest.py
.py
import os from typing import Any import pytest @pytest.fixture def jira_connector_config() -> dict[str, Any]: jira_base_url = os.environ.get("JIRA_BASE_URL", "https://danswerai.atlassian.net") return { "jira_base_url": jira_base_url, "project_key": "", # Empty to sync all projects "...
30
797
onyx
backend/tests/external_dependency_unit/mcp/test_mcp_oauth_dead_grant.py
.py
"""OAuth MCP grants that can never refresh must read as unauthenticated (ext-dep): `user_can_authenticate` semantics, Craft config exclusion, and the persisted token discard on an `invalid_grant` refresh response, against a real DB.""" from __future__ import annotations import asyncio import time from typing import A...
173
5,785
onyx
backend/tests/external_dependency_unit/mcp/test_craft_admin_api.py
.py
"""Craft-facing MCP admin API (ext-dep): per-tool policy PATCH round-trip and the user-facing disconnect endpoint, against a real DB.""" from __future__ import annotations from uuid import uuid4 import pytest from sqlalchemy.orm import Session from onyx.auth.schemas import UserRole from onyx.db.enums import ( E...
283
10,596
onyx
backend/tests/external_dependency_unit/file_store/test_azure_blob_file_store.py
.py
"""Tests for AzureBlobBackedFileStore against a real Azure Blob endpoint. Runs against Azurite, Microsoft's official Azure Storage emulator (the role MinIO plays for the S3 backend tests): docker run -d -p 10000:10000 mcr.microsoft.com/azure-storage/azurite \ azurite-blob --blobHost 0.0.0.0 --skipApiVersi...
440
15,798
onyx
backend/tests/external_dependency_unit/file_store/test_postgres_file_store_non_mocked.py
.py
"""External dependency tests for PostgresBackedFileStore. These tests interact with a real PostgreSQL database — no mocking. They exercise Large Object creation, reading, streaming, deletion, and verify consistency between the file_record / file_content tables and the underlying pg_largeobject storage. """ import uui...
497
18,351
onyx
backend/tests/external_dependency_unit/file_store/test_file_store_non_mocked.py
.py
import os import time import uuid from collections.abc import Generator from concurrent.futures import ThreadPoolExecutor, as_completed from io import BytesIO from typing import TYPE_CHECKING, Any, Dict, List, Tuple, TypedDict, cast from unittest.mock import patch import pytest from botocore.exceptions import ClientEr...
1,058
40,093
onyx
backend/tests/external_dependency_unit/file_store/test_staging.py
.py
"""External dependency tests for onyx.file_store.staging. Exercises the raw-file persistence hook used by the docfetching pipeline against a real file store (Postgres + MinIO/S3), since mocking the store would defeat the point of verifying that metadata round-trips through FileRecord. """ from collections.abc import ...
129
4,299
onyx
backend/tests/external_dependency_unit/file_store/test_staging_concurrent_attempt_skip.py
.py
"""Test that the start-of-run staging sweep skips files whose owning attempt is still non-terminal. The sweep at the start of a docfetching attempt deletes orphan staged files left behind by previous attempts on the same cc_pair. Without the terminal-status filter, a concurrent in-progress attempt (such as a targeted ...
251
7,987
onyx
backend/tests/external_dependency_unit/chat/test_spreadsheet_preview.py
.py
"""Tests for the parsed spreadsheet preview path used by GET /chat/file/{file_id}?parsed=true (xlsx chat attachments rendered as tables in the frontend instead of raw binary bytes).""" import csv import io from typing import cast from unittest.mock import patch import openpyxl import pytest from openpyxl.worksheet.wo...
151
5,603
onyx
backend/tests/external_dependency_unit/chat/test_incognito_persistence.py
.py
"""Guards the incognito persistence seams against real Postgres and Redis. Two behaviors the feature rests on: save_chat_turn keeps the assistant row for tracking but writes no text when content is not persisted, and the ephemeral store round-trips a turn's messages so the next turn has its context. Run here rather th...
267
8,919
onyx
backend/tests/external_dependency_unit/chat/test_incognito_availability.py
.py
"""Guards who may start an incognito chat. The availability rule composes the admin security setting (default off) with group membership under groups-only mode. Runs against real Postgres because the membership query is a real join, and a mocked session would return whatever it is told. """ from collections.abc impor...
128
4,492
onyx
backend/tests/external_dependency_unit/chat/test_build_python_chat_files.py
.py
"""External-dependency tests for `build_python_chat_files_from_search_docs`. This is the staging step that turns connector-file-bearing search hits into `ChatFile`s for the Python code interpreter. Uses real Postgres + real file store because the function reads bytes + file_records from the store, and mocking those wo...
257
8,889
onyx
backend/tests/external_dependency_unit/chat/test_user_reminder_message_type.py
.py
""" Tests for the USER_REMINDER message type handling in translate_history_to_llm_format. These tests verify that: 1. USER_REMINDER messages are wrapped with <system-reminder> tags 2. The wrapped messages are converted to UserMessage type for the LLM 3. The tags are properly applied around the message content 4. CODE_...
336
12,316
onyx
backend/tests/external_dependency_unit/chat/test_lazy_chat_file_loading.py
.py
"""External-dependency tests for the lazy chat-file loading path. These tests guard the OOM fix: ``load_all_chat_files`` and friends must NOT read raw file bytes from the file store at construction time. Bytes are read only when a downstream consumer (e.g. PythonTool) actually accesses ``.content``. Uses real Postgre...
473
16,849
onyx
backend/tests/external_dependency_unit/indexing/test_get_old_index_attempt_ids.py
.py
"""External dependency unit tests for `get_old_index_attempt_ids`. Validates the cleanup-query logic against real Postgres: - Short-circuits (returns []) when no rows exist OR when the oldest row is within the retention window. The short-circuit relies on the index on `time_created` to avoid the full-table window...
129
4,324
onyx
backend/tests/external_dependency_unit/indexing/test_persistent_indexing.py
.py
"""External-dependency-unit tests for PERSISTENT_INDEXING (docfetching side). Exercises `run_docfetching_entrypoint` against a mock checkpointed connector. PERSISTENT_INDEXING's docfetching-side contract: - It DISABLES the >3-failures-AND->10%-ratio threshold abort, so a flood of connector-yielded `ConnectorFai...
389
14,139
onyx
backend/tests/external_dependency_unit/indexing/test_index_doc_batch_prepare.py
.py
"""External dependency unit tests for `index_doc_batch_prepare`. Validates the file_id lifecycle that runs alongside the document upsert: * `document.file_id` is written on insert AND on conflict (upsert path) * Newly-staged files get promoted from INDEXING_STAGING -> CONNECTOR * Replaced files are delete...
270
9,286
onyx
backend/tests/external_dependency_unit/indexing/test_document_deletion_file_cleanup.py
.py
"""External dependency unit tests for the file_id cleanup that runs alongside document deletion across the three deletion paths: 1. `document_by_cc_pair_cleanup_task` (pruning + connector deletion) 2. `delete_ingestion_doc` (public ingestion API DELETE) 3. `delete_all_documents_for_connector_credential_pai...
279
9,847
onyx
backend/tests/external_dependency_unit/indexing/test_port_reembed.py
.py
"""Tests for the reindex-port re-embedding (port_reembed). These cover the pure re-embed logic: strategy selection, rebuilding the semantic metadata tail, the embed-input recovery (the crux — stored content carries the keyword tail, but the embedded text used the semantic tail), and the minimal DocAwareChunk reconstru...
665
27,171
onyx
backend/tests/external_dependency_unit/indexing/test_docfetching_orphan_cleanup.py
.py
"""End-to-end test for docfetching orphan-file cleanup. Two cleanup seams are covered: Start-of-run sweep (`reap_prior_attempt_staged_files`): run 1: a mock connector stages a raw file via raw_file_callback, then crashes — docfetching re-raises without reaping, because promot...
663
25,229
onyx
backend/tests/external_dependency_unit/celery/test_user_file_delete_queue.py
.py
""" External dependency unit tests for user file delete queue protections. Verifies that the three mechanisms added to check_for_user_file_delete work correctly: 1. Queue depth backpressure – when the broker queue exceeds USER_FILE_DELETE_MAX_QUEUE_DEPTH, no new tasks are enqueued. 2. Per-file Redis guard key – i...
299
11,125
onyx
backend/tests/external_dependency_unit/celery/test_docfetching_priority.py
.py
""" External dependency unit tests for document processing job priority. Tests that first-time indexing connectors (no last_successful_index_time) get higher priority than re-indexing jobs from connectors that have previously completed indexing. Uses real Redis for locking and real database objects for CC pairs and s...
393
13,456
onyx
backend/tests/external_dependency_unit/celery/test_document_sync_revoke_cleanup.py
.py
"""Doc-sync taskset cleanup on task revoke/expire (uses real Redis). Regression: an expired doc-sync task fires `task_revoked`, not `task_postrun`, so its id must be removed from the taskset by `app_base.on_task_revoked`. Otherwise the taskset never empties, `monitor_document_sync_taskset` never resets the fence, and ...
84
3,157
onyx
backend/tests/external_dependency_unit/celery/test_docprocessing_priority.py
.py
""" External dependency unit tests for docprocessing task priority. Tests that docprocessing tasks spawned by connector_document_extraction get the correct priority based on last_successful_index_time. Uses real database objects for CC pairs, search settings, and index attempts. """ from datetime import datetime, ti...
325
13,024
onyx
backend/tests/external_dependency_unit/celery/test_document_sync_no_pg_txn_during_index_io.py
.py
""" Regression coverage for document_index_metadata_sync_task holding a Postgres transaction across the document-index (Vespa/OpenSearch) HTTP round-trip. Under bulk-deletion fan-out, every docprocessing-sync worker slot used to pin a DB connection in state idle-in-transaction for the duration of the index call (up to...
154
5,938
onyx
backend/tests/external_dependency_unit/celery/test_persona_file_sync.py
.py
""" External dependency unit tests for persona file sync. Validates that: 1. The check_for_user_file_project_sync beat task picks up UserFiles with needs_persona_sync=True (not just needs_project_sync). 2. The process_single_user_file_project_sync worker task reads persona associations from the DB, passes pers...
964
36,586
onyx
backend/tests/external_dependency_unit/celery/test_pruning_hierarchy_nodes.py
.py
""" External dependency unit tests for pruning hierarchy node extraction and DB persistence. Verifies that: 1. extract_ids_from_runnable_connector correctly separates hierarchy nodes from doc IDs 2. Extracted hierarchy nodes are correctly upserted to Postgres via upsert_hierarchy_nodes_batch 3. Upserting is idempotent...
923
32,311
onyx
backend/tests/external_dependency_unit/celery/test_created_at_backfill.py
.py
"""External dependency unit tests for the doc_created_at backfill (acquisition half). Validates that the pruning-side collection of a source creation time works: 1. extract_ids_from_runnable_connector captures doc_created_at from slim docs. 2. backfill_docs_created_at__no_commit persists it and bumps last_modified so ...
161
5,806
onyx
backend/tests/external_dependency_unit/celery/test_user_file_indexing_adapter.py
.py
""" External dependency unit tests for UserFileIndexingAdapter metadata writing. Validates that prepare_enrichment produces DocMetadataAwareIndexChunk objects with both `user_project` and `personas` fields populated correctly based on actual DB associations. Uses real PostgreSQL for UserFile/Persona/UserProject rows....
309
10,450
onyx
backend/tests/external_dependency_unit/celery/test_user_file_processing_queue.py
.py
""" External dependency unit tests for user file processing queue protections. Verifies that the three mechanisms added to check_user_file_processing work correctly: 1. Queue depth backpressure – when the broker queue exceeds USER_FILE_PROCESSING_MAX_QUEUE_DEPTH, no new tasks are enqueued. 2. Per-file Redis guard...
299
11,061
onyx
backend/tests/external_dependency_unit/celery/test_version_telemetry_heartbeat.py
.py
"""Tests for the self-hosted version telemetry heartbeat task.""" from collections.abc import Generator from unittest.mock import patch import pytest from onyx import __version__ from onyx.background.celery.tasks.monitoring.tasks import ( _VERSION_TELEMETRY_EMITTED_KEY, emit_version_telemetry, ) from onyx.re...
123
4,323
onyx
backend/tests/external_dependency_unit/discord_bot/test_discord_events.py
.py
"""Tests for Discord bot event handling with mocked Discord API. These tests mock the Discord API to test event handling logic. """ from unittest.mock import AsyncMock, MagicMock, patch import discord import pytest from onyx.onyxbot.discord.handle_commands import ( get_text_channels, handle_dm, handle_r...
633
22,282
onyx
backend/tests/external_dependency_unit/discord_bot/conftest.py
.py
"""Fixtures for Discord bot external dependency tests.""" from collections.abc import Generator from unittest.mock import AsyncMock, MagicMock import discord import pytest from sqlalchemy.orm import Session from onyx.db.engine.sql_engine import SqlEngine, get_session_with_current_tenant from shared_configs.contextva...
160
4,797
onyx
backend/tests/external_dependency_unit/hierarchy/test_hierarchy_access_filter.py
.py
"""Tests hierarchy node and document visibility through connector permissions.""" from collections.abc import Generator from uuid import UUID, uuid4 import pytest from pydantic import BaseModel, ConfigDict from sqlalchemy import text, update from sqlalchemy.orm import Session from ee.onyx.db.hierarchy import _get_ac...
416
13,130
onyx
backend/tests/external_dependency_unit/hierarchy/test_hierarchy_node_search.py
.py
"""Tests for hierarchy node display_name search. Covers case-insensitive substring matching, source filtering, exclusion of STUB/SOURCE nodes, and ACL filtering in the EE version. """ from collections.abc import Generator from uuid import uuid4 import pytest from sqlalchemy.orm import Session from ee.onyx.db.hierar...
268
9,180
onyx
backend/tests/external_dependency_unit/hierarchy/test_upsert_parents_deep_chain.py
.py
"""Regression tests for `upsert_parents` recursion safety. Deeply nested Notion workspaces produced parent chains longer than Python's default recursion limit, causing ``upsert_parents`` to raise ``RecursionError``. These tests lock in the iterative implementation: a deep chain must complete, and a cyclic parent refer...
153
5,073
onyx
backend/tests/external_dependency_unit/hierarchy/test_stub_cross_batch.py
.py
"""Tests for STUB hierarchy node creation when a child is indexed before its parent. During Notion full syncs the search API returns pages in arbitrary order. When a child page lands in batch N and its parent in batch N+K, the child's hierarchy node must point to a STUB placeholder rather than SOURCE. The stub is prom...
217
7,651
onyx
backend/tests/external_dependency_unit/document_index/test_verify_write_blocked.py
.py
"""External dependency tests for behavior when the OpenSearch index carries a write block, as OpenSearch applies at the disk flood-stage watermark. Regression tests for api-server pods crash-looping on startup while the index was read_only_allow_delete-blocked: the mapping refresh is a metadata write, so it is rejecte...
124
4,848
onyx
backend/tests/external_dependency_unit/document_index/test_document_index.py
.py
"""External dependency tests for the new DocumentIndex interface. These tests assume OpenSearch is running. """ import time import uuid from collections.abc import Generator, Iterator from unittest.mock import patch import pytest from onyx.configs.constants import PUBLIC_DOC_PAT from onyx.context.search.models impo...
602
23,068
onyx
backend/tests/external_dependency_unit/document_index/conftest.py
.py
"""Shared fixtures for document_index external dependency tests. Provides OpenSearch index setup, tenant context, and chunk helpers. """ import uuid from collections.abc import Generator import pytest from onyx.access.models import DocumentAccess from onyx.configs.constants import DocumentSource from onyx.connector...
149
4,570
onyx
backend/tests/external_dependency_unit/db/test_sync_priority.py
.py
"""External dependency unit tests for the reindex-port sync-enqueue priority (T8/D9). Covers: the UNION select surfacing needs_sync + deferred docs (each self-tagged); the gate count including deferred-only docs; the any-FUTURE-port-in-progress pre-query; and the producer's per-doc priority (deferred doc LOW while a p...
179
7,019
onyx
backend/tests/external_dependency_unit/db/test_targeted_reindex_filter.py
.py
"""External dependency unit tests for the `targeted_reindex_job_id IS NULL` filter on IndexAttempt consumer queries. Validates that synthetic targeted-reindex attempts don't bleed into freshness, scheduling, or counting queries that should only see real full-crawl attempts, while cleanup/cancellation paths still see b...
587
18,602
onyx
backend/tests/external_dependency_unit/db/test_agent_sharing_groups.py
.py
"""EE regression coverage for group-based agent sharing: owner groups grant every member full owner rights, leveled group shares gate edit access, group ownership transfers, and group deletion orphans or deletes owned personas.""" import pytest from fastapi import HTTPException from sqlalchemy.orm import Session from...
157
5,755
onyx
backend/tests/external_dependency_unit/db/test_shard_enumeration.py
.py
"""Tenant enumeration across shards, exercised against two real databases. Enumeration is what tells beat which tenants to schedule and tells the migration runner which schemas to upgrade. Reading it from a single database silently drops every tenant that has been moved off that database: no error, they just stop bein...
261
9,661
onyx
backend/tests/external_dependency_unit/db/test_api_key_auth_result.py
.py
import pytest from sqlalchemy.orm import Session from onyx.auth.api_key import hash_api_key from onyx.auth.schemas import UserRole from onyx.db.api_key import fetch_api_key_auth_result, insert_api_key, remove_api_key from onyx.db.engine.async_sql_engine import ( get_async_session_context_manager, reset_sqlalch...
46
1,793
onyx
backend/tests/external_dependency_unit/db/agent_sharing_helpers.py
.py
"""Shared builders for the agent-sharing permission/transfer/lifecycle tests.""" from uuid import uuid4 from sqlalchemy.orm import Session from onyx.db.enums import PersonaSharePermission from onyx.db.models import ( Persona, Persona__User, Persona__UserGroup, User, User__UserGroup, UserGroup...
92
2,382
onyx
backend/tests/external_dependency_unit/db/test_prior_email_claim_release.py
.py
"""Guards the alias release against real rows rather than mocked calls. 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 claiming it has to strip it from every other user in the same flush. These ...
151
5,179
onyx
backend/tests/external_dependency_unit/db/test_shard_capacity_metric.py
.py
"""The per-shard tenant count that drives the capacity alert. Counted against two real databases, because the value has to reflect where schemas physically live — a mapping that disagrees with reality must not be able to hide capacity from the alert. """ import time from collections.abc import Generator from concurre...
164
5,907
onyx
backend/tests/external_dependency_unit/db/test_document_file_id_lookup.py
.py
"""External dependency tests for the `Document.file_id` enrichment pipeline. Two tightly-coupled surfaces live in this file: 1. `get_document_id_to_file_id_map` — the batched DB lookup that joins chunk-level `document_id`s to their `Document.file_id` rows. 2. `populate_file_ids_on_sections` — the post-retrie...
262
8,921
onyx
backend/tests/external_dependency_unit/db/test_admin_banner_notification.py
.py
"""Guards the admin site-wide announcement's delivery contract: it is materialized per-user as a SYSTEM_ANNOUNCEMENT notification on read, editing it re-shows it to users who dismissed the prior version, and deleting it clears it for everyone. """ from collections.abc import Generator import pytest from sqlalchemy.or...
158
5,535
onyx
backend/tests/external_dependency_unit/db/test_agent_sharing_permissions.py
.py
"""Regression coverage for the persona share-permission predicate: EDITOR shares grant edit access, VIEWER shares grant use only, public_permission can extend edit org-wide, and the computed access level / sharing status helpers agree with the SQL filter.""" import pytest from fastapi import HTTPException from sqlalch...
225
8,264
onyx
backend/tests/external_dependency_unit/db/test_port_flow_e2e.py
.py
"""End-to-end composition test for the reindex port flow (MODEL_ONLY strategy). Proves the layers COMPOSE with NO PortCopier mocking: check_for_port kickoff -> run_port_attempt (real PIT scan of PRESENT + real re-embed under the FUTURE model via the local model server + create-only write to FUTURE) -> the port-aware s...
438
17,684
onyx
backend/tests/external_dependency_unit/db/shard_test_utils.py
.py
"""Shared helpers for the shard suites. All of them need the same thing: a real second database on the same server. The seam routes per-DSN rather than per-host, so a second database is a faithful stand-in for a second instance and keeps the tests self-contained. """ from collections.abc import Generator from uuid im...
79
2,697
onyx
backend/tests/external_dependency_unit/db/test_usage_export_pairing.py
.py
from datetime import datetime, timezone from uuid import UUID from sqlalchemy.orm import Session from ee.onyx.db.usage_export import get_empty_chat_messages_entries__paginated from onyx.configs.constants import MessageType from onyx.db.chat import ( create_chat_session, create_new_chat_message, get_or_cre...
136
4,557
onyx
backend/tests/external_dependency_unit/db/test_rotate_encryption_key.py
.py
"""Tests for rotate_encryption_key against real Postgres. Uses real ORM models (Credential, InternetSearchProvider) and the actual Postgres database. Discovery is mocked in rotation tests to scope mutations to only the test rows — the real _discover_encrypted_columns walk is tested separately in TestDiscoverEncryptedC...
322
11,276
onyx
backend/tests/external_dependency_unit/db/test_sso_provider_store.py
.py
"""The sso_provider store must round-trip the encrypted per-type config, enforce the slug name contract, validate config against provider_type, preserve config on partial update, and keep disable-not-delete semantics.""" from collections.abc import Generator from uuid import uuid4 import pytest from sqlalchemy import...
198
6,605
onyx
backend/tests/external_dependency_unit/db/test_run_targeted_reindex.py
.py
"""External dependency unit tests for the per-cc-pair processor. The processor `process_targets_for_cc_pair` owns the path between target rows and the indexing pipeline: instantiate connector → check Resolver capability → convert targets to ConnectorFailure inputs → stream Documents → run pipeline once per (cc_pair × ...
348
11,199
onyx
backend/tests/external_dependency_unit/db/test_userfile_port_execution.py
.py
"""External dependency unit tests for the user-file port EXECUTION (PR2). Covers the scope branch in run_port_attempt (a user attempt ports its files and does NOT self-cancel down the cc_pair path), the scheduler's user loop + dedicated-queue routing, the swap gate's user-scope gating (incl. a zero-connector tenant), ...
404
14,799
onyx
backend/tests/external_dependency_unit/db/test_targeted_reindex_task.py
.py
"""External dependency unit tests for the targeted reindex celery task. Covers the lifecycle and resolution-tracking layers of the task: - Job + synthetic IndexAttempt lifecycle transitions - Resolution tracking on `IndexAttemptError` rows referenced by targets with `source_error_id` (gated on landed_doc_ids) - Idem...
450
16,274
onyx
backend/tests/external_dependency_unit/db/test_recompute_permissions.py
.py
"""LIMITED service accounts hold chat scope derived from their role, not from groups, so any recompute converges them to it instead of wiping it.""" from uuid import UUID from sqlalchemy.orm import Session from onyx.auth.schemas import UserRole from onyx.db.enums import AccountType from onyx.db.permissions import re...
50
1,756
onyx
backend/tests/external_dependency_unit/db/test_index_attempt_stage_metrics.py
.py
"""External dependency unit tests for stage-metric write helpers. Validates the upsert + Chan-combination logic against real Postgres: - ``record_single_event`` produces the right aggregate for a fresh row and for repeated events on the same ``(attempt, stage)`` key. - The upsert correctly preserves ``time_first_ev...
470
16,719
onyx
backend/tests/external_dependency_unit/db/test_index_reclaim.py
.py
"""External dependency unit tests for the old-index-reclamation DB helpers (reclaim helpers in db/search_settings.py; the won't-port picker in db/connector_credential_pair.py). Covers the pure/isolated helpers introduced in PR1: - compute_wont_port_cc_pair_ids: INVALID always; PAUSED only under ACTIVE_ONLY; ACTIVE/D...
286
9,497
onyx
backend/tests/external_dependency_unit/db/test_shard_placement.py
.py
"""Placement of *new* tenants onto a configured shard, against two real databases. The invariant is an ordering one — the mapping must be written before the schema is created — so these assert on which database the schema physically lands in, not on what a helper returned. """ import asyncio from collections.abc impo...
329
12,988
onyx
backend/tests/external_dependency_unit/db/test_agent_sharing_lifecycle.py
.py
"""Regression coverage for the persona ownership lifecycle: user deletion soft-deletes private personas and orphans shared/public ones, deactivation mutates nothing (vacancy is computed), and self-removal from the share list works for everyone except the owner.""" import pytest from sqlalchemy.orm import Session from...
205
7,665
onyx
backend/tests/external_dependency_unit/db/test_chat_session_eager_load.py
.py
from sqlalchemy import inspect from sqlalchemy.orm import Session from onyx.db.chat import create_chat_session, get_chat_session_by_id from onyx.db.models import Persona, UserProject from tests.external_dependency_unit.conftest import create_test_user def test_eager_load_persona_loads_relationships(db_session: Sessi...
49
1,649
onyx
backend/tests/external_dependency_unit/db/test_api_key_permissions.py
.py
"""Editing or rotating a key recomputes its permissions: legacy LIMITED keys with a blank grant are repaired, and healthy keys keep the permissions they already had.""" from uuid import UUID from sqlalchemy import select from sqlalchemy.orm import Session from onyx.auth.schemas import UserRole from onyx.db.api_key i...
144
4,497
onyx
backend/tests/external_dependency_unit/db/test_agent_sharing_transfer.py
.py
"""Regression coverage for persona ownership transfer: owner-only authority, target validation (no bots/service accounts/slack/inactive users, no groups in MIT), previous-owner demotion to an EDITOR share row, and admin transfer of vacant (orphaned) personas.""" from uuid import UUID import pytest from sqlalchemy.orm...
265
8,875
onyx
backend/tests/external_dependency_unit/db/test_port_swap_criterion.py
.py
"""External dependency unit tests for the port-aware swap criterion (T7/D8). The port-flow branch of `check_and_perform_index_swap` swaps on four conditions rather than the legacy successful-index count: every required cc_pair's port is SUCCESS, a real (non-seed) FUTURE index attempt landed after the port, nothing is ...
475
19,496
onyx
backend/tests/external_dependency_unit/db/test_orphan_tag_cleanup.py
.py
""" Tests for batched orphan-tag cleanup. Orphan tags (tags with no Document__Tag link) must be deleted in bounded server-side batches rather than one unbounded IN-list DELETE. """ from unittest.mock import patch from uuid import uuid4 from sqlalchemy import select from sqlalchemy.orm import Session from onyx.confi...
143
4,469
onyx
backend/tests/external_dependency_unit/db/test_tag_race_condition.py
.py
""" Test suite for tag creation race condition handling. Tests that concurrent tag creation operations don't fail due to UniqueViolation errors, which would occur if the upsert logic isn't properly implemented. """ from concurrent.futures import Future, ThreadPoolExecutor, as_completed from typing import Union from u...
286
10,686
onyx
backend/tests/external_dependency_unit/db/test_credential_sensitive_value.py
.py
"""Test that Credential with nested JSON round-trips through SensitiveValue correctly. Exercises the full encrypt → store → read → decrypt → SensitiveValue path with realistic nested OAuth credential data, and verifies SQLAlchemy dirty tracking works with nested dict comparison. Requires a running Postgres instance. ...
91
3,048
onyx
backend/tests/external_dependency_unit/db/test_shard_routing.py
.py
"""Tenant -> database routing seam, exercised against two real databases. The point of these tests is the thing that cannot be checked with mocks: that a session for tenant A physically talks to a different Postgres database than a session for tenant B, and that neither can see the other's rows. A second database is ...
872
32,836
onyx
backend/tests/external_dependency_unit/db/test_notification.py
.py
from collections.abc import Callable from concurrent.futures import ThreadPoolExecutor from concurrent.futures import TimeoutError as FutureTimeoutError from datetime import datetime, timedelta, timezone import pytest from sqlalchemy import select from sqlalchemy.orm import Session from onyx.auth.schemas import UserR...
860
27,384
onyx
backend/tests/external_dependency_unit/db/test_incognito_stale_sweep.py
.py
"""Guards which uploads the sweep's query returns, and how it reads the mode of the session that claims each one. An absent session row and an ordinary chat both arrive as a NULL mode through the outer join while meaning opposite things. Exercises the real SQL against Postgres, since the distinction lives entirely in ...
136
4,437