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/modules/cognify/test_estimator.py | .py | """Dry-run estimator: stage math, pipeline-faithful skips, and input routing.
The estimator must never make LLM calls, so everything here runs offline; the
tokenizer/prompt/config seams are monkeypatched where the arithmetic is under
test, and input routing (paths vs raw text vs rejected inputs) is exercised
against t... | 400 | 14,390 |
cognee | cognee/tests/unit/modules/cognify/test_recovery.py | .py | from contextlib import asynccontextmanager
from datetime import datetime, timedelta, timezone
from types import SimpleNamespace
from uuid import uuid4
import pytest
from cognee.modules.cognify import recovery as recovery_module
from cognee.modules.pipelines.models import PipelineRunStatus
class _FakeScalarsResult:
... | 162 | 5,369 |
cognee | cognee/tests/unit/modules/cognify/test_contradiction_detection_wiring.py | .py | """Wiring tests for opt-in contradiction detection (issue #3699).
Contradiction detection is toggled by the ``contradiction_detection`` CognifyConfig
flag rather than a cognify() argument, so what needs covering is the config surface,
the splice in get_default_tasks, and the fact that remember() — which builds its
gra... | 240 | 10,724 |
cognee | cognee/tests/unit/modules/pipelines/test_summarize_run_info_data.py | .py | """Tests for ``summarize_run_info_data``.
Guards against unbounded growth of the ``pipeline_runs`` table: large
payloads passed to ``add``/``cognify`` used to be stored verbatim in
``run_info["data"]`` on every run, with no reader and no size limit. The
helper now bounds that payload while preserving the existing beha... | 42 | 1,589 |
cognee | cognee/tests/unit/modules/pipelines/run_tasks_with_context_test.py | .py | import asyncio
import cognee
from cognee.modules.pipelines.tasks.task import Task
from cognee.modules.pipelines.models import PipelineContext
from cognee.modules.users.methods import get_default_user
from cognee.modules.pipelines.operations.run_tasks_base import run_tasks_base
from cognee.infrastructure.databases.rela... | 55 | 1,486 |
cognee | cognee/tests/unit/modules/pipelines/test_provenance_mode.py | .py | """Tests for COGNEE_PROVENANCE_MODE (issue #3634).
Covers the three modes — lightweight (default), deep, disabled — verifying:
- lightweight: minimal refs (source_pipeline, source_task, source_node_set,
source_content_hash) are stamped; no deeper fields needed.
- deep: same stamp path as today (backward compatible).... | 419 | 15,847 |
cognee | cognee/tests/unit/modules/pipelines/run_tasks_test.py | .py | import asyncio
import cognee
from cognee.modules.pipelines.operations.run_tasks_base import run_tasks_base
from cognee.modules.pipelines.tasks.task import Task
from cognee.modules.users.methods import get_default_user
from cognee.infrastructure.databases.relational import create_db_and_tables
async def run_and_check... | 55 | 1,399 |
cognee | cognee/tests/unit/modules/pipelines/test_pipeline_context_extras.py | .py | """Test that PipelineContext.extras flows from caller through to task functions.
Validates that the fix for dexters1's comment #26 actually works:
custom pipelines can pass arbitrary state via extras and read it inside tasks.
"""
from dataclasses import dataclass
from uuid import uuid4
import pytest
from cognee.mod... | 169 | 5,823 |
cognee | cognee/tests/unit/modules/pipelines/run_task_from_queue_test.py | .py | import asyncio
from queue import Queue
import cognee
from cognee.modules.pipelines.operations.run_tasks_base import run_tasks_base
from cognee.modules.pipelines.tasks.task import Task
from cognee.modules.users.methods import get_default_user
from cognee.infrastructure.databases.relational import create_db_and_tables
... | 67 | 1,705 |
cognee | cognee/tests/unit/modules/pipelines/test_provenance_stamping.py | .py | """Unit tests for the _stamp_provenance function from run_tasks_base.
Tests the provenance stamping logic that tags DataPoints with their
originating pipeline and task names. Uses inline reimplementation to
avoid the cognee.__init__ import chain (starlette version issue).
"""
from uuid import uuid4
from pydantic impo... | 166 | 5,304 |
cognee | cognee/tests/unit/modules/pipelines/test_topological_rank_stamping.py | .py | """Unit tests for topological_rank stamping in _stamp_provenance.
DataPoint.topological_rank defaults to 0 (a sentinel — the field is never
written anywhere else in the codebase). When a pipeline runs, each task's
output should be stamped with a 1-based pipeline-stage index so the
visualization can lay nodes out left-... | 211 | 6,990 |
cognee | cognee/tests/unit/modules/pipelines/test_run_tasks_rollback.py | .py | from contextlib import asynccontextmanager
import importlib
from types import SimpleNamespace
from uuid import uuid4
import pytest
from cognee.modules.pipelines.models.PipelineRunInfo import PipelineRunErrored, PipelineRunStarted
from cognee.modules.pipelines.tasks.task import Task
run_tasks_module = importlib.impor... | 108 | 3,316 |
cognee | cognee/tests/unit/modules/pipelines/test_background_pipeline_task_anchoring.py | .py | """Guards the strong-reference anchor for the background pipeline task.
``run_pipeline_as_background_process`` launches the rest of the run with
``asyncio.create_task``. 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 abo... | 63 | 2,548 |
cognee | cognee/tests/unit/modules/ingestion/test_classify.py | .py | """Regression tests for ``classify`` filename derivation.
Originally contributed by @YashasviThakur (GitHub #3341 / PR #3342).
``classify`` derived a binary stream's name with ``str(data.name).split("/")[-1]``.
On Windows, ``data.name`` is a backslash path (e.g. ``C:\\dir\\file.pdf``) with no
forward slashes, so the ... | 47 | 1,887 |
cognee | cognee/tests/unit/modules/ontology/test_construct_data_points_and_edges_with_ontology.py | .py | from unittest.mock import MagicMock
import pytest
from cognee.modules.engine.models import Entity, EntityType
from cognee.modules.ontology.base_ontology_resolver import BaseOntologyResolver
from cognee.modules.ontology.construct_data_points_and_edges_with_ontology import (
add_ontology_data_points_and_edges,
... | 187 | 6,631 |
cognee | cognee/tests/unit/modules/ontology/test_get_configured_ontology_resolver.py | .py | from unittest.mock import MagicMock, patch
import pytest
from cognee.modules.ontology.get_default_ontology_resolver import get_configured_ontology_resolver
def _mock_resolver():
return MagicMock()
@pytest.mark.parametrize(
"config",
[
{},
{"ontology_config": None},
{"ontology_c... | 56 | 1,943 |
cognee | cognee/tests/unit/modules/ontology/test_ontology_adapter.py | .py | import io
import pytest
from rdflib import Graph, Namespace, RDF, OWL, RDFS
from cognee.modules.ontology.rdf_xml.RDFLibOntologyResolver import RDFLibOntologyResolver
from cognee.modules.ontology.exceptions import OntologyInitializationError
from cognee.modules.ontology.models import AttachedOntologyNode
from cognee.mo... | 670 | 23,544 |
cognee | cognee/tests/unit/modules/agent_memory/test_agent_memory.py | .py | import importlib
from types import SimpleNamespace
from unittest.mock import AsyncMock
from uuid import uuid4
import pytest
import cognee
from cognee.exceptions import CogneeValidationError
from cognee.modules.agent_memory.runtime import (
AgentMemoryConfig,
AgentMemoryContext,
get_current_agent_memory_co... | 1,214 | 40,791 |
cognee | cognee/tests/unit/modules/retriever/test_description_to_codepart_search.py | .py | import pytest
from unittest.mock import AsyncMock, patch
@pytest.mark.asyncio
async def test_code_description_to_code_part_no_results():
"""Test that code_description_to_code_part handles no search results."""
mock_user = AsyncMock()
mock_user.id = "user123"
mock_vector_engine = AsyncMock()
mock_... | 120 | 4,182 |
cognee | cognee/tests/unit/modules/data/test_create_authorized_dataset_parent_share.py | .py | """Tests for ``create_authorized_dataset`` parent-user auto-share.
When a user has ``parent_user_id`` set (typical for agent/service
identities owned by a human), the parent should receive full permissions
on any dataset the agent creates.
"""
import importlib
from types import SimpleNamespace
from uuid import uuid4
... | 124 | 4,168 |
cognee | cognee/tests/unit/modules/data/test_open_data_file.py | .py | import os
import tempfile
import pytest
from pathlib import Path
from cognee.infrastructure.files.utils.open_data_file import open_data_file
class TestOpenDataFile:
"""Test cases for open_data_file function with file:// URL handling."""
@pytest.mark.asyncio
async def test_regular_file_path(self):
... | 114 | 4,443 |
cognee | cognee/tests/unit/modules/data/test_create_dataset_concurrency.py | .py | """Tests for ``create_dataset`` concurrent-creation safety.
Concurrent calls for the same dataset name race between the existence SELECT
and the INSERT and, because the dataset id is deterministic, collide on the
primary key. ``create_dataset`` must tolerate losing that race (catch the
IntegrityError and return the wi... | 139 | 4,910 |
cognee | cognee/tests/unit/modules/data/deletion/test_prune_data.py | .py | import pathlib
import pytest
import cognee
from cognee.base_config import get_base_config
from cognee.infrastructure.databases.cache.config import get_cache_config
from cognee.infrastructure.databases.cache.get_cache_engine import (
close_cache_engine,
create_cache_engine,
get_cache_engine,
)
from cognee.... | 43 | 1,400 |
cognee | cognee/tests/unit/modules/integrations/test_slack_adapter_enterprise.py | .py | """Unit tests for SlackIntegration.revoke_remote / .refresh.
Network calls are mocked via aioresponses-free patching of aiohttp — these
tests check the *contract* each hook must honor: revoke_remote never raises
(disconnect must always succeed locally even if Slack is unreachable or the
token is already dead), and ref... | 183 | 6,330 |
cognee | cognee/tests/unit/modules/integrations/test_app_registration.py | .py | """Confirms Slack actually self-registers when the real app is imported.
Every other test in this package builds its own bare FastAPI app + a fake
integration, which proves the router's generic logic works but never proves
the wiring that gets a REAL provider registered at process startup — that
only happens because s... | 21 | 1,065 |
cognee | cognee/tests/unit/modules/integrations/test_oauth_state.py | .py | """Unit tests for the OAuth state in cognee.modules.integrations.slack.oauth.
Pure functions — no DB, no network. The state is the callback's ONLY
credential (the callback is unauthenticated), so the invariants are strict:
only an untampered, unexpired state minted by us validates.
"""
import time
from uuid import uu... | 63 | 1,941 |
cognee | cognee/tests/unit/modules/integrations/test_handle_slack_event.py | .py | """Unit tests for cognee.modules.integrations.slack.handle_slack_event.
The dispatch logic only — DB access and the Slack API call are patched out.
Invariants: the url_verification handshake echoes the challenge, both
revoking event types revoke by team_id, app_home_opened publishes a Home
view exactly when there's a ... | 164 | 5,674 |
cognee | cognee/tests/unit/modules/integrations/test_handle_slack_interactive.py | .py | """Unit tests for cognee.modules.integrations.slack.handle_slack_interactive.
Payload parsing (form-encoded `payload=<json>`, not raw JSON), dispatch to
the "Remember this" message shortcut and the ``/cognee-ask`` answer review
prompt's Share/Discard buttons, and every reply delivered via response_url
rather than the ... | 258 | 9,020 |
cognee | cognee/tests/unit/modules/integrations/test_registry.py | .py | """Unit tests for cognee.modules.integrations.registry.
The registry is a plain dict behind two functions — the invariants that
matter: registering makes an integration look-up-able by its own `provider`
name, and an unregistered provider raises rather than silently returning
None (so the router can turn it into a cle... | 65 | 1,898 |
cognee | cognee/tests/unit/modules/integrations/test_handle_slack_link.py | .py | """Unit tests for cognee.modules.integrations.slack.handle_slack_link.
Two halves: /cognee-link mints a magic link (no API key involved at all),
and confirm_link (backing POST /api/v1/slack/link) resolves that link's
code and performs the actual member-link write.
"""
import time
from unittest.mock import AsyncMock, ... | 124 | 4,380 |
cognee | cognee/tests/unit/modules/integrations/test_get_slack_channels_router.py | .py | """Unit tests for get_slack_channels_router (the channel-allowlist settings API).
get_active_credential_for_user, decrypt_token_payload, list_channels, and
update_provider_metadata are all patched — these tests only check the
router's own logic: 404 when Slack isn't connected, correct allowed-flag
marking, and a clean... | 124 | 4,673 |
cognee | cognee/tests/unit/modules/integrations/test_connect.py | .py | """Unit tests for cognee.modules.integrations.connect.complete_installation.
upsert_credential itself is exercised by test_credentials.py — this only
checks that complete_installation wires exchange_code -> parse_installation
-> upsert_credential correctly, with the right fields going to the right
upsert_credential pa... | 91 | 2,870 |
cognee | cognee/tests/unit/modules/integrations/test_handle_slack_command.py | .py | """Unit tests for cognee.modules.integrations.slack.handle_slack_command.
Credential lookup and handle_cognee_ask are patched out. Invariants: an
unconnected workspace is rejected before anything else runs, an empty (or
absent) channel allowlist means unrestricted, and a non-empty allowlist
blocks every channel not on... | 135 | 5,337 |
cognee | cognee/tests/unit/modules/integrations/test_crypto.py | .py | """Unit tests for cognee.modules.integrations.crypto.
Pure functions — no DB, no network. The invariants: roundtrip fidelity,
loud failure on a missing/malformed key (never silent fallback), version
dispatch, AES-GCM's tamper detection, and — the point of the keyring — that a
key rotation leaves old rows decryptable u... | 114 | 4,633 |
cognee | cognee/tests/unit/modules/integrations/test_get_integrations_router.py | .py | """Unit tests for the generic {provider} dispatch in get_integrations_router.
A fake OAuthIntegration is registered under provider "fake" so these tests
exercise the router's own generic logic (dispatch, error-to-redirect
mapping, unknown-provider 404) without depending on Slack or any real
network call. Slack's own O... | 240 | 8,798 |
cognee | cognee/tests/unit/modules/integrations/test_oauth_flow.py | .py | """Unit tests for the provider-agnostic state signing in
cognee.modules.integrations.oauth_flow.
Pure functions — no DB, no network, no provider settings. Unlike
test_oauth_state.py (which tests the Slack adapter's thin wrapper and its
settings-based secret), these pass the signing secret explicitly, since this
module... | 117 | 4,408 |
cognee | cognee/tests/unit/modules/integrations/test_verify_slack_signature.py | .py | """Unit tests for cognee.modules.integrations.slack.verify_slack_signature.
Pure function — no DB, no network. The invariants that matter: only an
HMAC keyed with the signing secret over the exact raw bytes passes, and the
5-minute replay window is enforced in both directions.
"""
import hashlib
import hmac
import ti... | 77 | 2,507 |
cognee | cognee/tests/unit/modules/integrations/test_response_url.py | .py | """Unit tests for cognee.modules.integrations.slack.response_url.
Invariants: never raises, regardless of a missing URL or a network failure —
callers rely on this to be a safe fire-and-forget delivery.
"""
from unittest.mock import patch
import pytest
from cognee.modules.integrations.slack.response_url import post... | 24 | 777 |
cognee | cognee/tests/unit/modules/integrations/test_home.py | .py | """Unit tests for cognee.modules.integrations.slack.home.publish_home_view.
Network is mocked. Invariants: the call is authenticated with the bot token
and targets the given Slack user, and a rejected call raises with Slack's
error code rather than failing silently.
"""
from unittest.mock import MagicMock, patch
imp... | 65 | 1,886 |
cognee | cognee/tests/unit/modules/integrations/test_handle_cognee_remember.py | .py | """Unit tests for cognee.modules.integrations.slack.handle_cognee_remember.
Credential lookup, owner resolution, the ingest call and the response_url
delivery are all patched out — this is about the handler's contract, not
about cognee.remember.
Invariants: an unconnected workspace and an unlinked member are both ref... | 152 | 5,645 |
cognee | cognee/tests/unit/modules/integrations/test_channels.py | .py | """Unit tests for cognee.modules.integrations.slack.channels.list_channels.
Network is mocked — the invariants under test: pagination follows Slack's
next_cursor until exhausted, only the fields the allowlist UI needs are kept,
a rejected call (e.g. missing channels:read) raises rather than returning a
silently-empty ... | 166 | 5,577 |
cognee | cognee/tests/unit/modules/integrations/test_credentials.py | .py | """Unit tests for the cross-user guard in cognee.modules.integrations.credentials.
The DB is mocked — the invariant under test is policy, not persistence: a
workspace already active for one user must not be silently reassigned to
another on reconnect, while a same-user reconnect (token refresh) still goes
through.
"""... | 204 | 7,171 |
cognee | cognee/tests/unit/modules/integrations/test_slack_adapter.py | .py | """Unit tests for cognee.modules.integrations.slack.adapter.SlackIntegration.
Covers the field-extraction logic that used to live in persistence.py's
save_installation() — team vs. enterprise (Grid) routing id, secret/metadata
split, and expires_in -> token_expires_at conversion.
"""
from datetime import datetime, ti... | 87 | 3,038 |
cognee | cognee/tests/unit/modules/integrations/test_handle_cognee_ask.py | .py | """Unit tests for modules.integrations.slack.handle_cognee_ask.
``/cognee-ask`` validates the workspace/query/authorization and starts the
search immediately in the background, acking with an in_channel placeholder
— splitting into two groups: handle_cognee_ask's own fast-path behavior
(validation, immediate ack, sche... | 376 | 14,857 |
cognee | cognee/tests/unit/modules/integrations/test_remember_message.py | .py | """Unit tests for cognee.modules.integrations.slack.remember_message.
Invariants: the enriched text carries channel/author provenance (falling
back gracefully when either is missing), the Slack dataset name is used,
the source node_set is stamped so the origin survives into the graph,
and the background mode is always... | 57 | 2,089 |
cognee | cognee/tests/unit/modules/agents/test_agent_registry.py | .py | from types import SimpleNamespace
from uuid import uuid4
import pytest
import cognee
from cognee.modules.agents.registry import (
classify_memory_source_type,
clear_registered_agent_connections,
list_registered_agent_connections,
register_agent_connection,
)
from cognee.modules.users.methods import ge... | 109 | 3,479 |
cognee | cognee/tests/unit/modules/agents/conftest.py | .py | import asyncio
import pytest
@pytest.fixture(autouse=True, scope="session")
def _setup_db():
async def _run():
from cognee.infrastructure.databases.relational import get_relational_engine
from cognee.run_migrations import run_migrations
try:
await run_migrations()
exc... | 30 | 1,027 |
cognee | cognee/tests/unit/modules/retrieval/test_node_edge_vector_search.py | .py | import pytest
from unittest.mock import AsyncMock
from cognee.modules.retrieval.utils.node_edge_vector_search import NodeEdgeVectorSearch
from cognee.infrastructure.databases.vector.exceptions import CollectionNotFoundError
class MockScoredResult:
"""Mock class for vector search results."""
def __init__(sel... | 274 | 11,385 |
cognee | cognee/tests/unit/modules/retrieval/cypher_search_retriever_test.py | .py | import sys
from unittest.mock import AsyncMock, patch
import pytest
from cognee.modules.retrieval.cypher_search_retriever import CypherSearchRetriever
from cognee.modules.retrieval.natural_language_retriever import NaturalLanguageRetriever
POSTGRES_ADAPTER_MODULES = [
"cognee.infrastructure.databases.graph.postg... | 116 | 4,108 |
cognee | cognee/tests/unit/modules/retrieval/test_concurrent_turn.py | .py | import asyncio
from contextlib import ExitStack, contextmanager
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
from uuid import uuid4
import pytest
from cognee.infrastructure.session.feedback_models import SessionTurnAnalysis
from cognee.infrastructure.session.session_concurre... | 246 | 8,959 |
cognee | cognee/tests/unit/modules/retrieval/test_concurrent_turn_eligibility.py | .py | import pytest
from cognee.modules.retrieval.completion_retriever import CompletionRetriever
from cognee.modules.retrieval.graph_completion_retriever import GraphCompletionRetriever
from cognee.modules.retrieval.hybrid_retriever import HybridRetriever
from cognee.modules.retrieval.session_aware_completion import can_ru... | 64 | 2,066 |
cognee | cognee/tests/unit/modules/retrieval/test_include_references_wiring.py | .py | """Unit tests for the include_references wiring in the completion retrievers.
These verify the contracted append rules without any LLM or network:
- include_references=False preserves the old answer text exactly (no Evidence).
- include_references=True appends an answer-grounded Evidence block to str answers.
- Non-st... | 287 | 9,513 |
cognee | cognee/tests/unit/modules/retrieval/graph_completion_retriever_context_extension_test.py | .py | import pytest
from unittest.mock import AsyncMock, patch, MagicMock
from cognee.modules.retrieval.graph_completion_context_extension_retriever import (
GraphCompletionContextExtensionRetriever,
)
from cognee.modules.graph.cognee_graph.CogneeGraphElements import Edge
@pytest.fixture
def mock_edge():
"""Create... | 936 | 34,538 |
cognee | cognee/tests/unit/modules/retrieval/rag_completion_retriever_test.py | .py | import pytest
from unittest.mock import AsyncMock, patch, MagicMock
from cognee.modules.retrieval.completion_retriever import CompletionRetriever
from cognee.modules.retrieval.exceptions.exceptions import NoDataError
from cognee.infrastructure.databases.vector.exceptions import CollectionNotFoundError
@pytest.fixtur... | 371 | 13,053 |
cognee | cognee/tests/unit/modules/retrieval/code_retriever_test.py | .py | import json
import asyncio
from unittest.mock import AsyncMock, MagicMock, patch
from uuid import UUID
import pytest
from cognee.modules.retrieval.code_retriever import (
CODE_NODE_TYPES,
CodeRetriever,
CodeSearchValidationError,
_CodeGraphSnapshot,
_CodeGraphSnapshotCache,
_code_graph_snapsho... | 834 | 26,934 |
cognee | cognee/tests/unit/modules/retrieval/triplet_retriever_test.py | .py | import pytest
from unittest.mock import AsyncMock, patch, MagicMock
from cognee.infrastructure.session.session_manager import SessionTurnPreparation
from cognee.modules.retrieval.triplet_retriever import TripletRetriever
from cognee.modules.retrieval.exceptions.exceptions import NoDataError
from cognee.infrastructure.... | 385 | 13,967 |
cognee | cognee/tests/unit/modules/retrieval/test_references_helpers.py | .py | """Unit tests for the LLM-free reference (Evidence) helpers.
Covers ``format_chunk_references`` (sync, payload-driven, answer-grounded) and
``build_answer_grounded_chunk_references`` (async, vector-engine-driven),
including the old-data graceful-degradation cases and backend-failure cases.
"""
from unittest.mock impo... | 263 | 9,331 |
cognee | cognee/tests/unit/modules/retrieval/graph_completion_retriever_cot_test.py | .py | import pytest
from unittest.mock import AsyncMock, patch, MagicMock
from cognee.modules.retrieval.graph_completion_cot_retriever import (
GraphCompletionCotRetriever,
_as_answer_text,
)
from cognee.modules.graph.cognee_graph.CogneeGraphElements import Edge
from cognee.infrastructure.llm.LLMGateway import LLMGa... | 726 | 26,316 |
cognee | cognee/tests/unit/modules/retrieval/test_concurrent_turn_dispatch.py | .py | """Contract for where concurrent mode runs and what one turn costs.
Three guarantees are pinned here:
* ``get_retriever_output`` calls only ``run_session_aware_completion``; that door
dispatches to concurrent or sequential,
* retriever ``get_completion`` stays as on ``dev``,
* a turn costs one answer call, with the... | 360 | 14,395 |
cognee | cognee/tests/unit/modules/retrieval/test_completion.py | .py | import pytest
from unittest.mock import AsyncMock, patch, MagicMock
from typing import Type
class TestGenerateCompletion:
@pytest.mark.asyncio
async def test_generate_completion_with_system_prompt(self):
"""Test generate_completion with provided system_prompt."""
mock_llm_response = "Generated... | 433 | 16,914 |
cognee | cognee/tests/unit/modules/retrieval/test_access_tracking.py | .py | from datetime import datetime
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from cognee.modules.retrieval.utils.access_tracking import (
_extract_access_node_ids,
update_node_access_timestamps,
)
def test_extract_access_node_ids_from_hybrid_retrieval_dict():
chunk = MagicMock()
... | 81 | 2,599 |
cognee | cognee/tests/unit/modules/retrieval/temporal_retriever_test.py | .py | from types import SimpleNamespace
import pytest
import os
from unittest.mock import AsyncMock, patch, MagicMock
from datetime import datetime
from cognee.modules.retrieval.temporal_retriever import TemporalRetriever
from cognee.tasks.temporal_graph.models import QueryInterval, Timestamp
from cognee.infrastructure.llm ... | 745 | 26,818 |
cognee | cognee/tests/unit/modules/retrieval/chunks_retriever_test.py | .py | import pytest
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch, MagicMock
from cognee.modules.retrieval.chunks_retriever import ChunksRetriever
from cognee.modules.retrieval.exceptions.exceptions import NoDataError
from cognee.infrastructure.databases.vector.exceptions import CollectionNotF... | 203 | 6,426 |
cognee | cognee/tests/unit/modules/retrieval/test_merge_results.py | .py | """Ordering contract for combining two retrievals of the same shape."""
from unittest.mock import MagicMock
from cognee.modules.retrieval.utils.merge_results import (
conversational_reserve,
edge_identity,
merge_ranked,
)
def result(identifier, text, *, truthy=True):
item = MagicMock()
item.id =... | 124 | 3,893 |
cognee | cognee/tests/unit/modules/retrieval/validate_queries_test.py | .py | import pytest
from cognee.modules.retrieval.utils.validate_queries import validate_queries
# ── single-query whitespace rejection ─────────────────────────────────────────
def test_empty_string_is_rejected():
is_valid, msg = validate_queries("", None)
assert is_valid is False
assert "non-empty" in msg
... | 72 | 2,382 |
cognee | cognee/tests/unit/modules/retrieval/test_used_graph_elements.py | .py | import pytest
from unittest.mock import MagicMock
from cognee.modules.retrieval.utils.used_graph_elements import (
extract_from_edges,
extract_from_scored_results,
extract_from_temporal_dict,
is_edge_list,
)
def test_is_edge_list_empty_or_not_list():
"""is_edge_list returns False for empty list o... | 146 | 4,754 |
cognee | cognee/tests/unit/modules/retrieval/hybrid_facts_test.py | .py | from unittest.mock import MagicMock
from cognee.modules.graph.models.EdgeType import EdgeType
from cognee.modules.retrieval.hybrid.facts import (
connection_edge_type_id,
edge_rank_by_id,
format_facts,
select_facts,
)
def _edge_id(text):
return str(EdgeType.id_for(text))
def _hit(text):
hit... | 120 | 3,611 |
cognee | cognee/tests/unit/modules/retrieval/test_global_context.py | .py | from types import SimpleNamespace
from unittest.mock import AsyncMock
import pytest
from cognee.modules.retrieval.utils.global_context import (
format_global_context_prelude,
search_top_global_context_summaries,
)
def test_format_global_context_prelude_returns_empty_when_both_inputs_empty():
assert form... | 87 | 2,926 |
cognee | cognee/tests/unit/modules/retrieval/test_hybrid_truth_context.py | .py | from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from cognee.context_global_variables import current_dataset_id
from cognee.modules.retrieval.hybrid_retriever import HybridRetriever
from cognee.modules.truth_subspace.models import TruthCentroidPayload
def _unified_engine():
engine = MagicMock... | 61 | 2,047 |
cognee | cognee/tests/unit/modules/retrieval/test_session_turn_kwargs.py | .py | from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
from uuid import uuid4
import pytest
from cognee.infrastructure.session.session_manager import SessionTurnPreparation
from cognee.modules.retrieval.agentic_retriever import AgenticRetriever
from cognee.modules.retrieval.graph_completion_deco... | 61 | 2,327 |
cognee | cognee/tests/unit/modules/retrieval/graph_completion_retriever_test.py | .py | import pytest
from unittest.mock import AsyncMock, patch, MagicMock
from cognee.modules.retrieval.graph_completion_retriever import GraphCompletionRetriever
from cognee.modules.graph.cognee_graph.CogneeGraphElements import Edge
def _make_unified_mock(graph_engine=None):
if graph_engine is None:
graph_eng... | 493 | 17,092 |
cognee | cognee/tests/unit/modules/retrieval/test_bm25_retriever.py | .py | import pytest
from unittest.mock import AsyncMock, patch
from cognee.modules.retrieval.bm25_retriever import BM25ChunksRetriever
def _patch_graph(corpus: dict[str, str]):
"""Patch the graph engine so the lexical loader sees the given {chunk_id: text} corpus."""
nodes = [
(chunk_id, {"id": chunk_id, "... | 122 | 4,281 |
cognee | cognee/tests/unit/modules/retrieval/hybrid_retriever_test.py | .py | import asyncio
from unittest.mock import AsyncMock, MagicMock, patch
from uuid import UUID, uuid4, uuid5
import pytest
from cognee.infrastructure.databases.vector.exceptions import CollectionNotFoundError
from cognee.infrastructure.session.session_manager import SessionTurnPreparation
from cognee.modules.graph.models... | 1,402 | 49,088 |
cognee | cognee/tests/unit/modules/retrieval/graph_completion_decomposition_retriever_test.py | .py | import pytest
from unittest.mock import AsyncMock, MagicMock, patch, call
from cognee.modules.graph.cognee_graph.CogneeGraphElements import Edge
from cognee.modules.retrieval.exceptions.exceptions import QueryValidationError
from cognee.modules.retrieval.graph_completion_decomposition_retriever import (
Decomposit... | 631 | 22,000 |
cognee | cognee/tests/unit/modules/retrieval/test_graph_summary_completion_retriever.py | .py | import pytest
from unittest.mock import AsyncMock, patch, MagicMock
from cognee.modules.retrieval.graph_summary_completion_retriever import (
GraphSummaryCompletionRetriever,
)
from cognee.modules.graph.cognee_graph.CogneeGraphElements import Edge
@pytest.fixture
def mock_edge():
"""Create a mock edge."""
... | 157 | 6,143 |
cognee | cognee/tests/unit/modules/retrieval/test_graph_report_retriever.py | .py | """Unit tests for GraphReportRetriever.
Fixtures mirror the real shape returned by ``get_graph_data()``:
nodes are ``(id, props)`` with a ``type`` field; node_set membership is carried
by ``belongs_to_set`` edges pointing at ``NodeSet`` container nodes; edges are
``(src, tgt, relationship_name, props)``.
"""
from __f... | 276 | 10,495 |
cognee | cognee/tests/unit/modules/retrieval/summaries_retriever_test.py | .py | import pytest
from unittest.mock import AsyncMock, patch, MagicMock
from types import SimpleNamespace
from cognee.modules.retrieval.summaries_retriever import SummariesRetriever
from cognee.modules.retrieval.exceptions.exceptions import NoDataError
from cognee.infrastructure.databases.vector.exceptions import Collecti... | 197 | 6,767 |
cognee | cognee/tests/unit/modules/retrieval/test_brute_force_triplet_search.py | .py | import pytest
from unittest.mock import AsyncMock, patch, MagicMock
from cognee.exceptions import CogneeValidationError
from cognee.modules.retrieval.utils.brute_force_triplet_search import (
brute_force_triplet_search,
get_memory_fragment,
format_triplets,
)
from cognee.modules.graph.models.EdgeType impor... | 1,199 | 46,571 |
cognee | cognee/tests/unit/modules/retrieval/hybrid/test_merge.py | .py | """Merging two hybrid retrievals keeps the result shape and its per-channel budgets."""
from unittest.mock import MagicMock
import pytest
from cognee.modules.retrieval.hybrid.merge import merge_hybrid_results
EMPTY_CHANNELS = {"chunks": [], "entities": [], "facts": []}
def result(identifier, text):
item = Mag... | 103 | 3,669 |
cognee | cognee/tests/unit/modules/retrieval/hybrid/test_truth_epoch_ranking.py | .py | from cognee.modules.retrieval.hybrid.ranking import rank_chunk_summary_pairs
def _pair(chunk_id: str, rank: int) -> dict:
return {
"chunk": {"id": chunk_id, "text": chunk_id, "importance_weight": 0.5},
"chunk_id": chunk_id,
"bm25_rank": rank,
"vector_rank": None,
"summary_r... | 45 | 1,373 |
cognee | cognee/tests/unit/modules/graph/test_retrieve_existing_edges.py | .py | import importlib
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from cognee.infrastructure.databases.provenance import EdgeIdentity
from cognee.modules.engine.models import Entity
existing_edges_module = importlib.import_module(
"cognee.modules.graph.utils.retrieve_existing_edges"
)
@pytes... | 37 | 1,208 |
cognee | cognee/tests/unit/modules/graph/test_resolve_edges_to_text.py | .py | """
Unit Tests: resolve_edges_to_text
Pins the contract that the bracket label is a compact relationship label
(not the natural-language edge_text) and that edge_text, when present, is
surfaced alongside the markup rather than inside it.
"""
import pytest
from cognee.modules.graph.cognee_graph.CogneeGraphElements im... | 84 | 2,532 |
cognee | cognee/tests/unit/modules/graph/test_rdf_roundtrip.py | .py | """Tests for RDF URI preservation (Phase 0), RDF export + SPARQL (Phase 1),
and RDF ingestion (Phase 2)."""
import importlib
import pytest
from rdflib import Graph, Literal, RDF, RDFS, URIRef
from cognee.modules.engine.models import Entity, EntityType
from cognee.modules.graph.rdf.export import (
DEFAULT_BASE_IR... | 304 | 10,670 |
cognee | cognee/tests/unit/modules/graph/test_relational_upserts.py | .py | from importlib import import_module
from uuid import uuid4
from unittest.mock import AsyncMock, patch
import pytest
from cognee.infrastructure.engine import DataPoint
from cognee.modules.graph.methods.sanitize_relational_payload import sanitize_relational_payload
from cognee.modules.graph.methods.upsert_edges import ... | 171 | 5,080 |
cognee | cognee/tests/unit/modules/graph/test_delete_detag_nodeset.py | .py | """When delete_from_graph_and_vector processes a dataset whose uniquely-owned
NodeSet nodes are in the hard-delete set, it must also detag the deleted
NodeSet's name from every surviving row/node. This test exercises the
orchestration wiring without needing a live Neo4j or Postgres.
"""
from __future__ import annotati... | 171 | 5,387 |
cognee | cognee/tests/unit/modules/graph/test_graph_methods.py | .py | """
Unit Tests: Graph Methods
Tests for core graph deletion methods with specific inputs and outputs.
Test Coverage:
- test_get_data_related_nodes_excludes_shared: Verify shared nodes are excluded
- test_delete_data_nodes_and_edges_removes_from_all_systems: Verify complete cleanup
"""
import os
import pathlib
import... | 652 | 22,978 |
cognee | cognee/tests/unit/modules/graph/test_global_context_graph_inputs.py | .py | from uuid import uuid4
from unittest.mock import AsyncMock
import pytest
import cognee.modules.graph.methods.get_global_context_graph_inputs as gci
from cognee.modules.graph.methods.get_global_context_graph_inputs import (
DatasetEntityCounts,
DatasetGraphEntityInput,
SummaryEntityLoadResult,
_chunk_e... | 370 | 12,528 |
cognee | cognee/tests/unit/modules/graph/test_graph_provenance_delete_routing.py | .py | """Routing seam tests for graph-provenance delete (COG-5522).
Prove that the public delete entry points send graph-provenance graphs through the
unified boundary (and old/unmarked graphs stay on the relational-ledger path).
These mock the unified engine + marker so they stay fast and backend-free; the
real end-to-end ... | 273 | 11,849 |
cognee | cognee/tests/unit/modules/graph/cognee_graph_elements_test.py | .py | import numpy as np
import pytest
from fastapi.encoders import jsonable_encoder
from cognee.modules.graph.cognee_graph.CogneeGraphElements import Edge, Node
from cognee.modules.graph.exceptions import InvalidDimensionsError, DimensionOutOfRangeError
def test_node_initialization():
"""Test that a Node is initializ... | 220 | 7,195 |
cognee | cognee/tests/unit/modules/graph/test_temporal_conflict_resolver.py | .py | """Unit tests for temporal contradiction resolution (issue #3631, Approach E).
Pure-Python and deterministic: no LLM, no database, no network.
"""
import copy
from cognee.modules.graph.utils import tag_superseded_edges
def _edge(source, target, relationship_name, updated_at="", edge_object_id=None, **extra):
p... | 134 | 5,193 |
cognee | cognee/tests/unit/modules/graph/cognee_graph_test.py | .py | import pytest
from unittest.mock import AsyncMock
from cognee.modules.graph.models.EdgeType import EdgeType
from cognee.modules.graph.exceptions import EntityNotFoundError
from cognee.modules.graph.cognee_graph.CogneeGraph import CogneeGraph
from cognee.modules.graph.cognee_graph.CogneeGraphElements import Edge, Node
... | 1,139 | 37,607 |
cognee | cognee/tests/utils/filter_overlapping_relationships.py | .py | from cognee.modules.engine.utils import generate_node_id
def filter_overlapping_relationships(*relationship_groups):
relationship_count = {}
overlapping_relationships = []
for group in relationship_groups:
for relationship in group:
relationship_id = f"{relationship[0]}_{relationship[... | 34 | 1,138 |
cognee | cognee/tests/utils/assert_graph_nodes_present.py | .py | from typing import List
from cognee.infrastructure.databases.graph import get_graph_engine
from cognee.infrastructure.engine.models.DataPoint import DataPoint
async def assert_graph_nodes_present(data_points: List[DataPoint]):
graph_engine = await get_graph_engine()
nodes, __ = await graph_engine.get_graph_da... | 15 | 599 |
cognee | cognee/tests/utils/get_contains_edge_text.py | .py | def get_contains_edge_text(entity_name: str, entity_description: str) -> str:
description = (entity_description or "").strip()
if description:
return f"Document chunk mentions {entity_name}: {description}"
return f"Document chunk mentions {entity_name}."
| 7 | 276 |
cognee | cognee/tests/utils/assert_nodes_vector_index_not_present.py | .py | from typing import List
from cognee.infrastructure.databases.vector import get_vector_engine_async
from cognee.infrastructure.engine.models.DataPoint import DataPoint
async def assert_nodes_vector_index_not_present(data_points: List[DataPoint]):
vector_engine = await get_vector_engine_async()
data_points_by_... | 29 | 1,229 |
cognee | cognee/tests/utils/assert_edges_vector_index_not_present.py | .py | from uuid import UUID
from typing import Dict, List, Tuple
from cognee.infrastructure.databases.vector import get_vector_engine_async
from cognee.modules.graph.models.EdgeType import EdgeType
async def assert_edges_vector_index_not_present(relationships: List[Tuple[UUID, UUID, str, Dict]]):
vector_engine = await ... | 24 | 914 |
cognee | cognee/tests/utils/assert_graph_edges_not_present.py | .py | from uuid import UUID
from typing import Dict, List, Tuple
from cognee.infrastructure.databases.graph import get_graph_engine
async def assert_graph_edges_not_present(relationships: List[Tuple[UUID, UUID, str, Dict]]):
graph_engine = await get_graph_engine()
nodes, edges = await graph_engine.get_graph_data()... | 25 | 1,105 |
cognee | cognee/tests/utils/extract_summary.py | .py | from uuid import uuid5
from cognee.modules.chunking.models import DocumentChunk
from cognee.shared.data_models import SummarizedContent
from cognee.tasks.summarization.models import TextSummary
def extract_summary(document_chunk: DocumentChunk, summary=SummarizedContent) -> TextSummary:
return TextSummary(
... | 15 | 538 |
cognee | cognee/tests/utils/assert_edges_vector_index_present.py | .py | from uuid import UUID
from typing import Dict, List, Tuple
from cognee.infrastructure.databases.graph import get_graph_engine
from cognee.infrastructure.databases.vector import get_vector_engine_async
from cognee.modules.engine.utils import generate_node_name
from cognee.modules.graph.models.EdgeType import EdgeType
f... | 79 | 2,930 |
cognee | cognee/tests/utils/extract_relationships.py | .py | from cognee.shared.data_models import KnowledgeGraph
from cognee.modules.chunking.models.DocumentChunk import DocumentChunk
from cognee.modules.engine.models import Entity, EntityType
def extract_relationships(
document_chunk: DocumentChunk, graph: KnowledgeGraph, cache: dict | None = None
):
if cache is None... | 60 | 1,777 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.