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/onyxbot/discord/test_discord_utils.py | .py | """Unit tests for Discord bot utilities.
Tests for:
- Token management (get_bot_token)
- Registration key parsing (parse_discord_registration_key, generate_discord_registration_key)
"""
from unittest.mock import MagicMock, patch
from onyx.onyxbot.discord.utils import get_bot_token
from onyx.server.manage.discord_bot... | 159 | 6,189 |
onyx | backend/tests/unit/onyx/onyxbot/discord/test_should_respond.py | .py | """Unit tests for Discord bot should_respond logic.
Tests the decision tree for when the bot should respond to messages.
"""
from unittest.mock import AsyncMock, MagicMock, patch
import discord
import pytest
from onyx.onyxbot.discord.handle_message import (
check_implicit_invocation,
should_respond,
)
cla... | 646 | 24,350 |
onyx | backend/tests/unit/onyx/onyxbot/discord/test_api_client.py | .py | """Unit tests for Discord bot API client.
Tests for OnyxAPIClient class functionality.
"""
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
import aiohttp
import pytest
from onyx.chat.models import ChatFullResponse
from onyx.onyxbot.discord.api_client import OnyxAPIClient
from onyx.onyxb... | 442 | 13,835 |
onyx | backend/tests/unit/onyx/onyxbot/discord/test_message_utils.py | .py | """Unit tests for Discord bot message utilities.
Tests for:
- Message splitting (_split_message)
- Citation formatting (_append_citations)
"""
from unittest.mock import MagicMock
from onyx.chat.models import ChatFullResponse
from onyx.onyxbot.discord.constants import MAX_MESSAGE_LENGTH
from onyx.onyxbot.discord.hand... | 316 | 11,885 |
onyx | backend/tests/unit/onyx/onyxbot/discord/test_context_builders.py | .py | """Unit tests for Discord bot context builders.
Tests the thread and reply context building logic with mocked Discord API.
"""
from typing import Any
from unittest.mock import AsyncMock, MagicMock
import discord
import pytest
from onyx.onyxbot.discord.constants import MAX_CONTEXT_MESSAGES
from onyx.onyxbot.discord.... | 646 | 22,003 |
onyx | backend/tests/unit/onyx/onyxbot/discord/conftest.py | .py | """Fixtures for Discord bot unit tests."""
import random
from collections.abc import Callable
from typing import Any
from unittest.mock import AsyncMock, MagicMock
import discord
import pytest
class AsyncIteratorMock:
"""Helper class to mock async iterators like channel.history()."""
def __init__(self, ite... | 281 | 8,227 |
onyx | backend/tests/unit/onyx/context/search/test_base_filters_time_compat.py | .py | """Wire-compat tests for the deprecated time_cutoff alias on BaseFilters.
Older API clients send time_cutoff in request bodies
(e.g. SendMessageRequest.internal_search_filters, AdminSearchRequest.filters);
it must keep filtering on document update time via updated_at_range.
"""
from datetime import datetime, timezone... | 50 | 1,556 |
onyx | backend/tests/unit/onyx/context/search/test_forced_document_set.py | .py | """Unit tests for the operator-forced document-set scope.
Covers the name verifier (disabled when multitenant/unset, logs an error for a
missing name) and that _build_index_filters applies the scope only when the
Search-UI force flag is set. The DB is mocked so these run without external deps.
"""
from types import S... | 99 | 3,569 |
onyx | backend/tests/unit/onyx/context/search/federated/test_url_override.py | .py | """Tests for Slack URL parsing and direct thread fetch via URL override."""
from unittest.mock import MagicMock, patch
from onyx.context.search.federated.models import DirectThreadFetch
from onyx.context.search.federated.slack_search import _fetch_thread_from_url
from onyx.context.search.federated.slack_search_utils ... | 108 | 4,427 |
onyx | backend/tests/unit/onyx/context/search/federated/test_slack_query_construction.py | .py | from unittest.mock import MagicMock
from onyx.context.search.federated.slack_search_utils import (
build_channel_query_filter,
matches_exclude_pattern,
)
from onyx.onyxbot.slack.models import ChannelType
class TestChannelPatternMatching:
"""Test glob pattern matching for channel exclusion"""
def tes... | 333 | 12,141 |
onyx | backend/tests/unit/onyx/context/search/federated/test_slack_thread_context.py | .py | """Tests for Slack thread context fetching with rate limit handling."""
from datetime import datetime
from unittest.mock import MagicMock, patch
import pytest
from slack_sdk.errors import SlackApiError
from onyx.context.search.federated.models import SlackMessage
from onyx.context.search.federated.slack_search impor... | 448 | 16,157 |
onyx | backend/tests/unit/onyx/context/search/federated/test_build_thread_text.py | .py | """Tests for _build_thread_text function."""
from unittest.mock import MagicMock, patch
from onyx.context.search.federated.slack_search import _build_thread_text
def _make_msg(user: str, text: str, ts: str) -> dict[str, str]:
return {"user": user, "text": text, "ts": ts}
class TestBuildThreadText:
"""Veri... | 67 | 2,898 |
onyx | backend/tests/unit/onyx/federated_connectors/test_federated_connector_factory.py | .py | """
Unit tests for federated connector lazy loading factory to validate:
1. All federated connector mappings are correct
2. Module paths and class names are valid
3. Error handling works properly
4. Caching functions correctly
"""
import importlib
from unittest.mock import MagicMock, Mock, patch
import pytest
from o... | 200 | 7,774 |
onyx | backend/tests/unit/onyx/federated_connectors/test_oauth_utils.py | .py | """Unit tests for federated OAuth state generation and verification.
Uses unittest.mock to patch get_cache_backend so no external services
are needed. Verifies the generate -> verify round-trip, one-time-use
semantics, TTL propagation, and error handling.
"""
from unittest.mock import patch
import pytest
from onyx... | 165 | 5,328 |
onyx | backend/tests/unit/onyx/external_apps/test_url_glob.py | .py | import re
import pytest
from onyx.error_handling.exceptions import OnyxError
from onyx.external_apps.url_glob import UrlGlob
def _matches(glob: str, url: str) -> bool:
return re.fullmatch(UrlGlob(value=glob).to_regex(), url) is not None
def test_dot_is_literal_not_wildcard() -> None:
# The dot in the host... | 71 | 2,479 |
onyx | backend/tests/unit/onyx/prompts/test_prompt_utils.py | .py | from unittest.mock import MagicMock, patch
from onyx.prompts.chat_prompts import (
CITATION_GUIDANCE_REPLACEMENT_PAT,
DATETIME_REPLACEMENT_PAT,
REQUIRE_CITATION_GUIDANCE,
)
from onyx.prompts.constants import REMINDER_TAG_DESCRIPTION
from onyx.prompts.prompt_utils import (
apply_prompt_placeholders,
... | 173 | 5,977 |
onyx | backend/tests/unit/onyx/auth/test_verify_email_invite.py | .py | """Invite-only gating: when the toggle is on, the invite list governs every
signup regardless of login method, and a permission-sync placeholder never
counts as an existing member."""
from contextlib import contextmanager
from typing import Any, Iterator
from unittest.mock import MagicMock
import pytest
import onyx.... | 117 | 3,555 |
onyx | backend/tests/unit/onyx/auth/test_captcha_cookie.py | .py | """Unit tests for the OAuth reCAPTCHA cookie helpers in onyx.auth.captcha."""
from onyx.auth import captcha as captcha_module
def test_issued_cookie_validates() -> None:
"""A freshly issued cookie passes validation."""
cookie = captcha_module.issue_captcha_cookie_value()
assert captcha_module.validate_ca... | 48 | 1,822 |
onyx | backend/tests/unit/onyx/auth/test_email.py | .py | import pytest
from onyx.auth.email_utils import build_user_email_invite, send_email
from onyx.configs.constants import ONYX_DEFAULT_APPLICATION_NAME
from onyx.db.engine.sql_engine import SqlEngine
from onyx.server.runtime.onyx_runtime import OnyxRuntime
@pytest.mark.skip(
reason="This sends real emails, so only ... | 35 | 1,010 |
onyx | backend/tests/unit/onyx/auth/test_jwt_provisioning.py | .py | from collections.abc import Callable
from datetime import datetime, timezone
from typing import Any
from unittest.mock import AsyncMock, MagicMock
import pytest
from onyx.auth import users as users_module
from onyx.server.security.models import SecuritySettings
@pytest.fixture
def stub_security_settings(
monkey... | 251 | 8,762 |
onyx | backend/tests/unit/onyx/auth/test_is_same_origin.py | .py | import pytest
from onyx.auth.users import is_same_origin
class TestExactMatch:
"""Origins that are textually identical should always match."""
@pytest.mark.parametrize(
"origin",
[
"http://localhost:3000",
"https://app.example.com",
"https://app.example.co... | 121 | 4,270 |
onyx | backend/tests/unit/onyx/auth/test_auth_audit_events.py | .py | """Unit tests for audit-event emission from the auth seams in UserManager.
Verifies the right AuditAction / outcome / actor is emitted on login success,
login failure, forgot-password, and email-verify, without coupling to the
heavier register/logout flows (their emit calls follow the same one-line
pattern). Emission ... | 133 | 4,681 |
onyx | backend/tests/unit/onyx/auth/test_captcha_enterprise.py | .py | """Unit tests for the reCAPTCHA Enterprise Assessment rejection ladder."""
from collections.abc import Iterator
from datetime import datetime, timezone
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from onyx.auth import captcha as captcha_module
from onyx.auth.captcha import (
CaptchaAction... | 283 | 10,926 |
onyx | backend/tests/unit/onyx/auth/test_smtp_no_auth.py | .py | """Regression coverage for #10682: SMTP without auth / without STARTTLS.
`send_email_with_smtplib` must not call `starttls()` when STARTTLS is disabled
and must not call `login()` when credentials are not configured — internal
IP-whitelisted relays don't support either.
"""
from unittest.mock import MagicMock, patch
... | 103 | 3,567 |
onyx | backend/tests/unit/onyx/auth/test_verify_auth_setting.py | .py | from unittest.mock import MagicMock
import pytest
import onyx.auth.users as users
from onyx.auth.users import verify_auth_setting, verify_user_auth_secret
@pytest.mark.parametrize("stale_value", ["", "basic", "cloud"])
def test_verify_auth_setting_silent_for_inert_values(
monkeypatch: pytest.MonkeyPatch,
st... | 120 | 3,986 |
onyx | backend/tests/unit/onyx/auth/test_disposable_email_validator.py | .py | """
Tests for disposable email validation.
"""
from onyx.auth.disposable_email_validator import (
DisposableEmailValidator,
is_disposable_email,
)
class TestDisposableEmailValidator:
"""Test the DisposableEmailValidator class."""
def test_singleton_pattern(self) -> None:
"""Test that Disposa... | 102 | 3,952 |
onyx | backend/tests/unit/onyx/auth/test_email_archive_bcc.py | .py | from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
from onyx.auth import email_utils
def test_archive_bcc_added_to_sendgrid_payload(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(
email_utils,
"EMAIL_ARCHIVE_BCC_ADDRESSES",
("... | 39 | 1,141 |
onyx | backend/tests/unit/onyx/auth/test_user_create_schema.py | .py | """
Unit tests for UserCreate schema dict methods.
Verifies that account_type is always included in create_update_dict
and create_update_dict_superuser.
"""
from onyx.auth.schemas import UserCreate
from onyx.db.enums import AccountType
def test_create_update_dict_includes_default_account_type() -> None:
uc = Us... | 30 | 952 |
onyx | backend/tests/unit/onyx/auth/test_password_login_tenant_conflict.py | .py | """Guards that an ambiguous workspace reaches the password login caller.
Resolution raises CONFLICT when an address has several pending invitations and
no active membership, because picking one would join a workspace the user never
accepted. That response tells them to choose. A blanket handler around the
lookup would... | 112 | 4,223 |
onyx | backend/tests/unit/onyx/auth/test_optional_user_oauth_refresh.py | .py | from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from sqlalchemy.ext.asyncio import AsyncSession
from onyx.auth.users import _maybe_refresh_oauth_tokens
from onyx.db.models import User
@pytest.mark.asyncio
async def test_maybe_refresh_oauth_tokens_invokes_check_and_refresh(
mock_user: MagicMo... | 80 | 2,605 |
onyx | backend/tests/unit/onyx/auth/test_signup_rate_limit.py | .py | """Unit tests for the per-IP signup rate limiter."""
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from fastapi import Request
from onyx.auth import signup_rate_limit as rl
from onyx.auth.signup_rate_limit import (
_PER_IP_PER_HOUR,
_bucket_key,
_client_ip,
enforce_signup_rate_l... | 190 | 6,366 |
onyx | backend/tests/unit/onyx/auth/test_permissions.py | .py | """
Unit tests for onyx.auth.permissions — pure logic and FastAPI dependency.
"""
from types import SimpleNamespace
from typing import cast
from unittest.mock import MagicMock
import pytest
from fastapi import Request
from onyx.auth.permissions import (
ALL_PERMISSIONS,
IMPLIED_PERMISSIONS,
NON_TOGGLEABL... | 405 | 15,396 |
onyx | backend/tests/unit/onyx/auth/test_invite_only_failclosed.py | .py | """The invite-only check fails closed: a settings-read error is treated as
invite-only ON so a transient KV/DB failure can't silently admit uninvited
users."""
import pytest
import onyx.auth.users as users
from onyx.server.settings.models import Settings
def test_returns_setting_value_when_load_succeeds(
monkey... | 30 | 891 |
onyx | backend/tests/unit/onyx/auth/test_offline_access_auth_params.py | .py | """Providers like Google issue refresh tokens only when the authorize request
asks for offline access; these params must be injected into every flow."""
from urllib.parse import parse_qs, urlparse
from onyx.auth.oauth_token_manager import (
OAuthFlowParams,
build_oauth_authorization_url,
ensure_offline_ac... | 105 | 3,442 |
onyx | backend/tests/unit/onyx/auth/test_session_tenant_resolution.py | .py | """Which workspace a freshly issued session names.
Only a caller that has already decided the workspace may set it. The request's
own tenant context is whatever cookie the browser sent, which on a re-login can
name a workspace the user being authenticated does not belong to, so reading it
here would hand them a sessio... | 62 | 1,989 |
onyx | backend/tests/unit/onyx/auth/test_usage_credential_identity.py | .py | from typing import Any, cast
import pytest
from fastapi import Request
from onyx.auth import users
from onyx.db.enums import PatType
from onyx.db.models import User
from onyx.db.pat import PatAuthResult
from shared_configs.contextvars import UsageCredentialIdentity
from shared_configs.enums import UsageCredentialType... | 116 | 3,540 |
onyx | backend/tests/unit/onyx/auth/test_oauth_refresher.py | .py | from datetime import datetime, timezone
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from sqlalchemy.ext.asyncio import AsyncSession
from onyx.auth import oauth_refresher
from onyx.auth.oauth_refresher import (
_resolve_refresh_context,
_resolve_token_endpoint,
_test_expire_oauth_to... | 807 | 29,851 |
onyx | backend/tests/unit/onyx/auth/test_single_tenant_jwt_strategy.py | .py | import uuid
from datetime import datetime, timezone
from unittest.mock import AsyncMock, MagicMock
import jwt
import pytest
from onyx.auth.users import SingleTenantJWTStrategy
_TEST_SECRET = "test-secret-key-for-jwt-unit-tests"
_TEST_LIFETIME = 3600 # 1 hour
def _make_strategy(
lifetime_seconds: int | None = ... | 192 | 5,885 |
onyx | backend/tests/unit/onyx/auth/test_sso_url_guard.py | .py | """Which IdP URLs the server will fetch on an admin's behalf.
Admin-configured IdP URLs run through the shared outbound-SSRF guard, so this
covers the guard's own job: reject credentials in the URL, delegate the address
check to that guard, and honor the SSRF Protection setting. A private IdP is
reachable only when th... | 84 | 3,275 |
onyx | backend/tests/unit/onyx/auth/test_rekey_tenant_mapping_after_login.py | .py | """Guards that a catalog failure cannot fail a login that already succeeded.
The provider's address is committed to the tenant database before the catalog
rekey runs on a separate connection, so a raise here would fail the login over a
row the linked subject still resolves under its old address.
"""
from unittest.moc... | 61 | 2,266 |
onyx | backend/tests/unit/onyx/auth/test_login_claims_capture.py | .py | import json
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
import jwt
import pytest
import onyx.auth.login_claims_capture as claims_capture
from onyx.auth.login_claims_capture import (
capture_oauth_login_claims,
capture_saml_login_claims,
get_captured_oauth_claims,
get_i... | 678 | 23,602 |
onyx | backend/tests/unit/onyx/auth/test_scoped_pat_route_gate.py | .py | """Unit tests for the fail-closed scoped-PAT route gate.
`_scoped_pat_permitted_on_route` decides whether a PAT-authenticated request may
proceed past `optional_user`: an unrestricted token (None scopes) always may; a
scoped token may only reach routes that declare a `require_permission` (which
then adjudicates covera... | 64 | 2,284 |
onyx | backend/tests/unit/onyx/auth/test_verified_email_openid_client.py | .py | """The hardened OpenID client must reject any present email_verified value
other than true, tolerate an absent claim unless the provider opts into
require_verified_email, and refuse discovery documents whose issuer does
not own the configured endpoint."""
from typing import Any
from unittest.mock import MagicMock, pat... | 264 | 8,903 |
onyx | backend/tests/unit/onyx/auth/test_verify_email_domain.py | .py | import pytest
import onyx.auth.users as users
from onyx.auth.users import verify_email_domain
from onyx.error_handling.exceptions import OnyxError
def test_verify_email_domain_allows_case_insensitive_match() -> None:
# Configure whitelist to lowercase while email has uppercase domain
verify_email_domain("Use... | 106 | 3,408 |
onyx | backend/tests/unit/onyx/auth/test_user_registration.py | .py | """
Unit tests for the user registration workflow in UserManager.create().
Tests cover:
1. Disposable email validation (before tenant provisioning)
2. Multi-tenant vs single-tenant invite logic
3. Empty whitelist vs populated whitelist scenarios
4. Case-insensitive email matching for existing user checks
"""
from typ... | 1,040 | 41,036 |
onyx | backend/tests/unit/onyx/auth/test_seat_upgrade_helpers.py | .py | """Unit tests for the seat-counted-status helpers in onyx.auth.users.
These cover the predicate that decides whether upgrading a non-web-login
user to STANDARD will add a seat (i.e. flip the user from uncounted to
counted), so the surrounding upgrade paths can short-circuit when the
upgrade is seat-neutral.
``_user_c... | 215 | 7,469 |
onyx | backend/tests/unit/onyx/auth/test_captcha_replay.py | .py | """Unit tests for the reCAPTCHA token replay cache."""
from unittest.mock import AsyncMock, MagicMock, patch
import httpx
import pytest
from onyx.auth import captcha as captcha_module
from onyx.auth.captcha import (
CaptchaAction,
CaptchaVerificationError,
_replay_cache_key,
_reserve_token_or_raise,
... | 175 | 6,595 |
onyx | backend/tests/unit/onyx/auth/test_sso_web_error.py | .py | """The SSO web-error decorator turns OnyxError into a readable /auth/error
redirect for browser navigations, serves the standard JSON error to other
callers, and deletes the flow's single-use PKCE cookie either way."""
import enum
import json
from typing import Any
import pytest
from fastapi import Request
from fasta... | 134 | 4,543 |
onyx | backend/tests/unit/onyx/auth/test_oidc_pkce.py | .py | from typing import Any, cast
from unittest.mock import AsyncMock, MagicMock, patch
from urllib.parse import parse_qs, urlparse
from fastapi import FastAPI, Response
from fastapi.testclient import TestClient
from fastapi_users.authentication import AuthenticationBackend, CookieTransport
from fastapi_users.jwt import ge... | 396 | 14,541 |
onyx | backend/tests/unit/onyx/auth/test_user_default_pins.py | .py | from unittest.mock import AsyncMock, MagicMock
import pytest
from sqlalchemy.ext.asyncio import AsyncSession
from onyx.auth.users import UserManager
def _build_db_session(return_ids: list[int]) -> MagicMock:
scalar_result = MagicMock()
scalar_result.all.return_value = return_ids
execute_result = MagicMo... | 78 | 2,200 |
onyx | backend/tests/unit/onyx/auth/conftest.py | .py | from unittest.mock import AsyncMock, MagicMock
import pytest
from onyx.db.models import OAuthAccount, User
@pytest.fixture
def mock_user() -> MagicMock:
"""Creates a mock User instance for testing."""
user = MagicMock(spec=User)
user.email = "test@example.com"
user.id = "test-user-id"
return use... | 47 | 1,408 |
onyx | backend/tests/unit/onyx/natural_language_processing/test_search_nlp_models.py | .py | from collections.abc import AsyncGenerator
from threading import Lock
from typing import Any, cast
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from httpx import AsyncClient
from litellm.exceptions import RateLimitError
from tenacity import wait_none
from onyx.llm.constants import LlmProviderNa... | 676 | 22,280 |
onyx | backend/tests/unit/onyx/natural_language_processing/test_huggingface_cached_tokenizer_tls_fallback.py | .py | from pathlib import Path
import httpx
import huggingface_hub
import huggingface_hub.constants
import pytest
import requests
from huggingface_hub import file_download
from huggingface_hub.file_download import repo_folder_name
from packaging.version import Version
from tokenizers import Tokenizer
from tokenizers.models ... | 62 | 1,955 |
onyx | backend/tests/unit/onyx/voice/providers/test_azure_provider.py | .py | import asyncio
from typing import Any
from unittest.mock import MagicMock, patch
import pytest
from onyx.voice.providers.azure import AzureStreamingTranscriber, AzureVoiceProvider
def test_azure_provider_extracts_region_from_target_uri() -> None:
provider = AzureVoiceProvider(
api_key="key",
api... | 154 | 5,339 |
onyx | backend/tests/unit/onyx/voice/providers/test_openai_provider.py | .py | import io
import struct
import wave
from onyx.voice.providers.openai import (
OpenAIRealtimeMessageType,
OpenAIVoiceProvider,
_create_wav_header,
_http_to_ws_url,
)
# --- _http_to_ws_url ---
def test_http_to_ws_url_converts_https_to_wss() -> None:
assert _http_to_ws_url("https://api.openai.com")... | 99 | 2,877 |
onyx | backend/tests/unit/onyx/voice/providers/test_azure_ssml.py | .py | import io
import struct
import wave
import pytest
from onyx.voice.providers.azure import (
AzureVoiceProvider,
_parse_stt_languages,
_voice_locale,
)
# --- _is_azure_cloud_url ---
def test_is_azure_cloud_url_speech_microsoft() -> None:
assert AzureVoiceProvider._is_azure_cloud_url(
"https:/... | 259 | 7,594 |
onyx | backend/tests/unit/onyx/voice/providers/test_elevenlabs_provider.py | .py | import struct
from onyx.voice.providers.elevenlabs import (
DEFAULT_ELEVENLABS_API_BASE,
ElevenLabsSTTMessageType,
ElevenLabsVoiceProvider,
_http_to_ws_url,
)
# --- _http_to_ws_url ---
def test_http_to_ws_url_converts_https_to_wss() -> None:
assert _http_to_ws_url("https://api.elevenlabs.io") ==... | 119 | 3,816 |
onyx | backend/tests/unit/onyx/connectors/test_source_operations.py | .py | from functools import cached_property
from typing import Any, cast
import pytest
from onyx.configs.constants import DocumentSource
from onyx.connectors import source_operations as source_operations_module
from onyx.connectors.capability_checks.models import CredentialCapability
from onyx.connectors.credentials_provid... | 501 | 17,069 |
onyx | backend/tests/unit/onyx/connectors/test_connector_factory.py | .py | """
Unit tests for lazy loading connector factory to validate:
1. All connector mappings are correct
2. Module paths and class names are valid
3. Error handling works properly
4. Caching functions correctly
"""
import importlib
from types import SimpleNamespace
from unittest.mock import MagicMock, Mock, patch
import ... | 380 | 14,189 |
onyx | backend/tests/unit/onyx/connectors/source_operation_harnesses.py | .py | """Reusable logic behind the auto-discovering source-operations harnesses.
The harness tests (coverage and import fence) parametrize over
``registered_source_operations()``; the functions here do the actual work so
they can be unit-tested against synthetic gateways and directories.
"""
import ast
import importlib
imp... | 184 | 7,033 |
onyx | backend/tests/unit/onyx/connectors/utils.py | .py | from typing import Generic, TypeVar
from pydantic import BaseModel
from onyx.connectors.connector_runner import CheckpointOutputWrapper
from onyx.connectors.interfaces import CheckpointedConnector, SecondsSinceUnixEpoch
from onyx.connectors.models import ConnectorCheckpoint, ConnectorFailure, Document
_ITERATION_LIM... | 63 | 2,086 |
onyx | backend/tests/unit/onyx/connectors/test_credentials_provider.py | .py | """Pins the shared credentials-provider construction helper.
``build_db_credentials_provider`` is the single construction site for the
DB-backed provider: ``instantiate_connector`` and source-operation gateways both
route through it, so its output shape is what keeps decrypt-audit, refresh
write-back, and rotation-loc... | 45 | 1,611 |
onyx | backend/tests/unit/onyx/connectors/test_source_operation_coverage.py | .py | """Auto-discovering coverage harness for source operations.
For every registered gateway, every (operation, variant) unit must be exercised,
per capability tag, by a capability check of that capability -- unless the
operation carries an ``untested`` reason. A per-connector session that registers
a gateway is picked up... | 51 | 1,798 |
onyx | backend/tests/unit/onyx/connectors/test_source_operation_harnesses.py | .py | from collections.abc import Callable
from pathlib import Path
from typing import Any
import pytest
from ee.onyx.connectors import capability_checks as ee_capability_checks
from onyx.configs.constants import DocumentSource
from onyx.connectors import source_operations as source_operations_module
from onyx.connectors.c... | 350 | 11,384 |
onyx | backend/tests/unit/onyx/connectors/test_source_operation_import_fence.py | .py | """Auto-discovering import fence for source operations.
For every registered gateway declaring ``sdk_modules``, the source SDK may be
imported only from the gateway's own file within the connector's OSS directory
and its EE perm-sync directory. This is what keeps the gateway boundary from
decaying over time.
"""
impo... | 50 | 1,504 |
onyx | backend/tests/unit/onyx/connectors/test_microsoft_graph_env.py | .py | import pytest
from office365.graph_client import AzureEnvironment
from onyx.connectors.exceptions import ConnectorValidationError
from onyx.connectors.microsoft_graph_env import resolve_microsoft_environment
def test_resolve_global_defaults() -> None:
env = resolve_microsoft_environment(
"https://graph.m... | 53 | 1,903 |
onyx | backend/tests/unit/onyx/connectors/test_document_metadata_coercion.py | .py | from onyx.configs.constants import DocumentSource
from onyx.connectors.models import Document, DocumentBase, TextSection
def _minimal_doc_kwargs(metadata: dict) -> dict:
return {
"id": "test-doc",
"sections": [TextSection(text="hello", link="http://example.com")],
"source": DocumentSource.... | 94 | 2,935 |
onyx | backend/tests/unit/onyx/connectors/mediawiki/test_mediawiki_family.py | .py | from typing import Final
import pytest
from pytest_mock import MockFixture
from pywikibot.families.wikipedia_family import Family as WikipediaFamily
from pywikibot.family import Family
from onyx.connectors.mediawiki import family
# Disabling these tests as they are flaky and rely on external wikis that are maintaine... | 80 | 3,094 |
onyx | backend/tests/unit/onyx/connectors/mediawiki/test_wiki.py | .py | from __future__ import annotations
import datetime
import tempfile
from collections.abc import Iterable
import pytest
import pywikibot.config
from pytest_mock import MockFixture
from onyx.connectors.mediawiki import wiki
# Some of these tests are disabled for now due to flakiness with wikipedia as the backend
pywi... | 154 | 5,349 |
onyx | backend/tests/unit/onyx/connectors/google_drive/test_drive_checkpoint_frontier.py | .py | """Checkpoint frontier (completed_until) semantics for Google Drive retrieval.
The retrieval listing is ordered by modifiedTime and resumes from
completed_until, so the frontier must never move backward within a stage +
drive/folder. A regression changes the listing query, invalidates the saved
page token, and restart... | 154 | 4,843 |
onyx | backend/tests/unit/onyx/connectors/google_drive/test_drive_conversion_batching.py | .py | """Regression coverage for the Drive connector's bounded sub-batch conversion:
documents materialize at most one DRIVE_CONVERSION_BATCH_SIZE chunk at a time,
and hierarchy-deferred files wait for their ancestor node before converting."""
from collections.abc import Callable, Iterator
from typing import cast
from unitt... | 318 | 11,817 |
onyx | backend/tests/unit/onyx/connectors/google_drive/test_drive_advanced_parse_cap.py | .py | """get_document_sections bounds the Docs-API fetch: it returns None once the
streamed response exceeds the byte cap, and parses normally under it."""
import json
from unittest.mock import MagicMock
from onyx.connectors.google_drive.section_extraction import get_document_sections
def _as_ctx(obj: MagicMock) -> Magic... | 41 | 1,251 |
onyx | backend/tests/unit/onyx/connectors/google_drive/test_drive_shortcut_following.py | .py | from collections.abc import Iterator
from typing import Any, cast
from unittest.mock import MagicMock, patch
import pytest
from googleapiclient.discovery import Resource
from onyx.connectors.google_drive.constants import (
DRIVE_FOLDER_TYPE,
DRIVE_SHORTCUT_TYPE,
)
from onyx.connectors.google_drive.doc_convers... | 414 | 13,403 |
onyx | backend/tests/unit/onyx/connectors/google_drive/test_slim_retrieval.py | .py | """Unit tests for GoogleDriveConnector slim retrieval routing.
Verifies that:
- GoogleDriveConnector implements SlimConnector so pruning takes the ID-only path
- retrieve_all_slim_docs() calls _extract_slim_docs_from_google_drive with include_permissions=False
- retrieve_all_slim_docs_perm_sync() calls _extract_slim_d... | 665 | 25,456 |
onyx | backend/tests/unit/onyx/connectors/slab/test_slab_validation.py | .py | from unittest.mock import patch
import pytest
from onyx.connectors.exceptions import ConnectorValidationError
from onyx.connectors.slab.connector import SlabConnector
def _build_connector(base_url: str = "https://myteam.slab.com") -> SlabConnector:
connector = SlabConnector(base_url=base_url)
connector.load... | 37 | 1,240 |
onyx | backend/tests/unit/onyx/connectors/airtable/test_airtable_index_all.py | .py | from typing import Any
from unittest.mock import MagicMock, patch
import pytest
from onyx.connectors.airtable.airtable_connector import (
AirtableConnector,
parse_airtable_url,
)
from onyx.connectors.exceptions import ConnectorValidationError
from onyx.connectors.models import Document
def _make_field_schem... | 631 | 21,366 |
onyx | backend/tests/unit/onyx/connectors/asana/test_asana_connector.py | .py | """Tests for Asana connector configuration parsing."""
from collections.abc import Iterator
from typing import Any, NamedTuple
from unittest.mock import MagicMock, patch
import pytest
from onyx.connectors.asana.asana_api import AsanaAPI
from onyx.connectors.asana.connector import AsanaConnector
class _AsanaTestSet... | 331 | 10,899 |
onyx | backend/tests/unit/onyx/connectors/gong/test_gong_checkpoint.py | .py | import time
from typing import Any
from unittest.mock import MagicMock, patch
import pytest
from onyx.connectors.gong.connector import GongConnector, GongConnectorCheckpoint
from onyx.connectors.models import ConnectorFailure, Document
def _make_transcript(call_id: str) -> dict[str, Any]:
return {
"call... | 693 | 24,720 |
onyx | backend/tests/unit/onyx/connectors/gmail/test_connector.py | .py | import copy
import datetime
import json
import os
from typing import Any, cast
from unittest.mock import MagicMock, patch
from onyx.access.models import ExternalAccess
from onyx.configs.constants import DocumentSource
from onyx.connectors.gmail.connector import (
GmailCheckpoint,
GmailConnector,
_build_tim... | 240 | 7,883 |
onyx | backend/tests/unit/onyx/connectors/teams/test_execute_query_with_retry.py | .py | """Tests for the Microsoft Graph SDK retry helper used by the Teams connector.
These exercise `execute_query_with_retry`, which wraps `office365` SDK
`execute_query()` calls and retries transient Graph errors (rate limits + 5xx
gateway/server hiccups). A live daily-connector test cannot reliably induce a
502, so the r... | 135 | 4,994 |
onyx | backend/tests/unit/onyx/connectors/teams/test_retry_request.py | .py | """Tests for `_retry`, the raw Microsoft Graph request path in the Teams
connector (`execute_request_direct`), used by `fetch_messages`/`fetch_replies`.
`_retry` retries transient Graph errors (rate limits + 5xx gateway/server
hiccups) with backoff and surfaces everything else immediately. A live
daily-connector test ... | 108 | 3,993 |
onyx | backend/tests/unit/onyx/connectors/teams/test_collect_teams.py | .py | """Test the OData filtering for MS Teams with special character handling."""
from unittest.mock import MagicMock
from onyx.connectors.teams.connector import _collect_all_teams
def test_special_characters_in_team_names() -> None:
"""Test that team names with special characters use client-side filtering."""
m... | 99 | 3,894 |
onyx | backend/tests/unit/onyx/connectors/clickup/test_clickup_connector.py | .py | from typing import Any
from unittest.mock import MagicMock, patch
from onyx.connectors.clickup.connector import CLICKUP_API_BASE_URL, ClickupConnector
def _mock_response(json_response: dict[str, Any]) -> MagicMock:
response = MagicMock()
response.json.return_value = json_response
return response
def te... | 47 | 1,471 |
onyx | backend/tests/unit/onyx/connectors/fireflies/test_fireflies_poll_overlap.py | .py | from datetime import datetime, timezone
from unittest.mock import patch
from onyx.connectors.fireflies.connector import (
_FIREFLIES_POLL_OVERLAP_SECONDS,
FirefliesConnector,
)
def _fmt(epoch_seconds: int) -> str:
return datetime.fromtimestamp(epoch_seconds, tz=timezone.utc).strftime(
"%Y-%m-%dT%... | 48 | 1,591 |
onyx | backend/tests/unit/onyx/connectors/confluence/test_confluence_user_cache_instance_isolation.py | .py | """Regression coverage for instance isolation of the Confluence user-resolution
caches. Confluence Server/DC usernames and userKeys are unique only within one
instance, so the username->email, userKey->email, and userid->display-name caches
must key on the instance base url. Otherwise one instance's user can resolve to... | 77 | 3,088 |
onyx | backend/tests/unit/onyx/connectors/confluence/test_confcloud_77618_fallback.py | .py | """Regression invariants for the CONFCLOUD-77618 / CONFCLOUD-76424
fallback: the offending 404 surfaces as a typed exception, perm-sync
restarts in per-page mode on it, the per-page lookup hits the dedicated
`restriction/byOperation` endpoint, and the EE walker skips unreadable
ancestors while caching shared ones."""
... | 548 | 19,426 |
onyx | backend/tests/unit/onyx/connectors/confluence/test_extract_text.py | .py | from unittest import mock
from onyx.connectors.confluence.onyx_confluence import extract_text_from_confluence_html
def _make_confluence_object(html: str) -> dict:
return {"body": {"storage": {"value": html}}}
def _make_mock_client() -> mock.Mock:
client = mock.Mock()
client.paginated_cql_retrieval.retu... | 40 | 1,240 |
onyx | backend/tests/unit/onyx/connectors/confluence/test_confluence_attachment_links.py | .py | """Confluence attachment links retain their platform-specific canonical form."""
from unittest import mock
import pytest
from onyx.connectors.confluence.connector import ConfluenceConnector
from onyx.connectors.confluence.onyx_confluence import OnyxConfluence
from onyx.connectors.models import Document
_PAGE_ID = "... | 127 | 4,089 |
onyx | backend/tests/unit/onyx/connectors/confluence/test_confluence_checkpointing.py | .py | import time
from collections.abc import Callable, Generator
from datetime import datetime, timezone
from typing import Any
from unittest.mock import MagicMock, patch
import pytest
from requests.exceptions import HTTPError
from onyx.configs.constants import DocumentSource
from onyx.connectors.confluence.connector impo... | 518 | 19,173 |
onyx | backend/tests/unit/onyx/connectors/confluence/test_slim_doc_image_skip.py | .py | """Regression test for slim-doc / main-doc admission drift on Confluence
attachments.
When image extraction is disabled (`allow_images=False`), the main indexing
pass skips image attachments and never produces a `Document` for them. The
slim-doc pass must apply the same filter; otherwise it emits a `SlimDocument`
for ... | 132 | 4,395 |
onyx | backend/tests/unit/onyx/connectors/confluence/test_attachment_pagination_400.py | .py | """A 4xx during attachment CQL pagination must not abort the whole index run.
Confluence Data Center intermittently 400s when offset pagination of an
attachment query advances past the first page. The connector keeps the
attachments retrieved before the error, records a ConnectorFailure for the
page, and continues. 40... | 264 | 9,195 |
onyx | backend/tests/unit/onyx/connectors/confluence/test_onyx_confluence.py | .py | import copy
from typing import Any
from unittest import mock
import pytest
import requests
from requests import HTTPError
from onyx.connectors.confluence import onyx_confluence as onyx_confluence_module
from onyx.connectors.confluence.onyx_confluence import (
_DEFAULT_PAGINATION_LIMIT,
_MINIMUM_PAGINATION_LIM... | 1,474 | 54,789 |
onyx | backend/tests/unit/onyx/connectors/confluence/test_include_attachments_skip.py | .py | """Tests that `include_attachments=False` suppresses attachments in both the
main indexing pass and the slim-doc pass, which must stay in lockstep (see
the admission comment in `_retrieve_all_slim_docs`)."""
from typing import Any
from unittest import mock
from onyx.connectors.confluence.connector import ConfluenceCo... | 138 | 4,636 |
onyx | backend/tests/unit/onyx/connectors/discord/test_discord_validation.py | .py | from unittest.mock import AsyncMock, patch
import pytest
from discord.errors import LoginFailure
from onyx.connectors.discord.connector import DiscordConnector
from onyx.connectors.exceptions import CredentialInvalidError
def _build_connector(token: str = "fake-bot-token") -> DiscordConnector:
connector = Disco... | 45 | 1,423 |
onyx | backend/tests/unit/onyx/connectors/canvas/test_canvas_connector.py | .py | """Tests for Canvas connector — client, credentials, conversion."""
from datetime import datetime, timezone
from typing import Any
from unittest.mock import MagicMock, patch
import pytest
from ee.onyx.external_permissions.canvas.access import (
CanvasCoursePermissionContext,
get_announcement_permissions,
... | 2,050 | 72,888 |
onyx | backend/tests/unit/onyx/connectors/google_utils/test_google_retrieval_retry.py | .py | """Drive/Gmail paginated retrieval must retry transient connection drops
(broken pipe, reset, TLS EOF, timeout) instead of letting one dropped socket
fail the whole crawl, and must re-raise when the drop persists."""
import socket
import ssl
from collections.abc import Callable
import pytest
from onyx.connectors.goo... | 83 | 2,545 |
onyx | backend/tests/unit/onyx/connectors/google_utils/test_rate_limit_detection.py | .py | import json
import httplib2
from googleapiclient.errors import HttpError
from onyx.connectors.google_utils.google_utils import _is_rate_limit_error
def _make_http_error(
status: int,
reason: str = "unknown",
error_reason: str = "",
) -> HttpError:
resp = httplib2.Response({"status": status})
if ... | 66 | 1,654 |
onyx | backend/tests/unit/onyx/connectors/google_utils/test_impersonation_guard.py | .py | from collections.abc import Callable
from unittest.mock import MagicMock
from google.auth.exceptions import RefreshError
from onyx.connectors.google_utils.resources import (
ImpersonationError,
UserRemovedError,
make_user_removal_checker,
)
from onyx.connectors.google_utils.shared_constants import MISSING... | 86 | 3,119 |
onyx | backend/tests/unit/onyx/connectors/google_utils/test_google_credential_storage.py | .py | """Guards Google OAuth app-credential resolution off the credential row: read
the app cred from the row, reconstruct it from the row's token blob when
absent, and restore the PKCE verifier for the callback token exchange."""
import json
from datetime import datetime, timedelta, timezone
from typing import Any, cast
i... | 542 | 18,251 |
onyx | backend/tests/unit/onyx/connectors/cross_connector_utils/test_tabular_section_utils.py | .py | import io
from collections.abc import Callable
from typing import IO, cast
import openpyxl
import pytest
from openpyxl.worksheet.worksheet import Worksheet
from onyx.connectors.cross_connector_utils.tabular_section_utils import (
is_tabular_file,
tabular_file_to_sections,
)
def _make_stage_callback() -> tup... | 139 | 4,549 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.