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/server/metrics/test_indexing_pipeline_collectors.py
.py
"""Tests for indexing pipeline Prometheus collectors.""" from collections.abc import Iterator from unittest.mock import MagicMock, patch import pytest from onyx.server.metrics.indexing_pipeline import QueueDepthCollector @pytest.fixture(autouse=True) def _mock_broker_client() -> Iterator[None]: """Patch celery...
134
4,433
onyx
backend/tests/unit/server/metrics/test_deletion_metrics.py
.py
"""Tests for deletion-specific Prometheus metrics.""" import pytest from onyx.server.metrics.deletion_metrics import ( DELETION_BLOCKED, DELETION_COMPLETED, DELETION_FENCE_RESET, DELETION_STARTED, DELETION_TASKSET_DURATION, inc_deletion_blocked, inc_deletion_completed, inc_deletion_fen...
207
7,063
onyx
backend/tests/unit/server/metrics/test_opensearch_search_metrics.py
.py
"""Tests for OpenSearch search Prometheus metrics.""" from unittest.mock import patch import pytest from onyx.document_index.opensearch.constants import OpenSearchSearchType from onyx.server.metrics.opensearch_search import ( _client_duration, _client_server_overhead, _search_errors, _search_total, ...
341
13,480
onyx
backend/tests/unit/server/metrics/test_perm_sync_metrics.py
.py
"""Tests for permission-sync-specific Prometheus metrics.""" import pytest from onyx.server.metrics.perm_sync_metrics import ( DOC_PERM_SYNC_DB_UPDATE_DURATION, DOC_PERM_SYNC_DOCS_PROCESSED, DOC_PERM_SYNC_DURATION, DOC_PERM_SYNC_ERRORS, GROUP_SYNC_DURATION, GROUP_SYNC_ERRORS, GROUP_SYNC_GR...
319
10,742
onyx
backend/tests/unit/server/metrics/test_pruning_metrics.py
.py
"""Tests for pruning-specific Prometheus metrics.""" import pytest from onyx.server.metrics.pruning_metrics import ( PRUNING_DIFF_DURATION, PRUNING_ENUMERATION_DURATION, PRUNING_RATE_LIMIT_ERRORS, inc_pruning_rate_limit_error, observe_pruning_diff_duration, observe_pruning_enumeration_duration...
131
4,499
onyx
backend/tests/unit/server/metrics/test_mcp_metrics.py
.py
import asyncio from unittest.mock import AsyncMock, MagicMock, patch import httpx import pytest from fastapi.testclient import TestClient from onyx.db.enums import MCPAuthenticationType from onyx.mcp_server.api import create_mcp_fastapi_app from onyx.mcp_server.auth import OnyxTokenVerifier from onyx.mcp_server.tools...
198
6,837
onyx
backend/tests/unit/server/metrics/test_embedding_metrics.py
.py
"""Tests for embedding Prometheus metrics.""" from unittest.mock import patch from onyx.server.metrics.embedding import ( LOCAL_PROVIDER_LABEL, PROVIDER_LABEL_NAME, TEXT_TYPE_LABEL_NAME, _client_duration, _embedding_input_chars_total, _embedding_requests_total, _embedding_texts_total, ...
259
8,604
onyx
backend/tests/unit/server/metrics/test_indexing_pipeline_setup.py
.py
"""Tests for indexing pipeline setup.""" from unittest.mock import MagicMock from onyx.server.metrics.indexing_pipeline import ( QueueDepthCollector, RedisHealthCollector, ) class TestCollectorCeleryAppSetup: def test_queue_depth_collector_uses_celery_app(self) -> None: """QueueDepthCollector.se...
25
853
onyx
backend/tests/unit/server/metrics/test_craft_sandbox_metrics.py
.py
"""Tests for Craft sandbox provisioning Prometheus metrics. Values are read through ``REGISTRY.get_sample_value`` rather than collector internals, so the assertions cover the samples Prometheus actually scrapes. Metrics are process-global, so every assertion is a delta against a baseline. """ from unittest.mock impor...
187
7,046
onyx
backend/tests/unit/server/metrics/test_indexing_task_metrics.py
.py
"""Tests for per-connector indexing task Prometheus metrics.""" from collections.abc import Iterator from unittest.mock import MagicMock, patch import pytest from onyx.server.metrics.indexing_task_metrics import ( INDEXING_TASK_COMPLETED, INDEXING_TASK_DURATION, INDEXING_TASK_STARTED, ConnectorInfo, ...
321
11,738
onyx
backend/tests/unit/server/metrics/test_worker_health.py
.py
"""Tests for WorkerHeartbeatMonitor and WorkerHealthCollector.""" import time from unittest.mock import MagicMock from onyx.server.metrics.indexing_pipeline import ( WorkerHealthCollector, WorkerHeartbeatMonitor, ) class TestWorkerHeartbeatMonitor: def test_heartbeat_registers_worker(self) -> None: ...
197
7,507
onyx
backend/tests/unit/tools/test_memory_tool_packets.py
.py
"""Tests for memory tool streaming packet emissions.""" import queue from unittest.mock import MagicMock, patch import pytest from onyx.chat.emitter import Emitter from onyx.server.query_and_chat.placement import Placement from onyx.server.query_and_chat.session_loading import create_memory_packets from onyx.server....
215
6,919
onyx
backend/tests/unit/federated_connector/test_reject_masked_credentials.py
.py
import pytest from onyx.configs.constants import MASK_CREDENTIAL_CHAR from onyx.utils.encryption import reject_masked_credentials class TestRejectMaskedCredentials: """Verify that masked credential values are never accepted for DB writes. mask_string() has two output formats: - Short strings (< 14 chars...
108
4,086
onyx
backend/tests/unit/federated_connector/slack/test_slack_federated_connnector.py
.py
from datetime import datetime, timedelta, timezone from typing import Any from unittest.mock import patch import pytest from pydantic import ValidationError from onyx.federated_connectors.models import OAuthResult from onyx.federated_connectors.slack.federated_connector import SlackFederatedConnector from onyx.federa...
429
16,318
onyx
backend/tests/unit/ee/conftest.py
.py
"""Auto-enable EE mode for all tests under tests/unit/ee/.""" import logging from collections.abc import Generator import pytest @pytest.fixture(autouse=True) def _enable_ee_for_directory(enable_ee: None) -> None: """Wraps the shared enable_ee fixture with autouse for this directory.""" @pytest.fixture(autous...
28
840
onyx
backend/tests/unit/ee/onyx/background/celery/tasks/test_license_reclaim_task.py
.py
"""Guards the reclaim_license_task gating contract: it re-claims only for self-hosted deployments whose license is expired or near expiry, swallows control-plane failures, and throttles its own control-plane attempts so its triggers (request-path debounce, periodic poller) can fire it freely.""" from datetime import d...
377
15,646
onyx
backend/tests/unit/ee/onyx/background/celery/tasks/license_notifications/test_grace_sync.py
.py
"""Guards the grace-entry renewal fetch: an expired instance pulls the license it is waiting on where the stage is already computed, and an admin is told what actually failed rather than to renew something Onyx already tried to renew.""" from datetime import datetime, timedelta, timezone from unittest.mock import Magi...
123
4,872
onyx
backend/tests/unit/ee/onyx/server/settings/test_license_enforcement_settings.py
.py
"""Tests for license enforcement in settings API.""" from unittest.mock import MagicMock, patch import pytest from redis.exceptions import RedisError from onyx.server.settings.models import ApplicationStatus, Settings # Fields we assert on across all tests _ASSERT_FIELDS = { "application_status", "ee_featur...
294
11,319
onyx
backend/tests/unit/ee/onyx/server/reporting/test_usage_report_data.py
.py
"""Aggregation behind the usage report review pack.""" from datetime import datetime, timezone from io import BytesIO from unittest.mock import MagicMock, patch import pytest from PIL import Image as PILImage from pypdf import PdfReader from ee.onyx.server.reporting.usage_report_branding import ReportBranding from e...
285
9,466
onyx
backend/tests/unit/ee/onyx/server/reporting/test_usage_report_branding.py
.py
"""Which logo the review pack renders under.""" from unittest.mock import MagicMock, patch from ee.onyx.server.enterprise_settings.models import EnterpriseSettings from ee.onyx.server.reporting.usage_report_branding import ( ReportBranding, load_report_branding, ) from onyx.utils.file import FileWithMimeType ...
89
2,861
onyx
backend/tests/unit/ee/onyx/server/tenants/test_impersonation_gate.py
.py
"""Tests for the impersonation feature gate. Impersonation is gated at the router level: the endpoint is only registered when IMPERSONATION_ENABLED is set. When disabled it is not mounted at all, so a request 404s rather than reaching the handler or the auth layer. """ from fastapi import APIRouter from fastapi.routi...
35
1,209
onyx
backend/tests/unit/ee/onyx/server/tenants/test_proxy.py
.py
"""Tests for proxy endpoints for self-hosted data planes.""" import inspect from datetime import datetime, timedelta, timezone from unittest.mock import AsyncMock, MagicMock, patch import httpx import pytest from fastapi import HTTPException from ee.onyx.server.license.models import LicensePayload, PlanType from ee....
653
24,673
onyx
backend/tests/unit/ee/onyx/server/tenants/test_product_gating.py
.py
"""Tests for product gating functions.""" from unittest.mock import MagicMock, patch import pytest class TestIsTenantGated: """Tests for is_tenant_gated - the O(1) Redis check used by middleware.""" @pytest.mark.parametrize( "redis_result,expected", [ (True, True), (...
69
2,195
onyx
backend/tests/unit/ee/onyx/server/tenants/test_access.py
.py
"""Tests for data-plane token generation. PyJWT (>=2.13) raises InvalidKeyError for an empty HMAC key, whereas earlier versions silently signed with it. Callers only anticipate the ValueError that signals a misconfigured secret, so an empty DATA_PLANE_SECRET must be treated the same as unset. """ import jwt import py...
32
1,126
onyx
backend/tests/unit/ee/onyx/server/tenants/test_billing_seat_enforcement.py
.py
"""Unit tests for cloud (multi-tenant) auto-bill seat enforcement. Covers ``attempt_seat_billing_increase`` (Stripe error mapping + idempotency) and ``enforce_cloud_seat_limit`` (trial bypass + decline surfacing as ``OnyxError(SEAT_LIMIT_EXCEEDED)``). """ from __future__ import annotations from unittest.mock import ...
250
9,038
onyx
backend/tests/unit/ee/onyx/server/tenants/test_billing_api.py
.py
"""Tests for billing API endpoints.""" from unittest.mock import AsyncMock, MagicMock, patch import httpx import pytest from onyx.error_handling.error_codes import OnyxErrorCode from onyx.error_handling.exceptions import OnyxError class TestGetStripePublishableKey: """Tests for get_stripe_publishable_key endpo...
286
11,846
onyx
backend/tests/unit/ee/onyx/server/tenants/test_schema_management.py
.py
"""Tests for schema management functions.""" import pytest from ee.onyx.server.tenants.schema_management import drop_schema class TestDropSchemaValidation: """Tests for drop_schema input validation (no DB required - fails before SQL).""" @pytest.mark.parametrize( "dangerous_input,description", ...
31
1,116
onyx
backend/tests/unit/ee/onyx/server/tenants/test_tenant_resolution_by_oauth_account.py
.py
"""Guards the resolution order that keeps a renamed user out of a fresh tenant. `resolve_tenant_id` must consult the IdP subject before the email, because the subject is the only identifier that survives an address change at the provider. If the order inverts, a renamed user resolves nowhere and `get_or_provision_tena...
282
10,410
onyx
backend/tests/unit/ee/onyx/server/tenants/test_provisioning.py
.py
"""Tests for tenant provisioning helpers.""" from unittest.mock import MagicMock, patch _PROVISIONING_MODULE = "ee.onyx.server.tenants.provisioning" def _patch_recommendations() -> MagicMock: """Build a MagicMock that imitates `LLMProviderRecommendations`. `configure_default_api_keys` calls `get_default_mo...
83
3,304
onyx
backend/tests/unit/ee/onyx/server/tenants/test_impersonation_tenant_binding.py
.py
"""The impersonation token must name the impersonated user's workspace. Session issuance takes an explicit override when the caller has already decided the workspace. Without one it would fall back to resolving the superuser's own address, minting a session for the wrong workspace. """ from types import SimpleNamespa...
75
2,998
onyx
backend/tests/unit/ee/onyx/server/tenants/test_record_oauth_identity.py
.py
"""Guards the mapping-table writers: cloud-only sessions, link-once semantics for subjects, and identity movement through rename and invitation flows. The `public.user_tenant_mapping*` tables are created by the `alembic_tenants` tree, which only multi-tenant deployments run. Opening a session against them anywhere els...
616
25,176
onyx
backend/tests/unit/ee/onyx/server/billing/test_proxy.py
.py
"""Tests for the billing proxy endpoints.""" from unittest.mock import AsyncMock, MagicMock, patch import httpx import pytest from ee.onyx.server.license.models import LicensePayload from .conftest import make_license_payload, make_mock_http_client, make_mock_response class TestProxySeatUpdate: """Tests for p...
363
13,223
onyx
backend/tests/unit/ee/onyx/server/billing/test_billing_service.py
.py
"""Tests for the billing service layer.""" from unittest.mock import AsyncMock, MagicMock, patch import httpx import pytest from ee.onyx.server.billing.models import ( BillingInformationResponse, CreateCheckoutSessionResponse, CreateCustomerPortalSessionResponse, SeatUpdateResponse, SubscriptionS...
326
11,824
onyx
backend/tests/unit/ee/onyx/server/billing/test_billing_api.py
.py
"""Tests for the unified billing API endpoints.""" from unittest.mock import AsyncMock, MagicMock, patch import pytest from ee.onyx.server.billing.models import ( BillingInformationResponse, CreateCheckoutSessionResponse, CreateCustomerPortalSessionResponse, SeatUpdateResponse, SubscriptionStatus...
616
23,990
onyx
backend/tests/unit/ee/onyx/server/billing/test_billing_cache.py
.py
"""Unit tests for the Redis-backed billing cache.""" from collections.abc import Generator from datetime import datetime, timedelta, timezone from unittest.mock import MagicMock, patch import pytest from redis.exceptions import RedisError from ee.onyx.server.billing import billing_cache as bc from ee.onyx.server.bil...
337
12,235
onyx
backend/tests/unit/ee/onyx/server/billing/conftest.py
.py
"""Shared fixtures and utilities for billing tests.""" from datetime import datetime, timedelta, timezone from unittest.mock import AsyncMock, MagicMock import pytest from ee.onyx.server.license.models import LicensePayload, PlanType @pytest.fixture def mock_license_payload() -> LicensePayload: """Create a val...
81
2,220
onyx
backend/tests/unit/ee/onyx/server/metrics/test_license_metrics.py
.py
"""Tests for the self-hosted license Prometheus collector.""" from datetime import datetime, timezone from unittest.mock import MagicMock, patch from prometheus_client.core import GaugeMetricFamily from ee.onyx.server.metrics.license_metrics import LicenseMetricsCollector from onyx.server.settings.models import Appl...
126
5,059
onyx
backend/tests/unit/ee/onyx/server/license/test_api.py
.py
"""Tests for license API utilities.""" from datetime import datetime, timedelta, timezone from unittest.mock import MagicMock, patch import pytest from ee.onyx.server.license.api import claim_license from ee.onyx.server.license.models import LicensePayload, PlanType from ee.onyx.utils.license import ( LicenseNot...
193
7,157
onyx
backend/tests/unit/ee/onyx/server/gateway/test_openai_passthrough.py
.py
from __future__ import annotations import hashlib import json from collections.abc import Iterator from contextlib import contextmanager, nullcontext from typing import Any from unittest.mock import MagicMock, patch import httpx import pytest from fastapi import Request from fastapi.responses import JSONResponse fro...
1,225
40,452
onyx
backend/tests/unit/ee/onyx/server/gateway/test_llm_gateway_api.py
.py
from __future__ import annotations import json import threading from collections.abc import Awaitable, Callable, Generator, Iterator from contextlib import contextmanager, nullcontext from pathlib import Path from typing import Any, cast from unittest.mock import MagicMock, patch import pytest from fastapi import Fas...
2,064
69,383
onyx
backend/tests/unit/ee/onyx/server/gateway/test_anthropic_messages_api.py
.py
from __future__ import annotations import json import threading from contextlib import nullcontext from typing import Any, cast from unittest.mock import MagicMock, patch import pytest from fastapi import Request from fastapi.responses import StreamingResponse from sqlalchemy.orm import Session from ee.onyx.server.g...
1,109
35,393
onyx
backend/tests/unit/ee/onyx/server/gateway/test_anthropic_passthrough.py
.py
from __future__ import annotations import hashlib import json from contextlib import contextmanager, nullcontext from typing import Any from unittest.mock import MagicMock, patch import httpx import pytest from fastapi import Request from fastapi.responses import JSONResponse from ee.onyx.server.gateway import anthr...
1,020
32,861
onyx
backend/tests/unit/ee/onyx/server/middleware/test_license_enforcement.py
.py
"""Tests for license enforcement middleware.""" from collections.abc import Awaitable, Callable from datetime import datetime, timedelta, timezone from typing import Any from unittest.mock import MagicMock, patch import pytest from starlette.requests import Request from starlette.responses import Response from ee.on...
296
11,378
onyx
backend/tests/unit/ee/onyx/server/middleware/test_tenant_tracking.py
.py
"""Tests for the api-server tenant-resolution middleware. Focus: tenant resolution must **fail closed**. A transient Redis error during the cookie- or Bearer-header session-token lookup must propagate (500), not get swallowed into a silent default-schema fallback β€” otherwise a request could be served against the wrong...
118
4,659
onyx
backend/tests/unit/ee/onyx/server/middleware/test_tier_gate.py
.py
"""Tests for the unified tier_gate middleware.""" from collections.abc import Awaitable, Callable from typing import Any from unittest.mock import MagicMock, patch import pytest from starlette.requests import Request from starlette.responses import Response from onyx.server.settings.models import Tier MiddlewareHar...
201
7,063
onyx
backend/tests/unit/ee/onyx/server/features/hooks/test_api.py
.py
"""Unit tests for ee.onyx.server.features.hooks.api helpers. Covers: - _check_ssrf_safety: scheme enforcement and private-IP blocklist, driven by the admin SSRF Protection level (allow_private_network opens RFC1918 hosts while loopback/metadata stay blocked; https_only holds at every level) - _validate_endpoint: h...
347
14,386
onyx
backend/tests/unit/ee/onyx/server/token_rate_limits/test_cost_budget_api.py
.py
"""Global token-rate-limit create/read round-trips cost_budget_cents (cents at the API boundary), and a limit may carry only a cost budget (no token budget).""" from collections.abc import Generator from typing import cast import pytest from fastapi import FastAPI from fastapi.testclient import TestClient from sqlalc...
104
3,306
onyx
backend/tests/unit/ee/onyx/server/log_export/test_expiring_lock.py
.py
from ee.onyx.server.log_export.api import _ExpiringLock def test_expiring_lock_ttl_steal_and_stale_release() -> None: now = [0.0] lock = _ExpiringLock(ttl_seconds=60.0, clock=lambda: now[0]) first = lock.try_acquire() assert first is not None assert lock.try_acquire() is None # Expiry lets a...
26
683
onyx
backend/tests/unit/ee/onyx/server/log_export/test_export_state.py
.py
from datetime import datetime, timedelta, timezone from ee.onyx.server.log_export.models import ( LogExportManifest, LogExportReceipt, LogExportReceiptStatus, LogExportSnapshot, LogExportState, ) from ee.onyx.server.log_export.storage import derive_export_state _NOW = datetime(2026, 7, 31, 12, 0, ...
73
2,116
onyx
backend/tests/unit/ee/onyx/server/log_export/test_log_collection.py
.py
import os import zipfile from pathlib import Path import pytest from ee.onyx.server.log_export.collection import README_FILE_NAME, build_log_zip SCOPE_NOTE = "Scope: test scope note." def _zip_names(zip_file: zipfile.ZipFile) -> list[str]: return zip_file.namelist() def _entry_ending_with(zip_file: zipfile.Z...
172
6,792
onyx
backend/tests/unit/ee/onyx/hooks/test_executor.py
.py
"""Unit tests for the hook executor.""" import json from typing import Any from unittest.mock import MagicMock, patch import httpx import pytest from pydantic import BaseModel from ee.onyx.hooks.executor import _execute_hook_impl as execute_hook from onyx.db.enums import HookFailStrategy, HookPoint from onyx.error_h...
693
24,536
onyx
backend/tests/unit/ee/onyx/connectors/test_ee_capability_checks.py
.py
from unittest.mock import MagicMock import pytest from ee.onyx.connectors import capability_checks as ee_capability_checks from ee.onyx.connectors.capability_checks import ( get_applicable_perm_sync_capabilities, get_perm_sync_capability_checks, ) from onyx.configs.constants import DocumentSource from onyx.co...
226
7,784
onyx
backend/tests/unit/ee/onyx/connectors/test_perm_sync_valid.py
.py
from unittest.mock import MagicMock from ee.onyx.connectors.perm_sync_valid import ( source_has_perm_sync_probe, validate_perm_sync, ) from onyx.configs.constants import DocumentSource from onyx.connectors.canvas.connector import CanvasConnector from onyx.connectors.interfaces import BaseConnector def test_p...
60
1,964
onyx
backend/tests/unit/ee/onyx/utils/test_license_trial_copy.py
.py
"""Guards that expiry notifications name a trial ending as a trial ending. A trialing subscription mints a license that expires at the trial end, so the ordinary expiry stages fire during a perfectly healthy trial. The copy has to follow the license's trial_end, and licenses issued without that field have to keep the ...
134
4,450
onyx
backend/tests/unit/ee/onyx/utils/test_license_utils.py
.py
"""Tests for license signature verification utilities.""" import base64 import json from datetime import datetime, timedelta, timezone from unittest.mock import patch import pytest from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import padding, rsa from...
307
11,176
onyx
backend/tests/unit/ee/onyx/utils/test_license_reclaim.py
.py
"""Guards the license persistence contract: a blob is stored only after its signature verifies, and the control-plane re-claim authenticates with the stored license, validates the response, and persists through the same path. Also guards the point-of-use scheduler: one debounced reclaim per window, never an exception i...
586
22,936
onyx
backend/tests/unit/ee/onyx/utils/test_tier.py
.py
"""Unit tests for `ee.onyx.utils.tier`: self-hosted tier resolution (cache-failure resilience) and the tier-requirement guards. """ from unittest.mock import MagicMock, patch import pytest from redis.exceptions import RedisError from sqlalchemy.exc import SQLAlchemyError from ee.onyx.server.license.models import Cus...
289
11,183
onyx
backend/tests/unit/ee/onyx/utils/test_license_expiry.py
.py
from datetime import datetime, timedelta, timezone from unittest.mock import patch import pytest from ee.onyx.utils.license_expiry import ( LICENSE_GRACE_PERIOD_DAYS, ExpiryWarningStage, get_expiry_warning_stage, get_grace_days_remaining, get_grace_period_end, ) NOW = datetime(2026, 5, 1, 12, 0, ...
180
6,795
onyx
backend/tests/unit/ee/onyx/utils/test_telemetry_client_ip.py
.py
"""Unit tests for the client-IP enrichment in ee.onyx.utils.telemetry.""" from unittest.mock import MagicMock from ee.onyx.utils import telemetry as ee_telemetry from onyx.utils import client_ip as client_ip_mod def test_event_telemetry_reads_client_ip_from_contextvar(monkeypatch): fake_posthog = MagicMock() ...
65
1,929
onyx
backend/tests/unit/ee/onyx/utils/test_encryption.py
.py
"""Tests for EE AES-CBC encryption/decryption with explicit key support. With EE mode enabled (via conftest), fetch_versioned_implementation resolves to the EE implementations, so no patching of the MIT layer is needed. """ from unittest.mock import patch import pytest from ee.onyx.utils.encryption import ( _de...
168
6,606
onyx
backend/tests/unit/ee/onyx/external_permissions/google_drive/test_get_drive_members_admin_403.py
.py
import time from unittest.mock import MagicMock, patch import pytest from googleapiclient.errors import HttpError from ee.onyx.external_permissions.google_drive.group_sync import _get_drive_members def _make_http_error(status: int) -> HttpError: resp = MagicMock() resp.status = status resp.reason = "For...
62
2,267
onyx
backend/tests/unit/ee/onyx/external_permissions/google_drive/test_get_all_folders_streaming.py
.py
import inspect import time from typing import Any from unittest.mock import MagicMock, patch import pytest from ee.onyx.external_permissions.google_drive.group_sync import ( _get_all_folders, _get_all_google_groups, ) def _folder(folder_id: str) -> dict[str, Any]: """A Drive folder payload carrying one ...
189
6,898
onyx
backend/tests/unit/ee/onyx/external_permissions/google_drive/test_gdrive_domain_permission_scoping.py
.py
"""Drive "everyone at <domain>" shares must map to a domain group (domain:<domain>), never to instance-public, on both the file and folder permission paths. The user-side token comes from the synced domain group's real Workspace membership, not from the user's email string.""" import time from types import SimpleNames...
345
12,281
onyx
backend/tests/unit/ee/onyx/external_permissions/confluence/test_space_access.py
.py
"""Dispatcher-level tests for Confluence space permission sync. The companion file `backend/tests/unit/onyx/connectors/confluence/test_onyx_confluence.py` covers the OnyxConfluence client methods (REST 404/500 handling, version probe, userKey-email cache). Tests here cover the EE-side dispatcher in `ee/onyx/external_p...
306
11,034
onyx
backend/tests/unit/ee/onyx/external_permissions/sharepoint/test_permission_utils.py
.py
from collections.abc import Generator from typing import Any from unittest.mock import MagicMock, patch import pytest from office365.runtime.client_request import ClientRequestException from ee.onyx.external_permissions.sharepoint.permission_utils import ( AD_GROUP_ENUMERATION_THRESHOLD, AZURE_AD_GROUP_PRINCI...
846
28,302
onyx
backend/tests/unit/ee/onyx/external_permissions/jira/test_jira_group_sync.py
.py
import logging from unittest.mock import MagicMock import pytest from jira import JIRA from jira.exceptions import JIRAError from ee.onyx.external_permissions.jira.group_sync import ( _fetch_group_member_page, _get_group_member_emails, ) def test_get_group_member_emails_skips_deleted_group( caplog: pyte...
42
1,164
onyx
backend/tests/unit/ee/onyx/external_permissions/jira/test_jira_page_access.py
.py
import logging from types import SimpleNamespace from unittest.mock import MagicMock from pytest import LogCaptureFixture from ee.onyx.external_permissions.jira.page_access import get_project_permissions from onyx.connectors.jira.utils import JIRA_CLOUD_API_VERSION, JIRA_SERVER_API_VERSION PROJECT_KEY = "PROJ" def...
320
11,856
onyx
backend/tests/unit/ee/onyx/external_permissions/box/test_box_group_sync.py
.py
from typing import cast from unittest.mock import MagicMock, patch import pytest from box_sdk_gen import BoxClient from box_sdk_gen.box.errors import BoxAPIError from box_sdk_gen.schemas.group_full import GroupFull from box_sdk_gen.schemas.user_mini import UserMini from ee.onyx.external_permissions.box import group_s...
137
5,132
onyx
backend/tests/unit/ee/onyx/external_permissions/slack/test_grid_perm_sync.py
.py
"""Unit tests for EE Slack perm sync on Enterprise Grid.""" from typing import Any, cast from unittest.mock import MagicMock, patch from ee.onyx.external_permissions.slack.channel_access import ( get_channel_access as ee_get_channel_access, ) from ee.onyx.external_permissions.slack.doc_sync import ( _fetch_ch...
503
19,418
onyx
backend/tests/unit/ee/onyx/external_permissions/salesforce/test_postprocessing.py
.py
from datetime import datetime from ee.onyx.external_permissions.salesforce.postprocessing import ( censor_salesforce_chunks, ) from onyx.configs.app_configs import BLURB_SIZE from onyx.configs.constants import DocumentSource from onyx.connectors.salesforce.utils import BASE_DATA_PATH from onyx.context.search.model...
203
6,066
onyx
backend/tests/unit/ee/onyx/external_permissions/salesforce/test_salesforce_perm_cache_tenant_isolation.py
.py
"""Regression coverage for tenant isolation of the Salesforce permission-censoring caches: the per-tenant Salesforce client and the email->user_id map must never let one tenant's org, credentials, or resolved user id serve another tenant's access check.""" from unittest.mock import MagicMock, patch import ee.onyx.ext...
77
3,058
onyx
backend/tests/unit/ee/onyx/db/test_user_group_cost_token_limit.py
.py
"""Group token-limit inserts preserve either supported budget.""" 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 as PGUUID from sqlalchem...
67
2,142
onyx
backend/tests/unit/ee/onyx/db/test_user_group_audit.py
.py
"""Unit tests for user.group_change audit emission from update_user_group. The emit is guarded on an actual membership delta, so a pure cc_pair update must emit nothing while an add/remove of users must emit exactly one event. """ import json import logging from typing import Any from unittest.mock import MagicMock, ...
106
3,700
onyx
backend/tests/unit/ee/onyx/db/test_user_group_rename.py
.py
"""Tests for user group rename DB operation.""" from unittest.mock import MagicMock, patch import pytest from ee.onyx.db.user_group import rename_user_group from onyx.db.models import UserGroup class TestRenameUserGroup: """Tests for rename_user_group function.""" @patch("ee.onyx.db.user_group.DISABLE_VEC...
53
1,799
onyx
backend/tests/unit/ee/onyx/db/test_license.py
.py
"""Tests for license database CRUD operations.""" from datetime import datetime, timedelta, timezone from unittest.mock import MagicMock, patch from ee.onyx.db.license import ( check_seat_availability, delete_license, get_license, get_used_seats, refresh_license_cache, upsert_license, ) from e...
395
14,835
onyx
backend/tests/unit/external_apps/test_notion_catalog.py
.py
"""The Notion provider catalog: REST routes resolve to exactly the intended action, and default policies match the design (reads auto-approve; page / block / database / comment writes require approval). The DB-driven ``recognize_actions`` path is covered elsewhere; here we exercise the pure rule layer directly, mirror...
122
5,464
onyx
backend/tests/unit/external_apps/test_managed_credentials.py
.py
"""Each Onyx-managed provider resolves its Onyx-owned credentials from the per-field ``managed_org_credentials`` values (``OnyxManagedExtApp.configured_managed_credentials``).""" from __future__ import annotations import pytest from onyx.db.enums import ExternalAppType from onyx.external_apps.providers.base import O...
68
2,352
onyx
backend/tests/unit/external_apps/test_linear_api_helper.py
.py
"""The bundled ``linear_api.py`` sandbox helper: the pure ``IssueCreateInput`` builder used by ``create-issue``. The helper is a standalone script under the skills dir (not an importable package), so load it by path. These tests require no network and no onyx imports.""" from __future__ import annotations import argp...
181
5,275
onyx
backend/tests/unit/external_apps/test_hubspot_catalog.py
.py
"""The HubSpot provider catalog: REST routes resolve to exactly the intended action, and default policies match the design (reads + CRM search auto-approve; object writes require approval). Here we exercise the pure rule layer directly (the DB-driven ``recognize_actions`` path is covered elsewhere).""" from __future_...
89
3,971
onyx
backend/tests/unit/external_apps/test_provider_granted_scopes.py
.py
"""Per-provider granted-scope extraction (ENG-4261). On the OAuth callback each provider derives the scopes the user actually granted, persisted onto ``ExternalAppUserCredential.granted_scopes`` for downstream action gating. Most providers echo the RFC 6749 ``scope`` field and inherit the base default; only Slack (nes...
160
5,699
onyx
backend/tests/unit/external_apps/test_google_drive_provider.py
.py
"""The Google Drive built-in provider: full read/write, Onyx-managed, and its action catalog matches the request paths the bundled ``gdrive_api.py`` helper calls. Reads are auto-approved (ALWAYS); mutations default to ASK.""" from __future__ import annotations from onyx.db.enums import EndpointPolicy, ExternalAppType...
113
5,219
onyx
backend/tests/unit/external_apps/test_slack_catalog.py
.py
"""The Slack provider catalog: REST routes resolve to exactly the intended action, and default policies match the design (reads auto-approve; message and file writes require approval). Exercises the pure rule layer directly, mirroring ``test_github_catalog``.""" from __future__ import annotations import pytest from...
79
3,293
onyx
backend/tests/unit/external_apps/test_path_matching.py
.py
"""Unit tests for RestRoute path-template matching.""" import pytest from pydantic import ValidationError from onyx.external_apps.providers.actions import RestRoute, path_matches def test_non_trailing_wildcard_rejected_at_construction() -> None: """A `{name...}` wildcard is only valid as the last segment; defin...
88
3,688
onyx
backend/tests/unit/external_apps/test_gmail_catalog.py
.py
"""The Gmail provider catalog: every route resolves to exactly the intended action (no collection/item/send cross-matching), and each action's ``default_policy`` matches the design (reads + draft create/update auto-approve; draft delete/send require approval).""" from __future__ import annotations import pytest from...
76
3,237
onyx
backend/tests/unit/external_apps/test_action_policy_defaults.py
.py
"""Per-action ``default_policy`` on ``EndpointSpec`` and how the registry uses it. A provider declares the out-of-the-box policy for each catalog action (defaults to ``ASK``). The write path persists only deviations from that default (``resolve_action_overrides``); the policy views resolve missing rows back to it. """...
137
4,584
onyx
backend/tests/unit/external_apps/test_token_utils.py
.py
from datetime import datetime, timedelta, timezone from onyx.external_apps.token_utils import needs_refresh, stamp_expires_at _NOW = datetime(2026, 5, 29, 12, 0, 0, tzinfo=timezone.utc) # --------------------------------------------------------------------------- # stamp_expires_at # -------------------------------...
88
3,573
onyx
backend/tests/unit/external_apps/test_google_cloud_scopes.py
.py
"""The cloud/self-hosted scope split for the Google providers: the cloud scope stays clear of Google's restricted tier, the catalog it exposes never outruns it, and the SKILL.md rendered under it surfaces the withheld actions and per-grant caveats.""" from __future__ import annotations import pytest from onyx.db.enu...
190
7,870
onyx
backend/tests/unit/external_apps/test_hubspot_provider.py
.py
"""The HubSpot provider's OAuth scopes: read scopes (+ the mandatory `oauth` scope) are requested as required, while write scopes ride under HubSpot's `optional_scope` param so read-only/free accounts β€” which can't grant writer scopes β€” can still complete OAuth. See ENG-4260.""" from __future__ import annotations fro...
109
4,106
onyx
backend/tests/unit/external_apps/test_credentials.py
.py
"""Unit tests for build_auth_headers β€” pure auth_template β†’ headers rendering.""" from __future__ import annotations from onyx.external_apps.credentials import build_auth_headers def test_fills_placeholder_from_credentials() -> None: headers = build_auth_headers( {"Authorization": "Bearer {access_token}...
76
2,497
onyx
backend/tests/unit/external_apps/test_github_catalog.py
.py
"""The GitHub provider catalog: REST routes and the `gh` CLI's GraphQL operations resolve to exactly the intended action, and default policies match the design (reads auto-approve; issue/comment writes require approval). The DB-driven ``recognize_actions`` path is covered in ``external_dependency_unit/craft/test_actio...
180
7,397
onyx
backend/tests/unit/external_apps/test_token_refresh.py
.py
import json from contextlib import contextmanager from typing import Any from unittest.mock import ANY, MagicMock from uuid import UUID, uuid4 import pytest import requests from redis.exceptions import ConnectionError as RedisConnectionError from sqlalchemy.exc import SQLAlchemyError from onyx.external_apps import to...
417
16,083
onyx
backend/tests/unit/external_apps/test_gdrive_api_helper.py
.py
"""The bundled ``gdrive_api.py`` sandbox helper: Drive ``q`` construction, the native-export-vs-raw-download branch in ``read``, URL-tolerant id arguments, and the Docs tab flags. The helper is a standalone script under the skills dir (not an importable package), so load it by path.""" from __future__ import annotatio...
503
16,049
onyx
backend/tests/unit/external_apps/matching/test_engine.py
.py
"""Pure unit tests for the matching engine. The DB-driven ``recognize_actions`` path is covered in ``external_dependency_unit/craft/test_action_matching.py``.""" from __future__ import annotations import pytest from pydantic import ValidationError from onyx.db.enums import EndpointPolicy, ExternalAppType, GatedAppKi...
102
3,568
onyx
backend/tests/unit/external_apps/matching/test_approval_actions.py
.py
from onyx.db.enums import EndpointPolicy from onyx.external_apps.matching.engine import MatchedAction, actions_requiring_approval def _action(action_type: str, policy: EndpointPolicy) -> MatchedAction: return MatchedAction( action_type=action_type, display_name=action_type, description="de...
37
1,240
onyx
backend/tests/unit/external_apps/presentation/test_payload_decoders.py
.py
from __future__ import annotations import base64 from email.message import EmailMessage from typing import Any from onyx.external_apps.presentation.decode import decode_payload from onyx.external_apps.presentation.payload_decoders import GmailRawMimeDecoder from onyx.external_apps.providers.gmail import GmailAction, ...
170
5,265
onyx
backend/tests/unit/scripts/test_env_inventory.py
.py
"""Unit tests for the env-var inventory tool's classifier and AST extraction. The classifier drives an actionable "should be documented" shortlist, so its heuristics are worth locking down β€” a wrong tag silently hides a var (or mislabels a secret). """ import ast from pathlib import Path import pytest from scripts.e...
187
5,942
onyx
backend/tests/unit/file_store/test_file_store.py
.py
import datetime from collections.abc import Generator from contextlib import nullcontext from io import BytesIO from typing import Any from unittest.mock import MagicMock, Mock, patch import pytest from sqlalchemy import DateTime, Enum, String, create_engine from sqlalchemy.orm import DeclarativeBase, Mapped, Session,...
839
33,371
onyx
backend/tests/unit/file_store/test_postgres_file_store.py
.py
"""Unit tests for PostgresBackedFileStore. These tests mock the database layer (sessions, raw connections, large objects) so they run without any external services. """ from io import BytesIO, StringIO from typing import Any from unittest.mock import MagicMock, patch import pytest from onyx.configs.constants import...
374
12,391
onyx
backend/tests/unit/shared_configs/test_cors_config.py
.py
import pytest from shared_configs.configs import cors_allow_credentials, parse_cors_allowed_origins def test_empty_env_allows_all_origins_without_credentials() -> None: origins = parse_cors_allowed_origins("") assert origins == ["*"] assert cors_allow_credentials(origins) is False def test_explicit_wil...
41
1,388
onyx
backend/tests/unit/shared_configs/test_user_id_contextvar.py
.py
from collections.abc import Generator from typing import Any, cast from uuid import uuid4 import pytest from fastapi import Depends, FastAPI, WebSocket from fastapi.responses import StreamingResponse from fastapi.testclient import TestClient from onyx.auth import users from onyx.auth.users import ( current_chat_a...
187
5,653