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/test_ladybug_requirement.py | .py | """Guards the ladybug macOS version-split markers against evaluator drift.
The two ladybug dependency lines partition environments: macOS 13/14
(Darwin 22/23) get 0.17.x (the last line with macosx_13_0 wheels), everything
else gets the newest supported range. The markers may use ONLY substring
operators ('in'/'not in'... | 115 | 4,544 |
cognee | cognee/tests/unit/test_agents_sdk_cli.py | .py | """Unit tests for the agents SDK namespace (``cognee.agents``) and the
``AgentsCommand`` CLI command.
These tests run WITHOUT a live LLM, network, or relational database. The
backend ``cognee.modules.agents.*`` functions and permission helpers are
monkeypatched at the names imported into the SDK module, so the SDK's o... | 550 | 19,395 |
cognee | cognee/tests/unit/test_temporal_awareness.py | .py | """Unit tests for bi-temporal node validity (issue #3700 / SDK-200).
Covers the ``valid_to`` field, the ``is_valid`` staleness check, and — crucially —
that ``close_node`` actually calls a real graph update and returns its result (the
original PR swallowed an ``AttributeError`` and was a silent no-op on every backend)... | 169 | 6,260 |
cognee | cognee/tests/unit/exceptions/test_cognee_error_contract.py | .py | """Contract tests for the ``CogneeApiError`` exception hierarchy.
Regression guard for https://github.com/topoteretes/cognee/issues/3749, where
``EntityNotFoundError`` and ``NodesetFilterNotSupportedError`` (and, with the
same root cause, ``WrongTaskTypeError``) overrode ``__init__`` but never called
``super().__init_... | 277 | 10,810 |
cognee | cognee/tests/unit/distributed/test_islo_sandbox.py | .py | """Offline unit tests for distributed/deploy/islo_sandbox.py.
The ``islo`` SDK is a documented script prerequisite (like ``daytona`` for
daytona_sandbox.py), not a project dependency, so these tests inject fake
``islo`` modules before importing the deploy script. No network access and no
API key are required.
"""
imp... | 329 | 11,282 |
cognee | cognee/tests/unit/tasks/test_dlt_document_mode.py | .py | """Unit tests for the connector-agnostic DLT document-mode seam.
A dlt source opts into the "document" ingestion path (LLM entity extraction)
by setting ``DOCUMENT_SOURCE_ATTR`` on itself; resolve_dlt_sources then tags its
rows ``system_metadata["source"] = <tag>`` (NOT "dlt"), so ``is_dlt_sourced``
returns False and ... | 76 | 2,818 |
cognee | cognee/tests/unit/tasks/test_data_item_to_text_file.py | .py | """Regression test for the Windows temp-file reopen bug in
``data_item_to_text_file`` (S3 ingestion path).
``tempfile.NamedTemporaryFile`` defaults to ``delete=True``, which on Windows
keeps an exclusive lock on the file and forbids reopening it *by name* while the
handle is still open. The S3 branch writes the downlo... | 90 | 3,339 |
cognee | cognee/tests/unit/tasks/test_dlt_p0_correctness.py | .py | """Unit tests for DLT ingestion P0 correctness fixes.
Covers the DB-free behaviors:
- dropped FK references are recorded for reporting (no longer silent)
The DB-dependent behaviors (PK-collision warning, failed-orphan tracking, and
deferred orphan cleanup) require mocked engines and belong with the broader
mocked D... | 76 | 2,288 |
cognee | cognee/tests/unit/tasks/chunks/test_create_chunk_associations_provenance.py | .py | from types import SimpleNamespace
from unittest.mock import AsyncMock
from uuid import uuid4
import importlib
import pytest
from cognee.modules.pipelines.models import PipelineContext
chunk_module = importlib.import_module("cognee.tasks.chunks.create_chunk_associations")
@pytest.mark.asyncio
async def test_create_... | 68 | 2,235 |
cognee | cognee/tests/unit/tasks/code_graph/test_remember_code_graph.py | .py | """remember(content_type='code') routes repos through the code-graph pipeline."""
import importlib
from unittest.mock import AsyncMock
import pytest
from cognee.api.v1.remember.remember import remember
remember_module = importlib.import_module("cognee.api.v1.remember.remember")
resolve_module = importlib.import_mod... | 98 | 3,709 |
cognee | cognee/tests/unit/tasks/code_graph/test_install_enola.py | .py | import hashlib
import importlib
import io
import os
import tarfile
import pytest
enola_module = importlib.import_module("cognee.tasks.code_graph.enola")
install_module = importlib.import_module("cognee.tasks.code_graph.install_enola")
def _make_archive(tmp_path, member_name, content=b"#!/bin/sh\nexit 0\n"):
arc... | 197 | 6,879 |
cognee | cognee/tests/unit/tasks/code_graph/test_incremental_code_graph.py | .py | """Incremental code-graph ingestion: snapshot-id skip and stale sweep (COG-6115)."""
import importlib
import json
from unittest.mock import AsyncMock
import pytest
from cognee.tasks.code_graph.enola import snapshot_identity
from cognee.tasks.code_graph.extract_code_graph import (
add_code_graph_data_points,
... | 255 | 9,947 |
cognee | cognee/tests/unit/tasks/code_graph/test_enola_runner.py | .py | import asyncio
import importlib
import pytest
enola_module = importlib.import_module("cognee.tasks.code_graph.enola")
def _make_fake_binary(tmp_path):
fake_binary = tmp_path / "enola"
fake_binary.write_text("#!/bin/sh\nexit 0\n")
fake_binary.chmod(0o755)
return fake_binary
def test_find_enola_bina... | 111 | 3,567 |
cognee | cognee/tests/unit/tasks/code_graph/test_code_repo.py | .py | """Code-project detection and partition for directory adds.
A directory carrying a project marker resolves to ONE repo-level manifest
item plus its document files; junk is skipped. These tests lock in the
partition semantics: code and manifests go to the repo item, prose stays in
the document pipeline, and binaries/do... | 153 | 5,889 |
cognee | cognee/tests/unit/tasks/code_graph/test_resolve_repo.py | .py | import importlib
import pytest
resolve_module = importlib.import_module("cognee.tasks.code_graph.resolve_repo")
def test_is_remote_repo_detection():
assert resolve_module.is_remote_repo("https://github.com/org/repo")
assert resolve_module.is_remote_repo("http://gitlab.example.com/org/repo.git")
assert r... | 131 | 4,369 |
cognee | cognee/tests/unit/tasks/code_graph/test_enola_parser.py | .py | import json
from pathlib import Path
import pytest
from cognee.tasks.code_graph.enola import (
EnolaSnapshotError,
normalize_relation,
parse_enola_snapshot,
)
FIXTURES_DIR = Path(__file__).parent / "fixtures"
def test_parse_enola_snapshot_reads_all_valid_facts():
facts, _receipt = parse_enola_snaps... | 130 | 4,074 |
cognee | cognee/tests/unit/tasks/code_graph/test_enola_integration.py | .py | """Integration test that runs the real enola binary; skipped when not installed."""
import shutil
import pytest
from cognee.tasks.code_graph.enola import parse_enola_snapshot, run_enola_generate
pytestmark = pytest.mark.skipif(
shutil.which("enola") is None, reason="enola binary is not installed"
)
@pytest.ma... | 30 | 851 |
cognee | cognee/tests/unit/tasks/code_graph/test_extract_code_graph.py | .py | import importlib
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
from uuid import UUID, uuid4
import cognee
import pytest
from cognee.modules.pipelines.models import PipelineContext
from cognee.modules.pipelines.operations.run_tasks_base import run_tasks_base
... | 651 | 23,190 |
cognee | cognee/tests/unit/tasks/storage/test_add_data_points.py | .py | import pytest
from unittest.mock import AsyncMock, MagicMock, patch
import sys
from types import SimpleNamespace
from uuid import uuid4
from cognee.infrastructure.engine import DataPoint
from cognee.modules.chunking.models.DocumentChunk import DocumentChunk
from cognee.modules.data.processing.document_types.Document i... | 898 | 32,235 |
cognee | cognee/tests/unit/tasks/documents/test_classify_documents.py | .py | import uuid
from types import SimpleNamespace
import pytest
from cognee.modules.data.processing.document_types import (
CsvDocument,
PdfDocument,
TextDocument,
)
from cognee.tasks.documents.classify_documents import classify_documents
def _make_data_item(extension):
return SimpleNamespace(
i... | 45 | 1,184 |
cognee | cognee/tests/unit/tasks/codingagents/test_coding_rule_associations_provenance.py | .py | from types import SimpleNamespace
from unittest.mock import AsyncMock
from uuid import uuid4
import pytest
import cognee.tasks.codingagents.coding_rule_associations as rule_module
from cognee.modules.pipelines.models import PipelineContext
def _wire_rule_module(monkeypatch, graph, edge, provenance_kwargs):
"""P... | 88 | 3,351 |
cognee | cognee/tests/unit/tasks/web_scraper/test_ssrf_protection.py | .py | """Unit tests for the SSRF protection guard used by outbound URL fetching."""
import ipaddress
import pytest
from cognee.tasks.web_scraper import ssrf_protection as ssrf
from cognee.tasks.web_scraper.ssrf_protection import (
SSRFProtectionError,
is_http_requests_allowed,
validate_outbound_url,
)
@pytes... | 132 | 3,973 |
cognee | cognee/tests/unit/tasks/memify/test_cross_connect_entities.py | .py | from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from cognee.tasks.memify.cross_connect_entities import (
INFERRED_EDGE_FEEDBACK_WEIGHT,
InferredRelation,
cross_connect_entities,
)
MODULE = "cognee.tasks.memify.cross_connect_entities"
class FakeGraph... | 231 | 8,686 |
cognee | cognee/tests/unit/tasks/memify/test_global_context_index_graph_bucketing.py | .py | import pytest
from cognee.tasks.memify.global_context_index.bucketing.graph.placement import (
place_graph_summaries_incrementally,
rebuild_graph_buckets_for_level,
validate_graph_buckets_can_be_extended,
validate_vector_buckets_can_be_extended,
)
from cognee.tasks.memify.global_context_index.ids impor... | 432 | 13,045 |
cognee | cognee/tests/unit/tasks/memify/test_session_persist_watermark.py | .py | """Watermark-based incremental session persistence.
Covers the three contract guarantees:
1. Completeness — every session entry is ingested (nothing skipped).
2. Incrementality — already-persisted entries are never re-ingested.
3. Retry safety — a failed cognify leaves the watermark untouched so the
same window is ... | 272 | 9,745 |
cognee | cognee/tests/unit/tasks/memify/test_global_context_index.py | .py | from importlib import import_module
from types import SimpleNamespace
from unittest.mock import AsyncMock
from uuid import NAMESPACE_URL, uuid4, uuid5
import pytest
from cognee.modules.graph.cognee_graph.CogneeGraph import CogneeGraph
from cognee.modules.graph.cognee_graph.CogneeGraphElements import Edge, Node
from c... | 1,439 | 51,149 |
cognee | cognee/tests/unit/tasks/memify/test_global_context_index_idf.py | .py | import math
import pytest
from cognee.tasks.memify.global_context_index.bucketing.graph.scoring import (
compute_idf_from_counts,
entities_weight,
entity_weight,
weighted_jaccard,
)
def test_compute_idf_from_counts_uses_expected_math():
weights = compute_idf_from_counts(
4,
{
... | 87 | 2,176 |
cognee | cognee/tests/unit/tasks/ingestion/test_dlt_csv_inputs.py | .py | """CSV ingestion routes through the loader engine's dlt_csv_loader.
With the dlt extra installed, the engine's priority order puts
``dlt_csv_loader`` above the plain ``csv_loader``, so every CSV takes the
structured DLT route: staging ingestion, one manifest per file with a stable
``data_id``, and the ``system_metadat... | 135 | 5,488 |
cognee | cognee/tests/unit/tasks/ingestion/test_ingest_data_update_branch.py | .py | import ast
from pathlib import Path
from cognee.modules.data.models import Data
def test_data_model_has_data_size_column_not_file_size():
columns = {column.name for column in Data.__table__.columns}
assert "data_size" in columns
assert "file_size" not in columns
def test_ingest_data_update_branch_assig... | 71 | 2,654 |
cognee | cognee/tests/unit/tasks/ingestion/test_dlt_column_values.py | .py | """Tests for optional ColumnValue node emission in the DLT pipeline.
Column selection (resolve_dlt_sources._selected_column_values) supports
per-table column lists with "*" wildcards on either side; emission
(emit_dlt_schema_graph) creates one shared ColumnValue node per unique
(table, column, value) with a column-nam... | 259 | 10,172 |
cognee | cognee/tests/unit/tasks/ingestion/test_save_data_item_to_storage.py | .py | import importlib
import ntpath
import os
from types import SimpleNamespace
from unittest.mock import AsyncMock
import pytest
from cognee.modules.ingestion.exceptions import IngestionError
from cognee.tasks.ingestion.save_data_item_to_storage import save_data_item_to_storage
# The package __init__ rebinds the name ``... | 134 | 5,928 |
cognee | cognee/tests/unit/tasks/ingestion/test_dlt_internal_table_filter.py | .py | """Tests for DLT internal-table detection in schema extraction.
DLT's own artifacts (bookkeeping tables, staging-schema copies) must be
excluded from the ingested schema by exact prefix/suffix convention — never
by substring, which silently dropped user tables like "staging_orders".
"""
import pytest
from cognee.tas... | 45 | 1,571 |
cognee | cognee/tests/unit/tasks/ingestion/test_dlt_ctx_extras_state.py | .py | """Cross-batch dedup state for extract_dlt_source_edges lives in ctx.extras.
The state used to be mutable ``set()`` kwargs baked into the Task object,
which the old cognify executor shared across datasets — dataset B skipped schema
emission because dataset A had already "emitted" it, writing edges to nodes
that only e... | 172 | 6,374 |
cognee | cognee/tests/unit/tasks/ingestion/test_dlt_stable_manifest_id.py | .py | """Stable manifest identity: idempotent re-adds and loud collisions.
The manifest Data id is seeded from (dataset, source name) — no content hash —
so re-adding a source resolves to the SAME record instead of orphaning it
between add and cognify. Two invariants keep that safe:
1. add() is idempotent: a completed item... | 170 | 5,950 |
cognee | cognee/tests/unit/tasks/ingestion/test_dlt_schema_graph_emit.py | .py | """emit_dlt_schema_graph: dual-provenance writes and UUID edge tuples.
Behaviors formerly pinned through the removed legacy per-row task — they
belong to the shared emitter, which the manifest pipeline
(extract_dlt_source_edges) drives:
- graph-provenance graphs get writes stamped with the source ref and the
relati... | 141 | 4,979 |
cognee | cognee/tests/unit/tasks/summarization/test_summarize_text.py | .py | import importlib
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
import pytest
from cognee.modules.chunking.models import DocumentChunk
from cognee.modules.data.processing.document_types import TextDocument
summarize_text_module = importlib.import_module("cognee.tasks.summarization.summa... | 49 | 1,417 |
cognee | cognee/tests/unit/tasks/graph/test_detect_contradictions.py | .py | import importlib
from contextlib import contextmanager
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from cognee.modules.cognify.config import CognifyConfig
from cognee.tasks.graph.detect_contradictions import (
_build_candidate_facts,
_collect_touched_n... | 278 | 9,485 |
cognee | cognee/tests/unit/tasks/graph/test_extract_graph_from_data.py | .py | import importlib
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from cognee.shared.data_models import KnowledgeGraph, Node, Edge as KGEdge
from cognee.tasks.graph.extract_graph_from_data import (
extract_graph_from_data,
integrate_chunk_graphs,
)
from cognee.tasks.graph.exceptions import ... | 352 | 11,904 |
cognee | cognee/tests/unit/tasks/graph/test_extract_graph_from_data_v2.py | .py | import importlib
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from cognee.shared.data_models import KnowledgeGraph
cascade_module = importlib.import_module("cognee.tasks.graph.extract_graph_from_data_v2")
@pytest.mark.asyncio
@patch.object(cascade_module, "integrate_chunk_graphs", new_callab... | 48 | 1,577 |
cognee | cognee/tests/unit/tasks/graph/test_resolve_temporal_contradictions.py | .py | """Unit tests for the temporal contradiction resolution task (issue #3631, Approach E).
Deterministic: no LLM, no database, no network — the graph engine is mocked.
"""
import importlib
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from cognee.tasks.graph.reso... | 210 | 7,989 |
cognee | cognee/tests/unit/users/roles/test_role_management_methods.py | .py | import importlib
from types import SimpleNamespace
from uuid import uuid4
import pytest
from cognee.modules.users.roles.methods.delete_role import delete_role
from cognee.modules.users.roles.methods.remove_user_from_role import remove_user_from_role
_delete_role_mod = importlib.import_module("cognee.modules.users.ro... | 116 | 3,415 |
cognee | cognee/tests/unit/users/tenants/test_role_visibility.py | .py | """Visibility rules for the role listing methods.
Role members may see the roles they belong to and who shares them, without
holding tenant-wide user management permission.
"""
import importlib
from uuid import uuid4
import pytest
from cognee.modules.users.exceptions import PermissionDeniedError, RoleNotFoundError
... | 217 | 6,783 |
cognee | cognee/tests/unit/users/tenants/test_remove_user_from_tenant.py | .py | import importlib
from uuid import uuid4
import pytest
from cognee.exceptions import CogneeValidationError
from cognee.infrastructure.databases.exceptions import EntityNotFoundError
from cognee.modules.users.exceptions import PermissionDeniedError
from cognee.modules.users.tenants.methods.remove_user_from_tenant impor... | 101 | 3,283 |
cognee | cognee/tests/unit/users/permissions/test_has_user_management_permission.py | .py | import importlib
from uuid import uuid4
import pytest
from cognee.modules.users.exceptions import PermissionDeniedError, TenantNotFoundError
from cognee.modules.users.permissions.methods import has_user_management_permission
# Module where get_tenant is looked up when has_user_management_permission runs
_perm_mod = ... | 100 | 3,330 |
cognee | cognee/tests/unit/users/permissions/test_authorized_get_principal_datasets.py | .py | import importlib
from uuid import uuid4
import pytest
from cognee.modules.users.exceptions import PermissionDeniedError, RoleNotFoundError
from cognee.modules.users.permissions.methods import authorized_get_principal_datasets
# Module where the collaborators are looked up when the method runs.
_mod = importlib.impor... | 224 | 8,089 |
cognee | cognee/tests/unit/truth_subspace/test_centroids.py | .py | import math
from uuid import UUID
import pytest
from cognee.modules.truth_subspace.centroids import (
build_centroids_from_learning_vectors,
centroid_id,
centroids_changed,
extend_centroids_with_learning_vectors,
learning_id,
normalize,
pad_coords,
unique_learning_vectors,
weighted... | 126 | 4,007 |
cognee | cognee/tests/unit/truth_subspace/test_build_centroid_slots.py | .py | from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
from uuid import uuid4
import pytest
from cognee.modules.truth_subspace.build import build_truth_subspace
class _EmbeddingEngine:
async def embed_text(self, texts):
vectors_by_text = {
"alpha": [1.0, 0.0]... | 99 | 3,377 |
cognee | cognee/tests/unit/truth_subspace/test_align.py | .py | import math
import cognee.modules.truth_subspace.align as align
def test_cosine_identical_vectors():
assert align.cosine([1.0, 0.0], [1.0, 0.0]) == 1.0
def test_cosine_orthogonal_vectors():
assert align.cosine([1.0, 0.0], [0.0, 1.0]) == 0.0
def test_cosine_opposite_vectors():
assert align.cosine([1.0... | 113 | 3,857 |
cognee | cognee/tests/unit/shared/test_telemetry_tracking.py | .py | """Unit tests for telemetry identity helpers."""
import asyncio
from collections.abc import Coroutine
from typing import Any
import pytest
from cognee.shared import utils
from cognee.shared.utils import _get_api_key_tracking_id, send_telemetry
def test_api_key_tracking_id_uses_full_key_not_visible_tail(monkeypatch... | 157 | 5,752 |
cognee | cognee/tests/unit/shared/test_async_utils.py | .py | import asyncio
import pytest
from cognee.shared.async_utils import gather_with_concurrency_limit
class TestGatherWithConcurrencyLimit:
@pytest.mark.asyncio
async def test_preserves_input_order(self):
async def call(value: int) -> int:
await asyncio.sleep(0.01 * (3 - value))
r... | 46 | 1,475 |
cognee | cognee/tests/unit/shared/test_auto_rate_limit.py | .py | """Seam tests: the dispatch context manager wires config, pacing, and the overload policy."""
import asyncio
from types import SimpleNamespace
import httpx
import openai
import pytest
import cognee.infrastructure.llm.config as llm_config_module
import cognee.infrastructure.llm.overload_policy as overload_policy_modu... | 96 | 3,080 |
cognee | cognee/tests/unit/shared/test_usage_logger.py | .py | """Unit tests for usage logger core functions."""
import pytest
from datetime import datetime, timezone
from uuid import UUID
from types import SimpleNamespace
from cognee.shared.usage_logger import (
_sanitize_value,
_sanitize_dict_key,
_get_param_names,
_get_param_defaults,
_extract_user_id,
... | 242 | 7,934 |
cognee | cognee/tests/unit/shared/test_data_models.py | .py | from pathlib import Path
from cognee.shared.data_models import Edge as KGEdge
def test_kg_edge_accepts_missing_description():
edge = KGEdge(source_node_id="Alice", target_node_id="Acme", relationship_name="works_at")
assert edge.description is None
assert "description" in edge.model_dump()
def test_kg... | 34 | 1,176 |
cognee | cognee/tests/unit/shared/test_logging_setup_excepthook.py | .py | """Regression tests for the uncaught-exception hook installed by setup_logging().
The hook was once silently dropped during a refactor — handle_exception was
defined but never assigned to sys.excepthook, disabling structlog handling of
uncaught exceptions without any test noticing. These tests pin the contract.
"""
i... | 91 | 3,469 |
cognee | cognee/tests/unit/migration/test_remember_router_cogx.py | .py | """Unit tests for the cogx-archive branch of the /v1/remember router.
All tests are pure: ``import_memory_source`` and dataset resolution are
monkeypatched, so no databases, LLM calls, or network are involved. Archive
unpacking and COGX parsing run for real against small in-memory tarballs.
"""
from types import Simp... | 326 | 12,156 |
cognee | cognee/tests/unit/migration/test_snapshot.py | .py | """Unit tests for the Pydantic-native export (GraphSnapshot). Pure: no DB, no LLM."""
import asyncio
from uuid import uuid4
from cognee.infrastructure.engine import DataPoint
from cognee.modules.engine.models import Entity, EntityType
from cognee.modules.migration.snapshot import (
GraphSnapshot,
build_snapsh... | 187 | 7,383 |
cognee | cognee/tests/unit/migration/test_import_source.py | .py | """Unit tests for import_memory_source and the remember() MemorySource dispatch.
All tests are pure: no databases, no LLM calls, no network. The three sinks the
import orchestration can hit (run_custom_pipeline, add, the nested remember)
are monkeypatched so each test asserts exactly which of them fire per mode.
"""
... | 681 | 28,670 |
cognee | cognee/tests/unit/migration/test_export_roundtrip.py | .py | """Round-trip tests for the real export mapping: _write_cogx -> read_archive -> translate_records.
These exercise the cognee -> COGX -> cognee path on synthetic (nodes, edges)
shaped exactly like ``get_graph_data()`` output — Entity, DocumentChunk,
EntityType, and TextSummary nodes with contains/is_a edges — without t... | 449 | 20,001 |
cognee | cognee/tests/unit/migration/test_push.py | .py | """Unit tests for cognee.push() and the COGX archive transport helpers.
All tests are pure: no databases, no LLM calls, no network.
"""
import asyncio
import importlib
import io
import tarfile
import pytest
from cognee.modules.migration.archive import (
ARCHIVE_SUFFIX,
find_archive_root,
pack_archive,
... | 441 | 16,905 |
cognee | cognee/tests/unit/migration/test_provenance_ctx.py | .py | """Drift guard between PipelineContext and the COGX import ctx adaptation.
The COGX import path adapts the pipeline context before handing it to
``add_data_points`` (``_provenance_ctx`` in ``cognee/modules/migration/loader.py``).
A hand-copied field list there silently drops any parameter later added to
``PipelineCont... | 76 | 3,057 |
cognee | cognee/tests/unit/migration/test_migration.py | .py | """Unit tests for the memory-migration module (COGX, sources, loader, formats).
All tests are pure: no databases, no LLM calls.
"""
import asyncio
import json
import xml.etree.ElementTree as ET
from datetime import datetime, timezone
from cognee.modules.migration.cogx import (
COGX_VERSION,
COGXArchiveWriter... | 685 | 27,697 |
cognee | cognee/tests/unit/migration/test_langmem_source.py | .py | """Unit tests for LangMemSource.
Pure: no databases, no LLM calls, no network. Exercises the dump parsing and
COGX record mapping for the shapes a LangMem export can take.
"""
import json
from pathlib import Path
import pytest
from cognee.modules.migration.cogx import COGXMemory
from cognee.modules.migration.source... | 130 | 3,840 |
cognee | cognee/tests/unit/processing/chunks/test_input.py | .py | import pytest
INPUT_TEXTS = {
"empty": "",
"single_char": "x",
"whitespace": " \n\t \r\n ",
"unicode_special": "Hello 👋 مرحبا שָׁלוֹם",
"mixed_endings": "line1\r\nline2\nline3\r\nline4",
"many_newlines": "\n\n\n\ntext\n\n\n\n",
"html_mixed": "<p>Hello</p>\nPlain text\n<div>World</div... | 288 | 9,463 |
cognee | cognee/tests/unit/processing/chunks/chunk_by_paragraph_test.py | .py | from unittest.mock import patch
from cognee.tasks.chunks import chunk_by_paragraph
import sys
chunk_by_sentence_module = sys.modules.get("cognee.tasks.chunks.chunk_by_sentence")
def mock_get_embedding_engine():
class MockEngine:
tokenizer = None
return MockEngine()
GROUND_TRUTH = {
"whole_text... | 85 | 2,658 |
cognee | cognee/tests/unit/processing/chunks/chunk_by_row_test.py | .py | from itertools import product
import numpy as np
import pytest
from cognee.infrastructure.databases.vector.embeddings import get_embedding_engine
from cognee.tasks.chunks import chunk_by_row
INPUT_TEXTS = "name: John, age: 30, city: New York, country: USA"
max_chunk_size_vals = [8, 32]
# Two rows separated by a bla... | 116 | 4,617 |
cognee | cognee/tests/unit/processing/chunks/chunk_by_sentence_test.py | .py | from itertools import product
import numpy as np
import pytest
from cognee.tasks.chunks import chunk_by_sentence
from cognee.tests.unit.processing.chunks.test_input import INPUT_TEXTS_LONGWORDS, INPUT_TEXTS
from cognee.infrastructure.databases.vector.embeddings import get_embedding_engine
maximum_length_vals = [None... | 60 | 1,874 |
cognee | cognee/tests/unit/processing/chunks/chunk_by_word_test.py | .py | import numpy as np
import pytest
from cognee.tasks.chunks import chunk_by_word
from cognee.tests.unit.processing.chunks.test_input import INPUT_TEXTS, INPUT_TEXTS_LONGWORDS
@pytest.mark.parametrize(
"input_text",
[
INPUT_TEXTS["english_text"],
INPUT_TEXTS["english_lists"],
INPUT_TEXTS... | 39 | 1,177 |
cognee | cognee/tests/unit/processing/chunks/chunk_by_paragraph_2_test.py | .py | from itertools import product
import numpy as np
import pytest
from cognee.tests.unit.processing.chunks.test_input import INPUT_TEXTS
from cognee.infrastructure.databases.vector.embeddings import get_embedding_engine
from cognee.tasks.chunks import chunk_by_paragraph
batch_paragraphs_vals = [True, False]
max_chunk_s... | 82 | 2,487 |
cognee | cognee/tests/unit/processing/utils/utils_test.py | .py | import os
import tempfile
import pytest
from unittest.mock import patch, mock_open
from io import BytesIO
from uuid import uuid4
from pathlib import Path
from cognee.root_dir import ensure_absolute_path
from cognee.infrastructure.files.utils.get_file_content_hash import get_file_content_hash
from cognee.shared.utils i... | 74 | 2,193 |
cognee | cognee/tests/unit/search/test_search_result_payload.py | .py | import pytest
from pydantic import BaseModel
from cognee.modules.search.models.SearchResultPayload import SearchResultPayload
from cognee.modules.search.types.SearchType import SearchType
class DealBrief(BaseModel):
deal_name: str = ""
health: str = ""
def test_search_result_payload_with_string_completion()... | 67 | 2,757 |
cognee | cognee/tests/unit/entity_extraction/regex_entity_extraction_test.py | .py | import pytest
from cognee.tasks.entity_completion.entity_extractors.regex_entity_extractor import (
RegexEntityExtractor,
)
@pytest.fixture
def regex_extractor():
"""Create a RegexEntityExtractor instance for testing."""
return RegexEntityExtractor()
@pytest.mark.asyncio
async def test_extract_emails(re... | 292 | 10,415 |
cognee | cognee/tests/unit/pipelines/test_bound_task_pipeline.py | .py | """Tests for the deferred-call pipeline pattern (BoundTask + run_pipeline)."""
import pytest
from cognee.modules.pipelines.tasks.task import task, BoundTask, TaskSpec, Task
from cognee.pipelines.types import _Drop as Drop
# ---------------------------------------------------------------------------
# Fake "existing"... | 187 | 6,609 |
cognee | cognee/tests/unit/pipelines/test_simplified_pipelines.py | .py | """Tests for the simplified pipeline API: Drop, FieldAnnotations, @task, Task.with_config, legacy compat."""
import asyncio
from typing import Annotated
from uuid import UUID
import pytest
from cognee.pipelines.types import Drop
from cognee.modules.pipelines.tasks.task import BoundTask
# -- Drop sentinel tests --
... | 251 | 8,212 |
cognee | cognee/tests/unit/interfaces/graph/test_expand_with_nodes_and_edges.py | .py | from unittest.mock import MagicMock
import pytest
from cognee.infrastructure.engine.models.Edge import Edge
from cognee.modules.engine.models import Entity
from cognee.modules.graph.utils.expand_with_nodes_and_edges import (
attach_new_edges_to_data_points,
construct_data_points_and_edges,
)
from cognee.share... | 285 | 9,596 |
cognee | cognee/tests/unit/interfaces/graph/test_weighted_edges.py | .py | import pytest
from typing import List, Any
from pydantic import SkipValidation
from cognee.infrastructure.engine import DataPoint
from cognee.infrastructure.engine.models.Edge import Edge
from cognee.modules.graph.utils import get_graph_from_model
class Product(DataPoint):
name: str
description: str
metad... | 392 | 13,315 |
cognee | cognee/tests/unit/interfaces/graph/get_graph_from_model_unit_test.py | .py | import pytest
from typing import List, Any
from cognee.infrastructure.engine import DataPoint, Edge
from cognee.modules.graph.utils import get_graph_from_model
from cognee.modules.engine.models import Entity as RealEntity, EntityType as RealEntityType
class Document(DataPoint):
path: str
metadata: dict = {"i... | 231 | 7,638 |
cognee | cognee/tests/unit/interfaces/graph/get_graph_from_huge_model_test.py | .py | import time
import random
import pytest
import asyncio
from typing import List
from uuid import NAMESPACE_OID, uuid5
from cognee.infrastructure.engine import DataPoint
from cognee.modules.graph.utils import get_graph_from_model
random.seed(1500)
class Repository(DataPoint):
path: str
metadata: dict = {"ind... | 138 | 3,398 |
cognee | cognee/tests/unit/interfaces/graph/test_expand_with_nodes_and_edges_parity.py | .py | """Characterization tests for extracted graph construction and ontology enrichment."""
from __future__ import annotations
import io
from typing import Any
from unittest.mock import MagicMock
import pytest
from rdflib import OWL, RDF, RDFS, Graph, Namespace
from cognee.infrastructure.databases.provenance import Edge... | 721 | 24,070 |
cognee | cognee/tests/unit/interfaces/graph/get_graph_from_model_circular_test.py | .py | import random
import pytest
import asyncio
from typing import List
from uuid import NAMESPACE_OID, uuid5
from cognee.infrastructure.engine import DataPoint
from cognee.modules.graph.utils import get_graph_from_model
random.seed(1500)
class Repository(DataPoint):
path: str
metadata: dict = {"index_fields": ... | 68 | 1,478 |
cognee | cognee/tests/unit/api/test_cloud_client_skills_upload.py | .py | """CloudClient.remember(content_type='skills') reads local SKILL.md files
and uploads their contents — not the path string.
Before the fix, a remote ``cognee.remember("./skills", content_type="skills")``
sent the literal string ``"./skills"`` (10 bytes) as the form body. The pod
then handed an UploadFile containing th... | 149 | 4,830 |
cognee | cognee/tests/unit/api/test_build_brains_payload.py | .py | """build_brains_payload: the overview across every dataset a user may read.
Patches at the ``fetch_dataset_graph_data`` boundary rather than the graph
engine: seed resolution and bounded truncation are already exercised end to
end in test_visualize_subgraph.py, and get_all_user_permission_datasets is
CLO-399's existin... | 74 | 2,736 |
cognee | cognee/tests/unit/api/test_get_schema_router.py | .py | from types import SimpleNamespace
from importlib import import_module
from uuid import uuid4
from fastapi import FastAPI
from fastapi.testclient import TestClient
inventory_module = import_module("cognee.api.v1.visualize.get_schema_inventory")
router_module = import_module("cognee.api.v1.visualize.routers.get_schema_... | 61 | 2,106 |
cognee | cognee/tests/unit/api/test_get_raw_data_endpoint.py | .py | import io
import uuid
from contextlib import asynccontextmanager
from types import SimpleNamespace
from unittest.mock import AsyncMock
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from cognee.modules.users.methods import get_authenticated_user
@pytest.fixture(scope="session")
... | 209 | 6,383 |
cognee | cognee/tests/unit/api/test_permissions_router.py | .py | from cognee.api.v1.permissions.routers.get_permissions_router import get_permissions_router
def test_principal_datasets_route_is_registered():
routes = {route.name: route for route in get_permissions_router().routes}
route = routes["get_principal_datasets"]
assert route.path == "/principals/{principal_i... | 11 | 367 |
cognee | cognee/tests/unit/api/test_datasets_missing_dataset_404.py | .py | """Regression test: dataset data endpoints return 404 for missing/unauthorized datasets.
``GET /datasets/{id}/data`` and ``GET /datasets/{id}/data/{data_id}/raw`` guard
with ``if dataset is None`` and then index ``dataset[0].id``. But
``get_authorized_existing_datasets`` always returns a *list* (``[]`` when the
datase... | 89 | 2,956 |
cognee | cognee/tests/unit/api/test_visualize_subgraph.py | .py | """End-to-end tests: visualize_graph renders exactly the expected subgraph.
Only the I/O boundaries (graph engine, DB context, session events) are mocked;
the real seed-resolution, truncation, and HTML renderer all run, and we assert
on the node/edge payload actually embedded in the produced HTML.
"""
import json
imp... | 153 | 6,056 |
cognee | cognee/tests/unit/api/test_delete_ontology.py | .py | """Tests for the delete ontology feature.
Covers:
- OntologyService.delete_ontology: removes file and metadata
- OntologyService.delete_ontology: raises ValueError for unknown key
- OntologyService.delete_ontology: handles missing .owl file gracefully
- DELETE /api/v1/ontologies/{key} endpoint: success, 400, upload-th... | 231 | 8,217 |
cognee | cognee/tests/unit/api/test_cognify_memify_error_detail.py | .py | """Regression test: cognify/memify error responses surface the real error.
When a cognify/memify pipeline run errors, the routers build the 500 response
``detail`` from ``getattr(run, "error", None) or str(run)``. ``PipelineRunErrored``
has no ``error`` attribute — the failing task's message is carried on ``payload``
... | 90 | 3,164 |
cognee | cognee/tests/unit/api/test_get_schema_inventory.py | .py | """Unit tests for get_schema_inventory over a synthetic knowledge graph."""
from contextlib import asynccontextmanager
from importlib import import_module
from unittest.mock import AsyncMock
from uuid import uuid4
import pytest
# Import via importlib: the cognee.api.v1 package rebinds the name "visualize"
# to the v... | 183 | 7,191 |
cognee | cognee/tests/unit/api/test_ontology_endpoint.py | .py | import pytest
import uuid
from fastapi.testclient import TestClient
from unittest.mock import Mock
from types import SimpleNamespace
from cognee.api.client import app
from cognee.modules.users.methods import get_authenticated_user
@pytest.fixture(scope="session")
def test_client():
# Keep a single TestClient (and... | 253 | 8,873 |
cognee | cognee/tests/unit/api/test_api_error_responses.py | .py | """
Consolidated tests for API endpoint error responses and basic endpoint functionality.
Tests cover:
- Error handling (PipelineRunErrored → 422, PermissionDenied → 403, etc.)
- Basic endpoint functionality (happy path with mocked backends)
"""
import importlib
from types import SimpleNamespace
from uuid import uuid... | 638 | 23,459 |
cognee | cognee/tests/unit/api/test_memory_provenance_role_grants.py | .py | """_read_roles_and_grants runs against a real database.
Mocking cannot cover the failure this exists to catch: CLO-399's own
dataset-groups endpoint first read Principal.id/Principal.type through an
outer join across User/Role/Tenant and got a user labelled "tenant" back,
because the ORM tried to resolve one polymorph... | 238 | 8,108 |
cognee | cognee/tests/unit/api/test_live_events.py | .py | """get_live_events: the delta cursor for the Memory tab's live timeline.
Authorization and session-event collection are mocked (get_authorized_
existing_datasets, collect_session_events); what this pins is the cursor
arithmetic itself — strict '>' filtering so nothing repeats, the response
cursor coming from the newes... | 126 | 4,394 |
cognee | cognee/tests/unit/api/test_skills_router.py | .py | """Tests for the dataset-scoped skills router (DELETE /api/v1/skills/{skill_id})."""
from types import SimpleNamespace
from importlib import import_module
from uuid import uuid4
from fastapi import FastAPI
from fastapi.testclient import TestClient
router_module = import_module("cognee.api.v1.skills.routers.get_skill... | 95 | 2,691 |
cognee | cognee/tests/unit/api/test_memory_provenance.py | .py | """Unit tests for the memory-provenance graph builder (pure projection logic)."""
from importlib import import_module
# Import via importlib for consistency with the visualize submodule access pattern.
_module = import_module("cognee.api.v1.visualize.memory_provenance")
build_provenance_graph = _module.build_provenan... | 194 | 7,108 |
cognee | cognee/tests/unit/api/test_improve_global_context_index.py | .py | from importlib import import_module
from types import SimpleNamespace
from unittest.mock import AsyncMock
from uuid import uuid4
import pytest
class DummySpan:
def __init__(self):
self.attributes = {}
def __enter__(self):
return self
def __exit__(self, exc_type, exc, traceback):
... | 150 | 5,613 |
cognee | cognee/tests/unit/api/test_memory_provenance_graph_provenance.py | .py | from types import SimpleNamespace
from unittest.mock import AsyncMock
from uuid import uuid4
import importlib
import pytest
from cognee.infrastructure.databases.provenance import EdgeIdentity, make_source_ref_key
provenance_module = importlib.import_module("cognee.api.v1.visualize.memory_provenance")
class _EmptyE... | 174 | 6,452 |
cognee | cognee/tests/unit/api/test_ontology_router_offload.py | .py | """Ontology routes must not block the event loop on synchronous file IO.
`OntologyService.delete_ontology` / `list_ontologies` do blocking filesystem IO
(stat / unlink / metadata read). The async routes must dispatch them via
`asyncio.to_thread` rather than calling them inline on the event loop.
"""
import asyncio
fr... | 62 | 2,158 |
cognee | cognee/tests/unit/api/recall/test_recall_logs_query_history.py | .py | """Recall records the questions it answers, the same way /v1/search does.
Recall calls ``authorized_search`` directly, so it skips the logging that
``search()`` wraps around that call. Agents recall through this endpoint, so
without this their questions never reach recall history at all.
A search fans out over every ... | 168 | 6,003 |
cognee | cognee/tests/unit/api/v2/test_query_router.py | .py | """Tests for the rule-based query router."""
import pytest
from cognee.api.v1.recall.query_router import route_query, record_override, override_counts
from cognee.modules.search.types import SearchType
class TestFactualQueries:
def test_simple_who(self):
assert route_query("Who won Nobel Prizes?").searc... | 189 | 7,186 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.