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/background/test_periodic_task_claim.py
.py
"""External dependency unit tests for periodic task claiming. Tests ``_try_claim_task`` and ``_try_run_periodic_task`` against real PostgreSQL, verifying happy-path behavior and concurrent-access safety. The claim mechanism uses a transaction-scoped advisory lock + a KVStore timestamp for cross-instance dedup. The D...
256
8,875
onyx
backend/tests/external_dependency_unit/server/test_feedback_rate_limiting.py
.py
"""Tests for the per-user rate limiting applied to the chat message feedback endpoints (ON-009). Uses a real Redis connection via the centralized pool β€” the FastAPI app is a minimal stand-in for the real router, with auth dependency-overridden to control the resolved user.""" import uuid from collections.abc import As...
97
3,521
onyx
backend/tests/external_dependency_unit/server/manage/test_list_all_users_redos.py
.py
"""ReDoS regression test for the invited-user search filter in list_all_users. The `q` search param used to be compiled as a regex and matched against every invited email (`re.search(r"{}".format(q), email, re.I)`), so a crafted pattern could cause catastrophic backtracking and hang API worker threads. It is now a pla...
42
1,815
onyx
backend/tests/external_dependency_unit/server/security/test_security_settings_store.py
.py
"""Loader tests against the real Postgres-backed singleton row.""" import threading from collections.abc import Generator from typing import Any from unittest.mock import patch import pytest from pydantic import ValidationError from sqlalchemy import delete from sqlalchemy.orm import Session from onyx.db.engine.sql_...
234
8,356
onyx
backend/tests/external_dependency_unit/server/security/test_security_settings_put.py
.py
"""PUT /admin/security tests. Invokes the handler directly with a Request shim β€” exercises merge and lock-serialization semantics against the real DB + Redis lock without HTTP framing. """ import asyncio import json import threading from collections.abc import Generator from typing import Any, cast import pytest fro...
424
15,368
onyx
backend/tests/external_dependency_unit/server/documents/test_list_connector_files.py
.py
"""Tests for GET /manage/admin/connector/{connector_id}/files. The endpoint used to issue a file-record query plus an object-store size lookup per file (O(N) round-trips), which made it unusably slow for large file connectors. It now resolves every file in a single batched query against ``file_record``, using the pers...
393
12,414
onyx
backend/tests/external_dependency_unit/server/pat/test_pat_log_injection.py
.py
"""Log-injection regression test for PAT creation. ``create_token`` logged the user-supplied token name with ``'%s'``, so CR/LF in the name could forge lines in the shared log stream. It now logs the name with ``%r``, which escapes control characters. """ from unittest.mock import patch from sqlalchemy.orm import Se...
32
1,129
onyx
backend/tests/external_dependency_unit/server/features/mcp/test_per_user_api_token_credentials.py
.py
"""Per-user API_TOKEN MCP credentials must satisfy two invariants that only show up in DB state, not in API responses: `save_user_credentials` resolves `{user_email}` (and other auto placeholders) when persisting headers, and `_upsert_mcp_server` preserves the editing admin's stored per-user credentials when the form f...
254
9,390
onyx
backend/tests/external_dependency_unit/server/features/mcp/test_mcp_oauth_authenticated_status.py
.py
"""`user_can_authenticate` for per-user OAuth servers must reflect a completed handshake (stored tokens), not mere connection-config row existence, since the row is created before token exchange. API-token servers stay authenticated on row existence alone.""" from uuid import uuid4 from sqlalchemy.orm import Session ...
99
3,457
onyx
backend/tests/external_dependency_unit/server/features/mcp/test_mcp_user_group_deletion.py
.py
"""Group deletion must clear MCP server grants (no ON DELETE CASCADE on mcp_server__user_group.user_group_id).""" from uuid import uuid4 import pytest from sqlalchemy import select from sqlalchemy.orm import Session from ee.onyx.db.user_group import prepare_user_group_for_deletion from onyx.db.models import MCPServe...
42
1,254
onyx
backend/tests/external_dependency_unit/server/features/mcp/test_shared_api_token_template_visibility.py
.py
"""A shared (admin-managed) API-token template must only be serialized in the owner/admin auth-config response. Basic users who can merely attach the server never supply shared credentials and must not receive the template, which can carry literal header values alongside the `{api_key}` placeholder. Basic users receive...
198
7,442
onyx
backend/tests/external_dependency_unit/server/features/mcp/test_mcp_access_control.py
.py
"""Group/public access control for MCP servers, exercised at the DB layer. These verify the read path (`get_mcp_servers_accessible_to_user` / `user_can_access_mcp_server`) directly against Postgres rows, so they don't depend on the EE group-write path. Access rows are inserted by hand.""" from uuid import uuid4 from...
122
4,688
onyx
backend/tests/external_dependency_unit/server/features/mcp/test_mcp_access_edge_cases.py
.py
"""Edge cases for MCP group/public access, beyond the basic matrix. All cases insert access rows directly, so they exercise the read path without the EE write path.""" from uuid import uuid4 from sqlalchemy.orm import Session from onyx.auth.schemas import UserRole from onyx.db.mcp import get_mcp_servers_accessible_...
127
4,761
onyx
backend/tests/external_dependency_unit/server/features/mcp/test_mcp_grant_reconciliation.py
.py
"""MCP grant updates preserve share dimensions omitted from the request.""" from uuid import uuid4 from sqlalchemy import select from sqlalchemy.orm import Session from onyx.auth.schemas import UserRole from onyx.db.models import MCPServer, MCPServer__User, MCPServer__UserGroup, UserGroup from onyx.server.features.m...
85
2,534
onyx
backend/tests/external_dependency_unit/server/features/mcp/test_mcp_persona_gate.py
.py
"""Security gate: a user cannot attach a restricted MCP server's tools to an agent by passing tool IDs directly. `upsert_persona` must reject it before the persona is written.""" from uuid import uuid4 import pytest from sqlalchemy.orm import Session from onyx.auth.schemas import UserRole from onyx.db.models import ...
158
5,103
onyx
backend/tests/external_dependency_unit/slack_bot/test_slack_bot_federated_search.py
.py
# NOTE: ruff and black disagree after applying this noqa, so we just set file-level. # ruff: noqa: ARG005 import os from typing import Any from unittest.mock import MagicMock, Mock, patch from uuid import uuid4 from onyx.db.llm import update_default_provider, upsert_llm_provider from onyx.server.manage.llm.models impo...
886
33,612
onyx
backend/tests/external_dependency_unit/slack_bot/test_slack_bot_crud.py
.py
"""Tests that SlackBot CRUD operations return properly typed SensitiveValue fields. Regression test for the bug where insert_slack_bot/update_slack_bot returned objects with raw string tokens instead of SensitiveValue wrappers, causing 'str object has no attribute get_value' errors in SlackBot.from_model(). """ from ...
85
2,943
onyx
backend/tests/external_dependency_unit/llm/test_llm_provider.py
.py
""" Tests for the test_llm_configuration endpoint (/admin/llm/test). This tests the LLM configuration testing functionality which verifies that LLM credentials are valid before saving them. """ from collections.abc import Generator from unittest.mock import MagicMock, patch from uuid import uuid4 import pytest from ...
597
22,937
onyx
backend/tests/external_dependency_unit/llm/test_llm_provider_user_default_cleanup.py
.py
""" Tests that deleting an LLM provider clears personal default models (User.default_model) referencing it, so users fall back to the global default instead of a dangling provider reference. """ from uuid import uuid4 from sqlalchemy import delete from sqlalchemy.orm import Session from onyx.db.llm import remove_llm...
71
2,390
onyx
backend/tests/external_dependency_unit/llm/test_prompt_caching.py
.py
"""External dependency unit tests for prompt caching functionality. These tests call LLM providers directly and use litellm's completion_cost() to verify that prompt caching reduces costs. """ import json import os import tempfile import time from pathlib import Path from typing import Any import pytest from litellm...
769
27,884
onyx
backend/tests/external_dependency_unit/llm/test_llm_provider_default_model_protection.py
.py
""" This should act as the main point of reference for testing that default model logic is consisten. - """ from collections.abc import Generator from uuid import uuid4 import pytest from sqlalchemy.orm import Session from onyx.db.llm import ( fetch_existing_llm_provider, remove_llm_provider, update_de...
225
8,159
onyx
backend/tests/external_dependency_unit/llm/test_bedrock.py
.py
"""Live behavior tests for AWS Bedrock through LiteLLM. Covers: - Nova models on Bedrock do NOT leak `<thinking>...</thinking>` tags into visible content. Issue #10090 reports these tags rendering as plain text in the chat UI; the fix should route the inner-tag tokens to `Delta.reasoning_content` and only ship t...
89
3,272
onyx
backend/tests/external_dependency_unit/llm/test_llm_provider_called.py
.py
from collections.abc import Generator from contextlib import contextmanager from typing import Any from unittest.mock import patch from uuid import uuid4 import pytest from fastapi_users.password import PasswordHelper from sqlalchemy.orm import Session from onyx.db.enums import AccountType from onyx.db.llm import ( ...
247
8,013
onyx
backend/tests/external_dependency_unit/llm/test_azure_responses_api.py
.py
"""Live guard for the Azure Responses API surface routing (#11420). `LitellmLLM` routes true OpenAI models on Azure through LiteLLM's responses bridge. The bridge must target the modern `/openai/v1/responses` surface even when the provider is configured with a dated api-version: dated versions make LiteLLM build the l...
111
4,414
onyx
backend/tests/external_dependency_unit/llm/test_ollama_streaming.py
.py
"""Live behavior test for Ollama streaming through LiteLLM. `_patch_ollama_chunk_parser` (in `monkey_patches.py`) ensures reasoning tokens are routed to `Delta.reasoning_content` and visible answer tokens land on `Delta.content`, for both native `thinking` field chunks and legacy `<think>...</think>`-tagged content ch...
95
3,832
onyx
backend/tests/external_dependency_unit/llm/test_llm_provider_api_base.py
.py
""" Tests for LLM provider api_base and custom_config change restrictions. This ensures we don't have a vulnerability where an admin could change the api_base or custom_config of an LLM provider without changing the API key, allowing them to redirect API requests (containing the real API key in headers) to an attacker...
932
34,562
onyx
backend/tests/external_dependency_unit/llm/test_openai_responses_api.py
.py
"""Live behavior tests for the OpenAI Responses API path through LiteLLM. `LitellmLLM` routes true OpenAI models through LiteLLM's Responses API bridge (model name prefixed with `openai/responses/`). These tests exercise behavior of that bridge that cannot be reached with mocks: - Parallel tool calls land in distinct...
306
11,732
onyx
backend/tests/external_dependency_unit/llm/test_llm_provider_auto_mode.py
.py
""" Tests for the LLM Provider Auto Mode feature. This tests the automatic model syncing from GitHub config when a provider is uploaded with is_auto_mode=True. """ from collections.abc import Generator from datetime import datetime from unittest.mock import MagicMock, patch from uuid import uuid4 import pytest from ...
1,331
53,480
onyx
backend/tests/external_dependency_unit/tier/test_tier_order.py
.py
"""Tests for the Tier total ordering and tier_gate longest-prefix logic.""" import pytest from ee.onyx.configs.license_enforcement_config import PATH_PREFIX_MIN_TIER from ee.onyx.server.middleware.tier_gate import _required_tier from onyx.server.settings.models import Tier from onyx.server.settings.tier_order import ...
68
2,598
onyx
backend/tests/external_dependency_unit/tools/test_memory_tool_integration.py
.py
"""Tests for MemoryTool integration: registration, construction, and DB persistence.""" import pytest from sqlalchemy import select from sqlalchemy.orm import Session from onyx.db.memory import ( MAX_MEMORIES_PER_USER, add_memory, get_memories, update_memory_at_index, ) from onyx.db.models import Memo...
255
9,235
onyx
backend/tests/external_dependency_unit/tools/test_oauth_tool_integration.py
.py
""" Test suite for OAuth integration in tool_constructor. Tests the priority logic for OAuth tokens when constructing custom tools: 1. Priority 1: OAuth config (per-tool OAuth) 2. Priority 2: Passthrough auth (user's login OAuth token) All external HTTP calls are mocked, but Postgres and Redis are running. """ impor...
546
19,371
onyx
backend/tests/external_dependency_unit/tools/test_python_tool.py
.py
# """ # External dependency unit tests for Python tool. # These tests run against a real Code Interpreter service (no mocking of the service). # They verify code execution, error handling, timeout behavior, and file generation. # Requirements: # - CODE_INTERPRETER_BASE_URL must be configured and point to a running se...
1,447
51,854
onyx
backend/tests/external_dependency_unit/tools/test_oauth_config_crud.py
.py
""" Test suite for OAuth Config CRUD operations. Tests the basic CRUD operations for OAuth configurations and user tokens, including creation, retrieval, updates, deletion, and token management. """ from uuid import uuid4 import pytest from sqlalchemy.orm import Session from onyx.db.models import OAuthConfig, Tool ...
617
24,270
onyx
backend/tests/external_dependency_unit/tools/test_oauth_token_manager.py
.py
""" Test suite for OAuthTokenManager. Tests the OAuth token management functionality including token validation, refresh, expiration checking, and authorization URL building. All HTTP requests to external OAuth providers are mocked. """ import time from unittest.mock import Mock, patch from urllib.parse import parse_...
613
24,088
onyx
backend/tests/external_dependency_unit/tools/test_python_tool_server_enabled.py
.py
"""Tests that PythonTool.is_available() respects the server_enabled DB flag. Uses a real DB session with CODE_INTERPRETER_BASE_URL mocked so the environment-variable check passes and the DB flag is the deciding factor. """ from unittest.mock import patch from sqlalchemy.orm import Session from onyx.db.code_interpre...
56
1,882
onyx
backend/tests/external_dependency_unit/tools/test_mcp_passthrough_oauth.py
.py
""" Test suite for MCP Pass-Through OAuth (PT_OAUTH) integration. Tests the pass-through OAuth flow where Onyx forwards the user's login OAuth token to an MCP server for authentication. This test: 1. Creates a test user with an OAuthAccount (simulating Google OAuth login) 2. Creates an MCP server with PT_OAUTH auth t...
554
20,543
onyx
backend/tests/external_dependency_unit/tools/open_url/test_open_url_resolution.py
.py
"""External dependency tests for open_url URL -> Document.id resolution. Uses real Postgres because the resolution under test (_resolve_urls_to_document_ids) matches candidate URLs against actual `Document.id` rows via `filter_existing_document_ids`. The bug this guards: a Google Doc indexed under the `docs.google.com...
79
2,535
onyx
backend/tests/external_dependency_unit/feature_flags/test_feature_flag_provider_factory.py
.py
""" External dependency unit tests for the feature flag service. These tests verify the feature flag service implementation with real PostHog integration when available, and fallback behavior otherwise. """ from uuid import UUID from ee.onyx.feature_flags.posthog_provider import PostHogFeatureFlagProvider from onyx....
38
1,398
onyx
backend/tests/external_dependency_unit/answer/stream_test_utils.py
.py
from __future__ import annotations from collections.abc import Iterator from uuid import UUID from sqlalchemy.orm import Session from onyx.chat.chat_utils import create_chat_session_from_request from onyx.chat.models import AnswerStreamPart from onyx.chat.process_message import handle_stream_message_objects from ony...
131
3,455
onyx
backend/tests/external_dependency_unit/answer/stream_test_builder.py
.py
from __future__ import annotations from collections.abc import Iterator from onyx.chat.models import AnswerStreamPart from onyx.context.search.models import SearchDoc from onyx.server.query_and_chat.streaming_models import ( AgentResponseStart, OverallStop, Packet, ReasoningDone, ReasoningStart, )...
139
4,582
onyx
backend/tests/external_dependency_unit/answer/test_stream_chat_message.py
.py
from __future__ import annotations import json from uuid import UUID import pytest from sqlalchemy.orm import Session from onyx.chat.models import CreateChatSessionID from onyx.configs.constants import DocumentSource from onyx.server.query_and_chat.models import MessageResponseIDInfo from onyx.server.query_and_chat....
960
32,710
onyx
backend/tests/external_dependency_unit/answer/test_answer_without_openai.py
.py
from __future__ import annotations import os from uuid import uuid4 from sqlalchemy.orm import Session from onyx.chat.models import AnswerStreamPart, StreamingError from onyx.chat.process_message import handle_stream_message_objects from onyx.db.chat import create_chat_session from onyx.db.enums import LLMModelFlowT...
111
3,841
onyx
backend/tests/external_dependency_unit/answer/test_current_datetime_replacement.py
.py
import re from datetime import datetime from sqlalchemy.orm import Session from onyx.chat.models import AnswerStreamPart, StreamingError from onyx.chat.process_message import handle_stream_message_objects from onyx.db.chat import create_chat_session from onyx.db.models import User from onyx.db.persona import get_pers...
89
3,429
onyx
backend/tests/external_dependency_unit/answer/test_stream_chat_message_objects.py
.py
import uuid from typing import Any from unittest.mock import MagicMock import pytest from sqlalchemy.orm import Session from onyx.chat.models import AnswerStreamPart, StreamingError from onyx.chat.process_message import handle_stream_message_objects from onyx.db.chat import create_chat_session from onyx.db.models imp...
134
5,149
onyx
backend/tests/external_dependency_unit/answer/stream_test_assertions.py
.py
from __future__ import annotations from typing import cast from onyx.chat.models import AnswerStreamPart, CreateChatSessionID from onyx.context.search.models import SearchDoc from onyx.server.query_and_chat.models import MessageResponseIDInfo from onyx.server.query_and_chat.streaming_models import ( AgentResponse...
160
5,345
onyx
backend/tests/external_dependency_unit/answer/conftest.py
.py
import os from collections.abc import Iterator, Mapping from typing import Any from unittest.mock import MagicMock, patch import pytest from sqlalchemy.orm import Session from onyx.db.llm import update_default_provider, upsert_llm_provider from onyx.llm.constants import LlmProviderNames from onyx.server.manage.llm.mo...
126
3,984
onyx
backend/tests/external_dependency_unit/ee/onyx/background/celery/test_license_notifications_task.py
.py
"""External dependency unit tests for the license-expiry beat task. Verifies the task short-circuits correctly when: - Multi-tenant cloud mode is enabled - No license row exists - License signature verification fails - Stage derivation returns NONE And dispatches to ``notify_admins_for_stage`` only when there is a re...
130
4,613
onyx
backend/tests/external_dependency_unit/ee/onyx/server/enterprise_settings/test_custom_analytics_script.py
.py
""" Tests for the `GET /enterprise-settings/custom-analytics-script` handler. Regression coverage for the multi-tenant case where a pre-auth / anonymous page load reaches the endpoint with no tenant context resolved (the contextvar defaults to the public schema, which has no per-tenant `key_value_store`). The handler ...
96
3,826
onyx
backend/tests/external_dependency_unit/ee/onyx/server/query_and_chat/test_user_group_cost_budget_enforcement.py
.py
"""Enterprise user and group budget enforcement against the usage ledger.""" from datetime import datetime, timezone from typing import NoReturn from uuid import uuid4 import pytest from sqlalchemy import delete from sqlalchemy.orm import Session import ee.onyx.server.query_and_chat.token_limit as ee_token_limit fro...
213
6,655
onyx
backend/tests/external_dependency_unit/ee/onyx/server/log_export/test_log_export_storage.py
.py
"""External dependency unit tests for log-export file-store storage. Runs against the real (Postgres/MinIO-backed) file store; log files come from tmp directories. """ from datetime import datetime, timedelta, timezone from io import BytesIO from pathlib import Path from unittest.mock import patch from uuid import uu...
170
5,833
onyx
backend/tests/external_dependency_unit/ee/onyx/server/log_export/test_start_export.py
.py
"""External dependency unit tests for the async log-export start endpoint. Runs against the real (Postgres/MinIO-backed) file store; celery sends and log directories are patched. """ from datetime import datetime, timezone from pathlib import Path from unittest.mock import MagicMock, patch import pytest from ee.ony...
147
5,273
onyx
backend/tests/external_dependency_unit/ee/onyx/utils/test_trial_promotion.py
.py
"""External-dependency unit tests for the trial-business β†’ enterprise promotion. Covers `ee.onyx.utils.tier.get_tier()` end-to-end against real Redis. The CP boundary (`fetch_billing_information`) is the only thing mocked β€” everything else (cache reads/writes, JSON serialization, datetime comparisons) runs for real. "...
209
8,109
onyx
backend/tests/external_dependency_unit/ee/onyx/utils/test_license_notifications.py
.py
"""External dependency unit tests for license-expiry notification orchestration. Verifies idempotency, stage-transition behavior, and grace-period daily cadence against a real PostgreSQL database. The email send path is patched so we can assert "fresh insert only" behavior without configuring SendGrid. """ from datet...
220
8,158
onyx
backend/tests/external_dependency_unit/ee/onyx/db/test_license_cache.py
.py
"""External-dependency unit tests for the license metadata cache. Runs `update_license_cache` and `get_cached_license_metadata` end-to-end against real Redis. The cache singleton + 24h TTL + tier round-trip are what makes a license re-upload reflect immediately in `get_tier()` β€” verified manually during BUSINESS β†’ ENT...
137
5,391
onyx
backend/tests/external_dependency_unit/craft/test_action_approval_db.py
.py
"""External-dependency-unit tests for the ``action_approval`` query module. Runs real ORM/SQL against Postgres so schema/query regressions (race arbiter, refresh-after-UPDATE, filter inclusivity) actually fail. """ from __future__ import annotations import datetime as dt from collections.abc import Callable from typ...
194
6,662
onyx
backend/tests/external_dependency_unit/craft/test_prompt_slot_distributed.py
.py
"""Prompt-slot serialization for build sessions, against a real cache (Redis). The slot is a distributed lock, so these run against a real cache rather than a stub: two manager instances stand in for two ``api_server`` replicas sharing one cache, proving cross-pod serialization an in-process test can't. """ from __fu...
263
8,675
onyx
backend/tests/external_dependency_unit/craft/test_skill_db_mutations.py
.py
from __future__ import annotations from uuid import UUID, uuid4 import pytest from sqlalchemy import select from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session from onyx.auth.schemas import UserRole from onyx.db.enums import SkillSharePermission from onyx.db.models import Skill, Skill__User,...
538
15,703
onyx
backend/tests/external_dependency_unit/craft/test_skill_github_import.py
.py
from __future__ import annotations import io import zipfile from uuid import UUID, uuid4 import pytest from sqlalchemy import select from sqlalchemy.orm import Session from onyx.db.models import Skill, User, UserSkillPreference from onyx.file_store.file_store import get_default_file_store from onyx.server.features.s...
207
6,744
onyx
backend/tests/external_dependency_unit/craft/test_scheduled_task_executor.py
.py
"""Scheduled tasks (executor half, ext-dep). Drives the real ``run_scheduled_task_logic`` end-to-end against Postgres and the real ``LocalSandboxManager``. Scope of this file: * Dispatcher concurrency (``SELECT ... FOR UPDATE SKIP LOCKED``). * Stuck-run cleanup sweeper. * The executor's wake-failure contract β€” when ...
544
20,246
onyx
backend/tests/external_dependency_unit/craft/test_credential_injection.py
.py
from __future__ import annotations from sqlalchemy.orm import Session from onyx.db.enums import ExternalAppType from onyx.external_apps.credentials import resolve_injection_headers from tests.external_dependency_unit.craft.db_helpers import ( make_external_app, make_skill, make_user, make_user_credent...
109
3,046
onyx
backend/tests/external_dependency_unit/craft/test_connectable_apps.py
.py
from __future__ import annotations from sqlalchemy.orm import Session from onyx.db.external_app import get_connectable_apps_for_user from onyx.server.features.build.sandbox.util.agent_instructions import ( build_connectable_apps_list, ) from tests.external_dependency_unit.craft.db_helpers import ( make_extern...
76
2,550
onyx
backend/tests/external_dependency_unit/craft/test_user_library_fileset.py
.py
"""External-dependency unit tests for user-library sandbox sync helpers.""" from __future__ import annotations from collections.abc import Callable import pytest from sqlalchemy.orm import Session from onyx.db.enums import SandboxStatus from onyx.db.models import Sandbox, User from onyx.server.features.build.db.use...
144
4,856
onyx
backend/tests/external_dependency_unit/craft/db_helpers.py
.py
"""Shared Craft database row factories. Helpers live here, not in a ``conftest.py``, because they're plain functions: external-dependency tests import row factories directly. Pure payload builders live in ``tests.common.craft.payloads`` so integration tests do not depend on DB factory modules for value construction. ...
368
11,046
onyx
backend/tests/external_dependency_unit/craft/test_granted_scopes_persistence.py
.py
"""Persisting the OAuth grant onto ``ExternalAppUserCredential.granted_scopes`` via ``upsert_external_app_user_credential`` (ENG-4261). The connect flow records the authoritative grant (a list, or ``None`` for "unknown" β€” both overwrite); refresh and credential-form saves omit the argument (``UNSET``) and must leave a...
212
6,626
onyx
backend/tests/external_dependency_unit/craft/test_action_matching.py
.py
"""Outbound-request β†’ policy-verdict matching for connected external apps. Exercises the real provider catalogs + a real DB (no structural mocking). Three layers are tested here: - ``recognize_actions`` β€” pure recognition: which catalog action(s) a request invokes, each carrying its ``effective_policy`` (stored ove...
407
15,786
onyx
backend/tests/external_dependency_unit/craft/test_background_snapshots.py
.py
"""Background snapshot behavior of the sandbox sweep (Celery task). Exercises the snapshot half of ``cleanup_idle_sandboxes_task`` β€” non-idle RUNNING sandboxes get their changed sessions snapshotted in place β€” end-to-end against real Postgres + Redis. Sandbox operations (``list_session_workspaces``, ``create_snapshot`...
356
12,819
onyx
backend/tests/external_dependency_unit/craft/test_session_lifecycle.py
.py
"""Session lifecycle (DB-bound half). Drives ``SessionManager`` end-to-end against a real Postgres + Redis with a ``StubSandboxManager`` standing in for the pod backend. Covers session create, empty-session reuse, delete cascade, snapshot blob cleanup, port allocation, the per-user Redis lock, idle-restore status flip...
1,532
57,153
onyx
backend/tests/external_dependency_unit/craft/test_built_in_skill_seeding.py
.py
"""Tests for built-in skill *row* behavior. The ``skill`` rows for built-ins are seeded by the ``skill_built_in_id_discriminator`` migration β€” migrations are the source of truth and there is no boot-time seeder. These tests cover the runtime behaviors that depend on those rows plus the codified ``BUILT_IN_SKILLS``: av...
259
8,203
onyx
backend/tests/external_dependency_unit/craft/test_skill_ownership_transfer.py
.py
from uuid import uuid4 import pytest from sqlalchemy import select from sqlalchemy.orm import Session from onyx.db.enums import AccountType, SkillSharePermission from onyx.db.models import Skill, Skill__User, User, UserRole from onyx.error_handling.error_codes import OnyxErrorCode from onyx.error_handling.exceptions ...
250
7,849
onyx
backend/tests/external_dependency_unit/craft/test_sandbox_lifecycle.py
.py
"""Sandbox lifecycle (status state machine), DB-only half. DB-bound tests that pin the reserve β†’ reconcile β†’ finalize state machine: PROVISIONING β†’ RUNNING, durable failure state with attempt-number advancement on retry, idempotent provisioning, the health-check failure -> re-provision recovery path, and the idle-sele...
671
25,352
onyx
backend/tests/external_dependency_unit/craft/test_skill_visibility.py
.py
"""Skill visibility (user/admin access-control filter).""" from __future__ import annotations import pytest from sqlalchemy.orm import Session from onyx.db.enums import SkillSharePermission from onyx.db.models import User, UserRole from onyx.db.skill import ( SkillManagementPolicy, fetch_skill, list_skil...
282
9,135
onyx
backend/tests/external_dependency_unit/craft/test_scheduled_task_pre_approvals.py
.py
"""Scheduled-task pre-approvals (ext-dep): real SQL for the grant lookup, the pre-decided insert, and the grant patch semantics. The gate-side short-circuit behavior (skip park / fall through / DENY ordering) is covered with stubs in ``tests/unit/sandbox_proxy/test_gate.py``; this file pins the queries those stubs sta...
500
15,936
onyx
backend/tests/external_dependency_unit/craft/test_company_search_skill.py
.py
"""Tests for build_available_sources_section() and company-search skill rendering.""" from __future__ import annotations import pytest from sqlalchemy.orm import Session from onyx.configs.constants import DocumentSource from onyx.db.models import User from onyx.skills.rendering import build_available_sources_section...
85
2,973
onyx
backend/tests/external_dependency_unit/craft/test_external_app_skill_associations.py
.py
from __future__ import annotations from uuid import UUID, uuid4 import pytest from sqlalchemy import select from sqlalchemy.orm import Session from onyx.db.enums import ExternalAppType, SkillSharePermission from onyx.db.external_app import ( associate_custom_skill_with_external_app__no_commit, create_externa...
412
13,660
onyx
backend/tests/external_dependency_unit/craft/test_custom_external_app_create.py
.py
from __future__ import annotations from uuid import UUID, uuid4 import pytest from sqlalchemy import delete, select from sqlalchemy.orm import Session from onyx.db.enums import ExternalAppType, SkillSharePermission from onyx.db.external_app import ( associate_built_in_skill__no_commit, create_external_app, ...
369
11,449
onyx
backend/tests/external_dependency_unit/craft/test_sandbox_pat.py
.py
"""Tests for sandbox PAT infrastructure (PR 1: PAT provisioning, reuse, expiry, filtering).""" from __future__ import annotations from datetime import datetime, timedelta, timezone from typing import Any from uuid import uuid4 import pytest from sqlalchemy.orm import Session from onyx.auth.pat import hash_pat from ...
345
12,718
onyx
backend/tests/external_dependency_unit/craft/test_external_app_skill_visibility.py
.py
"""External-app skill management and runtime dependency behavior.""" from __future__ import annotations from uuid import UUID, uuid4 import pytest from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session from onyx.db.enums import ExternalAppType, SkillSharePermission from onyx.db.external_app im...
477
15,204
onyx
backend/tests/external_dependency_unit/craft/test_terminated_sandbox_fast_fail.py
.py
"""Cross-replica fast-fail for sandboxes with no live backend. A fresh ``StubSandboxManager`` (empty local tombstone) stands in for a peer replica, so bus creation is driven purely off the DB ``Sandbox.status``: TERMINATED / FAILED / SLEEPING are refused, RUNNING / PROVISIONING proceed. """ from __future__ import ann...
94
3,476
onyx
backend/tests/external_dependency_unit/craft/test_connect_app.py
.py
from __future__ import annotations from uuid import uuid4 from onyx.cache.factory import get_cache_backend from onyx.cache.interface import CacheBackend from onyx.server.features.build import connect_app from shared_configs.configs import POSTGRES_DEFAULT_SCHEMA_STANDARD_VALUE def _cache() -> CacheBackend: retu...
46
1,492
onyx
backend/tests/external_dependency_unit/craft/test_ensure_sandbox_running.py
.py
"""State-machine coverage for ``SessionManager.ensure_sandbox_running``. The headless entry point (``manager.py:ensure_sandbox_running``) delegates to ``ensure_sandbox_ready`` (``sandbox_lifecycle.py:197``) under the ``POLL`` provisioning policy. These tests drive the public ``SessionManager`` API against the real Pos...
252
9,934
onyx
backend/tests/external_dependency_unit/craft/test_skill_api_access.py
.py
"""Route-level skill access checks.""" from __future__ import annotations import io from types import SimpleNamespace from typing import cast from unittest.mock import MagicMock import pytest from fastapi import UploadFile from sqlalchemy.orm import Session from onyx.db.enums import SkillAccessLevel, SkillSharePerm...
399
11,739
onyx
backend/tests/external_dependency_unit/craft/test_mcp_config_resolution.py
.py
"""External-dependency-unit tests for ``resolve_craft_mcp_servers``. Verifies the DB β†’ opencode-config-input step: only craft-enabled servers the user may access *and the proxy can authenticate them against* are emitted, tools split into enabled/disabled by the admin's chat-side curation, and the opencode server key i...
400
13,453
onyx
backend/tests/external_dependency_unit/craft/test_durable_provisioning.py
.py
"""Durable provisioning lifecycle: reserve β†’ reconcile β†’ finalize. Pins the transaction-ordering contract with real PostgreSQL and a controlled sandbox-manager double: * the sandbox identity, owner, PAT, and attempt number are committed β€” and visible to an independent database connection β€” before the first external...
428
16,625
onyx
backend/tests/external_dependency_unit/craft/test_skill_affected_users.py
.py
from __future__ import annotations from uuid import uuid4 from sqlalchemy.orm import Session from onyx.db.enums import SandboxStatus from onyx.db.models import OAuthAccount, User from onyx.db.skill import affected_user_ids_for_skill from onyx.server.features.build.db.sandbox import get_sandbox_user_map from tests.ex...
127
4,444
onyx
backend/tests/external_dependency_unit/craft/test_streaming_persistence.py
.py
"""Streaming persistence tests (ext-dep). These cover what ``persist_sandbox_event`` actually writes to the DB (assistant/thought rows, tool-call gating, plan upsert, turn indexing, finalize semantics). Tests drive the same shared helpers used by the background interactive-turn runner against Postgres with a stubbed `...
691
24,208
onyx
backend/tests/external_dependency_unit/craft/test_interrupt_message.py
.py
"""Interrupt-triggered direct abort of the in-flight opencode session. ``SessionManager.interrupt_message`` always sets the interrupt fence, and additionally spawns a best-effort daemon thread that calls ``abort_opencode_session`` when the session has a live opencode session and an active sandbox. These tests verify t...
74
2,640
onyx
backend/tests/external_dependency_unit/craft/test_managed_external_apps.py
.py
"""Onyx-managed (cloud) built-in external apps: registry invariants + cloud guards. Covers the cloud lockdown in ``external_apps_api`` (admins may only set policies on built-in apps; never create, edit credentials/config, or delete them). See ``docs/craft/features/external-apps/cloud-managed-app-credentials.md``. Bui...
226
8,214
onyx
backend/tests/external_dependency_unit/craft/test_skill_push_fault.py
.py
"""Skill-push fault-injection: one failing sandbox must not abort pushes to others.""" from __future__ import annotations import logging from collections.abc import Callable from uuid import uuid4 import pytest from sqlalchemy.orm import Session from onyx.db.enums import BuildSessionStatus, SandboxStatus, SessionOr...
180
6,597
onyx
backend/tests/external_dependency_unit/craft/test_turn_heartbeat_refresh.py
.py
"""``yield_sandbox_events`` must refresh ``sandbox.last_heartbeat`` β€” the idle reaper's only activity signal β€” at turn start and periodically while events flow.""" from __future__ import annotations import datetime from uuid import UUID, uuid4 import pytest from acp.schema import AgentMessageChunk, PromptResponse, T...
154
4,495
onyx
backend/tests/external_dependency_unit/craft/test_skills_fileset.py
.py
"""Ext-dep tests for ``build_skills_fileset_for_user``.""" from __future__ import annotations from collections.abc import Callable from pathlib import Path from uuid import uuid4 import pytest from sqlalchemy.orm import Session from onyx.configs.constants import DocumentSource from onyx.db.models import Skill, User...
251
9,269
onyx
backend/tests/external_dependency_unit/craft/redis_helpers.py
.py
"""Redis helper assertions shared by Craft tests.""" from __future__ import annotations import threading from redis import Redis from onyx.redis.tenant_redis_client import TenantRedisClient def assert_lock_serializes_two_threads( redis_client: Redis | TenantRedisClient, lock_key: str, ) -> None: """Ve...
59
1,745
onyx
backend/tests/external_dependency_unit/craft/test_external_app_admin_update.py
.py
"""The unified ``PATCH /admin/apps/{id}`` update path, single-tenant (non-managed, so config fields are editable): full update, partial update, and sandbox reconciliation ordering. The managed (cloud) variant lives in ``test_managed_external_apps.py``. """ from __future__ import annotations from collections.abc impor...
132
4,124
onyx
backend/tests/external_dependency_unit/craft/test_credential_encryption.py
.py
"""External-app credential values are encrypted at rest. ``ExternalApp.organization_credentials`` and ``ExternalAppUserCredential.user_credentials`` store encrypted bytes (via the same ``EncryptedJson`` pipeline as ``credential.credential_json``) rather than plaintext JSONB. These tests assert the raw column is binary...
86
2,869
onyx
backend/tests/external_dependency_unit/craft/test_external_app_sandbox_push.py
.py
from __future__ import annotations from uuid import UUID, uuid4 import pytest from sqlalchemy.orm import Session import onyx.server.features.build.external_apps.api as api from onyx.db.enums import ExternalAppType from onyx.db.external_app import ( get_external_app_by_skill_id, get_external_app_user_credenti...
339
9,283
onyx
backend/tests/external_dependency_unit/craft/test_external_app_fileset.py
.py
"""Ext-dep tests for external-app skill content delivery via ``build_skills_fileset_for_user``. External-app providers are *built-in skills* created on demand: their ``Skill`` row carries a ``built_in_skill_id`` (e.g. ``slack``) so it renders through the exact same disk-backed path as a seeded built-in β€” there is no e...
147
5,311
onyx
backend/tests/external_dependency_unit/craft/test_build_llm_provider_access.py
.py
"""Permission scoping for Craft provider selection (real DB). ``fetch_all_accessible_llm_providers`` must respect LLM-provider access control (is_public / group membership) so a user never gets a sandbox keyed with a provider's API key they aren't entitled to use. """ from __future__ import annotations from uuid imp...
251
7,469
onyx
backend/tests/external_dependency_unit/craft/test_craft_access_admin.py
.py
"""Tests for the admin per-user Craft access toggle. Route functions are invoked directly with constructed ``User`` rows and the test ``db_session`` (no ``TestClient``).""" from __future__ import annotations import pytest from sqlalchemy.orm import Session from onyx.auth.schemas import UserRole from onyx.error_handl...
104
4,157
onyx
backend/tests/external_dependency_unit/craft/test_provisioning_lock.py
.py
"""Cross-replica sandbox provisioning serialization, against a real Redis. Two ``KubernetesSandboxManager`` instances stand in for two api_server replicas sharing one Redis. Exactly one replica may create the pod and run the startup restore handshake; a concurrent provisioner fails fast with ``SandboxProvisionContenti...
241
8,322
onyx
backend/tests/external_dependency_unit/craft/test_idle_cleanup.py
.py
"""Idle cleanup (Celery task). Exercises ``cleanup_idle_sandboxes_task`` end-to-end against real Postgres + Redis; the per-sandbox reap runs through ``sleep_sandbox`` (sandbox lifecycle). The sandbox operations (``list_session_workspaces``, ``create_snapshot``, ``terminate``) are routed through the ``StubSandboxManage...
863
33,037
onyx
backend/tests/external_dependency_unit/craft/test_approvals_api.py
.py
"""Tests for the approvals router. Route functions are invoked directly with a constructed ``User`` and the test ``db_session`` (no ``TestClient``).""" from __future__ import annotations from collections.abc import Callable from datetime import datetime, timedelta, timezone from uuid import UUID, uuid4 import pytest...
548
19,091