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/infrastructure/databases/cache/test_sql_adapter_crud.py
.py
"""Unit tests for SqlCacheAdapter CRUD operations (run on sqlite+aiosqlite, no server).""" import uuid from datetime import datetime, timedelta, timezone from uuid import uuid4 import pytest import pytest_asyncio from sqlalchemy import select, text, update from cognee.infrastructure.databases.cache.sql.SqlCacheAdapt...
960
39,182
cognee
cognee/tests/unit/infrastructure/databases/cache/test_cache_config.py
.py
"""Tests for cache configuration.""" import pytest from cognee.infrastructure.databases.cache.config import CacheConfig, get_cache_config def test_cache_config_defaults(monkeypatch): """Test that CacheConfig has the correct default values.""" for env_var in ( "CACHE_BACKEND", "CACHE_DB_URL", ...
189
6,110
cognee
cognee/tests/unit/infrastructure/databases/cache/test_qa_entry_time_timezone_aware.py
.py
"""Regression tests: session-cache QA entries use a timezone-aware UTC timestamp. The cache adapters previously stamped ``SessionQAEntry.time`` with the deprecated, timezone-*naive* ``datetime.utcnow().isoformat()``. They now use ``datetime.now(timezone.utc).isoformat()``, which is timezone-aware and carries an explic...
29
1,245
cognee
cognee/tests/unit/infrastructure/databases/graph/test_neo4j_community_dataset_database_handler.py
.py
from types import SimpleNamespace from uuid import UUID import pytest from cognee.context_global_variables import multi_user_support_possible from cognee.infrastructure.databases.dataset_database_handler.supported_dataset_database_handlers import ( supported_dataset_database_handlers, ) from cognee.infrastructure...
492
17,927
cognee
cognee/tests/unit/infrastructure/databases/graph/test_kuzu_subprocess_proxy.py
.py
"""White-box tests for the Kuzu subprocess proxies. Pin lifecycle invariants the harness relies on but which would otherwise only be visible at runtime as silent state corruption β€” specifically that ``close()`` deregisters every replay step the proxy registered so a post-close worker respawn can't resurrect a handle t...
216
8,046
cognee
cognee/tests/unit/infrastructure/databases/graph/test_kuzu_compat.py
.py
"""Tests for legacy Kuzu compatibility shims.""" def test_kuzu_import_shim_points_to_ladybug(): from cognee.infrastructure.databases.graph.kuzu.kuzu_migrate import kuzu_migration import kuzu import kuzu.database import ladybug import ladybug.database assert kuzu.__version__ == ladybug.__versi...
15
478
cognee
cognee/tests/unit/infrastructure/databases/graph/test_postgres_adapter.py
.py
from contextlib import asynccontextmanager import importlib.util import sys import types import pytest _created_asyncpg_stub = False if importlib.util.find_spec("asyncpg") is None: asyncpg_stub = types.ModuleType("asyncpg") class DeadlockDetectedError(Exception): pass asyncpg_stub.DeadlockDetect...
58
1,448
cognee
cognee/tests/unit/infrastructure/databases/graph/test_neo4j_has_node.py
.py
from unittest.mock import AsyncMock import pytest from cognee.infrastructure.databases.graph.neo4j_driver.adapter import Neo4jAdapter @pytest.mark.asyncio async def test_has_node_awaits_query_and_returns_true(): """Regression test: has_node must await the async query(). The bug called ``self.query(...)`` w...
29
934
cognee
cognee/tests/unit/infrastructure/databases/graph/test_triplets_batch_pagination.py
.py
"""`get_triplets_batch` pages the whole graph, so its result order has to be stable. `get_triplet_datapoints` walks every triplet with a `while True` loop that raises `offset` by the batch size and stops on the first empty batch. That is only correct if two calls with different offsets read from the same ordering. Pos...
59
2,239
cognee
cognee/tests/unit/infrastructure/databases/graph/test_neptune_edge_label_default.py
.py
"""Regression test: Neptune get_predecessors/get_successors default edge label. Both methods accept an optional ``edge_label`` and guard it with ``f" :{edge_label}" if edge_label is not None else ""``. The default used to be the empty string ``""`` instead of ``None``. Since ``"" is not None`` is True, calling either ...
58
2,137
cognee
cognee/tests/unit/infrastructure/databases/graph/test_neptune_is_empty.py
.py
from types import SimpleNamespace from unittest.mock import AsyncMock import pytest from cognee.infrastructure.databases.graph.neptune_driver.adapter import NeptuneGraphDB def test_neptune_adapter_implements_is_empty(): """Regression test: NeptuneGraphDB must implement the abstract is_empty. GraphDBInterfa...
57
1,888
cognee
cognee/tests/unit/infrastructure/databases/graph/test_ladybug_truth_state.py
.py
import json from unittest.mock import AsyncMock import pytest from cognee.infrastructure.databases.graph.ladybug.adapter import LadybugAdapter def test_build_node_truth_state_updates_preserves_properties_and_adds_epoch(): adapter = LadybugAdapter.__new__(LadybugAdapter) updates = adapter._build_node_truth_s...
40
1,415
cognee
cognee/tests/unit/infrastructure/databases/graph/test_ladybug_migrate.py
.py
"""Tests for Ladybug migration helpers.""" import os import struct import subprocess import tempfile import pytest from cognee.infrastructure.databases.graph.ladybug.ladybug_migrate import ( ladybug_version_mapping, run_migration_step, read_ladybug_storage_version, ) def _write_catalog_kz(dir_path: str...
97
3,612
cognee
cognee/tests/unit/infrastructure/databases/graph/neo4j_deadlock_test.py
.py
import pytest import asyncio from unittest.mock import MagicMock, AsyncMock from neo4j.exceptions import Neo4jError, DatabaseUnavailable from cognee.infrastructure.databases.graph.neo4j_driver.deadlock_retry import deadlock_retry @pytest.mark.asyncio async def test_deadlock_retry_errored(): mock_return = asyncio....
98
3,522
cognee
cognee/tests/unit/infrastructure/databases/graph/test_neptune_graph_metrics.py
.py
import sys from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock import pytest # Mock optional AWS dependencies if not installed (the adapter imports # botocore.config at module level and langchain_aws behind a guard) if "langchain_aws" not in sys.modules: sys.modules["langchain_aws"] =...
46
1,786
cognee
cognee/tests/unit/infrastructure/databases/graph/test_neo4j_adapter_close.py
.py
import sys import gc import asyncio from unittest.mock import AsyncMock, MagicMock, patch import pytest # Ensure neo4j and related modules are mocked if they are not installed in the environment try: import neo4j except ModuleNotFoundError: sys.modules["neo4j"] = MagicMock() sys.modules["neo4j.exceptions"]...
97
3,004
cognee
cognee/tests/unit/infrastructure/databases/graph/test_ladybug_subprocess_lock_race.py
.py
"""Regression test for issue #3708: re-creating a subprocess graph engine for a path whose previous worker is still shutting down must NOT fail with "Could not set lock on file (Lock is held by PID ...)". Root cause: the previous worker held the on-disk file lock for its whole lifetime; a new worker opened the same pa...
122
4,472
cognee
cognee/tests/unit/infrastructure/databases/graph/test_ladybug_write_chunking.py
.py
"""Bulk node/edge writes must be chunked so no single statement can run past the subprocess engine's per-call deadline on large graphs (COG: ladybug ingestion of e.g. 30k-fact code graphs previously sent one statement for all rows and could never finish).""" from types import SimpleNamespace from unittest.mock import ...
192
6,695
cognee
cognee/tests/unit/infrastructure/databases/graph/test_neptune_adapter_close.py
.py
import sys import gc import asyncio import importlib.util from unittest.mock import MagicMock, patch import pytest # Mock langchain_aws if not installed if "langchain_aws" not in sys.modules: mock_lc = MagicMock() sys.modules["langchain_aws"] = mock_lc # The adapter imports botocore.config at module level; st...
137
4,406
cognee
cognee/tests/unit/infrastructure/databases/graph/test_neo4j_filtered_graph_data.py
.py
from unittest.mock import AsyncMock import pytest pytest.importorskip("neo4j") from cognee.infrastructure.databases.graph.neo4j_driver.adapter import Neo4jAdapter @pytest.mark.asyncio async def test_filtered_graph_edges_fall_back_to_returned_endpoint_ids(): adapter = Neo4jAdapter( "bolt://unused", ...
39
1,130
cognee
cognee/tests/unit/infrastructure/databases/graph/test_ladybug_temporal.py
.py
from unittest.mock import AsyncMock import pytest from cognee.infrastructure.databases.graph.ladybug.adapter import LadybugAdapter from cognee.tasks.temporal_graph.models import Timestamp @pytest.mark.asyncio async def test_collect_time_ids_returns_list_for_unwind_params(): adapter = LadybugAdapter.__new__(Lady...
39
1,251
cognee
cognee/tests/unit/infrastructure/databases/graph/test_neo4j_dataset_database_handler.py
.py
from types import SimpleNamespace from uuid import UUID import pytest from cognee.context_global_variables import ( multi_user_support_possible, ) from cognee.infrastructure.databases.dataset_database_handler.supported_dataset_database_handlers import ( supported_dataset_database_handlers, ) from cognee.infra...
236
7,908
cognee
cognee/tests/unit/infrastructure/dataset_queue/test_dataset_queue.py
.py
"""Tests for the Dataset Queue system. The Dataset Queue is a semaphore-based concurrency limiter that restricts the number of parallel dataset operations (search, run_pipeline_per_dataset). Configuration via environment variables: - DATASET_QUEUE_ENABLED: Enable/disable the queue (default: False) - DATABASE_MAX_LRU_...
1,050
39,381
cognee
cognee/tests/unit/infrastructure/session/test_feedback_detection.py
.py
from pathlib import Path from unittest.mock import AsyncMock, patch import pytest from cognee.infrastructure.session.feedback_detection import detect_feedback from cognee.infrastructure.session.feedback_models import FeedbackDetectionResult from cognee.infrastructure.session.session_context_models import ( Candid...
311
13,056
cognee
cognee/tests/unit/infrastructure/session/test_session_concurrent_turn.py
.py
from unittest.mock import AsyncMock, MagicMock, patch from uuid import uuid4 import pytest from pydantic import BaseModel from cognee.infrastructure.session.feedback_models import SessionTurnAnalysis from cognee.infrastructure.session.session_concurrent_turn import ( SessionTurnContext, TurnPrompts, analy...
337
11,062
cognee
cognee/tests/unit/infrastructure/session/test_session_embeddings.py
.py
"""Unit tests for session QA vector recall and active-context helpers.""" import importlib from datetime import datetime from types import SimpleNamespace from unittest.mock import AsyncMock from uuid import uuid4 import pytest from cognee.infrastructure.databases.cache.models import SessionQAEntry from cognee.infra...
406
14,207
cognee
cognee/tests/unit/infrastructure/session/test_session_context_models.py
.py
import pytest from pydantic import TypeAdapter, ValidationError from cognee.infrastructure.session.session_context_models import ( AGENT_VALID_SECTIONS, MAX_CONTEXT_CONTENT_CHARS, MIN_CANDIDATE_CONFIDENCE, VALID_PROFILES, AgentCandidateContextUpdate, AgentCandidateContextUpdateVariant, Agen...
258
8,444
cognee
cognee/tests/unit/infrastructure/session/test_session_context_builder.py
.py
"""Unit tests for the deterministic session-context builder, ranker, and candidate applier. These tests use FAKE session managers (plain in-memory objects, no real cache / Redis) so they run anywhere. They verify ranker ordering, budget capping, candidate validation/dedup, and the fail-open contract. """ from datetim...
457
15,396
cognee
cognee/tests/unit/infrastructure/session/test_session_default_session_scoping.py
.py
"""Dataset-scoped default session IDs. When a caller omits session_id and the SessionManager knows its dataset (constructor argument or the dataset context variable), the default resolves to ``default_session_<dataset_id>`` instead of the single global ``"default_session"`` β€” so omitting session_id in two different da...
77
3,331
cognee
cognee/tests/unit/infrastructure/session/test_session_manager.py
.py
import pytest from unittest.mock import AsyncMock, MagicMock, patch from cognee.infrastructure.databases.cache.models import SessionQAEntry from cognee.infrastructure.databases.exceptions import SessionParameterValidationError from cognee.infrastructure.session.feedback_models import ( AgentTraceFeedbackSummary, ...
1,326
57,962
cognee
cognee/tests/unit/infrastructure/session/test_agent_context_extraction.py
.py
"""Unit tests for agent-context extraction (live deterministic pass + LLM batch pass). Uses fake session managers and a fake LLM so the tests run anywhere; verifies that only errored steps produce a live failure_lessons lesson, that the batch pass stores LLM-proposed lessons, and the fail-open contract for both. """ ...
434
14,506
cognee
cognee/tests/unit/infrastructure/locks/test_session_turn_lock.py
.py
import asyncio import pytest from cognee.infrastructure.locks import session_turn_lock @pytest.mark.asyncio async def test_session_turn_lock_serializes_same_user_and_session(): active = 0 peak = 0 async def run_turn(): nonlocal active, peak async with session_turn_lock("u1", "s1"): ...
49
1,211
cognee
cognee/tests/unit/infrastructure/locks/test_dataset_lock.py
.py
"""Tests for the shared per-dataset lock (cognee.infrastructure.locks.dataset_lock). The lock registry is shared between pipeline runs (add/cognify/memify) and delete operations, so a delete on a dataset must wait for an in-flight pipeline run on that dataset (and vice versa), while operations on different datasets pr...
110
3,727
cognee
cognee/tests/unit/eval_framework/answer_generation_test.py
.py
import pytest from cognee.eval_framework.answer_generation.answer_generation_executor import ( AnswerGeneratorExecutor, ) from cognee.eval_framework.benchmark_adapters.dummy_adapter import DummyAdapter from unittest.mock import AsyncMock @pytest.mark.asyncio async def test_answer_generation(): limit = 1 c...
39
1,460
cognee
cognee/tests/unit/eval_framework/metrics_test.py
.py
import pytest from typing import Optional import sys from unittest.mock import patch, MagicMock import unittest import numpy as np from cognee.eval_framework.analysis.metrics_calculator import bootstrap_ci with patch.dict( sys.modules, {"deepeval": MagicMock(), "deepeval.test_case": MagicMock()}, ): from ...
88
2,962
cognee
cognee/tests/unit/eval_framework/test_eval_runner.py
.py
"""Deterministic, keyless tests for the productized eval runner and the optional-addon decoupling (issue #3623). These cover the two chunks that productize the harness: - the eval/DeepEval optional addon (lazy engine imports + actionable errors), and - the one-command runner / CLI surface (path resolution, flag mappin...
366
14,500
cognee
cognee/tests/unit/eval_framework/dashboard_test.py
.py
import unittest import json import os from cognee.eval_framework.analysis.dashboard_generator import ( create_distribution_plots, create_ci_plot, generate_details_html, get_dashboard_html_template, create_dashboard, ) class TestDashboardFunctions(unittest.TestCase): def setUp(self): ...
89
2,994
cognee
cognee/tests/unit/eval_framework/deepeval_adapter_test.py
.py
import pytest from unittest.mock import patch, MagicMock from cognee.eval_framework.eval_config import EvalConfig import sys with patch.dict( sys.modules, { "deepeval": MagicMock(), "deepeval.metrics": MagicMock(), "deepeval.test_case": MagicMock(), "cognee.eval_framework.evalua...
97
2,453
cognee
cognee/tests/unit/eval_framework/corpus_builder_test.py
.py
import pytest from cognee.eval_framework.corpus_builder.corpus_builder_executor import CorpusBuilderExecutor from unittest.mock import AsyncMock, patch from cognee.eval_framework.benchmark_adapters.hotpot_qa_adapter import HotpotQAAdapter from cognee.eval_framework.benchmark_adapters.dummy_adapter import DummyAdapter ...
71
2,874
cognee
cognee/tests/unit/eval_framework/dashboard_escaping_test.py
.py
"""Regression tests: eval dashboards must HTML-escape benchmark text. ``generate_details_html`` interpolates per-item benchmark fields (question, answer, golden_answer, reason) straight into an HTML table. Without escaping, any ``<`` / ``&`` / tag-like content in the model or golden answer corrupts the table layout (a...
58
2,186
cognee
cognee/tests/unit/eval_framework/benchmark_adapters_test.py
.py
import pytest from cognee.eval_framework.benchmark_adapters.hotpot_qa_adapter import HotpotQAAdapter from cognee.eval_framework.benchmark_adapters.logistics_system_adapter import ( LogisticsSystemAdapter, ) from cognee.eval_framework.benchmark_adapters.musique_adapter import MusiqueQAAdapter from cognee.eval_framew...
169
6,794
cognee
cognee/tests/unit/eval_framework/logistics_ontology_test.py
.py
from pathlib import Path from types import SimpleNamespace from unittest.mock import patch import pytest from cognee.eval_framework.benchmark_adapters.logistics_system_utils.entities.package import ( Package, ) from cognee.eval_framework.benchmark_adapters.logistics_system_utils.ontology import ( add_packages...
105
3,352
cognee
cognee/tests/unit/eval_framework/test_get_default_tasks_by_indices.py
.py
import importlib from unittest.mock import AsyncMock, MagicMock, patch import pytest from cognee.modules.pipelines.tasks.task import Task task_getter_module = importlib.import_module( "cognee.eval_framework.corpus_builder.task_getters.get_default_tasks_by_indices" ) @pytest.mark.asyncio @patch.object(task_gett...
56
1,790
cognee
cognee/tests/unit/modules/conftest.py
.py
"""Shared fixtures for pipeline-runner unit tests. The run_tasks generator needs the same mock plumbing everywhere it is driven directly: a relational session that returns the dataset, a no-op database context, and captured run-lifecycle log calls. """ from types import SimpleNamespace from unittest.mock import Async...
60
2,235
cognee
cognee/tests/unit/modules/session_distillation/test_distillation_helpers.py
.py
"""Unit tests for the deterministic parts of session distillation. The gate, the timeline batching, and the document renderer are pure functions, so they are tested directly with fixtures β€” no LLM, cache, or vector engine involved. """ from types import SimpleNamespace from unittest.mock import AsyncMock, patch from ...
394
14,805
cognee
cognee/tests/unit/modules/provenance/test_provenance_entry_model.py
.py
"""Pydantic <-> ORM roundtrip and defaults for ProvenanceEntry.""" from datetime import datetime from cognee.modules.provenance.models import ProvenanceEntry, ProvenanceEntryRow def _full_entry() -> ProvenanceEntry: return ProvenanceEntry( entity_id="entity-1", entity_type="entity", acti...
95
3,489
cognee
cognee/tests/unit/modules/provenance/test_record_provenance_task.py
.py
"""record_provenance task: ledger writes, degradation, and pipeline wiring.""" import os import sys from types import SimpleNamespace from unittest.mock import patch from uuid import uuid4 import pytest from cognee.api.v1.cognify.cognify import get_default_tasks from cognee.infrastructure.databases.provenance import...
296
12,151
cognee
cognee/tests/unit/modules/provenance/test_integrity.py
.py
"""Checksum canonicalization and tamper detection (pure, no DB).""" import pytest from cognee.modules.provenance.integrity import ( _HASHED_FIELDS, canonical_entity_id, compute_checksum, verify_checksum, ) from cognee.modules.provenance.models import ProvenanceEntry _LAST_UPDATED = "2026-08-14T00:00:...
125
4,655
cognee
cognee/tests/unit/modules/provenance/test_verify_chain.py
.py
"""Hash-chain verification: tamper detection, deletion detection, concurrency.""" import asyncio import pytest from cognee.modules.provenance import storage pytestmark = pytest.mark.asyncio async def _seed(manager, count=5): for index in range(1, count + 1): await manager.track_entity(f"e{index}", sou...
71
2,856
cognee
cognee/tests/unit/modules/provenance/test_provenance_manager.py
.py
"""ProvenanceManager behavior over an isolated async SQLite ledger.""" import pytest from cognee.modules.provenance import storage from cognee.modules.provenance.integrity import compute_checksum pytestmark = pytest.mark.asyncio async def _archive_entries(entity_id): return [ entry for entry in...
320
14,377
cognee
cognee/tests/unit/modules/provenance/conftest.py
.py
"""Fixtures for the provenance-ledger unit tests. A private async SQLite database (one file per test, via ``tmp_path``) stands in for the shared relational DB: only the ``provenance_entries`` table is created, ``cognee.modules.provenance.storage.get_async_session`` is patched to hand out sessions bound to it, and both...
58
2,069
cognee
cognee/tests/unit/modules/storage/test_json_encoder.py
.py
import json from datetime import date, datetime, timezone from decimal import Decimal from uuid import UUID import pytest from cognee.modules.storage.utils import JSONEncoder @pytest.mark.parametrize( ("value", "expected"), [ (date(2026, 6, 5), "2026-06-05"), (datetime(2026, 6, 5, 14, 30, tz...
29
835
cognee
cognee/tests/unit/modules/chunking/test_text_chunker_with_overlap.py
.py
"""Unit tests for TextChunkerWithOverlap overlap behavior.""" import sys import pytest from uuid import uuid4 from unittest.mock import patch from cognee.modules.chunking.text_chunker_with_overlap import TextChunkerWithOverlap from cognee.modules.data.processing.document_types import Document from cognee.tasks.chunks...
325
10,969
cognee
cognee/tests/unit/modules/chunking/test_chunk_reference_fields.py
.py
"""Unit tests asserting chunkers populate the reference scalar fields. The References (Evidence) feature relies on every produced ``DocumentChunk`` carrying flat ``document_id`` / ``document_name`` scalars (basename only, never an absolute path). These tests run the real chunkers over an in-memory text generator (no L...
104
3,514
cognee
cognee/tests/unit/modules/chunking/test_text_chunker.py
.py
"""Unit tests for TextChunker and TextChunkerWithOverlap behavioral equivalence.""" import pytest from uuid import uuid4 from cognee.modules.chunking.TextChunker import TextChunker from cognee.modules.chunking.text_chunker_with_overlap import TextChunkerWithOverlap from cognee.modules.data.processing.document_types i...
249
9,557
cognee
cognee/tests/unit/modules/chunking/test_langchain_chunker.py
.py
"""Regression tests for LangchainChunker. LangchainChunker was left targeting the pre-unification chunker API (``max_chunk_tokens``, a 4-arg base ``Chunker.__init__``, and ``word_count``/``token_count`` fields ``DocumentChunk`` does not define), so it could not be instantiated at all β€” neither positionally nor through...
118
3,679
cognee
cognee/tests/unit/modules/recall/test_model_from_json_schema.py
.py
from enum import Enum from typing import Literal, Optional import pytest from pydantic import BaseModel, ValidationError from cognee.exceptions import CogneeValidationError from cognee.modules.recall.methods.model_from_json_schema import model_from_json_schema class Ingredient(BaseModel): name: str grams: f...
149
4,936
cognee
cognee/tests/unit/modules/recall/test_normalize_search_payload.py
.py
from pydantic import BaseModel, Field from cognee.modules.recall.methods.normalize_search_payload import normalize_search_payload from cognee.modules.recall.types.SearchResultItem import SearchResultKind from cognee.modules.search.models.SearchResultPayload import SearchResultPayload from cognee.modules.search.types i...
117
3,959
cognee
cognee/tests/unit/modules/users/test_get_by_token_single_session.py
.py
"""Regression tests for the API-key auth pool-deadlock fix (issue #4197). `UserManager.get_by_token` used to look up the API key in one session and then call `self.get()` β€” which borrows the request-scoped `get_user_db` session β€” *while its own session was still open*. Every concurrent authenticated request therefore ...
93
3,215
cognee
cognee/tests/unit/modules/users/test_get_default_user_db_not_created.py
.py
"""Fresh-install error classification in get_default_user. On a pristine install the SQLite databases directory does not exist yet, so the first session raises OperationalError("unable to open database file") β€” or, if the file exists but the schema does not, "no such table: ...". Both must be classified as DatabaseNot...
101
4,170
cognee
cognee/tests/unit/modules/users/test_conditional_authentication.py
.py
import os import sys import pytest from unittest.mock import AsyncMock, patch from uuid import uuid4 from types import SimpleNamespace import importlib from cognee.modules.users.models import User gau_mod = importlib.import_module("cognee.modules.users.methods.get_authenticated_user") class TestConditionalAuthent...
291
11,346
cognee
cognee/tests/unit/modules/tools/test_write_proposals.py
.py
import sqlite3 from uuid import uuid4 import pytest import cognee.modules.tools.text_to_sql.write_proposals as wp_mod from cognee.modules.tools.config import ToolsConfig from cognee.modules.tools.errors import ( ToolCallsDisabledError, ToolError, ToolWriteNotAllowedError, ) from cognee.modules.tools.text_...
299
10,478
cognee
cognee/tests/unit/modules/tools/test_skill_ingest.py
.py
from __future__ import annotations import asyncio import importlib import os import tempfile import unittest from pathlib import Path from types import SimpleNamespace from unittest.mock import AsyncMock, patch from uuid import uuid4 _SKILL = """\ --- description: Review code changes for correctness and regressions....
616
25,222
cognee
cognee/tests/unit/modules/tools/test_text_to_sql_engine.py
.py
import sqlite3 import pytest import cognee.modules.tools.text_to_sql.engine as engine_mod from cognee.modules.tools.config import ToolsConfig from cognee.modules.tools.errors import ToolCallsDisabledError from cognee.modules.tools.text_to_sql.engine import run_text_to_sql @pytest.fixture def sample_db(tmp_path): ...
168
5,343
cognee
cognee/tests/unit/modules/tools/test_tool_connections.py
.py
import base64 import os from uuid import uuid4 import pytest import cognee.modules.tools.connections as connections_mod from cognee.modules.tools.config import ToolsConfig from cognee.modules.tools.errors import ToolConnectionNotFoundError, ToolError from cognee.modules.tools.connections import ( delete_tool_conn...
161
5,806
cognee
cognee/tests/unit/modules/tools/test_readonly_executor.py
.py
import sqlite3 from datetime import datetime import pytest from sqlalchemy import text from cognee.modules.tools.text_to_sql.engine_factory import ( get_external_sql_engine, introspect_schema, ) from cognee.modules.tools.text_to_sql.executor import execute_readonly @pytest.fixture def sample_db(tmp_path): ...
109
3,551
cognee
cognee/tests/unit/modules/tools/test_write_guard.py
.py
import pytest from cognee.modules.tools.errors import SqlGuardError from cognee.modules.tools.text_to_sql.write_guard import validate_update def test_plain_update_with_where_passes(): sql, table = validate_update("UPDATE orders SET region = 'eu' WHERE id = 42") assert table == "orders" assert sql.startsw...
67
2,198
cognee
cognee/tests/unit/modules/tools/test_tools_config.py
.py
import pytest from cognee.modules.tools.config import ToolsConfig def test_tool_calls_disabled_by_default(): config = ToolsConfig(_env_file=None) assert config.tool_calls_enabled is False def test_default_limits(): config = ToolsConfig(_env_file=None) assert config.text_to_sql_max_rows == 100 a...
56
1,839
cognee
cognee/tests/unit/modules/tools/test_sql_guard.py
.py
import pytest from cognee.modules.tools.errors import SqlGuardError from cognee.modules.tools.text_to_sql.sql_guard import ensure_limit, strip_sql, validate_select class TestStripSql: def test_removes_markdown_fences(self): assert strip_sql("```sql\nSELECT 1\n```") == "SELECT 1" def test_removes_com...
89
3,201
cognee
cognee/tests/unit/modules/memify_tasks/test_cognify_agent_trace_feedback.py
.py
from unittest.mock import AsyncMock, patch import pytest from cognee.exceptions import CogneeSystemError, CogneeValidationError from cognee.tasks.memify.cognify_agent_trace_feedback import cognify_agent_trace_feedback @pytest.mark.asyncio async def test_cognify_agent_trace_feedback_success(): trace_content = "S...
104
3,513
cognee
cognee/tests/unit/modules/memify_tasks/test_extract_feedback_qas.py
.py
import sys from unittest.mock import AsyncMock, MagicMock, patch import pytest from cognee.exceptions import CogneeValidationError from cognee.infrastructure.databases.cache.models import SessionQAEntry from cognee.infrastructure.session.session_manager import SessionManager from cognee.tasks.memify.extract_feedback_...
201
6,320
cognee
cognee/tests/unit/modules/memify_tasks/test_extract_user_sessions.py
.py
import sys import pytest from unittest.mock import AsyncMock, MagicMock, patch from cognee.infrastructure.databases.cache.models import SessionQAEntry from cognee.tasks.memify.extract_user_sessions import extract_user_sessions from cognee.exceptions import CogneeSystemError from cognee.modules.users.models import User...
227
8,035
cognee
cognee/tests/unit/modules/memify_tasks/test_cognify_session.py
.py
import sys import pytest from unittest.mock import AsyncMock, MagicMock, patch from cognee.infrastructure.session.session_persist_watermark import SessionPersistWindow from cognee.tasks.memify.cognify_session import cognify_session from cognee.exceptions import CogneeValidationError, CogneeSystemError # Get the actua...
196
7,368
cognee
cognee/tests/unit/modules/memify_tasks/test_extract_agent_trace_feedbacks.py
.py
import sys from unittest.mock import AsyncMock, MagicMock, patch import pytest from cognee.exceptions import CogneeSystemError from cognee.infrastructure.databases.cache.models import SessionAgentTraceEntry from cognee.modules.users.models import User from cognee.tasks.memify.extract_agent_trace_feedbacks import extr...
403
13,729
cognee
cognee/tests/unit/modules/memify_tasks/test_get_triplet_datapoints.py
.py
import sys import pytest from unittest.mock import AsyncMock, patch from cognee.tasks.memify.get_triplet_datapoints import get_triplet_datapoints from cognee.modules.engine.models import Triplet from cognee.modules.engine.models.Entity import Entity from cognee.infrastructure.engine import DataPoint from cognee.module...
215
7,758
cognee
cognee/tests/unit/modules/memify_tasks/test_apply_feedback_weights.py
.py
import sys from unittest.mock import AsyncMock, MagicMock, patch import pytest from cognee.tasks.memify.apply_feedback_weights import ( apply_feedback_weights, normalize_feedback_score, stream_update_weight, ) from cognee.tasks.memify.feedback_weights_constants import ( MEMIFY_METADATA_FEEDBACK_WEIGHT...
272
9,874
cognee
cognee/tests/unit/modules/visualization/test_orchestrator_assembly.py
.py
"""Sanity tests for the visualization orchestrator after the Phase 1c split. The orchestrator must: - Read ``template.html`` from disk. - Inject every view's JS chunk into the right token slot. - Substitute every data token (``__NODES_DATA__`` etc.) with valid JSON. - Leave NO ``__TOKEN__`` placeholders in th...
152
5,428
cognee
cognee/tests/unit/modules/visualization/test_memory_map_payload.py
.py
"""Unit tests for the Memory-tab payload builder (``_build_memory_map``). Pure tests over ``preprocess()`` with synthetic graphs β€” no DB, no LLM. They pin the STEP 1 contract the STEP 2 JS renderer builds on: - ``t_created`` is preserved from ``created_at`` before the pop. - Chunk cells order by ``chunk_index``; ...
376
15,050
cognee
cognee/tests/unit/modules/visualization/test_preprocessor.py
.py
"""Unit tests for the visualization preprocessor. The preprocessor is the single place where Story-view fields are derived from raw graph adapter output. These tests pin the contract: - Every known node type maps to a non-default stage. - ``visual_rank`` prefers stamped ``topological_rank`` (Phase 1a) and fal...
556
21,776
cognee
cognee/tests/unit/modules/visualization/visualization_test.py
.py
import pytest from cognee.modules.visualization.cognee_network_visualization import ( cognee_network_visualization, ) @pytest.mark.asyncio async def test_create_cognee_style_network_with_logo(tmp_path): nodes_data = [ ( 1, { "type": "Entity", "na...
253
9,794
cognee
cognee/tests/unit/modules/visualization/test_embedding_join.py
.py
"""Unit tests for the embedding join β€” the seam between graph nodes and vectors. Fully offline and deterministic: a fake vector engine stands in for the real adapter (the single mocking seam), so there are no LLM calls and no live store. Covers collection resolution, batched retrieve, the re-embed fallback for adapter...
280
10,902
cognee
cognee/tests/unit/modules/visualization/test_semantic_clusters.py
.py
"""Unit tests for clustering + NN precompute β€” deterministic, offline, no LLM. Covers seeded k-means determinism and k bounds, cosine nearest-neighbor correctness, the deterministic top-entity label path, and the optional (mocked) summary seam. """ from unittest.mock import Mock import numpy as np from cognee.modul...
188
7,772
cognee
cognee/tests/unit/modules/visualization/test_semantic_map_assembly.py
.py
"""Assembly tests for the semantic tab β€” offline, embedding seam mocked. Pins the wiring contract: the semantic tab, layout, and view JS are injected; the position/cluster data tokens are substituted (real JSON when embeddings exist, ``null`` when they don't); and no ``__TOKEN__`` placeholder ever leaks. The embedding...
116
4,761
cognee
cognee/tests/unit/modules/visualization/test_subgraph_data.py
.py
"""Unit tests for bounded-subgraph seed resolution and truncation.""" from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock, patch import pytest from cognee.modules.visualization.subgraph_data import ( DEFAULT_NEIGHBORHOOD_DEPTH, fetch_visualization_graph_data, resolve_seed_nod...
262
9,080
cognee
cognee/tests/unit/modules/visualization/test_visualization_payload.py
.py
"""build_visualization_payload / build_semantic_payload: the JSON API surface. The one thing worth pinning here that test_preprocessor.py does not: the whole payload has to survive a real ``json.dumps``, including ``provenance_index`` β€” the field CLO-401 flagged as unverified because it is the one dataclass field that...
105
4,009
cognee
cognee/tests/unit/modules/visualization/test_semantic_layout.py
.py
"""Unit tests for the semantic layout β€” deterministic offline projection. No LLM, no vector store: embeddings are handed in directly. Covers PCA determinism + sign convention, [-1,1] normalization, the no-vector neighbor fallback, isolated-node ring placement, de-overlap separation, and the UMAP ImportError fallback (...
133
5,162
cognee
cognee/tests/unit/modules/visualization/test_session_events.py
.py
"""Unit tests for the session operation-event mapper (pure, no cache/DB).""" from cognee.infrastructure.databases.cache.models import SessionQAEntry from cognee.modules.visualization.session_events import map_session_entries_to_events def _entry(**overrides): base = { "time": "2026-06-11T10:00:00", ...
67
2,585
cognee
cognee/tests/unit/modules/search/test_get_search_type_retriever_instance.py
.py
import importlib from unittest.mock import AsyncMock, MagicMock, patch import pytest from cognee.modules.search.exceptions import UnsupportedSearchTypeError from cognee.modules.search.types import SearchType from cognee.modules.retrieval.hybrid_retriever import HybridRetriever from cognee.modules.retrieval.graph_comp...
425
16,148
cognee
cognee/tests/unit/modules/search/test_search.py
.py
import types from uuid import uuid4, uuid5, NAMESPACE_OID import pytest from cognee.modules.search.models.SearchResultPayload import SearchResultPayload 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=tenan...
314
9,925
cognee
cognee/tests/unit/modules/search/test_top_k_validation.py
.py
import pytest from cognee.modules.retrieval.exceptions.exceptions import QueryValidationError from cognee.modules.search.types import SearchType # ── invalid top_k values are rejected at the factory level ──────────────────── @pytest.mark.asyncio async def test_top_k_zero_raises_query_validation_error(): impor...
76
3,192
cognee
cognee/tests/unit/modules/search/test_search_history_dataset_id.py
.py
"""Round-trip coverage for ``dataset_id`` on recall/search history. Exercises the real log -> read path against a temporary SQLite database: ``log_query``/``log_result`` write the column and ``get_history`` projects it back on both sides of its UNION. """ import importlib from uuid import uuid4 import pytest import ...
124
4,315
cognee
cognee/tests/unit/modules/search/test_search_prepare_search_result_contract.py
.py
## The Objective of these tests is to cover the search - prepare search results behavior (later to be removed) import types from uuid import uuid4, uuid5, UUID, NAMESPACE_OID import pytest from pydantic import BaseModel from cognee.modules.search.models.SearchResultPayload import SearchResultPayload from cognee.modu...
194
6,079
cognee
cognee/tests/unit/modules/search/test_get_retriever_output.py
.py
import importlib from unittest.mock import AsyncMock, patch import pytest from cognee.infrastructure.session.session_manager import SessionTurnPreparation from cognee.modules.retrieval.session_aware_completion import count_retrieved_objects from cognee.modules.search.methods.get_retriever_output import get_retriever_...
219
7,391
cognee
cognee/tests/unit/modules/observability/test_memory_semconv.py
.py
"""Tests for memory-semconv v0.1.0 OTel instrumentation. Validates that the core memory operations emit correct spans (with memory.* attributes), metrics, and that the log bridge attaches without error. """ import time import pytest # --------------------------------------------------------------------------- # Fix...
355
12,486
cognee
cognee/tests/unit/modules/observability/test_langfuse_otel.py
.py
"""Tests for the Langfuse OTLP integration. Covers the three pieces of the feature, all offline (no live Langfuse): 1. ergonomic ``LANGFUSE_*`` config -> OTLP endpoint + Basic-auth header, 2. the exporter wiring (Langfuse forces the HTTP exporter), 3. the attribute mapping, asserted on *exported* span payloads v...
380
13,544
cognee
cognee/tests/unit/modules/observability/test_get_observe.py
.py
import pytest from unittest.mock import patch from cognee.modules.observability.get_observe import get_observe from cognee.modules.observability.observers import Observer from cognee.modules.observability.exceptions import UnsupportedObserverError def test_get_observe_raises_for_unsupported_observer(): """Unsupp...
16
692
cognee
cognee/tests/unit/modules/observability/test_tracing_kill_switch_and_batching.py
.py
"""COGNEE_TRACING_ENABLED=false must be authoritative, and OTLP log export must batch on a background thread. Two production defects pinned here: Langfuse keys used to force ``cognee_tracing_enabled = True`` over an explicit false, leaving no working off-switch; and the OTLP log exporters were attached through ``Simpl...
116
4,160
cognee
cognee/tests/unit/modules/observability/test_tracing.py
.py
"""Unit tests for the cognee tracing / observability module.""" import os import pytest from cognee.modules.observability.tracing import ( CogneeSpanExporter, CogneeTrace, redact_secrets, setup_tracing, shutdown_tracing, get_tracer, get_exporter, ) from cognee.modules.observability.trace_c...
375
11,490
cognee
cognee/tests/unit/modules/cognify/test_cognify_single_logical_run.py
.py
"""Every dataset gets exactly ONE cognify_pipeline run, with per-item routing. cognify() makes a single run_pipeline call whose ``tasks`` is a resolver closure; each data item resolves to the task list its kind requires (DLT manifests β†’ the deterministic DLT list, everything else β†’ the standard list). run_tasks execut...
310
12,553
cognee
cognee/tests/unit/modules/cognify/test_rollback.py
.py
from types import SimpleNamespace from uuid import uuid4 import pytest from cognee.modules.cognify import rollback as rollback_module class _FakeScalarsResult: def __init__(self, items): self._items = items def all(self): return self._items class _FakeExecuteResult: def __init__(self,...
237
8,310