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 |
|---|---|---|---|---|---|
cognee | cognee/tests/unit/api/v1/test_sync_background_task_anchoring.py | .py | """Guards the strong-reference anchor for the background sync task.
``sync`` launches ``_perform_background_sync`` with ``asyncio.create_task`` and
returns immediately. The event loop keeps only a *weak* reference to a task, so
unless the task is anchored somewhere it can be garbage-collected mid-flight,
silently abor... | 62 | 2,340 |
cognee | cognee/tests/unit/api/v1/test_add_remember_label.py | .py | """The add and remember endpoints accept `labels` and `external_metadata` form fields.
Each field is a single part because multipart clients — Swagger UI included —
cannot reliably repeat array form fields (swagger-api/swagger-ui#10221).
`labels` accepts a JSON array ('["finance", ""]') or the comma-separated form
("f... | 380 | 13,977 |
cognee | cognee/tests/unit/api/v1/test_dataset_schema_endpoints.py | .py | """Tests for dataset schema endpoints and related utilities."""
import pytest
from uuid import uuid4
def test_dataset_configuration_model_creation():
"""Verify DatasetConfiguration model can be instantiated with expected fields."""
from cognee.modules.data.models.DatasetConfiguration import DatasetConfigurat... | 182 | 6,077 |
cognee | cognee/tests/unit/api/v1/test_public_memory_api.py | .py | import importlib
from unittest.mock import AsyncMock, MagicMock, patch
from uuid import uuid4
import pytest
# Import the module directly so we can patch attributes via patch.object.
# Patching by the dotted string "cognee.api.v1.serve.state…" fails on
# Python 3.10's unittest.mock because `cognee.api.v1.serve` is sha... | 100 | 3,488 |
cognee | cognee/tests/unit/api/v1/serve/test_cloud_client_text_filename.py | .py | """Raw-text cloud uploads must be named by content hash, not a shared placeholder.
A fixed ``data.txt`` made every text upload for a tenant land on one remote
object; rapid adds then raced the server's content-hash read-back into
FileContentHashingError 409s (first surfaced by the nightly cloud 50-small-
documents ben... | 43 | 1,724 |
cognee | cognee/tests/unit/api/v1/improve/test_improve_default_projection_skip.py | .py | """Unit tests for improve() stage 3's projection-skip sentinel.
The default memify tasks never read the projected graph (they stream triplets
from the graph DB or no-op), so improve() passes the non-empty ``data=[{}]``
sentinel — the same one every other improve stage uses — to skip the
full-graph projection. Caller-s... | 85 | 2,668 |
cognee | cognee/tests/unit/api/v1/improve/test_improve_agent_context.py | .py | """Unit tests for the improve() agent-context extraction stage (_extract_agent_context).
The stage iterates sessions, is gated on automatic session context, and is fail-open per
session. These tests stub the session manager and pending extractor so no LLM/cache is needed.
"""
import importlib
import types
from uuid i... | 82 | 2,651 |
cognee | cognee/tests/unit/api/v1/recall/test_recall_api.py | .py | import importlib
import types
from uuid import uuid4
import pytest
from cognee.modules.search.types import SearchType
def _make_user(user_id=None, tenant_id=None):
return types.SimpleNamespace(id=user_id or uuid4(), tenant_id=tenant_id)
@pytest.fixture
def api_recall_mod():
return importlib.import_module(... | 469 | 14,041 |
cognee | cognee/tests/unit/api/v1/recall/test_recall_tools.py | .py | """Wiring tests for the recall "tools" scope (text-to-SQL tool calls)."""
import importlib
import types
from uuid import uuid4
import pytest
from pydantic import TypeAdapter
from cognee.exceptions import CogneeValidationError
from cognee.memory.entries import normalize_scope
from cognee.modules.recall.types.RecallRe... | 280 | 9,593 |
cognee | cognee/tests/unit/api/v1/search/test_code_search_dispatch.py | .py | from types import SimpleNamespace
from unittest.mock import AsyncMock
import pytest
from cognee.api.v1.responses import dispatch_function as dispatch_module_export
@pytest.mark.asyncio
async def test_response_search_tool_forwards_code_query(monkeypatch):
# Import the module explicitly because the package re-exp... | 53 | 1,716 |
cognee | cognee/tests/unit/api/v1/search/test_search_api.py | .py | import types
from uuid import uuid4, uuid5, NAMESPACE_OID
import pytest
from cognee.exceptions import CogneeValidationError
from cognee.modules.search.types import SearchType
def _make_user(user_id: str = "u1", tenant_id=None):
return types.SimpleNamespace(id=user_id, tenant_id=tenant_id)
def _make_dataset(*,... | 135 | 3,850 |
cognee | cognee/tests/unit/api/v1/search/test_cloud_client_code_search.py | .py | from unittest.mock import AsyncMock
import pytest
from cognee.api.v1.serve.cloud_client import CloudClient
from cognee.api.v1.search.routers.get_search_router import SearchPayloadDTO
from cognee.modules.search.types import SearchType
class _Response:
status = 200
async def __aenter__(self):
return ... | 64 | 1,665 |
cognee | cognee/tests/unit/api/v1/datasets/test_delete_dataset_lock.py | .py | """Delete operations acquire the same per-dataset lock as pipeline runs.
While a pipeline run holds a dataset's lock (via
cognee.infrastructure.locks.get_dataset_lock, as run_pipeline_per_dataset
does), datasets.empty_dataset and datasets.delete_data on that dataset
must wait until the lock is released.
"""
import as... | 105 | 3,511 |
cognee | cognee/tests/unit/api/v1/forget/test_forget_memory_only.py | .py | """Tests for the memory_only option in cognee.forget().
Covers:
- _forget_dataset_memory: clears graph+vector, resets pipeline_status, preserves data
- _forget_data_memory: clears graph+vector for a single item, resets its pipeline_status
- Validation: memory_only without dataset raises ValueError
- Routing: memory_on... | 413 | 14,368 |
cognee | cognee/tests/unit/api/v1/forget/test_forget_dataset_args.py | .py | """Tests for explicit dataset/dataset_id handling in cognee.forget()."""
import importlib
import pytest
from types import SimpleNamespace
from uuid import uuid4
from unittest.mock import AsyncMock, patch
forget_module = importlib.import_module("cognee.api.v1.forget.forget")
serve_state_module = importlib.import_modul... | 105 | 3,640 |
cognee | cognee/tests/unit/api/v1/forget/test_forget_endpoint.py | .py | """Tests for the POST /v1/forget endpoint with memory_only flag.
Covers:
- memory_only is passed through to the forget() function
- Validation error when memory_only=True without dataset
"""
import uuid
import importlib
import pytest
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
from fa... | 110 | 3,466 |
cognee | cognee/tests/unit/api/v1/cognify/test_cognify_ontology_resolution.py | .py | import importlib
from unittest.mock import AsyncMock, patch
import pytest
cognify_module = importlib.import_module("cognee.api.v1.cognify.cognify")
serve_state_module = importlib.import_module("cognee.api.v1.serve.state")
@pytest.mark.asyncio
@pytest.mark.parametrize(
"input_config", [None, {}, {"ontology_confi... | 50 | 1,954 |
cognee | cognee/tests/unit/api/v1/config/test_llmconfig_export.py | .py | from cognee.api.v1.config import LLMConfig
from cognee.infrastructure.llm.config import LLMConfig as InfrastructureLLMConfig
def test_llmconfig_is_reexported_from_public_api_package():
assert LLMConfig is InfrastructureLLMConfig
| 7 | 235 |
cognee | cognee/tests/unit/api/v1/config/test_config_set_method.py | .py | """Test for the config.set method to verify Issue #2047 fix."""
import pytest
import inspect
from cognee.api.v1.config.config import config
from cognee.api.v1.exceptions.exceptions import InvalidConfigAttributeError
class TestConfigSetMethod:
"""Test the generic set method with @staticmethod decorator."""
d... | 135 | 5,456 |
cognee | cognee/tests/unit/api/v1/session/test_session_visibility.py | .py | """Tests for parent-user visibility of child-agent sessions.
Parent users should see sessions created by their child agents via the
``user_ids`` parameter on ``list_session_rows`` and ``get_session_row``.
"""
from datetime import datetime, timezone
from uuid import uuid4
import pytest
import pytest_asyncio
from cog... | 146 | 5,114 |
cognee | cognee/tests/unit/api/v1/session/test_session_api.py | .py | import sys
import pytest
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
from uuid import uuid4
from cognee.exceptions import CogneeValidationError
from cognee.infrastructure.databases.cache.models import SessionQAEntry
from cognee.infrastructure.databases.exceptions import DatabaseNotCre... | 605 | 22,573 |
cognee | cognee/tests/unit/api/v1/session/test_session_memory_flows.py | .py | import asyncio
import importlib
from contextlib import contextmanager
from datetime import datetime
from unittest.mock import AsyncMock, MagicMock, patch
from uuid import UUID, uuid4
import pytest
from cognee.api.v1.session import SessionQAEntry
from cognee.exceptions import CogneeValidationError
from cognee.modules.... | 985 | 34,632 |
cognee | cognee/tests/unit/api/v1/remember/test_remember_background_task_anchoring.py | .py | """Guards the strong-reference anchor for background remember tasks (#4312).
``remember`` launches its background work (permanent add+cognify run, or the
session→graph bridge) with ``asyncio.create_task`` and keeps the task only on
``RememberResult._task``. The API router serializes the result and drops it,
and the ev... | 113 | 3,604 |
cognee | cognee/tests/unit/api/v1/validate/test_validate.py | .py | """Unit tests for cognee.validate().
Graph-shaped fixtures mirror the real get_graph_data() contract — nodes are
(id, props) with a "type" field, edges are (src, tgt, relationship_name, props) —
the same shape test_graph_report_retriever.py's fixtures are pinned to.
"""
from __future__ import annotations
from contex... | 466 | 14,750 |
cognee | cognee/tests/unit/api/v1/ui/test_docker_preflight.py | .py | """Tests for Docker daemon preflight checks in cognee.api.v1.ui.ui."""
import subprocess
from unittest.mock import patch, MagicMock, call
from cognee.api.v1.ui.ui import _check_docker_available
class TestCheckDockerAvailable:
"""Unit tests for _check_docker_available()."""
def test_docker_not_on_path(self)... | 143 | 5,636 |
cognee | cognee/tests/unit/memify_pipelines/test_memify_task_registry.py | .py | import pytest
from cognee.exceptions import CogneeValidationError
from cognee.memify_pipelines.memify_task_registry import (
resolve_memify_tasks,
supported_memify_task_names,
)
from cognee.modules.pipelines.tasks.task import Task
def test_supported_task_names_are_resolvable():
names = supported_memify_t... | 81 | 2,399 |
cognee | cognee/tests/unit/memify_pipelines/test_consolidate_entities_pipeline.py | .py | """Unit tests for the consolidate_entities memify tasks and pipeline.
Everything here is mocked: no graph backend, no vector backend, no network.
The tests assert the consolidation *logic* (clustering, canonical selection,
direction-preserving edge re-pointing, duplicate + embedding deletion, the
dry_run no-op) and th... | 482 | 19,836 |
cognee | cognee/tests/unit/memify_pipelines/test_persist_agent_trace_feedbacks_pipeline.py | .py | from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from cognee.memify_pipelines.persist_agent_trace_feedbacks_in_knowledge_graph import (
persist_agent_trace_feedbacks_in_knowledge_graph_pipeline,
)
@pytest.mark.asyncio
async def test_persist_agent_trace_feedba... | 64 | 2,698 |
cognee | cognee/tests/unit/memify_pipelines/test_apply_feedback_weights_pipeline.py | .py | from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from cognee.exceptions import CogneeValidationError
from cognee.memify_pipelines.apply_feedback_weights import apply_feedback_weights_pipeline
def _make_async_ctx_mock():
"""Build a ``MagicMock`` that behaves a... | 84 | 3,248 |
cognee | cognee/tests/unit/infrastructure/test_embedding_rate_limiting_realistic.py | .py | import os
import time
import asyncio
import logging
import cognee.shared.rate_limiting as rate_limiting
from cognee.infrastructure.databases.vector.embeddings.config import (
get_embedding_config,
)
from cognee.tests.unit.infrastructure.mock_embedding_engine import MockEmbeddingEngine
# Configure logging
logging.... | 226 | 8,601 |
cognee | cognee/tests/unit/infrastructure/test_rate_limiting_realistic.py | .py | import asyncio
import os
from unittest.mock import patch
from cognee.shared.logging_utils import get_logger
from cognee.infrastructure.llm.structured_output_framework.litellm_instructor.llm.rate_limiter import (
llm_rate_limiter,
)
from cognee.infrastructure.llm.config import (
get_llm_config,
)
async def tes... | 169 | 6,160 |
cognee | cognee/tests/unit/infrastructure/mock_embedding_engine.py | .py | import asyncio
from typing import List
from cognee.infrastructure.databases.vector.embeddings.LiteLLMEmbeddingEngine import (
LiteLLMEmbeddingEngine,
)
from cognee.shared.rate_limiting import embedding_rate_limiter_context_manager
class MockEmbeddingEngine(LiteLLMEmbeddingEngine):
"""
Mock version of Lit... | 52 | 1,833 |
cognee | cognee/tests/unit/infrastructure/test_embedding_context_window_fallbacks.py | .py | from unittest.mock import AsyncMock, Mock, patch
import numpy as np
import pytest
from cognee.infrastructure.databases.exceptions import (
EmbeddingContextWindowTooSmallError,
EmbeddingException,
)
@pytest.mark.asyncio
async def test_ollama_embedding_splits_batch_on_context_window_error():
with patch(
... | 192 | 7,064 |
cognee | cognee/tests/unit/infrastructure/test_rate_limiting_retry.py | .py | import time
import asyncio
from cognee.shared.logging_utils import get_logger
from cognee.infrastructure.llm.structured_output_framework.litellm_instructor.llm.rate_limiter import (
sleep_and_retry_sync,
sleep_and_retry_async,
is_rate_limit_error,
)
logger = get_logger()
# Test function to be decorated
@... | 194 | 6,924 |
cognee | cognee/tests/unit/infrastructure/test_openai_compatible_embedding_engine.py | .py | """
Tests for OpenAICompatibleEmbeddingEngine.
Verifies that the engine:
- Returns mock embeddings when MOCK_EMBEDDING is set
- Calls the OpenAI SDK with encoding_format="float"
- Reports correct vector size and batch size
"""
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
class TestOpenAIComp... | 108 | 4,120 |
cognee | cognee/tests/unit/infrastructure/llm/test_overload_policy.py | .py | """Tests for the LLM overload policy: evidence taxonomy and cooldown episodes."""
import asyncio
import time
from types import SimpleNamespace
import httpx
import openai
import pytest
import cognee.infrastructure.llm.overload_policy as overload_policy_module
from cognee.infrastructure.llm.overload_policy import Over... | 180 | 6,204 |
cognee | cognee/tests/unit/infrastructure/llm/test_ollama_adapter.py | .py | """OllamaAPIAdapter uses a native async client — it must not block the event loop.
The adapter wraps an async ``AsyncOpenAI`` client (``instructor.from_openai``), so its
``async def`` methods ``await`` the client directly. (The previous implementation wrapped a
*synchronous* client and offloaded the blocking call via ... | 133 | 4,498 |
cognee | cognee/tests/unit/infrastructure/llm/test_get_llm_client.py | .py | from dataclasses import asdict
import pytest
from pydantic import BaseModel
from cognee.context_global_variables import llm_config as llm_config_ctx
from cognee.infrastructure.llm.config import LLMConfig
from cognee.infrastructure.llm.exceptions import LLMAPIKeyNotSetError
from cognee.infrastructure.llm.structured_ou... | 239 | 8,577 |
cognee | cognee/tests/unit/infrastructure/llm/test_bedrock_overload_wiring.py | .py | """Wiring test: BedrockAdapter dispatches through the pacing seam.
The overload policy only sees errors raised inside
``llm_rate_limiter_context_manager()``; this locks the Bedrock adapter to that
seam so a recognized overload error paces the attempts that follow.
"""
from types import SimpleNamespace
from unittest.m... | 91 | 2,775 |
cognee | cognee/tests/unit/infrastructure/llm/test_embedding_connection_dimensions.py | .py | from types import SimpleNamespace
import pytest
from cognee.infrastructure.llm import utils as llm_utils
class _FakeEmbeddingEngine:
def __init__(self, vector, dimensions):
self._vector = vector
self.dimensions = dimensions
async def embed_text(self, _texts):
return [self._vector]
... | 81 | 2,861 |
cognee | cognee/tests/unit/infrastructure/llm/test_ollama_validation.py | .py | import logging
import os
import pytest
from unittest.mock import patch, AsyncMock
from cognee.infrastructure.llm.ollama_support import (
normalize_model_name,
classify_model,
emit_warning,
_warned_models,
)
from cognee.infrastructure.llm.config import LLMConfig
from cognee.infrastructure.llm.LLMGateway ... | 145 | 5,237 |
cognee | cognee/tests/unit/infrastructure/llm/test_litellm_native.py | .py | """Unit tests for the litellm_native structured output framework.
Tests cover:
- Successful structured output via the schema-native path
- Validation-error retry with error-context injection (JSON-fallback path)
- Auth errors propagating immediately without retry
- Quota/budget errors mapped to LLMPaymentRequiredError... | 480 | 17,601 |
cognee | cognee/tests/unit/infrastructure/llm/test_llm_config_rate_limit_defaults.py | .py | """Tests for LLMConfig.default_local_rate_limit_budget (provider-aware RPM default)."""
import pytest
from cognee.infrastructure.llm.config import LOCAL_DEFAULT_RATE_LIMIT_REQUESTS, LLMConfig
def _build(**kwargs):
defaults = dict(llm_api_key="test-key", llm_endpoint="http://localhost:11434/v1")
defaults.upd... | 60 | 1,900 |
cognee | cognee/tests/unit/infrastructure/llm/test_stage_routing.py | .py | """Tests for per-stage LLM model routing.
`LLMConfig.stage_config(stage)` merges `llm_<stage>_*` overrides onto the base
`llm_*` fields, and `pipeline_stage(stage)` applies that merged config onto the
`llm_config` ContextVar for the duration of a pipeline stage. Since
`get_llm_client` reads that same ContextVar (via `... | 125 | 4,543 |
cognee | cognee/tests/unit/infrastructure/llm/test_structured_output_retry.py | .py | """Structured-output retries must satisfy BOTH floors before giving up.
The ``acreate_structured_output`` adapters are decorated with the shared
``llm_retry_stop_condition`` (``stop_after_attempt(N) & stop_after_delay(S)``).
The ``&`` builds tenacity's ``stop_all`` predicate, which stops retrying only
once *every* sub... | 243 | 10,580 |
cognee | cognee/tests/unit/infrastructure/llm/test_render_prompt.py | .py | """Tests for prompt template rendering (SDK-203).
The Jinja2 environment previously enabled autoescape for ``.txt`` templates,
HTML-escaping every interpolated variable in every LLM prompt on the wire
(``'`` -> ``'``, ``-->`` -> ``-->``). Prompts must render content
verbatim; only markup templates (``.html``/``... | 45 | 1,608 |
cognee | cognee/tests/unit/infrastructure/llm/test_transcribe_image.py | .py | """transcribe_image builds the correct multimodal request (prompt, image, token cap).
Only litellm.acompletion (the network boundary) is mocked, so the adapter's real request
construction — base64 encoding, MIME detection, message assembly, prompt/cap wiring — is exercised.
"""
from pathlib import Path
from types imp... | 68 | 2,253 |
cognee | cognee/tests/unit/infrastructure/llm/test_llm_config.py | .py | import pytest
from cognee.infrastructure.llm.config import LLMConfig
def test_strip_quotes_from_strings():
"""
Test if the LLMConfig.strip_quotes_from_strings model validator behaves as expected.
"""
config = LLMConfig(
# Strings with surrounding double quotes ("value" → value)
llm_ap... | 269 | 9,732 |
cognee | cognee/tests/unit/infrastructure/llm/test_tokenizer_resolver.py | .py | """Tests for embedding model to tokenizer resolution (issue #3646).
Resolution must pick the tokenizer that matches the configured embedding model
and warn (advisory, never raising) when it has to fall back. These tests patch
the three tokenizer classes in the resolver with sentinels so they assert the
selection logic... | 187 | 7,277 |
cognee | cognee/tests/unit/infrastructure/llm/test_mcp_sampling_adapter.py | .py | """Tests for the MCP-sampling LLM backend (issue #3644).
The adapter delegates completions to a host MCP session via
``sampling/createMessage``. Core behaviour is pinned with a mock session (no real
MCP host, no LLM_API_KEY): the mock is injected by patching
``get_sampling_session`` where the adapter calls it, so thes... | 335 | 12,599 |
cognee | cognee/tests/unit/infrastructure/llm/test_llm_payment_required.py | .py | """
Tests that LLMPaymentRequiredError is raised and not retried when an LLM provider
returns HTTP 402 Payment Required.
"""
import pytest
from pydantic import BaseModel
from cognee.infrastructure.llm.exceptions import LLMPaymentRequiredError
from cognee.infrastructure.llm.structured_output_framework.litellm_instruct... | 217 | 6,839 |
cognee | cognee/tests/unit/infrastructure/llm/test_llm_global_cache.py | .py | """Tests for the LLM "global cache" — the per-context ``llm_config`` ContextVar
override that feeds the LRU-cached LLM client.
The feature (see ``feat: add global context for LLM and embedding settings``)
lets a caller pin an ``LLMConfig`` onto the current async context via
``set_database_global_context_variables(...,... | 76 | 3,048 |
cognee | cognee/tests/unit/infrastructure/loaders/test_code_loader.py | .py | """Code files are recognized through the loader system.
The code loader claiming a file at add time IS the recognition that routes it
down the cognify CODE route (ingest_data tags system_metadata.source="code"
when the selected loader is the code loader). These tests lock in the
selection seam: code extensions go to c... | 163 | 6,513 |
cognee | cognee/tests/unit/infrastructure/engine/test_identity_fields.py | .py | import logging
from uuid import UUID, uuid4
from cognee.infrastructure.engine.models.DataPoint import DataPoint
class PersonWithIdentity(DataPoint):
name: str
metadata: dict = {"index_fields": ["name"], "identity_fields": ["name"]}
class DepartmentWithIdentity(DataPoint):
name: str
metadata: dict =... | 232 | 8,001 |
cognee | cognee/tests/unit/infrastructure/files/test_local_path_safety.py | .py | from pathlib import Path
import pytest
from cognee.infrastructure.files.storage.LocalFileStorage import LocalFileStorage
from cognee.infrastructure.files.utils.local_path_safety import (
ALLOWED_LOCAL_FILE_ROOTS_ENV,
resolve_local_path,
)
def test_resolve_local_path_rejects_outside_allowed_roots(monkeypatch... | 56 | 2,063 |
cognee | cognee/tests/unit/infrastructure/files/utils/test_guess_file_type.py | .py | """``guess_file_type`` must detect extensions case-insensitively.
Extensions are case-insensitive by convention, but the extension-based mapping
only matched lowercase. For types with no magic-number signature
(csv/md/json/xml/yaml), an uppercase extension fell through to
``filetype.guess``, returned ``None``, and was... | 44 | 1,671 |
cognee | cognee/tests/unit/infrastructure/files/utils/test_get_file_metadata.py | .py | """Tests for document-name derivation in ``get_file_metadata``.
The authoritative document name (``FileMetadata["name"]`` -> ``Data.name``) is derived
from the opened file's ``.name``, which the ingestion pipeline sets to a percent-encoded
``file://`` URI (LocalFileStorage wraps files in a FileBufferedReader named
``P... | 84 | 3,608 |
cognee | cognee/tests/unit/infrastructure/databases/test_index_graph_edges.py | .py | import pytest
from unittest.mock import AsyncMock, patch, MagicMock
from cognee.tasks.storage.index_graph_edges import create_edge_type_datapoints, index_graph_edges
@pytest.mark.asyncio
async def test_index_graph_edges_success():
"""Test that index_graph_edges retrieves edges and delegates to index_data_points."... | 115 | 3,952 |
cognee | cognee/tests/unit/infrastructure/databases/test_closing_lru_cache.py | .py | """Tests for ClosingLRUCache and the @closing_lru_cache decorator."""
import gc
from cognee.infrastructure.databases.utils.closing_lru_cache import (
ClosingLRUCache,
_start_close,
closing_lru_cache,
)
class _Closeable:
"""Stub with a sync close() that records calls."""
def __init__(self, name=... | 1,618 | 55,018 |
cognee | cognee/tests/unit/infrastructure/databases/test_worker_import_hygiene.py | .py | """Guardrail: the DB worker subprocesses must NOT import cognee.
This regressed silently in the past (old SubprocessGraphDBWrapper /
SubprocessVectorDBWrapper wrapped cognee adapter classes in the child,
dragging the entire ~200 MB cognee import graph into every child).
The new design puts worker code under the top-l... | 87 | 2,768 |
cognee | cognee/tests/unit/infrastructure/databases/test_subprocess_session_failures.py | .py | """Failure-path tests for the subprocess harness.
Covers the scenarios that used to silently hang or leak:
- Worker killed mid-request
- Init timeout
- Per-call timeout on a hung worker
- Non-picklable return value from the worker
- Table-handle release on ``RemoteLanceDBTable``
- Closed-adapter reuse is a hard error ... | 890 | 33,282 |
cognee | cognee/tests/unit/infrastructure/databases/test_rate_limiter.py | .py | """Tests for the LLM rate limiter."""
import pytest
from unittest.mock import patch
from cognee.infrastructure.llm.structured_output_framework.litellm_instructor.llm.rate_limiter import (
llm_rate_limiter,
rate_limit_async,
rate_limit_sync,
)
LLM_RATE_LIMITER = "cognee.infrastructure.llm.structured_output... | 173 | 6,098 |
cognee | cognee/tests/unit/infrastructure/databases/test_unified_store_engine.py | .py | """Unit tests for the UnifiedStoreEngine and EngineCapability."""
import pytest
from cognee.infrastructure.databases.unified.capabilities import EngineCapability
from cognee.infrastructure.databases.unified.unified_store_engine import UnifiedStoreEngine
# ------------------------------------------------------------... | 166 | 5,622 |
cognee | cognee/tests/unit/infrastructure/databases/test_kuzu_worker_load_extension.py | .py | """Unit tests for the Kuzu worker's LOAD EXTENSION retry-with-install path.
The warm-up ``INSTALL JSON`` on a throwaway database is best-effort and can
fail silently (e.g. a transient network error downloading the extension on a
fresh CI runner). ``_load_extension`` must then install on the live
connection and retry, ... | 76 | 2,410 |
cognee | cognee/tests/unit/infrastructure/databases/test_engine_cache_ops.py | .py | """Tests for EngineCacheOps — the shared cache-management facade.
Each engine module exposes one public instance of this class
(graph_engine_cache / vector_engine_cache); these tests pin the routing contract against a fake
decorated factory.
"""
import pytest
from unittest.mock import AsyncMock, MagicMock
from cogne... | 93 | 3,299 |
cognee | cognee/tests/unit/infrastructure/databases/test_has_edges_error_propagation.py | .py | """``has_edges`` must not turn a store failure into a wrong answer.
The Ladybug adapter's batch existence check used to ``except Exception: return
[]``. Callers (the cognify dedup in ``retrieve_existing_edges``) read ``[]`` as
"none of these edges exist" and go on to write them, so when the underlying
store is unavail... | 47 | 1,853 |
cognee | cognee/tests/unit/infrastructure/databases/test_neptune_relationship_quoting.py | .py | """Unit tests for relationship-type quoting and batch fallback in ``NeptuneGraphDB``.
openCypher cannot parameterize a created relationship type, so the type is interpolated
into the query string. It must be backtick-quoted (and internal backticks doubled) so that
labels produced by LLM extraction -- which routinely c... | 77 | 2,712 |
cognee | cognee/tests/unit/infrastructure/databases/test_postgres_hybrid_batching.py | .py | """Regression tests: PostgresHybridAdapter must respect embedding batch size.
The pghybrid adapter delegates embeddings to its underlying vector adapter.
Some embedding providers (e.g. gemini-embedding-001, batch limit 100) reject
calls with too many inputs in a single request. Both add_nodes_with_vectors
and add_edge... | 206 | 8,005 |
cognee | cognee/tests/unit/infrastructure/databases/test_neptune_analytics_hybrid.py | .py | """Unit tests for NeptuneAnalyticsAdapter hybrid-write methods and search().
- add_nodes_with_vectors / add_edges_with_vectors
- search() include_payload handling and node_name filtering
These tests verify the hybrid-write methods and search behaviour. They are skipped
automatically when the Neptune optional dependen... | 360 | 12,326 |
cognee | cognee/tests/unit/infrastructure/databases/test_subprocess_session_concurrent.py | .py | """Concurrent-RPC tests for ``SubprocessSession``.
Exercise the request-id + reader-thread design: many in-flight calls,
out-of-order completion, crash-with-N-pending, sync/async interleaving,
caller cancellation, and per-call timeout cleanup.
Uses a small async-capable worker so the worker-side concurrent dispatch
(... | 476 | 18,096 |
cognee | cognee/tests/unit/infrastructure/databases/test_index_data_points.py | .py | import asyncio
from types import SimpleNamespace
import pytest
from unittest.mock import AsyncMock, patch, MagicMock
from cognee.tasks.storage.index_data_points import index_data_points
from cognee.infrastructure.engine import DataPoint
class TestDataPoint(DataPoint):
name: str
metadata: dict = {"index_field... | 87 | 2,789 |
cognee | cognee/tests/unit/infrastructure/databases/test_index_schema_reference_fields.py | .py | """Regression tests: every vector adapter's IndexSchema must carry the
reference scalars used by the search "Evidence" feature.
These are pure schema/serialization checks (no DB connection) guarding against
an adapter silently dropping ``document_id`` / ``document_name`` / ``chunk_index``
from its payload — which woul... | 75 | 3,047 |
cognee | cognee/tests/unit/infrastructure/databases/test_kuzu_worker_open_retry.py | .py | """Tests for the worker-side lock-retry on opening a Ladybug database
(``cognee_db_workers.kuzu_worker._retry_open_locked``).
These don't import ``ladybug`` — the worker imports it lazily and the retry
helper is driven with a fake stand-in.
"""
from __future__ import annotations
import pytest
import cognee_db_worke... | 84 | 3,231 |
cognee | cognee/tests/unit/infrastructure/databases/test_get_unified_engine.py | .py | """Unit tests for get_unified_engine factory."""
import pytest
from cognee.infrastructure.databases.unified.capabilities import EngineCapability
from cognee.infrastructure.databases.unified.get_unified_engine import (
_is_hybrid_provider,
HYBRID_PROVIDERS,
)
class TestIsHybridProvider:
# NOTE: This test... | 60 | 2,372 |
cognee | cognee/tests/unit/infrastructure/databases/provenance/test_markers.py | .py | """Unit tests for graph-provenance marker detection (COG-5522).
Cover the two behaviors that keep destructive routing safe:
- both marker fields (delete_mode + provenance_version) are required;
- a missing-provenance backend reads as "not graph-provenance", but any *other*
metadata error propagates so destructive op... | 119 | 3,939 |
cognee | cognee/tests/unit/infrastructure/databases/provenance/fakes.py | .py | from dataclasses import dataclass, field
from cognee.infrastructure.databases.unified import GraphVectorStoreInterface
@dataclass
class FakeGraphVectorStore(GraphVectorStoreInterface):
"""Test-only implementation of the unified graph/vector provenance contract."""
deleted_source_refs: list[str] = field(defa... | 22 | 871 |
cognee | cognee/tests/unit/infrastructure/databases/provenance/test_source_ref_state.py | .py | """Fast, DB-free unit tests for the pure source-ref state transitions (COG-5522).
These cover the Part 0 contract invariants directly, without spinning up a graph
backend — so a regression in the derive/merge logic is caught instantly.
"""
from uuid import uuid4
from cognee.infrastructure.databases.provenance.source... | 114 | 4,826 |
cognee | cognee/tests/unit/infrastructure/databases/provenance/test_write_context.py | .py | from types import SimpleNamespace
from uuid import uuid4
import pytest
from cognee.infrastructure.databases.provenance import (
data_item_id,
graph_provenance_write_kwargs,
make_source_ref_key,
source_ref_from_context,
)
def test_data_item_id_resolves_data_dot_id_and_dataitem_dot_data_id():
# Re... | 112 | 3,634 |
cognee | cognee/tests/unit/infrastructure/databases/provenance/test_unified_graph_provenance_delete.py | .py | """Unit tests for the Part 2 graph-provenance delete/rollback spine.
These exercise ``UnifiedStoreEngine.delete_by_source_ref`` /
``delete_by_dataset_id`` / ``rollback_by_pipeline_run_id`` and the planner
(`execute_source_ref_removal`) against an in-memory fake graph engine that
implements Lazar's Part 0 provenance co... | 642 | 24,698 |
cognee | cognee/tests/unit/infrastructure/databases/provenance/test_provenance_contract.py | .py | from uuid import UUID, uuid4
import pytest
from cognee.infrastructure.databases.exceptions import UnsupportedProvenanceCapability
from cognee.infrastructure.databases.graph.graph_db_interface import GraphDBInterface
from cognee.infrastructure.databases.provenance import (
GRAPH_DELETE_MODE_GRAPH_PROVENANCE,
G... | 170 | 6,348 |
cognee | cognee/tests/unit/infrastructure/databases/vector/test_belongs_to_set_merge.py | .py | """Upserting the same DataPoint with different `belongs_to_set` values must
accumulate the set names, not overwrite them. This guards against losing
dataset tags when the same content is cognified into multiple datasets.
"""
from __future__ import annotations
from uuid import uuid4
import pytest
from cognee.infrast... | 223 | 8,373 |
cognee | cognee/tests/unit/infrastructure/databases/vector/test_lancedb_dataset_database_handler.py | .py | from importlib import import_module
from types import SimpleNamespace
from uuid import uuid4
import pytest
import cognee.infrastructure.databases.dataset_database_handler # noqa: F401
handler_module = import_module(
"cognee.infrastructure.databases.vector.lancedb.LanceDBDatasetDatabaseHandler"
)
@pytest.mark... | 40 | 1,289 |
cognee | cognee/tests/unit/infrastructure/databases/vector/test_embedding_config.py | .py | """Tests for embedding-dimension auto-derivation in EmbeddingConfig."""
from unittest.mock import patch
from cognee.infrastructure.databases.vector.embeddings.config import (
EmbeddingConfig,
_resolve_embedding_dimensions,
)
def test_resolve_openai_text_embedding_3_large():
# Default cognee config — mus... | 94 | 3,422 |
cognee | cognee/tests/unit/infrastructure/databases/vector/test_lancedb_lifecycle.py | .py | """White-box tests for LanceDBAdapter lifecycle synchronization.
Pin the invariant that ``get_connection()`` and ``close()`` cannot race
into a state where a coroutine returns a connection from an adapter that
has already been closed — exactly the bug CodeRabbit flagged in the
"Serialize get_connection and close" comm... | 258 | 8,699 |
cognee | cognee/tests/unit/infrastructure/databases/vector/test_lancedb_provenance_capabilities.py | .py | """Backend capability tests for graph-provenance vector cleanup on the default
vector backend (LanceDB) — COG-5522 Part 1.
Graph-provenance delete computes vector ids from graph snapshots and hands them to
``delete_data_points``. Those ids may be UUIDs or graph-computed deterministic
strings, and the delete must be id... | 135 | 4,267 |
cognee | cognee/tests/unit/infrastructure/databases/vector/test_vector_distance_semantics.py | .py | from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import AsyncMock
from uuid import uuid4
import pytest
try:
from cognee.infrastructure.databases.vector.lancedb.LanceDBAdapter import LanceDBAdapter
HAS_LANCEDB = True
except ModuleNotFoundError:
HAS_LANCEDB = False
... | 189 | 5,224 |
cognee | cognee/tests/unit/infrastructure/databases/vector/test_vector_db_config.py | .py | """Test for vector database configuration validation."""
import pytest
from cognee.api.v1.config.config import config
from cognee.api.v1.exceptions.exceptions import InvalidConfigAttributeError
def test_set_vector_db_config_invalid_attribute_raises():
"""Ensure invalid vector DB config attributes raise an error... | 13 | 452 |
cognee | cognee/tests/unit/infrastructure/databases/vector/test_lancedb_delete_data_points.py | .py | from __future__ import annotations
from uuid import uuid4
import pytest
from pydantic import BaseModel
try:
from cognee.infrastructure.databases.vector.lancedb.LanceDBAdapter import LanceDBAdapter
HAS_LANCEDB = True
except ModuleNotFoundError:
HAS_LANCEDB = False
class _FakeEmbeddingEngine:
def ge... | 107 | 3,303 |
cognee | cognee/tests/unit/infrastructure/databases/vector/test_turso_adapter.py | .py | """Behavioral tests for ``TursoVectorAdapter`` against a real embedded libSQL DB.
These run without an LLM/embedding provider: a deterministic fake embedding
engine maps keywords to vector axes so cosine ordering and NodeSet filtering
are exercised on real ``vector_distance_cos`` / JSON1 SQL, not mocks.
"""
from __fu... | 237 | 8,466 |
cognee | cognee/tests/unit/infrastructure/databases/vector/test_lancedb_schema_migration.py | .py | """Tests for LanceDB schema migration when the payload schema evolves."""
from __future__ import annotations
import pyarrow as pa
import pytest
from uuid import uuid4
from cognee.infrastructure.engine import DataPoint
try:
from cognee.infrastructure.databases.vector.lancedb.LanceDBAdapter import (
LanceD... | 350 | 12,187 |
cognee | cognee/tests/unit/infrastructure/databases/vector/test_lancedb_raw_vectors.py | .py | from __future__ import annotations
from uuid import uuid4
import pytest
from pydantic import BaseModel
try:
from cognee.infrastructure.databases.vector.lancedb.LanceDBAdapter import LanceDBAdapter
HAS_LANCEDB = True
except ModuleNotFoundError:
HAS_LANCEDB = False
class _FakeEmbeddingEngine:
def ge... | 80 | 2,074 |
cognee | cognee/tests/unit/infrastructure/databases/relational/test_SqlAlchemyAdapter.py | .py | import asyncio
from unittest.mock import patch, MagicMock
import pytest
from sqlalchemy import text, NullPool
from sqlalchemy.ext.asyncio import AsyncSession
from cognee.infrastructure.databases.relational.sqlalchemy.SqlAlchemyAdapter import (
SQLAlchemyAdapter,
)
def _make_sqlite_adapter(tmp_path) -> SQLAlchem... | 342 | 14,547 |
cognee | cognee/tests/unit/infrastructure/databases/relational/test_RelationalConfig.py | .py | import os
import pytest
from unittest.mock import patch
from pydantic import ValidationError
from cognee.infrastructure.databases.relational.config import RelationalConfig
class TestRelationalConfig:
"""Test suite for RelationalConfig DATABASE_CONNECT_ARGS parsing."""
def test_database_connect_args_valid_jso... | 72 | 3,271 |
cognee | cognee/tests/unit/infrastructure/databases/relational/test_create_relational_engine.py | .py | import sys
import types
from unittest.mock import patch, MagicMock, call
import pytest
from cognee.infrastructure.databases.relational.create_relational_engine import (
create_relational_engine,
)
POSTGRES_PARAMS = {
"db_path": "/tmp",
"db_name": "test_db",
"db_host": "localhost",
"db_port": "54... | 117 | 4,470 |
cognee | cognee/tests/unit/infrastructure/databases/relational/test_turso_adapter.py | .py | """Unit tests for TursoAdapter — the Turso (libSQL) relational backend.
Turso is driven through aiosqlite (a libSQL file is a SQLite file), so the
adapter is a drop-in for the SQLite backend. These tests exercise the local
drop-in against a real temporary libSQL/SQLite file, and the remote
embedded-replica wiring (see... | 157 | 5,736 |
cognee | cognee/tests/unit/infrastructure/databases/cache/test_kv_interface.py | .py | """Regression tests for the formalized KV methods on CacheDBInterface.
Covers:
- FsCacheAdapter get_value/set_value/delete_value round-trip.
- RedisAdapter KV methods producing byte-identical keys/values to the legacy
``adapter.async_redis`` duck-typed path.
"""
import tempfile
import pytest
from unittest.mock imp... | 169 | 6,164 |
cognee | cognee/tests/unit/infrastructure/databases/cache/test_get_cache_engine.py | .py | """Tests for the cache engine factory (create_cache_engine backend dispatch)."""
import importlib
import types
from unittest.mock import MagicMock, patch
import pytest
from cognee.infrastructure.databases.exceptions import CacheConnectionError
# The cache package __init__ re-exports the get_cache_engine function, s... | 175 | 6,470 |
cognee | cognee/tests/unit/infrastructure/databases/cache/test_redis_adapter_crud.py | .py | """Unit tests for RedisAdapter CRUD operations."""
from datetime import datetime
from uuid import uuid4
import pytest
from unittest.mock import MagicMock, patch
from cognee.infrastructure.databases.exceptions import (
CacheConnectionError,
SessionQAEntryValidationError,
)
from cognee.tasks.memify.feedback_wei... | 631 | 22,644 |
cognee | cognee/tests/unit/infrastructure/databases/cache/test_sql_cache_pool_args.py | .py | """Regression tests: shared POOL_ARGS values reach the SQL cache engine intact.
POOL_ARGS is one env var consumed by both the relational adapter and the SQL
cache adapter. The relational adapter accepts poolclass="nullpool" and
normalizes the string to the NullPool class; the cache adapter previously
splatted the raw ... | 33 | 1,419 |
cognee | cognee/tests/unit/infrastructure/databases/cache/test_fs_adapter_crud.py | .py | """Unit tests for FsCacheAdapter CRUD operations."""
from datetime import datetime
from uuid import uuid4
import tempfile
from contextlib import contextmanager
import pytest
from unittest.mock import patch
from cognee.infrastructure.databases.exceptions import (
CacheConnectionError,
SessionQAEntryValidationE... | 417 | 14,533 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.