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/integration/tests/image_generation/test_image_generation_config.py
.py
"""Integration tests for image generation config endpoints. Tests cover CRUD operations for /admin/image-generation/config endpoints. The /admin/image-generation/test endpoint is not tested as it makes real API calls. Uses module-scoped fixtures to reset DB and create users once per module for faster execution. """ ...
491
16,080
onyx
backend/tests/integration/tests/anonymous_user/test_anonymous_user.py
.py
from tests.integration.common_utils.constants import API_SERVER_URL from tests.integration.common_utils.http_client import client from tests.integration.common_utils.managers.settings import SettingsManager from tests.integration.common_utils.managers.user import UserManager from tests.integration.common_utils.test_mod...
147
4,830
onyx
backend/tests/integration/connector_job_tests/sharepoint/test_sharepoint_permissions.py
.py
import os import pytest from onyx.db.engine.sql_engine import get_session_with_current_tenant from onyx.utils.logger import setup_logger from tests.integration.common_utils.document_acl import ( get_all_connector_documents, get_documents_by_permission_type, get_user_document_access_via_acl, ) from tests.i...
124
4,401
onyx
backend/tests/integration/connector_job_tests/sharepoint/conftest.py
.py
import os from collections.abc import Generator from datetime import datetime, timezone import pytest from onyx.configs.constants import DocumentSource from onyx.connectors.models import InputType from onyx.connectors.sharepoint.connector import SharepointAuthMethod from onyx.db.enums import AccessType from tests.int...
116
4,244
onyx
backend/tests/integration/connector_job_tests/jira/test_jira_permission_sync_full.py
.py
import os from datetime import datetime, timezone import pytest from tests.integration.common_utils.managers.cc_pair import CCPairManager from tests.integration.connector_job_tests.jira.conftest import JiraTestEnvSetupTuple @pytest.mark.skipif( os.environ.get("ENABLE_PAID_ENTERPRISE_EDITION_FEATURES", "").lower...
39
1,026
onyx
backend/tests/integration/connector_job_tests/jira/conftest.py
.py
import os from collections.abc import Generator from datetime import datetime, timezone import pytest from onyx.configs.constants import DocumentSource from onyx.connectors.models import InputType from onyx.db.enums import AccessType from tests.integration.common_utils.managers.cc_pair import CCPairManager from tests...
68
2,151
onyx
backend/tests/integration/connector_job_tests/slack/test_prune.py
.py
import os from datetime import datetime, timezone import pytest from onyx.connectors.models import InputType from onyx.connectors.slack.models import ChannelType from onyx.db.enums import AccessType from onyx.server.documents.models import DocumentSource from tests.integration.common_utils.managers.cc_pair import CCP...
213
7,526
onyx
backend/tests/integration/connector_job_tests/slack/slack_api_utils.py
.py
""" Assumptions: - The test users have already been created - General is empty of messages - In addition to the normal slack oauth permissions, the following scopes are needed: - channels:manage - groups:write - chat:write - chat:write.public """ from collections.abc import Callable, Generator from typ...
326
10,811
onyx
backend/tests/integration/connector_job_tests/slack/test_permission_sync.py
.py
import os from datetime import datetime, timezone import pytest from onyx.connectors.models import InputType from onyx.connectors.slack.models import ChannelType from onyx.db.enums import AccessType from onyx.server.documents.models import DocumentSource from tests.integration.common_utils.managers.cc_pair import CCP...
333
11,141
onyx
backend/tests/integration/connector_job_tests/slack/conftest.py
.py
import os from collections.abc import Generator import pytest from onyx.connectors.slack.models import ChannelType from tests.integration.connector_job_tests.slack.slack_api_utils import SlackManager SLACK_ADMIN_EMAIL = os.environ.get("SLACK_ADMIN_EMAIL", "evan@onyx.app") SLACK_TEST_USER_1_EMAIL = os.environ.get("SL...
52
1,760
onyx
backend/tests/integration/connector_job_tests/github/utils.py
.py
from typing import Optional from github import Github from github.GithubException import GithubException from onyx.utils.logger import setup_logger logger = setup_logger() class GitHubManager: """ Manager class for GitHub operations used in testing. Provides methods to change repository visibility, che...
188
6,001
onyx
backend/tests/integration/connector_job_tests/github/test_github_permission_sync.py
.py
import os from datetime import datetime, timezone import pytest from github import Github from onyx.db.engine.sql_engine import get_session_with_current_tenant from onyx.utils.logger import setup_logger from tests.integration.common_utils.document_acl import ( get_all_connector_documents, get_user_document_ac...
358
13,428
onyx
backend/tests/integration/connector_job_tests/github/test_github_empty_repository.py
.py
from onyx.configs.constants import DocumentSource from onyx.connectors.models import InputType from onyx.db.engine.sql_engine import get_session_with_current_tenant from onyx.db.enums import AccessType, IndexingStatus from tests.integration.common_utils.document_acl import get_all_connector_documents from tests.integra...
64
2,620
onyx
backend/tests/integration/connector_job_tests/github/conftest.py
.py
import os from collections.abc import Generator from datetime import datetime, timezone import pytest from onyx.configs.constants import DocumentSource from onyx.connectors.models import InputType from onyx.db.enums import AccessType from tests.integration.common_utils.managers.cc_pair import CCPairManager from tests...
161
5,571
onyx
backend/tests/integration/connector_job_tests/google/test_google_drive_permission_sync.py
.py
import json import os from collections.abc import Generator from datetime import datetime, timezone from uuid import uuid4 import pytest from onyx.configs.constants import DocumentSource from onyx.connectors.google_utils.resources import GoogleDriveService from onyx.connectors.google_utils.shared_constants import ( ...
333
11,596
onyx
backend/tests/integration/connector_job_tests/google/google_drive_api_utils.py
.py
from typing import Any from uuid import uuid4 from google.oauth2.service_account import Credentials from onyx.connectors.google_utils.resources import ( GoogleDocsService, GoogleDriveService, get_drive_service, get_google_docs_service, ) GOOGLE_SCOPES = { "google_drive": [ "https://www.go...
199
6,725
onyx
backend/tests/integration/common_utils/cimd_oauth.py
.py
from pathlib import Path from pydantic import BaseModel class CimdHttpsEndpoint(BaseModel): origin: str ca_file: Path class CimdOAuthTestServices(BaseModel): mcp_server_url: str oidc_issuer: str client_metadata_url: str class MockOidcStatus(BaseModel): client_metadata_fetch_count: int ...
21
384
onyx
backend/tests/integration/common_utils/reset.py
.py
import logging import os from types import SimpleNamespace import psycopg2 from alembic import command from alembic.config import Config from sqlalchemy.orm import Session from onyx.configs.app_configs import ( POSTGRES_HOST, POSTGRES_PASSWORD, POSTGRES_PORT, POSTGRES_USER, ) from onyx.db.engine.sql_e...
377
12,003
onyx
backend/tests/integration/common_utils/test_file_utils.py
.py
import io from PIL import Image def create_test_image( width: int = 1, height: int = 1, color: str = "white", format: str = "PNG", ) -> io.BytesIO: """Create a test image file in memory for file attachment testing. Args: width: Width of the image in pixels. Defaults to 1. hei...
44
1,238
onyx
backend/tests/integration/common_utils/timeout.py
.py
# import multiprocessing # from collections.abc import Callable # from typing import Any # from typing import TypeVar # T = TypeVar("T") # def run_with_timeout_multiproc( # task: Callable[..., T], timeout: int, kwargs: dict[str, Any] # ) -> T: # # Use multiprocessing to prevent a thread from blocking the mai...
76
2,089
onyx
backend/tests/integration/common_utils/http_client.py
.py
"""Module-level proxy to the active integration HTTP client. The default integration ``conftest.py`` builds one in-process FastAPI ``TestClient`` per test session and registers it via :func:`set_test_client`. Directory-specific suites can install a raw ``httpx.Client`` instead when they need to hit an out-of-process A...
112
3,538
onyx
backend/tests/integration/common_utils/chat.py
.py
from onyx.db.engine.sql_engine import get_session_with_current_tenant from onyx.db.models import User from tests.integration.common_utils.http_client import client def test_create_chat_session_and_send_messages() -> None: # Create a test user with get_session_with_current_tenant() as db_session: test_...
65
2,359
onyx
backend/tests/integration/common_utils/constants.py
.py
import os ADMIN_USER_NAME = "admin_user" API_SERVER_PROTOCOL = os.getenv("API_SERVER_PROTOCOL") or "http" API_SERVER_HOST = os.getenv("API_SERVER_HOST") or "127.0.0.1" API_SERVER_PORT = os.getenv("API_SERVER_PORT") or "8080" API_SERVER_URL = f"{API_SERVER_PROTOCOL}://{API_SERVER_HOST}:{API_SERVER_PORT}" MAX_DELAY = 3...
21
755
onyx
backend/tests/integration/common_utils/document_acl.py
.py
""" Utilities for testing document access control lists (ACLs) and permissions. """ from typing import List from uuid import UUID from sqlalchemy import select from sqlalchemy.orm import Session from ee.onyx.access.access import _get_access_for_documents from ee.onyx.db.external_perm import fetch_external_groups_for...
143
4,498
onyx
backend/tests/integration/common_utils/test_models.py
.py
from dataclasses import dataclass from datetime import datetime from enum import Enum from typing import Any from uuid import UUID from pydantic import BaseModel, Field from onyx.auth.schemas import UserRole from onyx.configs.constants import MessageType, QAFeedbackType from onyx.context.search.models import SavedSea...
319
7,940
onyx
backend/tests/integration/common_utils/vespa.py
.py
from typing import Any from opensearchpy import OpenSearch from opensearchpy.exceptions import NotFoundError from onyx.configs.app_configs import ( OPENSEARCH_ADMIN_PASSWORD, OPENSEARCH_ADMIN_USERNAME, OPENSEARCH_HOST, OPENSEARCH_REST_API_PORT, OPENSEARCH_USE_SSL, ) from onyx.db.engine.sql_engine ...
90
3,515
onyx
backend/tests/integration/common_utils/test_document_utils.py
.py
import uuid from datetime import datetime, timezone from onyx.configs.constants import DocumentSource from onyx.connectors.models import ( ConnectorFailure, Document, DocumentFailure, TextSection, ) def create_test_document( doc_id: str | None = None, text: str = "Test content", link: str...
59
1,846
onyx
backend/tests/integration/common_utils/managers/external_app.py
.py
from typing import Any from onyx.db.enums import EndpointPolicy, ExternalAppType from onyx.server.features.build.external_apps.models import ( CreateBuiltInExternalAppRequest, CreateCustomExternalAppRequest, ExternalAppAdminResponse, ExternalAppUserResponse, UpdateExternalAppRequest, UpsertUser...
217
7,813
onyx
backend/tests/integration/common_utils/managers/document_set.py
.py
import time from typing import Any from uuid import UUID, uuid4 from tests.integration.common_utils.constants import API_SERVER_URL, MAX_DELAY from tests.integration.common_utils.http_client import client from tests.integration.common_utils.test_models import DATestDocumentSet, DATestUser class DocumentSetManager: ...
180
6,949
onyx
backend/tests/integration/common_utils/managers/user.py
.py
from copy import deepcopy from urllib.parse import urlencode from uuid import uuid4 import httpx import pytest from onyx.auth.schemas import UserRole from onyx.configs.constants import ( ANONYMOUS_USER_EMAIL, ANONYMOUS_USER_UUID, FASTAPI_USERS_AUTH_COOKIE_NAME, ) from onyx.server.documents.models import P...
361
12,129
onyx
backend/tests/integration/common_utils/managers/llm_provider.py
.py
import os from uuid import uuid4 from onyx.llm.constants import LlmProviderNames from onyx.server.manage.llm.models import ( DefaultModel, LLMProviderUpsertRequest, LLMProviderView, ModelConfigurationUpsertRequest, ) from tests.integration.common_utils.constants import API_SERVER_URL, GENERAL_HEADERS f...
179
6,709
onyx
backend/tests/integration/common_utils/managers/build_session.py
.py
"""HTTP wrapper for build-mode session endpoints. Modeled on ``SkillManager``: a thin static façade that turns "create a session, upload a file, send a message" into one method call from an integration test. Each method calls the API server through the same ``user.headers`` / ``user.cookies`` auth pattern used elsewhe...
275
9,120
onyx
backend/tests/integration/common_utils/managers/scim_client.py
.py
import httpx from tests.integration.common_utils.constants import API_SERVER_URL, GENERAL_HEADERS from tests.integration.common_utils.http_client import client class ScimClient: """HTTP client for making authenticated SCIM v2 client.""" @staticmethod def _headers(raw_token: str) -> dict[str, str]: ...
67
1,941
onyx
backend/tests/integration/common_utils/managers/document_search.py
.py
from ee.onyx.server.query_and_chat.models import ( SearchFullResponse, SendSearchQueryRequest, ) from tests.integration.common_utils.constants import API_SERVER_URL from tests.integration.common_utils.http_client import client from tests.integration.common_utils.test_models import DATestUser class DocumentSea...
46
1,543
onyx
backend/tests/integration/common_utils/managers/persona.py
.py
from uuid import UUID, uuid4 from onyx.server.features.persona.models import ( FullPersonaSnapshot, PersonaUpsertRequest, ) from tests.integration.common_utils.constants import API_SERVER_URL from tests.integration.common_utils.http_client import client from tests.integration.common_utils.test_models import ( ...
393
14,996
onyx
backend/tests/integration/common_utils/managers/cc_pair.py
.py
import time from datetime import datetime from typing import Any from uuid import uuid4 from onyx.connectors.models import InputType from onyx.db.enums import AccessType, ConnectorCredentialPairStatus from onyx.server.documents.models import ( CCPairFullInfo, ConnectorCredentialPairIdentifier, ConnectorInd...
666
24,127
onyx
backend/tests/integration/common_utils/managers/scim_token.py
.py
from tests.integration.common_utils.constants import API_SERVER_URL from tests.integration.common_utils.http_client import client from tests.integration.common_utils.test_models import DATestScimToken, DATestUser class ScimTokenManager: @staticmethod def create( name: str, user_performing_acti...
51
1,678
onyx
backend/tests/integration/common_utils/managers/discord_bot.py
.py
"""Manager for Discord bot API integration tests.""" from onyx.db.discord_bot import ( create_channel_config, create_guild_config, register_guild, ) from onyx.db.engine.sql_engine import get_session_with_current_tenant from onyx.db.utils import DiscordChannelView from onyx.server.manage.discord_bot.utils i...
314
10,819
onyx
backend/tests/integration/common_utils/managers/chat.py
.py
import json from typing import Any, Literal, TypedDict, cast from uuid import UUID import httpx from onyx.context.search.models import SavedSearchDoc, SearchDoc from onyx.file_store.models import FileDescriptor from onyx.llm.override_models import LLMOverride from onyx.server.query_and_chat.models import ( AUTO_P...
489
18,622
onyx
backend/tests/integration/common_utils/managers/api_key.py
.py
from uuid import uuid4 from onyx.db.models import UserRole from onyx.server.api_key.models import APIKeyArgs from tests.integration.common_utils.constants import API_SERVER_URL, GENERAL_HEADERS from tests.integration.common_utils.http_client import client from tests.integration.common_utils.test_models import DATestAP...
84
2,937
onyx
backend/tests/integration/common_utils/managers/build_approvals.py
.py
"""HTTP wrapper for build-mode approval endpoints. Modeled on ``BuildSessionManager``: a thin static façade over the approval HTTP API, using the same ``user.headers`` / ``user.cookies`` auth pattern used elsewhere in ``common_utils.managers``. """ from __future__ import annotations import time from uuid import UUID...
45
1,604
onyx
backend/tests/integration/common_utils/managers/connector.py
.py
from typing import Any from uuid import uuid4 from onyx.connectors.models import InputType from onyx.db.enums import AccessType from onyx.server.documents.models import ConnectorUpdateRequest, DocumentSource from tests.integration.common_utils.constants import API_SERVER_URL from tests.integration.common_utils.http_cl...
126
4,337
onyx
backend/tests/integration/common_utils/managers/pat.py
.py
"""Helper for managing Personal Access Tokens in integration tests.""" from uuid import UUID import httpx from onyx.db.engine.sql_engine import get_session_with_current_tenant from onyx.db.enums import Permission from onyx.db.pat import create_pat from tests.integration.common_utils.constants import API_SERVER_URL f...
164
5,434
onyx
backend/tests/integration/common_utils/managers/project.py
.py
from typing import List from onyx.server.features.projects.models import ( CategorizedFilesSnapshot, UserFileSnapshot, UserProjectSnapshot, ) from tests.integration.common_utils.constants import API_SERVER_URL from tests.integration.common_utils.http_client import client from tests.integration.common_utils...
165
5,697
onyx
backend/tests/integration/common_utils/managers/credential.py
.py
from typing import Any from uuid import uuid4 from onyx.server.documents.models import CredentialSnapshot, DocumentSource from tests.integration.common_utils.constants import API_SERVER_URL from tests.integration.common_utils.http_client import client from tests.integration.common_utils.test_models import DATestCreden...
118
4,127
onyx
backend/tests/integration/common_utils/managers/file.py
.py
import io import mimetypes from typing import IO, List, Tuple, cast from onyx.file_store.models import FileDescriptor from onyx.server.documents.models import FileUploadResponse from tests.integration.common_utils.constants import API_SERVER_URL from tests.integration.common_utils.http_client import client from tests....
112
3,764
onyx
backend/tests/integration/common_utils/managers/user_group.py
.py
import time from uuid import uuid4 import httpx from ee.onyx.server.user_group.models import UserGroup from tests.integration.common_utils.constants import API_SERVER_URL, MAX_DELAY from tests.integration.common_utils.http_client import client from tests.integration.common_utils.test_models import DATestUser, DATestU...
225
8,067
onyx
backend/tests/integration/common_utils/managers/index_attempt.py
.py
import time from datetime import datetime, timedelta from urllib.parse import urlencode from onyx.background.indexing.models import IndexAttemptErrorPydantic from onyx.db.engine.sql_engine import get_session_with_current_tenant from onyx.db.enums import IndexModelStatus from onyx.db.models import IndexAttempt, Indexin...
224
8,293
onyx
backend/tests/integration/common_utils/managers/query_history.py
.py
import time from datetime import datetime from urllib.parse import urlencode from uuid import UUID import httpx from ee.onyx.server.query_history.models import ChatSessionMinimal, ChatSessionSnapshot from onyx.configs.constants import QAFeedbackType from onyx.db.enums import TaskStatus from onyx.server.documents.mode...
112
4,159
onyx
backend/tests/integration/common_utils/managers/settings.py
.py
from typing import Any, Dict, Optional from tests.integration.common_utils.constants import API_SERVER_URL from tests.integration.common_utils.http_client import client from tests.integration.common_utils.test_models import DATestSettings, DATestUser class SettingsManager: @staticmethod def get_settings( ...
61
1,760
onyx
backend/tests/integration/common_utils/managers/tool.py
.py
import httpx from tests.integration.common_utils.constants import API_SERVER_URL from tests.integration.common_utils.http_client import client from tests.integration.common_utils.test_models import DATestTool, DATestUser class ToolManager: @staticmethod def list_tools( user_performing_action: DATestU...
53
1,668
onyx
backend/tests/integration/common_utils/managers/skill.py
.py
import io import zipfile from collections.abc import Sequence from typing import TypeVar from uuid import UUID, uuid4 import httpx from pydantic import BaseModel from onyx.db.enums import SkillSharePermission from onyx.server.features.skill.models import ( SkillCreateRequest, SkillEditableDetailResponse, ...
471
15,762
onyx
backend/tests/integration/common_utils/managers/document.py
.py
from uuid import uuid4 from sqlalchemy import and_, select from sqlalchemy.orm import Session from onyx.configs.constants import DocumentSource from onyx.db.enums import AccessType from onyx.db.models import ConnectorCredentialPair, DocumentByConnectorCredentialPair from tests.integration.common_utils.constants impor...
288
10,097
onyx
backend/tests/integration/common_utils/managers/image_generation.py
.py
import json import os from typing import Any from uuid import uuid4 from tests.integration.common_utils.constants import API_SERVER_URL from tests.integration.common_utils.http_client import client from tests.integration.common_utils.test_models import ( DATestImageGenerationConfig, DATestUser, ) def _serial...
234
8,738
onyx
backend/tests/integration/common_utils/managers/tenant.py
.py
from datetime import datetime, timedelta, timezone import jwt from onyx.server.manage.models import AllUsersResponse from onyx.server.models import FullUserSnapshot, InvitedUserSnapshot from tests.integration.common_utils.constants import API_SERVER_URL from tests.integration.common_utils.http_client import client fr...
54
1,910
onyx
backend/tests/api/test_api.py
.py
import os from collections.abc import Generator from typing import Any import pytest from fastapi import FastAPI from fastapi.testclient import TestClient from onyx.configs.constants import DEV_VERSION_PATTERN, STABLE_VERSION_PATTERN from onyx.main import fetch_versioned_implementation from onyx.utils.logger import s...
174
6,642
onyx
backend/tests/unit/fakes.py
.py
from __future__ import annotations from onyx.cache.interface import CacheBackend, CacheLock class FakeLock(CacheLock): def __init__(self) -> None: self._owned = False def acquire( self, blocking: bool = True, blocking_timeout: float | None = None, ) -> bool: _ = b...
73
1,919
onyx
backend/tests/unit/conftest.py
.py
"""Unit-suite conftest. Unit tests assume OSS resolution unless they opt into EE via the shared ``enable_ee`` fixture (see ``backend/tests/conftest.py``). """ from collections.abc import Generator import pytest from onyx.utils.variable_functionality import ( fetch_versioned_implementation, global_version, )...
35
1,280
onyx
backend/tests/unit/model_server/test_embedding.py
.py
import asyncio import time from typing import Any, List from unittest.mock import MagicMock, patch import pytest from model_server import encoders from model_server.encoders import embed_text, process_embed_request from shared_configs.configs import DEFAULT_DOCUMENT_ENCODER_MODEL from shared_configs.enums import Embe...
117
3,655
onyx
backend/tests/unit/model_server/test_cgroup_cpu_limit.py
.py
from pathlib import Path from model_server.utils import get_cgroup_cpu_limit def _missing(tmp_path: Path) -> Path: return tmp_path / "does_not_exist" def test_cgroup_v2_quota(tmp_path: Path) -> None: v2 = tmp_path / "cpu.max" v2.write_text("800000 100000") assert ( get_cgroup_cpu_limit( ...
145
3,971
onyx
backend/tests/unit/onyx/test_startup_validation.py
.py
"""Tests for startup validation in no-vector-DB mode. Verifies that DISABLE_VECTOR_DB raises RuntimeError when combined with incompatible settings (MULTI_TENANT, ENABLE_CRAFT). """ from unittest.mock import patch import pytest class TestValidateNoVectorDbSettings: @patch("onyx.main.DISABLE_VECTOR_DB", False) ...
53
1,971
onyx
backend/tests/unit/onyx/test_redis.py
.py
import os import pytest import redis from onyx.redis.redis_pool import RedisPool from onyx.utils.logger import setup_logger logger = setup_logger() @pytest.mark.skipif( os.getenv("REDIS_CLOUD_PYTEST_PASSWORD", "") == "", reason="Environment variable REDIS_CLOUD_PYTEST_PASSWORD is not set", ) def test_redis...
40
1,109
onyx
backend/tests/unit/onyx/conftest.py
.py
"""Shared fixtures for onyx unit tests.""" import logging from collections.abc import Generator import pytest @pytest.fixture(autouse=True) def _capture_audit_logger( caplog: pytest.LogCaptureFixture, ) -> Generator[None, None, None]: """Attach caplog's handler to ``onyx.audit`` so audit tests can assert on...
23
656
onyx
backend/tests/unit/onyx/error_handling/test_exceptions.py
.py
"""Tests for OnyxError and the global exception handler.""" import pytest from fastapi import FastAPI from fastapi.testclient import TestClient from onyx.error_handling.error_codes import OnyxErrorCode from onyx.error_handling.exceptions import OnyxError, register_onyx_exception_handlers class TestOnyxError: ""...
90
3,133
onyx
backend/tests/unit/onyx/file_processing/test_xlsx_to_text.py
.py
import io from typing import cast from unittest.mock import patch import openpyxl from openpyxl.worksheet.worksheet import Worksheet from onyx.file_processing.extract_file_text import ( _sheet_to_csv, xlsx_sheet_extraction, xlsx_to_text, ) def _make_xlsx(sheets: dict[str, list[list[str]]]) -> io.BytesIO...
541
18,828
onyx
backend/tests/unit/onyx/file_processing/test_pdf.py
.py
"""Unit tests for pypdf-dependent PDF processing functions. Tests cover: - read_pdf_file: text extraction, metadata, encrypted PDFs, image extraction - pdf_to_text: convenience wrapper - is_pdf_protected: password protection detection Fixture PDFs live in ./fixtures/ and are pre-built so the test layer has no depende...
267
11,101
onyx
backend/tests/unit/onyx/file_processing/test_detect_encoding.py
.py
from io import BytesIO from unittest import mock from onyx.file_processing.extract_file_text import detect_encoding def test_utf8_cyrillic_returns_utf8_without_chardet() -> None: """Valid UTF-8 Cyrillic text must be identified as utf-8 without calling chardet.""" cyrillic = "Привет мир".encode("utf-8") w...
30
1,111
onyx
backend/tests/unit/onyx/file_processing/test_pptx_to_text.py
.py
import io from pptx import Presentation from pptx.chart.data import CategoryChartData from pptx.enum.chart import XL_CHART_TYPE from pptx.util import Inches from onyx.file_processing.extract_file_text import ( extract_pptx_images, pptx_to_text, read_pptx_file, ) def _make_1x1_png() -> bytes: """Mini...
194
5,547
onyx
backend/tests/unit/onyx/file_processing/test_image_utils.py
.py
from unittest.mock import MagicMock, patch from onyx.connectors.models import ImageSection, TabularSection, TextSection from onyx.file_processing.image_utils import make_image_callback # Minimal valid file headers for testing magic-byte detection _PNG_BYTES = b"\x89PNG\r\n\x1a\n" + b"\x00" * 50 _JPEG_BYTES = b"\xff\x...
118
4,737
onyx
backend/tests/unit/onyx/file_processing/test_image_summarization_errors.py
.py
""" Unit tests for image summarization error handling. Verifies that: 1. LLM errors produce actionable error messages (not base64 dumps) 2. Unsupported MIME type logs include the magic bytes and size 3. The ValueError raised on LLM failure preserves the original exception """ from unittest.mock import MagicMock, patc...
92
3,467
onyx
backend/tests/unit/onyx/file_processing/test_image_summarization_litellm_errors.py
.py
""" Unit tests verifying that LiteLLM error details are extracted and surfaced in image summarization error messages. When the LLM call fails, the error handler should include the status_code, llm_provider, and model from LiteLLM exceptions so operators can diagnose the root cause (rate limit, content filter, unsuppor...
142
5,171
onyx
backend/tests/unit/onyx/tracing/test_tracing_setup.py
.py
"""setup_tracing: dynamic processor, user_usage registration, idempotency.""" from unittest.mock import patch import pytest from onyx.tracing import setup as tracing_setup from onyx.tracing.dynamic_processor import DynamicTracingProcessor from onyx.tracing.provider_config import ( BraintrustConfig, Effective...
108
3,880
onyx
backend/tests/unit/onyx/tracing/test_langfuse_incognito_suppression.py
.py
"""Incognito turns must leave no content in Langfuse: the processor drops the whole trace, spans included, keyed on membership recorded at trace start.""" from collections.abc import Generator from unittest.mock import MagicMock import pytest from onyx.tracing.langfuse_tracing_processor import LangfuseTracingProcess...
61
1,754
onyx
backend/tests/unit/onyx/tracing/test_braintrust_incognito_suppression.py
.py
"""Incognito turns must leave no content in Braintrust: the processor drops the whole trace, spans included, keyed on membership recorded at trace start.""" from collections.abc import Generator from unittest.mock import MagicMock import pytest from onyx.tracing.braintrust_tracing_processor import BraintrustTracingP...
81
2,453
onyx
backend/tests/unit/onyx/tracing/test_flows_registry.py
.py
"""Unit tests for ``onyx.tracing.flows`` and ``traced_llm_call``.""" import pytest from onyx.tracing.flows import IMAGE_FLOWS, LLMFlow from onyx.tracing.framework.create import trace from onyx.tracing.framework.span_data import GenerationSpanData from onyx.tracing.llm_utils import traced_llm_call def test_llmflow_v...
68
2,509
onyx
backend/tests/unit/onyx/tracing/test_braintrust_tracing_processor.py
.py
import sys from unittest.mock import MagicMock, patch import pytest from onyx.tracing.framework.span_data import GenerationSpanData # The connector tests also define a top-level package named braintrust. Stub the # optional SDK so full-suite collection cannot bind this import to that package. with patch.dict(sys.mod...
32
1,033
onyx
backend/tests/unit/onyx/tracing/test_langfuse_tracing_processor.py
.py
"""Unit tests for LangfuseTracingProcessor metadata handling.""" from collections.abc import Mapping from typing import Any from unittest.mock import MagicMock import pytest from onyx.tracing.framework.span_data import GenerationSpanData from onyx.tracing.langfuse_tracing_processor import LangfuseTracingProcessor ...
90
3,117
onyx
backend/tests/unit/onyx/tracing/test_dynamic_processor.py
.py
"""Unit tests for the live-reload behavior of DynamicTracingProcessor.""" from typing import Any, cast from unittest.mock import patch from onyx.tracing.dynamic_processor import DynamicTracingProcessor from onyx.tracing.framework.processor_interface import TracingProcessor from onyx.tracing.framework.spans import Spa...
148
4,960
onyx
backend/tests/unit/onyx/tracing/test_trace_metadata.py
.py
from onyx.tracing.framework.create import ChatTraceMetadata from shared_configs.contextvars import CURRENT_TENANT_ID_CONTEXTVAR def test_chat_trace_metadata_uses_current_tenant() -> None: token = CURRENT_TENANT_ID_CONTEXTVAR.set("tenant") try: metadata = ChatTraceMetadata(chat_session_id="session", us...
17
538
onyx
backend/tests/unit/onyx/tracing/test_user_usage_processor.py
.py
"""Per-user usage recorder: capture, pricing args, drain, shutdown. `record_user_usage` is Postgres-only; these tests mock it and assert call args rather than executing the upsert against SQLite.""" from __future__ import annotations from collections.abc import Generator from contextlib import contextmanager from da...
367
11,356
onyx
backend/tests/unit/onyx/background/test_user_file_delete_enqueue.py
.py
"""Guards that queued user file deletes reach a consumer on every deployment. Lite deployments run no Celery, so a send_task there lands on a queue nothing drains and the delete waits on the recovery poll instead of running with the request. """ from unittest.mock import MagicMock, patch from uuid import uuid4 from ...
52
1,768
onyx
backend/tests/unit/onyx/background/test_periodic_poller_license_reclaim.py
.py
"""Guards license renewal on deployments the poller exists for: no Redis and no Celery worker, so the point-of-use scheduler has nothing to enqueue onto and this thread is the only thing that can renew an expiring license.""" from unittest.mock import MagicMock, patch from onyx.background.periodic_poller import _buil...
48
2,116
onyx
backend/tests/unit/onyx/background/indexing/test_simple_job_terminate.py
.py
"""Unit tests for `SimpleJob.terminate_and_wait`. These tests do NOT exercise the full indexing watchdog. They only validate the small primitive added so the watchdog can hard-kill a stuck spawned process when its IndexAttempt has been finalized. We need real OS processes here (multiprocessing.Process) - mocking woul...
127
4,268
onyx
backend/tests/unit/onyx/background/celery/test_app_base_logging.py
.py
""" Unit tests for the LOG_LEVEL env var override in Celery's ``setup_logging`` handler. Verifies the precedence rule in ``onyx.background.celery.apps.app_base.on_setup_logging``: explicit --loglevel CLI arg > LOG_LEVEL env var > Celery default. """ import logging import sys from collections.abc import Generator ...
244
7,516
onyx
backend/tests/unit/onyx/background/celery/test_celery_redis.py
.py
"""Tests for celery_get_broker_client singleton.""" from collections.abc import Iterator from unittest.mock import MagicMock, patch import pytest from onyx.background.celery import celery_redis @pytest.fixture(autouse=True) def reset_singleton() -> Iterator[None]: """Reset the module-level singleton between te...
87
3,101
onyx
backend/tests/unit/onyx/background/celery/tasks/test_docfetching_worker_shutdown.py
.py
"""Guards the graceful-shutdown wiring: the process-global signal the worker_shutting_down handler sets and the indexing watchdog polls, plus the existence of the watchdog terminal-status constant the shutdown branch keys off. """ from onyx.background.celery.tasks.docfetching import worker_shutdown from onyx.backgroun...
25
946
onyx
backend/tests/unit/onyx/background/celery/tasks/test_user_file_processing_no_vectordb.py
.py
"""Tests for no-vector-DB user file processing paths. Verifies that when DISABLE_VECTOR_DB is True: - process_user_file_impl calls _process_user_file_without_vector_db (not indexing) - _process_user_file_without_vector_db extracts text, counts tokens, stores plaintext, sets status=COMPLETED and chunk_count=0 - delet...
476
17,722
onyx
backend/tests/unit/onyx/background/celery/tasks/test_user_file_project_sync_queue.py
.py
from unittest.mock import MagicMock, patch from uuid import uuid4 import pytest from onyx.background.celery.tasks.user_file_processing.tasks import ( _user_file_project_sync_queued_key, check_for_user_file_project_sync, enqueue_user_file_project_sync_task, process_single_user_file_project_sync, ) from...
160
5,433
onyx
backend/tests/unit/onyx/background/celery/tasks/test_user_file_impl_redis_locking.py
.py
"""Tests for the _impl functions' redis_locking parameter. Verifies that: - redis_locking=True acquires/releases Redis locks and clears queued keys - redis_locking=False skips all Redis operations entirely - Both paths execute the same business logic (DB lookup, status check) """ from unittest.mock import MagicMock, ...
293
9,739
onyx
backend/tests/unit/onyx/background/celery/tasks/test_port_wiring.py
.py
"""Guards the Celery wiring of the reindex-port flow. The port logic itself is covered by the external_dependency_unit `db/test_*port*` suites (which run against real Postgres/OpenSearch). Those mock the celery app, so nothing there proves a beat-enqueued port task actually reaches a worker. These unit tests guard exa...
75
3,223
onyx
backend/tests/unit/onyx/background/celery/tasks/test_hierarchyfetching_queue.py
.py
from unittest.mock import MagicMock, patch from onyx.background.celery.tasks.hierarchyfetching.tasks import ( _connector_supports_hierarchy_fetching, check_for_hierarchy_fetching, ) from onyx.connectors.factory import ConnectorMissingException from onyx.connectors.interfaces import ( BaseConnector, Hie...
194
7,537
onyx
backend/tests/unit/onyx/background/celery/tasks/test_indexing_interrupted.py
.py
"""Guards the INTERRUPTED reclassification: an attempt stopped mid-run by infrastructure (deploy / autoscaling) must not count as a failure, so it never trips the repeated-error auto-pause, while genuine consecutive FAILED still does. """ from unittest.mock import MagicMock, patch from onyx.background.celery.tasks.do...
82
2,842
onyx
backend/tests/unit/onyx/background/celery/tasks/tenant_provisioning/test_check_available_tenants.py
.py
""" Unit tests for the check_available_tenants task. Tests verify: - Provisioning loop calls pre_provision_tenant the correct number of times - Batch size is capped at _MAX_TENANTS_PER_RUN - A failure in one provisioning call does not stop subsequent calls - No provisioning happens when pool is already full - TARGET_A...
215
6,812
onyx
backend/tests/unit/onyx/background/celery/tasks/port/test_run_port_attempt_cursor.py
.py
"""Unit coverage for the reindex-port producer's cursor-advance invariant. `run_port_attempt` must only advance `last_processed_doc_id` past a batch that was FULLY ported. When a batch aborts mid-copy (the copier returns aborted=True, e.g. the stall watchdog marked the attempt FAILED while it was re-embedding), the cu...
99
3,848
onyx
backend/tests/unit/onyx/access/test_user_file_access.py
.py
"""Tests for user file ACL computation, including shared persona access.""" from unittest.mock import MagicMock, patch from uuid import uuid4 from onyx.access.access import collect_user_file_access, get_access_for_user_files_impl from onyx.access.utils import prefix_user_email from onyx.configs.constants import PUBLI...
162
5,571
onyx
backend/tests/unit/onyx/access/test_acl_prior_emails.py
.py
"""Guards that a renamed user keeps matching their old address. Indexed ACLs keep naming the address the source system knew, so matching only the current one locks a renamed user out of their own documents until every connector re-syncs. Treating prior addresses as the same principal is what makes a rename invisible t...
68
2,264
onyx
backend/tests/unit/onyx/server/test_incognito_upload_guard.py
.py
"""Guards which incognito sessions the upload endpoint accepts files for. Switching incognito on mints the session id client-side, so uploads arrive naming a session that holds no context until its first message. Only a teardown tombstone closes a session to new files, and an upload that overlaps one has to claim its ...
120
4,082
onyx
backend/tests/unit/onyx/server/test_prometheus_instrumentation.py
.py
"""Unit tests for Prometheus instrumentation module.""" import threading from typing import Any from unittest.mock import MagicMock, patch from fastapi import FastAPI from fastapi.testclient import TestClient from prometheus_client import CollectorRegistry, Gauge from onyx.server.metrics.per_tenant import per_tenant...
243
7,768
onyx
backend/tests/unit/onyx/server/test_settings_store.py
.py
import pytest from onyx.configs.app_configs import DEFAULT_USER_FILE_MAX_UPLOAD_SIZE_MB from onyx.key_value_store.interface import KvKeyNotFoundError from onyx.server.settings import store as settings_store from onyx.server.settings.models import ( DEFAULT_FILE_TOKEN_COUNT_THRESHOLD_K_NO_VECTOR_DB, DEFAULT_FIL...
171
6,917
onyx
backend/tests/unit/onyx/server/test_search_surface_scopes.py
.py
""" Pins the search surface's route gates to READ_SEARCH so a read:search-scoped PAT can reach every endpoint the scope's description promises ("Use search and query endpoints"). Scoped PATs can never satisfy BASIC_ACCESS (implication only flows basic -> read:search), so a route in this surface regressing to BASIC_ACCE...
56
1,827