repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
onyx | backend/tests/unit/onyx/server/test_projects_file_utils.py | .py | from io import BytesIO
from unittest.mock import MagicMock
import pytest
from fastapi import UploadFile
from onyx.natural_language_processing import utils as nlp_utils
from onyx.natural_language_processing.utils import BaseTokenizer, count_tokens
from onyx.server.features.projects import projects_file_utils as utils
... | 481 | 18,215 |
onyx | backend/tests/unit/onyx/server/test_admin_audit_events.py | .py | """Unit tests for audit-event emission from admin-config / access-control seams.
The API-key endpoints are the thinnest admin endpoints (each just calls one DB
function then emits), so they're used here as representatives of the uniform
emit-on-success wiring shared by the LLM-provider, connector, cc-pair,
credential,... | 106 | 3,556 |
onyx | backend/tests/unit/onyx/server/test_mcp_known_provider_oauth_helpers.py | .py | import asyncio
import time
from contextlib import contextmanager
from types import SimpleNamespace
from typing import Iterator, cast
from urllib.parse import parse_qs, urlparse
import httpx
import pytest
from mcp.client.auth import OAuthClientProvider
from mcp.client.auth.utils import should_use_client_metadata_url
fr... | 655 | 24,094 |
onyx | backend/tests/unit/onyx/server/test_oidc_multi.py | .py | """Unit coverage for the DB-backed OIDC/Google router: fail-closed provider
resolution, the per-provider client cache (keying, config-rotation bust),
per-provider client construction, and OAuth state/CSRF validation. No DB, no
network, no live IdP."""
from types import SimpleNamespace
from typing import Any, cast
imp... | 589 | 19,845 |
onyx | backend/tests/unit/onyx/server/test_saml_multi.py | .py | """Unit coverage for the DB-backed SAML router: the OneLogin settings built from
a provider row (fixed ACS), fail-closed resolution by name and by issuer, the
issuer extraction that routes the single callback, the per-provider email-domain
gate, and email extraction from SAML attributes. No DB or live IdP."""
import b... | 206 | 7,118 |
onyx | backend/tests/unit/onyx/server/test_pool_metrics.py | .py | """Unit tests for SQLAlchemy connection pool Prometheus metrics."""
from typing import Any
from unittest.mock import MagicMock, patch
from fastapi import FastAPI
from sqlalchemy.pool import NullPool
from onyx.server.metrics.postgres_connection_pool import (
PoolStateCollector,
_register_pool_events,
setu... | 305 | 10,369 |
onyx | backend/tests/unit/onyx/server/test_upload_files.py | .py | import io
import zipfile
from unittest.mock import MagicMock, patch
from zipfile import BadZipFile
import pytest
from fastapi import UploadFile
from starlette.datastructures import Headers
from onyx.configs.constants import FileOrigin
from onyx.server.documents.connector import upload_files
def _create_test_zip() -... | 109 | 3,935 |
onyx | backend/tests/unit/onyx/server/test_token_rate_limit_budget_models.py | .py | import datetime
from unittest.mock import Mock
import pytest
from pydantic import ValidationError
from onyx.configs.constants import TokenRateLimitScope
from onyx.db.models import TokenRateLimit
from onyx.db.token_limit import update_token_rate_limit
from onyx.db.user_usage import TokenUsageBucket
from onyx.error_han... | 156 | 4,544 |
onyx | backend/tests/unit/onyx/server/test_full_user_snapshot.py | .py | import datetime
from unittest.mock import MagicMock
from uuid import uuid4
from onyx.auth.schemas import UserRole
from onyx.db.enums import AccountType
from onyx.server.models import FullUserSnapshot, UserGroupInfo
def _mock_user(
personal_name: str | None = "Test User",
created_at: datetime.datetime | None ... | 56 | 1,670 |
onyx | backend/tests/unit/onyx/server/manage/test_users_directory_visibility.py | .py | from unittest.mock import MagicMock, patch
from uuid import uuid4
import pytest
from onyx.db.enums import AccountType, Permission
from onyx.error_handling.error_codes import OnyxErrorCode
from onyx.error_handling.exceptions import OnyxError
from onyx.server.manage.users import list_all_users_basic_info, verify_user_l... | 141 | 4,922 |
onyx | backend/tests/unit/onyx/server/manage/test_invite_rate_limit.py | .py | """Unit tests for the Redis-backed invite + remove-invited rate limits."""
from typing import cast
from unittest.mock import patch
from uuid import uuid4
import pytest
from redis.exceptions import ConnectionError as RedisConnectionError
from onyx.error_handling.error_codes import OnyxErrorCode
from onyx.error_handli... | 380 | 13,477 |
onyx | backend/tests/unit/onyx/server/manage/test_bulk_invite_limit.py | .py | """Test bulk invite limit for free trial tenants."""
import json
import logging
from collections.abc import Iterator
from contextlib import contextmanager
from typing import Any
from unittest.mock import MagicMock, patch
import pytest
from onyx.error_handling.error_codes import OnyxErrorCode
from onyx.error_handling... | 368 | 15,577 |
onyx | backend/tests/unit/onyx/server/manage/test_reindex_instant_backfill_guard.py | .py | """Guard that blocks a new reindex while an INSTANT swap is still backfilling the
live index (superseding it would abandon that backfill)."""
from unittest.mock import MagicMock, patch
import pytest
from onyx.context.search.models import SearchSettingsCreationRequest
from onyx.db.enums import EmbeddingPrecision
from... | 105 | 3,909 |
onyx | backend/tests/unit/onyx/server/manage/test_oauth_test_endpoint.py | .py | """Guards the admin OAuth Test endpoint: the admin-only permission gate on the
route, the missing-email rejection, and the snapshot-to-response mapping
(including the not-found shape)."""
import inspect
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from onyx.db.enums impo... | 90 | 3,223 |
onyx | backend/tests/unit/onyx/server/manage/llm/test_provider_change_validation.py | .py | """Tests for _validate_llm_provider_change's custom_config comparison.
Surface-mode keys pick a path on the same api_base, so changing them alone
must not force key re-entry; everything else still must.
"""
from unittest.mock import patch
import pytest
from onyx.error_handling.exceptions import OnyxError
from onyx.... | 81 | 2,739 |
onyx | backend/tests/unit/onyx/server/manage/llm/test_resolve_api_key.py | .py | """_resolve_api_key resolves a masked key (admin editing a saved provider) back
to the stored key β looked up by the reliable provider_id. A freshly typed key
is used as-is, and the stored key is only returned when the request's api_base
matches the stored one."""
from types import SimpleNamespace
from typing import c... | 71 | 2,013 |
onyx | backend/tests/unit/onyx/server/manage/llm/test_model_configuration.py | .py | """Tests for ModelConfigurationView.from_model and ModelConfigurationUpsertRequest.from_model.
These tests verify the flow plumbing:
- Stored flow takes precedence over the heuristic on the read path.
- Heuristic fires correctly when no flow is stored (legacy / static providers).
- ModelConfigurationUpsertRequest.from... | 463 | 16,470 |
onyx | backend/tests/unit/onyx/server/manage/llm/test_provider_cache.py | .py | import pytest
from redis.exceptions import RedisError
from onyx.server.manage.llm import provider_cache
from onyx.server.manage.llm.models import (
DefaultModel,
LLMProviderDescriptor,
LLMProviderResponse,
)
class _FakeCache:
def __init__(self) -> None:
self._vals: dict[str, bytes] = {}
... | 237 | 6,979 |
onyx | backend/tests/unit/onyx/server/manage/llm/test_nebius_tokenfactory_models.py | .py | """Tests for the Nebius Token Factory model fetcher.
Verifies the mapping from the provider's /v1/models?verbose response to
Onyx model configs: context length and vision (from architecture.modality).
"""
from typing import cast
from unittest.mock import patch
from sqlalchemy.orm import Session
from onyx.db.models ... | 154 | 5,608 |
onyx | backend/tests/unit/onyx/server/manage/llm/test_llm_provider_utils.py | .py | """Tests for LLM provider utilities."""
from onyx.server.manage.llm.utils import (
generate_bedrock_display_name,
generate_ollama_display_name,
is_embedding_model,
is_reasoning_model,
is_valid_bedrock_model,
strip_openrouter_vendor_prefix,
)
class TestGenerateBedrockDisplayName:
"""Tests ... | 259 | 9,794 |
onyx | backend/tests/unit/onyx/server/manage/llm/test_fetch_models_api.py | .py | """Tests for LLM model fetch endpoints.
These tests verify the full request/response flow for fetching models
from dynamic providers (Ollama, OpenRouter, Litellm), including the
sync-to-DB behavior when provider_id is specified.
"""
import os
from typing import Any
from unittest.mock import MagicMock, patch
import h... | 1,789 | 72,961 |
onyx | backend/tests/unit/onyx/server/manage/llm/test_portkey_models.py | .py | """Tests for the Portkey model fetcher.
Verifies the mapping from Portkey's OpenAI-shaped /v1/models response to Onyx
model configs: embedding models dropped, context length mapped, id-less entries
skipped, and results sorted by name.
"""
from typing import cast
from unittest.mock import patch
from sqlalchemy.orm im... | 87 | 3,023 |
onyx | backend/tests/unit/onyx/server/manage/voice/test_chunked_transcriber.py | .py | """Tests for ChunkedTranscriber silence gating and PCM windowing.
STT models hallucinate training-data boilerplate on silent audio instead of
returning an empty transcript, so silent audio must never reach the provider.
"""
import math
from unittest.mock import AsyncMock
import pytest
from onyx.server.manage.voice.... | 199 | 6,963 |
onyx | backend/tests/unit/onyx/server/manage/voice/test_text_utils.py | .py | from onyx.server.manage.voice.text_utils import strip_markdown_for_tts
def test_strips_bold_italic_and_code() -> None:
assert strip_markdown_for_tts("**bold** and *italic* and `code`") == (
"bold and italic and code"
)
assert strip_markdown_for_tts("__bold__ and _italic_") == "bold and italic"
d... | 71 | 2,284 |
onyx | backend/tests/unit/onyx/server/manage/voice/test_voice_api_validation.py | .py | import pytest
from onyx.error_handling.exceptions import OnyxError
from onyx.server.manage.voice.api import _validate_voice_api_base
def test_validate_voice_api_base_blocks_private_for_non_azure() -> None:
with pytest.raises(OnyxError, match="Invalid target URI"):
_validate_voice_api_base("openai", "http... | 24 | 876 |
onyx | backend/tests/unit/onyx/server/manage/embedding/test_embedding_api.py | .py | from types import SimpleNamespace
from unittest.mock import MagicMock, patch
from onyx.db.models import SearchSettings
from onyx.server.manage.embedding.api import (
list_embedding_models,
list_embedding_providers,
)
from onyx.utils.encryption import (
decrypt_bytes_to_string,
encrypt_string_to_bytes,
... | 109 | 3,472 |
onyx | backend/tests/unit/onyx/server/manage/image_generation/test_image_generation_api.py | .py | from unittest.mock import MagicMock, patch
import pytest
from litellm.exceptions import BadRequestError
from onyx.error_handling.error_codes import OnyxErrorCode
from onyx.error_handling.exceptions import OnyxError
from onyx.server.manage.image_generation.api import (
test_image_generation as run_test_image_gener... | 50 | 1,703 |
onyx | backend/tests/unit/onyx/server/settings/test_admin_patch_settings.py | .py | from collections.abc import Iterator
from contextlib import contextmanager
from typing import Any
from unittest.mock import MagicMock
import pytest
from pydantic import ValidationError
from onyx.server.settings import api as settings_api
from onyx.server.settings.models import CRAFT_INSTRUCTIONS_MAX_LENGTH, Settings
... | 80 | 2,756 |
onyx | backend/tests/unit/onyx/server/security/test_store.py | .py | """Unit tests for the legacy-env β SSRF-level derivation in security.store.
No external deps: we monkeypatch the ``app_configs`` view (``store._cfg``) so the
derivation reads controlled values instead of the process environment.
"""
import logging
import pytest
from onyx.server.security import store
from onyx.serve... | 137 | 5,172 |
onyx | backend/tests/unit/onyx/server/security/test_models.py | .py | """Model-level tests (validators, field metadata) β no external deps."""
from typing import Any
import pytest
from pydantic import ValidationError
from onyx.db.enums import IncognitoRecordMode
from onyx.server.security.models import (
OPERATOR_LOCKED_FIELDS,
PASSWORD_LENGTH_CAP,
PASSWORD_MAX_LENGTH_FLOOR... | 142 | 4,987 |
onyx | backend/tests/unit/onyx/server/scim/test_providers.py | .py | from unittest.mock import MagicMock
from uuid import UUID, uuid4
from ee.onyx.server.scim.models import (
SCIM_ENTERPRISE_USER_SCHEMA,
SCIM_USER_SCHEMA,
ScimEmail,
ScimGroupMember,
ScimGroupResource,
ScimMeta,
ScimName,
ScimUserGroupRef,
ScimUserResource,
)
from ee.onyx.server.scim.... | 221 | 7,662 |
onyx | backend/tests/unit/onyx/server/scim/test_filtering.py | .py | import pytest
from ee.onyx.server.scim.filtering import (
ScimFilter,
ScimFilterOperator,
parse_scim_filter,
)
class TestParseScimFilter:
"""Tests for SCIM filter expression parsing."""
def test_eq_filter_double_quoted(self) -> None:
result = parse_scim_filter('userName eq "john@example.... | 96 | 3,116 |
onyx | backend/tests/unit/onyx/server/scim/test_patch.py | .py | import pytest
from ee.onyx.server.scim.models import (
ScimEmail,
ScimGroupMember,
ScimGroupResource,
ScimMeta,
ScimName,
ScimPatchOperation,
ScimPatchOperationType,
ScimPatchRequest,
ScimPatchResourceValue,
ScimPatchValue,
ScimUserResource,
)
from ee.onyx.server.scim.patch ... | 610 | 21,812 |
onyx | backend/tests/unit/onyx/server/scim/test_entra.py | .py | """Comprehensive Entra ID (Azure AD) SCIM compatibility tests.
Covers the full Entra provisioning lifecycle: service discovery, user CRUD
with enterprise extension schema, group CRUD with excludedAttributes, and
all Entra-specific behavioral quirks (PascalCase ops, enterprise URN in
PATCH value dicts).
"""
from __fut... | 989 | 33,372 |
onyx | backend/tests/unit/onyx/server/scim/test_auth.py | .py | from unittest.mock import MagicMock
import pytest
from ee.onyx.server.scim.auth import (
SCIM_TOKEN_PREFIX,
ScimAuthError,
_hash_scim_token,
generate_scim_token,
verify_scim_token,
)
class TestGenerateScimToken:
def test_returns_three_strings(self) -> None:
raw, hashed, display = gen... | 106 | 3,735 |
onyx | backend/tests/unit/onyx/server/scim/test_group_endpoints.py | .py | """Unit tests for SCIM Group CRUD endpoints."""
from __future__ import annotations
from unittest.mock import MagicMock, patch
from uuid import uuid4
from fastapi import Response
from ee.onyx.server.scim.api import (
create_group,
delete_group,
get_group,
list_groups,
patch_group,
replace_gro... | 683 | 19,841 |
onyx | backend/tests/unit/onyx/server/scim/test_admin.py | .py | """Tests for SCIM admin token management endpoints."""
from datetime import datetime
from unittest.mock import MagicMock, patch
from uuid import uuid4
import pytest
from sqlalchemy.orm import Session
from ee.onyx.db.scim import ScimDAL
from ee.onyx.server.enterprise_settings.api import (
create_scim_token,
g... | 138 | 4,384 |
onyx | backend/tests/unit/onyx/server/scim/test_user_endpoints.py | .py | """Unit tests for SCIM User CRUD endpoints."""
from __future__ import annotations
from unittest.mock import MagicMock, patch
from uuid import uuid4
from fastapi import Response
from sqlalchemy.exc import IntegrityError
from ee.onyx.db.license import seat_lock_id_for_tenant
from ee.onyx.server.scim.api import (
... | 1,063 | 34,698 |
onyx | backend/tests/unit/onyx/server/scim/conftest.py | .py | """Shared fixtures for SCIM endpoint unit tests."""
from __future__ import annotations
import json
from collections.abc import Generator
from typing import Any
from unittest.mock import MagicMock, patch
from uuid import uuid4
import pytest
from fastapi.responses import JSONResponse
from sqlalchemy.orm import Session... | 174 | 6,551 |
onyx | backend/tests/unit/onyx/server/query_and_chat/test_query_and_chat_chat_utils.py | .py | from onyx.file_store.models import ChatFileType
from onyx.server.query_and_chat.chat_utils import mime_type_to_chat_file_type
def test_mime_type_to_chat_file_type_strips_parameters() -> None:
assert (
mime_type_to_chat_file_type("text/csv; charset=utf-8") == ChatFileType.TABULAR
)
assert (
... | 22 | 713 |
onyx | backend/tests/unit/onyx/server/query_and_chat/test_any_rate_limit_exists_tenant_scope.py | .py | """Regression coverage for tenant scoping of the token-rate-limit existence cache.
`any_rate_limit_exists()` gates all token-rate-limit enforcement, so its per-process
cache must be keyed by tenant. Otherwise the first tenant to warm it fixes the answer
for every tenant on that worker, and a tenant that configured lim... | 80 | 3,171 |
onyx | backend/tests/unit/onyx/server/query_and_chat/test_update_chat_session_reasoning.py | .py | from collections.abc import Callable
from types import SimpleNamespace
from typing import cast
from unittest.mock import MagicMock
from uuid import uuid4
import pytest
from onyx.db.models import User
from onyx.error_handling.error_codes import OnyxErrorCode
from onyx.error_handling.exceptions import OnyxError
from on... | 79 | 2,648 |
onyx | backend/tests/unit/onyx/server/query_and_chat/test_token_limit.py | .py | """Unit tests for token-rate-limit enforcement (in-memory SQLite).
Guards the admin-facing unit: a stored ``token_budget`` of N is in thousands,
so it enforces at N * 1000 tokens (the Onyx convention).
"""
import datetime
from collections.abc import Generator
from typing import cast
import pytest
from sqlalchemy imp... | 605 | 21,947 |
onyx | backend/tests/unit/onyx/server/auth/test_login_captcha_middleware.py | .py | """Unit tests for LoginCaptchaMiddleware."""
from unittest.mock import AsyncMock, patch
from fastapi import FastAPI
from fastapi.testclient import TestClient
from onyx.auth.captcha import CaptchaAction, CaptchaVerificationError
from onyx.error_handling.exceptions import register_onyx_exception_handlers
from onyx.ser... | 242 | 8,292 |
onyx | backend/tests/unit/onyx/server/auth/test_captcha_api.py | .py | """Unit tests for the reCAPTCHA OAuth verify endpoint + cookie middleware."""
from unittest.mock import AsyncMock, patch
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from onyx.auth.captcha import CaptchaVerificationError
from onyx.error_handling.exceptions import register_onyx_... | 210 | 7,671 |
onyx | backend/tests/unit/onyx/server/gateway/test_model_catalog.py | .py | from onyx.server.gateway.model_catalog import build_gateway_model_catalog
from onyx.server.manage.llm.models import LLMProviderView, ModelConfigurationView
def _model(
name: str,
*,
visible: bool = True,
supports_image_input: bool = False,
supports_reasoning: bool = False,
) -> ModelConfigurationV... | 78 | 2,288 |
onyx | backend/tests/unit/onyx/server/middleware/test_api_prefix.py | .py | import pytest
from onyx.server.middleware import api_prefix
@pytest.mark.parametrize(
("configured_prefix", "path", "expected"),
[
("v2", "/v2/gateway/v1/models", "/gateway/v1/models"),
("/v2/", "/v2/gateway", "/gateway"),
("v2", "/v2", "/"),
("", "/gateway", "/gateway"),
... | 27 | 770 |
onyx | backend/tests/unit/onyx/server/features/usage/test_cost_overrides_api.py | .py | """Admin cost-override CRUD, auth, and cache invalidation."""
from collections.abc import Generator
from typing import cast
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from sqlalchemy import Table, create_engine
from sqlalchemy.engine import Engine
from sqlalchemy.orm import Se... | 191 | 6,086 |
onyx | backend/tests/unit/onyx/server/features/usage/test_admin_usage_export_api.py | .py | """Admin /admin/usage/export: grouping, filters, auth, and get_usage_export helper."""
import datetime
import sqlite3
from collections.abc import Generator
from typing import cast
from uuid import uuid4
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import Validation... | 423 | 14,688 |
onyx | backend/tests/unit/onyx/server/features/usage/test_user_usage_api.py | .py | """Self-service /user/usage: isolation, aggregation, budget, model price."""
import datetime
import sqlite3
from collections.abc import Generator
from typing import cast
from uuid import uuid4
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from sqlalchemy import Table, create_engi... | 635 | 21,028 |
onyx | backend/tests/unit/onyx/server/features/craft/test_feature_gate.py | .py | """Feature gating tests.
`is_craft_enabled_for_user` decides whether a user sees Craft. The decision
collapses two inputs: the `ENABLE_CRAFT` env var (used when no real feature
flag provider is configured) and the PostHog `onyx-craft-enabled` flag
(used otherwise). These tests pin the precedence: PostHog wins when pre... | 228 | 7,516 |
onyx | backend/tests/unit/onyx/server/features/craft/test_timeout_registry.py | .py | """Pins the Craft timeout registry: root values, derivations, and the
ordering invariants documented in ``onyx/server/features/build/timeouts.py``.
Value pins are the spec (hardcoded, not re-derived); relationship asserts are
the invariants that must survive any retuning of a root. Constants defined at
their point of ... | 131 | 5,360 |
onyx | backend/tests/unit/onyx/server/features/craft/test_sandbox_backend_parsing.py | .py | import importlib
import os
from collections.abc import Iterator
import pytest
from onyx.server.features.build import configs
@pytest.fixture(autouse=True)
def _restore_configs() -> Iterator[None]:
# SANDBOX_BACKEND is resolved at module import, so each case reloads the
# module under a chosen env. Reload on... | 124 | 4,075 |
onyx | backend/tests/unit/onyx/server/features/craft/test_webapp_proxy_header_stripping.py | .py | """The webapp proxy must strip Set-Cookie from upstream responses and
browser-context headers (Origin, sec-fetch-*) from forwarded requests."""
from __future__ import annotations
import asyncio
from collections.abc import AsyncGenerator
from unittest.mock import AsyncMock, MagicMock, patch
from uuid import uuid4
imp... | 104 | 3,311 |
onyx | backend/tests/unit/onyx/server/features/craft/test_kubernetes_sandbox_manager.py | .py | """Unit coverage for Kubernetes sandbox manager helpers."""
from __future__ import annotations
from uuid import UUID
from onyx.server.features.build.sandbox.kubernetes.kubernetes_sandbox_manager import (
KubernetesSandboxManager,
)
# K8s object names must be a DNS label: <=63 chars, lowercase alphanumerics
# an... | 29 | 1,122 |
onyx | backend/tests/unit/onyx/server/features/craft/test_session_gateway_config.py | .py | from __future__ import annotations
import json
from collections.abc import Iterator
from datetime import datetime, timezone
from typing import cast
from unittest.mock import MagicMock, patch
import pytest
from sqlalchemy.orm import Session
from onyx.db.models import BuildSession, Sandbox, User
from onyx.llm.well_kno... | 650 | 21,855 |
onyx | backend/tests/unit/onyx/server/features/craft/test_upload_validation.py | .py | """File upload validation tests (unit / pure-logic half).
Tests pin the contract for the pure validation helpers in
`onyx.server.features.build.utils`: size cap and filename sanitization.
Craft intentionally does NOT restrict uploads by extension or MIME type
(the sandbox is the security boundary), so those checks are... | 69 | 2,491 |
onyx | backend/tests/unit/onyx/server/features/craft/test_opencode_serve_ready_password_reset.py | .py | """Regression tests for the "sandbox stuck initializing" bug.
opencode-serve sits behind HTTP Basic auth whose password lives in a per-pod
k8s Secret, read into the container's env at start. The api_server caches that
password in memory. When a pod is re-provisioned with a fresh Secret, the cached
password goes stale ... | 120 | 4,482 |
onyx | backend/tests/unit/onyx/server/features/craft/test_session_manager_merger.py | .py | """Unit tests for `streaming.merge_events_with_announces`.
The merger is a generator that interleaves a synchronous event iterator with
approval-announce events drained from a Redis-style BLPOP. Two daemon threads
write onto a shared `queue.Queue` until the event iterator completes.
"""
import json
import threading
i... | 329 | 11,272 |
onyx | backend/tests/unit/onyx/server/features/craft/test_rewrite_asset_paths.py | .py | """Unit tests for the Craft webapp proxy."""
import re
from collections.abc import AsyncGenerator, AsyncIterator
from pathlib import Path
from types import SimpleNamespace
from typing import cast
from uuid import UUID
import httpx
import pytest
from fastapi import HTTPException, Request
from starlette.responses impor... | 584 | 23,168 |
onyx | backend/tests/unit/onyx/server/features/craft/test_nextjs_dev.py | .py | """Next.js dev server start script and readiness probe behavior."""
from __future__ import annotations
import json
import re
import subprocess
import tempfile
from pathlib import Path
from unittest.mock import MagicMock, patch
from uuid import UUID
from onyx.server.features.build.sandbox import nextjs_dev
from onyx.... | 282 | 10,567 |
onyx | backend/tests/unit/onyx/server/features/craft/test_approval_display_payload.py | .py | import base64
import datetime
from email.message import EmailMessage
from typing import Any
from uuid import uuid4
from onyx.db.enums import EndpointPolicy
from onyx.external_apps.matching.engine import MatchedAction
from onyx.external_apps.providers.gmail import GmailAction
from onyx.server.features.build.approvals.a... | 59 | 1,728 |
onyx | backend/tests/unit/onyx/server/features/craft/test_craft_gateway.py | .py | from __future__ import annotations
from typing import cast
from unittest.mock import MagicMock, patch
from fastapi import Request
from onyx.db.enums import Permission
from onyx.db.models import User
from onyx.server.features.build import craft_gateway
from onyx.server.features.build.craft_gateway import (
gatewa... | 82 | 3,292 |
onyx | backend/tests/unit/onyx/server/features/craft/interactive_turns/test_executor.py | .py | from __future__ import annotations
import time
from collections.abc import Callable, Iterator
from contextlib import contextmanager
from types import SimpleNamespace
from uuid import UUID, uuid4
import pytest
from onyx.server.features.build.interactive_turns import executor
from onyx.server.features.build.interactiv... | 1,167 | 39,240 |
onyx | backend/tests/unit/onyx/server/features/craft/interactive_turns/test_turns_api.py | .py | from __future__ import annotations
import time as real_time
from collections.abc import Iterator
from contextlib import contextmanager
from types import SimpleNamespace
from typing import cast
from uuid import UUID, uuid4
import pytest
from sqlalchemy.orm import Session
from onyx.db.enums import SandboxStatus
from o... | 595 | 19,784 |
onyx | backend/tests/unit/onyx/server/features/craft/interactive_turns/test_state.py | .py | from __future__ import annotations
from collections.abc import Callable
from uuid import UUID, uuid4
from onyx.server.features.build.interactive_turns.state import (
TURN_STATUS_FAILED,
TURN_STATUS_QUEUED,
TURN_STATUS_RUNNING,
InteractiveTurn,
acquire_active_turn_lock,
claim_turn_for_runner,
... | 297 | 8,896 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_sandbox_backend_selection.py | .py | """Unit tests for the ``get_sandbox_manager()`` factory.
Verifies the SANDBOX_BACKEND dispatch wires up the right manager class for
each backend value, without instantiating Docker/K8s clients.
"""
from __future__ import annotations
from typing import Any
import pytest
from onyx.server.features.build.configs impor... | 90 | 3,359 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_snapshot_manager_streams.py | .py | """Unit tests for the streaming helpers on ``SnapshotManager``.
Production callers (Docker backend) pipe tar bytes through these helpers
without ever materializing a snapshot on the api_server filesystem. The
helpers are content-agnostic but the path/display-name/metadata contract
must stay stable, so we assert it her... | 204 | 6,338 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_translate_opencode_event.py | .py | """Unit tests for ``translate_opencode_event``.
Pure-function tests against canned opencode ``/event`` payloads. Locks
the observed wire contract so regressions surface here. No network, no
subprocess, no real opencode serve.
"""
from __future__ import annotations
from typing import Any
import pytest
from onyx.ser... | 1,865 | 58,485 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_send_message_timeout_plumbing.py | .py | """Timeout settings must reach `OpencodeServeClient.send_message`."""
from __future__ import annotations
from collections.abc import Callable, Generator
from typing import Any
from uuid import uuid4
from onyx.server.features.build.configs import (
OPENCODE_PROMPT_INACTIVITY_TIMEOUT_SECONDS,
)
from onyx.server.fe... | 97 | 3,381 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_push_orchestration.py | .py | """Tests for push_to_sandbox and push_to_sandboxes on SandboxManager base class."""
from typing import Any
from unittest.mock import patch
from uuid import UUID
import pytest
from onyx.server.features.build.sandbox.models import (
FatalWriteError,
FileSet,
RetriableWriteError,
)
from tests.common.craft.s... | 182 | 6,095 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_k8s_push_error_mapping.py | .py | """K8s push error mapping tests (pure logic, no K8s needed).
Behavior assertions for ``KubernetesSandboxManager.write_files_to_sandbox``.
We mock ``httpx.Client`` (an external HTTP boundary) and
``CoreV1Api.read_namespaced_pod`` (the K8s API boundary) to inject failure
modes. All assertions target observable outcomes ... | 981 | 34,812 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_ensure_session.py | .py | """Unit tests for :meth:`OpencodeServeClient.ensure_session`.
The persistence story for ``BuildSession.opencode_session_id`` rests on
two invariants:
1. When given a valid id, ``ensure_session`` MUST do a single ``GET
/session/{id}`` and return the same id β no ``POST /session``.
Otherwise every turn would mint... | 248 | 9,605 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_file_listing.py | .py | from __future__ import annotations
from uuid import UUID
import pytest
from onyx.server.features.build.sandbox.kubernetes.kubernetes_sandbox_manager import (
KubernetesSandboxManager,
)
from onyx.server.features.build.sandbox.kubernetes.sidecar_client import (
SidecarStatusError,
)
from onyx.server.features.... | 89 | 2,936 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_agent_instructions.py | .py | import re
from pathlib import Path
import pytest
from onyx.db.models import ExternalApp
from onyx.server.features.build.sandbox.util import agent_instructions
_TEMPLATE_PLACEHOLDER_RE = re.compile(r"{{[A-Z0-9_]+}}")
def _template_path() -> Path:
return Path(agent_instructions.__file__).parents[2] / "AGENTS.tem... | 156 | 5,313 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_session_workspace_script.py | .py | """Replay-safety contract of the generated session-workspace scripts."""
import shlex
from uuid import uuid4
from onyx.server.features.build.sandbox.docker.docker_sandbox_manager import (
build_sandbox_labels,
)
from onyx.server.features.build.sandbox.labels import LABEL_PROVISIONING_ATTEMPT
from onyx.server.feat... | 126 | 5,599 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_send_message_with_bus.py | .py | """Unit tests for :meth:`OpencodeServeClient.send_message` post-bus-refactor.
After the bus refactor, ``send_message`` is mostly orchestration: subscribe
to the per-pod :class:`PodEventBus`, POST ``prompt_async``, drain the
subscriber queue, translate events, detect terminator, unsubscribe. These
tests drive that orch... | 984 | 34,953 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_opencode_config.py | .py | from __future__ import annotations
import json
from typing import Any
import pytest
from onyx.server.features.build.configs import MCP_SESSION_TAG_HEADER
from onyx.server.features.build.sandbox.models import (
CraftLLMProviderConfig,
CraftMCPServerConfig,
)
from onyx.server.features.build.sandbox.util.mcp_co... | 320 | 10,581 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_api_url_check.py | .py | from unittest.mock import MagicMock, patch
import httpx
import pytest
from onyx.error_handling.exceptions import OnyxError
from onyx.server.features.build.sandbox.util import api_url_check
@pytest.fixture(autouse=True)
def _reset_validation_cache() -> None:
api_url_check._validated = False
def _response(statu... | 118 | 4,250 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_prune_prior_snapshots.py | .py | """Unit tests for prune-on-write: deleting a session's superseded snapshots."""
from unittest.mock import MagicMock
from uuid import uuid4
import pytest
from onyx.db.models import Snapshot
from onyx.server.features.build.sandbox.models import SnapshotResult
from onyx.server.features.build.session import sandbox_life... | 185 | 6,394 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_event_bus_per_directory.py | .py | """Tests for per-(sandbox_id, directory) :class:`PodEventBus` keying in
:class:`KubernetesSandboxManager`.
Production bug (May 2026): when two build sessions ran on the same
opencode-serve pod, both sessions shared one bus subscribed to
``GET /event`` with no ``?directory=`` query param. opencode-serve's
``Instance.pr... | 261 | 10,503 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_k8s_workspace_setup_sentinel.py | .py | """K8s workspace setup must fail loudly without the completion sentinel.
The Kubernetes exec client returns whatever output was buffered when
``_request_timeout`` lapses WITHOUT raising, and never raises on a nonzero
exit β so the sentinel in the exec output is the only reliable success
signal for ``setup_session_work... | 82 | 2,674 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_docker_snapshot_failure_propagation.py | .py | """Docker snapshot failure-propagation contract.
The Docker backend streams ``tar`` stdout out of the container through
``_GeneratorReader`` into ``FileStore``. A non-zero ``tar`` exit must surface
as an exception (so ``create_snapshot`` raises and the fail-closed idle-cleanup
keeps the sandbox RUNNING) β it must NOT ... | 59 | 2,166 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_cold_pod_retry.py | .py | """Tests for the cold-pod retry in :meth:`OpencodeServeClient.ensure_session`.
Empirical finding from E2E chaos testing (2026-05-23): freshly recreated
sandbox pods can be K8s-Ready (2/2) for a few hundred ms before
opencode-serve has actually bound to :4096. The first HTTP request hits a
half-open TCP connection and ... | 197 | 7,282 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_tarball.py | .py | """Tests for the _build_targz function in kubernetes_sandbox_manager.py."""
import hashlib
import io
import tarfile
import pytest
from onyx.server.features.build.sandbox.kubernetes.kubernetes_sandbox_manager import (
_build_targz,
)
from onyx.server.features.build.sandbox.models import FatalWriteError, FileSet
... | 84 | 2,287 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_event_bus.py | .py | """Unit tests for :mod:`onyx.server.features.build.sandbox.opencode.event_bus`.
The bus is the most critical new component in the opencode-serve migration:
one long-lived ``/event`` SSE subscription per pod, multiplexed to
per-session subscriber queues. These tests cover the pure-Python pieces
of the bus β dispatch ro... | 823 | 29,580 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_workspace_cleanup_failure_propagation.py | .py | from unittest.mock import MagicMock
from uuid import uuid4
import pytest
from kubernetes.client.rest import ApiException
import onyx.server.features.build.sandbox.docker.docker_sandbox_manager as docker_module
import onyx.server.features.build.sandbox.kubernetes.kubernetes_sandbox_manager as kubernetes_module
from on... | 51 | 1,866 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_serve_transport_live_coalescing.py | .py | """Tests for live attach stream text coalescing in serve transport."""
from __future__ import annotations
import threading
import time
from collections.abc import Generator
from typing import Any
from uuid import uuid4
import pytest
from onyx.server.features.build.packets import SubagentStartedPacket
from onyx.serv... | 237 | 6,917 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_docker_serve_plumbing.py | .py | """Unit tests for ``DockerSandboxManager`` serve-transport wiring.
These tests exercise the pure logic added by the
docker-sandbox-serve port β no Docker engine required. We use
``object.__new__(DockerSandboxManager)`` to bypass ``__init__``
(which would try to open the Docker socket) and verify:
- ``_load_serve_conn... | 568 | 19,276 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_docker_exec_helpers.py | .py | """Unit tests for Docker exec helper plumbing."""
from __future__ import annotations
import socket
from collections.abc import Iterator
from unittest.mock import MagicMock
import pytest
import onyx.server.features.build.sandbox.docker.internal.exec_helpers as exec_helpers
class _FakeSocket:
def __init__(self)... | 83 | 2,278 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_resolve_proxy_ip.py | .py | """``_resolve_proxy_ip`` must resolve the egress-proxy hostAlias to the real
Service ClusterIP via the k8s API β not the api-server's OS resolver, which
under telepresence returns a synthetic, pod-unroutable IP. A numeric host (CI
passes the ClusterIP directly) is returned unchanged without an API call.
"""
from __fut... | 108 | 3,829 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_exec_helpers_redaction.py | .py | """Lock down that long shell scripts can't leak through ExecError messages.
Setup scripts (``setup_session_workspace``, ``restore_snapshot``) embed
the LLM API key inline via ``printf '%s' '<opencode.json>' > opencode.json``.
If exec fails, the script ends up in ``ExecError`` β which gets logged.
This test pins the re... | 44 | 1,550 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_docker_manager_config.py | .py | """Unit tests for ``DockerSandboxManager`` config helpers.
These tests exercise the pure naming / label / container-kwargs logic without
touching Docker. The kwargs builder is the load-bearing piece for the sandbox's
security posture (cap-drop, no-new-privileges, non-root user, no socket mount,
env allowlist), so we l... | 916 | 32,010 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_safe_extract.py | .py | """Tests for safe_extract_then_atomic_swap from the sandbox_daemon's extract module."""
import io
import os
import tarfile
from pathlib import Path
import pytest
from onyx.server.features.build.sandbox.image.sandbox_daemon.extract import (
safe_extract_then_atomic_swap,
)
@pytest.fixture(autouse=True)
def _pat... | 241 | 8,110 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_bus_closed_property.py | .py | """Test for ``PodEventBus.closed`` and the cached-bus eviction it enables.
Empirical finding (2026-05-23): when the per-pod event bus exhausts its
reconnect budget (20 consecutive failures, e.g. against a long-idle pod
that gets evicted), it sets ``_closed=True`` and signals subscribers, but
``KubernetesSandboxManager... | 55 | 2,143 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_ensure_opencode_session.py | .py | from __future__ import annotations
from collections.abc import Callable
from typing import Any
from uuid import UUID, uuid4
import pytest
from onyx.server.features.build.sandbox import serve_transport
from onyx.server.features.build.sandbox.kubernetes.kubernetes_sandbox_manager import (
KubernetesSandboxManager,... | 117 | 3,757 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_serve_readiness_probe.py | .py | """Unit tests for ``_ServeMixin._wait_for_opencode_serve_ready``.
Pins the multi-candidate probe contract: the readiness gate must succeed if
EITHER the Service ``base_url`` (FQDN) OR the pod-IP health-check URL answers
``GET /doc`` with 200. The FQDN is probed first (it routes in prod and under
telepresence, which pr... | 91 | 3,284 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/test_serve_client_401_reload.py | .py | """Focused test: OpencodeServeClient self-heals a 401 by reloading the password."""
from __future__ import annotations
import httpx
from onyx.server.features.build.sandbox.opencode.serve_client import OpencodeServeClient
def test_request_reloads_password_on_401_and_retries() -> None:
calls: list[str | None] = ... | 62 | 1,926 |
onyx | backend/tests/unit/onyx/server/features/craft/sandbox/sandbox_daemon/test_sandbox_daemon.py | .py | """In-pod sandbox_daemon server tests.
Behavior tests over the FastAPI sandbox_daemon (push + snapshot endpoints) using
``fastapi.testclient``. The sandbox_daemon module is loaded dynamically under the
``sandbox_daemon`` package name because its in-container layout (``COPY sandbox_daemon/
/workspace/sandbox_daemon``) ... | 1,598 | 56,407 |
onyx | backend/tests/unit/onyx/server/features/craft/external_apps/test_api_user_response.py | .py | from __future__ import annotations
import json
from types import SimpleNamespace
from typing import Any, cast
from onyx.db.enums import ExternalAppType
from onyx.db.models import ExternalApp, ExternalAppUserCredential
from onyx.server.features.build.external_apps.api import _to_user_response
from onyx.utils.encryptio... | 118 | 3,804 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.