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/tasks/translation/config_test.py
.py
""" Unit tests for translation configuration """ from typing import get_args from pydantic import ValidationError from cognee.tasks.translation.config import ( get_translation_config, TranslationConfig, TranslationProviderType, ) def test_default_translation_config(): """Test default translation co...
94
3,568
cognee
cognee/tests/tasks/translation/providers_test.py
.py
""" Unit tests for translation providers """ import os import pytest from cognee.tasks.translation.providers import ( get_translation_provider, LLMTranslationProvider, TranslationResult, ) from cognee.tasks.translation.exceptions import TranslationError def has_llm_api_key(): """Check if LLM API ke...
152
5,080
cognee
cognee/tests/tasks/descriptive_metrics/metrics_test_utils.py
.py
from typing import List from cognee.infrastructure.engine import DataPoint from cognee.tasks.storage.add_data_points import add_data_points import cognee from cognee.infrastructure.databases.graph import get_graph_engine import json from pathlib import Path class Document(DataPoint): path: str metadata: dict ...
97
3,305
cognee
cognee/tests/tasks/descriptive_metrics/metric_consistency_test.py
.py
from cognee.tests.tasks.descriptive_metrics.metrics_test_utils import get_metrics import asyncio async def check_graph_metrics_consistency_across_adapters(include_optional=False): neo4j_metrics = await get_metrics(provider="neo4j", include_optional=include_optional) networkx_metrics = await get_metrics(provi...
23
1,002
cognee
cognee/tests/tasks/descriptive_metrics/neo4j_metrics_test.py
.py
import asyncio async def main(): from cognee.tests.tasks.descriptive_metrics.metrics_test_utils import assert_metrics await assert_metrics(provider="neo4j", include_optional=False) await assert_metrics(provider="neo4j", include_optional=True) if __name__ == "__main__": asyncio.run(main())
13
311
cognee
cognee/tests/tasks/entity_extraction/entity_extraction_test.py
.py
import os import pathlib import asyncio import cognee import cognee.modules.ingestion as ingestion from cognee.infrastructure.llm import get_max_chunk_tokens from cognee.infrastructure.llm.extraction import extract_content_graph from cognee.modules.chunking.TextChunker import TextChunker from cognee.modules.data.proce...
95
3,081
cognee
cognee/tests/tasks/summarization/summarize_code_test.py
.py
import asyncio from cognee.shared.data_models import SummarizedContent from cognee.tasks.summarization import summarize_code from cognee.tests.tasks.graph.code_graph_test_data_generation import ( code_graph_test_data_generation, ) def test_summarize_code(): nodes, _ = code_graph_test_data_generation() no...
16
506
cognee
cognee/tests/tasks/web_scraping/web_scraping_test.py
.py
import asyncio import cognee from cognee.tasks.web_scraper.config import DefaultCrawlerConfig from cognee.tasks.web_scraper import cron_web_scraper_task async def test_web_scraping_using_bs4(): await cognee.prune.prune_data() await cognee.prune.prune_system() url = "https://quotes.toscrape.com/" rule...
173
5,126
cognee
cognee/tests/integration/test_belongs_to_set_neo4j.py
.py
"""Integration tests for Neo4j belongs_to_set upsert and detag. Exercises the wire-level Cypher behavior of `Neo4jAdapter.add_nodes` and `remove_belongs_to_set_tags` against a live Neo4j (with APOC) instance, without touching LLMs or embeddings. Skipped unless `TEST_NEO4J_URL` is set. Configure with the env vars `TES...
335
12,618
cognee
cognee/tests/integration/test_delete_edge_cases.py
.py
""" Integration Tests: Delete Edge Cases Tests for edge cases in the delete feature: 1. last_accessed field updates when retriever accesses data 2. cleanup_unused_data dry_run behavior 3. cleanup_unused_data actual deletion behavior Test Coverage: - test_last_accessed_updates_on_search: Verify last_accessed is update...
360
12,692
cognee
cognee/tests/integration/test_belongs_to_set_pgvector.py
.py
"""Integration tests for PGVector belongs_to_set upsert and detag. Exercises the wire-level behavior of `PGVectorAdapter.create_data_points` and `remove_belongs_to_set_tags` against a live Postgres+pgvector instance, without touching LLMs or embeddings — `embed_data` is stubbed to return a fixed vector so the tests co...
298
11,361
cognee
cognee/tests/integration/tasks/test_cognify_rollback_recovery.py
.py
import asyncio import importlib import pathlib from contextlib import asynccontextmanager from datetime import datetime, timedelta, timezone from types import SimpleNamespace from uuid import uuid4 import pytest import pytest_asyncio from sqlalchemy import select import cognee from cognee.context_global_variables imp...
523
20,069
cognee
cognee/tests/integration/tasks/test_graph_provenance_delete_default_stack.py
.py
"""Part 1 + Part 2 integration gate: graph-provenance delete/rollback on the REAL default graph adapter (Ladybug/Kuzu) driven through the UnifiedStoreEngine. These don't use the LLM or an embedding backend — they seed the graph directly via the real Ladybug adapter and use a recording vector engine. That keeps them fa...
186
7,644
cognee
cognee/tests/integration/tasks/test_update_id_stability.py
.py
"""update() id-stability contract, end to end on the real local stack. The document keeps its ``data_id`` through updates — the replacement is re-ingested pinned to the resolved id and cognify rebuilds the graph under it. Scenarios: 1. update by the row's own id: same id, content replaced, and the WHOLE stack ...
333
14,819
cognee
cognee/tests/integration/tasks/test_dataset_scoped_data.py
.py
"""Dataset-scoped Data identity: per-dataset rows, lookup dedup, no bleed. The refactor decouples document identity from content: ``Data.id`` is random, rows are dataset-scoped (``Data.dataset_id``), and dedup is a lookup on ``(dataset_id, content_hash)``. This suite pins the new contract at the ingestion layer (no co...
389
16,929
cognee
cognee/tests/integration/tasks/test_add_data_points.py
.py
import pathlib import pytest import pytest_asyncio import cognee from cognee.low_level import setup from cognee.infrastructure.engine import DataPoint from cognee.tasks.storage.add_data_points import add_data_points from cognee.tasks.storage.exceptions import InvalidDataPointsInAddDataPointsError from cognee.infrastru...
145
4,832
cognee
cognee/tests/integration/tasks/test_dlt_background_mixed.py
.py
"""Background mode with per-item routing: a mixed dataset under run_in_background=True returns an immediate handle and completes detached, with the manifest taking the DLT route and the document the standard route — one cognify_pipeline run, one terminal status, both artifact families present. The reviewer's verificat...
174
6,756
cognee
cognee/tests/integration/tasks/test_graph_provenance_delete_part2.py
.py
"""End-to-end graph-provenance delete tests on the real default stack. Runs the full add -> cognify -> delete pipeline against real Ladybug + LanceDB + SQLite. The LLM (entity/summary extraction) is mocked for a deterministic graph, and embeddings are stubbed to fixed zero vectors — these tests never *retrieve*, they ...
193
7,973
cognee
cognee/tests/integration/tasks/test_consolidate_entities_integration.py
.py
"""Real-backend integration test for the consolidate_entities pipeline. Unlike the mocked unit tests in ``cognee/tests/unit/memify_pipelines/test_consolidate_entities_pipeline.py``, this exercises the whole pipeline against the real default stack (Kuzu graph + LanceDB vectors) with real embeddings produced by the conf...
155
6,910
cognee
cognee/tests/integration/tasks/test_dlt_orphan_graph_vector_purge.py
.py
"""A row hard-deleted upstream must vanish from ALL per-dataset stores (relational, graph, vector) after a re-sync, under multi-user access control. Mechanism, under stable manifest identity: an explicit re-ingest (add(..., incremental_loading=False, data_cache=False) — plain add() is idempotent and skips completed it...
327
13,511
cognee
cognee/tests/integration/tasks/test_get_triplet_datapoints.py
.py
import os import pathlib import pytest import pytest_asyncio from unittest.mock import AsyncMock, patch import cognee from cognee.tasks.memify.get_triplet_datapoints import get_triplet_datapoints from cognee.modules.engine.models import Triplet @pytest_asyncio.fixture async def setup_test_environment(): """Set u...
70
2,663
cognee
cognee/tests/integration/tasks/test_add_foreground_orphan_cleanup.py
.py
"""Regression: a foreground ``add()`` must run the deferred DLT orphan_cleanup. ``resolve_dlt_sources`` returns a deferred ``orphan_cleanup`` that forgets rows deleted upstream. ``add()`` used to await it only for ``run_in_background=True``, so forget-on-source-deletion was silently broken in the default (foreground) ...
129
4,682
cognee
cognee/tests/integration/tasks/test_dlt_stable_id_reprocess.py
.py
"""E2E of the stable-manifest-id lifecycle: change one row, never vanish. The manifest data_id is stable (dlt_source:{dataset}:{source}), so a re-sync with changed content updates the Data row in place — the source must never be absent from the relational store between add and cognify. Re-cognify then purges the sourc...
199
7,466
cognee
cognee/tests/integration/tasks/test_dlt_csv_loader_route.py
.py
"""A CSV through plain add()/cognify() must take the DLT route via the loader engine. CSV handling moved out of resolve_dlt_sources into the loader system: ``dlt_csv_loader`` (registered above the text-flattening ``csv_loader``) runs staging ingestion inside the ingest pipeline and returns the manifest as a ``LoaderRe...
162
6,579
cognee
cognee/tests/integration/shared/test_usage_logger_integration.py
.py
"""Integration tests for usage logger with real Redis components.""" import os import pytest import asyncio from datetime import datetime, timezone from types import SimpleNamespace from uuid import UUID from unittest.mock import patch from cognee.shared.usage_logger import log_usage from cognee.infrastructure.databa...
256
9,371
cognee
cognee/tests/integration/documents/TextDocument_test.py
.py
import os import sys import uuid import pytest import pathlib from unittest.mock import patch from cognee.modules.chunking.TextChunker import TextChunker from cognee.modules.data.processing.document_types.TextDocument import TextDocument from cognee.tests.integration.documents.AudioDocument_test import mock_get_embedd...
61
2,159
cognee
cognee/tests/integration/documents/ImageDocument_test.py
.py
import sys import uuid import pytest from unittest.mock import patch from cognee.modules.chunking.TextChunker import TextChunker from cognee.modules.data.processing.document_types.ImageDocument import ImageDocument from cognee.tests.integration.documents.AudioDocument_test import mock_get_embedding_engine from cognee....
50
2,802
cognee
cognee/tests/integration/documents/UnstructuredDocument_test.py
.py
import os import sys import uuid import pytest import pathlib from unittest.mock import patch from cognee.modules.chunking.TextChunker import TextChunker from cognee.modules.data.processing.document_types.UnstructuredDocument import UnstructuredDocument from cognee.tests.integration.documents.AudioDocument_test import...
111
4,006
cognee
cognee/tests/integration/documents/async_gen_zip.py
.py
async def async_gen_zip(iterable1, async_iterable2): it1 = iter(iterable1) it2 = async_iterable2.__aiter__() while True: try: val1 = next(it1) val2 = await it2.__anext__() yield val1, val2 except (StopIteration, StopAsyncIteration): break
13
317
cognee
cognee/tests/integration/documents/PdfDocument_test.py
.py
import os import sys import uuid import pytest import pathlib from unittest.mock import patch from cognee.modules.chunking.TextChunker import TextChunker from cognee.modules.data.processing.document_types.PdfDocument import PdfDocument from cognee.tests.integration.documents.AudioDocument_test import mock_get_embeddin...
52
1,798
cognee
cognee/tests/integration/documents/CsvDocument_test.py
.py
import os import sys import uuid import pytest import pathlib from unittest.mock import patch from cognee.modules.chunking.CsvChunker import CsvChunker from cognee.modules.data.processing.document_types.CsvDocument import CsvDocument from cognee.tests.integration.documents.AudioDocument_test import mock_get_embedding_...
71
2,641
cognee
cognee/tests/integration/documents/AudioDocument_test.py
.py
import sys import uuid import pytest from unittest.mock import patch from cognee.modules.chunking.TextChunker import TextChunker from cognee.modules.data.processing.document_types.AudioDocument import AudioDocument from cognee.tests.integration.documents.async_gen_zip import async_gen_zip chunk_by_sentence_module = s...
67
2,790
cognee
cognee/tests/integration/web_url_crawler/test_keenable_crawler.py
.py
import os import pytest from cognee.tasks.web_scraper.utils import fetch_with_keenable skip_in_ci = pytest.mark.skipif( os.getenv("GITHUB_ACTIONS") == "true", reason="Skipping in Github for now - before we get KEENABLE_API_KEY", ) skip_without_key = pytest.mark.skipif( not os.getenv("KEENABLE_API_KEY"), ...
26
646
cognee
cognee/tests/integration/web_url_crawler/test_tavily_crawler.py
.py
import os import pytest from cognee.tasks.web_scraper.utils import fetch_with_tavily skip_in_ci = pytest.mark.skipif( os.getenv("GITHUB_ACTIONS") == "true", reason="Skipping in Github for now - before we get TAVILY_API_KEY", ) @skip_in_ci @pytest.mark.asyncio async def test_fetch(): url = "http://example...
20
493
cognee
cognee/tests/integration/web_url_crawler/test_url_adding_e2e.py
.py
import os import pytest import cognee from cognee.infrastructure.files.utils.get_data_file_path import get_data_file_path from cognee.infrastructure.loaders.LoaderEngine import LoaderEngine from cognee.infrastructure.loaders.external.beautiful_soup_loader import BeautifulSoupLoader from cognee.tasks.ingestion import sa...
331
11,127
cognee
cognee/tests/integration/web_url_crawler/test_default_url_crawler.py
.py
import pytest from cognee.tasks.web_scraper import DefaultUrlCrawler @pytest.mark.asyncio async def test_fetch(): crawler = DefaultUrlCrawler() url = "http://example.com/" results = await crawler.fetch_urls(url) assert len(results) == 1 assert isinstance(results, dict) html = results[url] ...
14
349
cognee
cognee/tests/integration/infrastructure/llm/test_embedding_tokenizer_delegation.py
.py
"""Each embedding engine must delegate tokenizer selection to ``resolve_embedding_tokenizer`` (issue #3646). The resolver's own selection logic is covered in ``test_tokenizer_resolver.py``. These tests lock in the *wiring*: if an engine re-hardcodes a tokenizer in its ``get_tokenizer()`` (the exact fastembed ``gpt-4o`...
116
3,751
cognee
cognee/tests/integration/infrastructure/dataset_queue/test_dataset_queue_integration.py
.py
"""Integration-style tests for Dataset Queue with pipeline-shaped operations. These tests demonstrate how the dataset queue should integrate with the async-generator shape used by ``run_pipeline_per_dataset``. """ import asyncio from uuid import uuid4 import pytest from unittest.mock import patch DATASET_QUEUE_MODU...
140
5,362
cognee
cognee/tests/integration/infrastructure/session/test_session_manager_redis.py
.py
"""Integration tests for SessionManager with RedisAdapter.""" import pytest from unittest.mock import AsyncMock, MagicMock, patch from cognee.infrastructure.session.feedback_models import ( AgentTraceFeedbackSummary, FeedbackDetectionResult, ) from cognee.infrastructure.session.session_manager import SessionM...
508
18,494
cognee
cognee/tests/integration/infrastructure/session/test_tapes_cache_adapter.py
.py
import tempfile from unittest.mock import AsyncMock, MagicMock, patch import pytest @pytest.fixture def tapes_adapter(): """TapesCacheAdapter rooted in a temp cache directory.""" with tempfile.TemporaryDirectory() as tmpdir: with patch( "cognee.infrastructure.databases.cache.fscache.FsCac...
136
4,629
cognee
cognee/tests/integration/infrastructure/session/test_session_manager_fs.py
.py
import tempfile from unittest.mock import AsyncMock, MagicMock, patch import pytest from cognee.infrastructure.session.feedback_models import ( AgentTraceFeedbackSummary, FeedbackDetectionResult, ) from cognee.infrastructure.session.session_manager import SessionManager @pytest.fixture def fs_adapter(): ...
450
16,509
cognee
cognee/tests/integration/infrastructure/session/test_session_context_turn_flow.py
.py
"""Integration-style tests for the session-context turn flow. These exercise SessionManager._generate_completion_with_session_inner against a REAL FS-backed cache (so the session-context CRUD round-trips) while the LLM calls are mocked. They cover the four branches: 1. first-turn -> no served context, empty b...
426
15,848
cognee
cognee/tests/integration/infrastructure/session/test_session_context_fs.py
.py
import tempfile from unittest.mock import patch import pytest from cognee.infrastructure.session.session_manager import SessionManager @pytest.fixture def fs_adapter(): """FsCacheAdapter with temp directory.""" with tempfile.TemporaryDirectory() as tmpdir: with patch( "cognee.infrastruct...
202
7,830
cognee
cognee/tests/integration/infrastructure/session/test_session_concurrent_turn_flow.py
.py
"""Integration-style tests for a concurrent session turn against a REAL cache adapter. The unit tests for `session_concurrent_turn` fake the session manager entirely, so nothing there would notice if `commit_turn`'s `add_qa` call stopped matching the real signature — `commit_turn` fails open on that write by design, s...
172
5,922
cognee
cognee/tests/integration/infrastructure/session/test_session_sdk_integration.py
.py
import asyncio import sys import tempfile from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock, patch from uuid import uuid4 import pytest import cognee from cognee.infrastructure.databases.cache.models import SessionQAEntry from cognee.infrastructure.session.session_manager import Session...
298
10,461
cognee
cognee/tests/integration/infrastructure/session/test_session_persistence_memify_integration.py
.py
import asyncio import os import pathlib import sys import tempfile from unittest.mock import MagicMock, patch import pytest import pytest_asyncio import cognee from cognee.context_global_variables import graph_db_config, vector_db_config from cognee.infrastructure.databases.graph import get_graph_engine from cognee.i...
663
24,678
cognee
cognee/tests/integration/infrastructure/session/test_session_manager_sql.py
.py
"""Integration tests for SessionManager with SqlCacheAdapter (aiosqlite-backed).""" import asyncio import tempfile import pytest from sqlalchemy import select from unittest.mock import AsyncMock, MagicMock, patch from cognee.infrastructure.databases.cache.sql.SqlCacheAdapter import SqlCacheAdapter from cognee.infras...
505
18,891
cognee
cognee/tests/integration/infrastructure/session/test_feedback_weights_memify_integration.py
.py
import asyncio import tempfile from unittest.mock import MagicMock, patch import pytest from cognee.infrastructure.session.session_manager import SessionManager from cognee.tasks.memify.apply_feedback_weights import apply_feedback_weights from cognee.tasks.memify.extract_feedback_qas import extract_feedback_qas from c...
211
7,538
cognee
cognee/tests/integration/infrastructure/graph/test_graph_provenance_adapter_contract.py
.py
"""Backend-neutral graph-provenance adapter contract tests. Add a provider to ``graph_provenance_adapter`` when implementing graph provenance for a new graph backend. These tests use only public graph adapter methods and provenance helpers; backend storage details belong in adapter- specific tests. """ from __future_...
591
23,986
cognee
cognee/tests/integration/infrastructure/graph/test_ladybug_provenance_checkpoint.py
.py
"""Ladybug/Kuzu checkpoint regressions for scalar graph provenance columns.""" from __future__ import annotations from uuid import UUID, uuid4 import pytest from cognee.infrastructure.databases.provenance import EdgeIdentity, make_source_ref_key from cognee.modules.chunking.models.DocumentChunk import DocumentChunk...
177
6,227
cognee
cognee/tests/integration/infrastructure/graph/test_graph_provenance_unified_contract.py
.py
"""Backend-neutral graph-provenance contract through UnifiedStoreEngine. Add a provider to ``graph_provenance_unified_engine`` when a graph backend claims support for graph-provenance delete/rollback. These tests use a real graph adapter and a recording vector engine so failures point at graph provenance behavior or p...
243
9,395
cognee
cognee/tests/integration/infrastructure/graph/test_kuzu_adapter.py
.py
"""Tests for KuzuAdapter in both local and subprocess-proxy modes. The subprocess mode uses ``get_graph_engine`` with ``graph_database_subprocess_enabled=True`` so the native ``kuzu.Database`` / ``kuzu.Connection`` live in a worker process while the adapter stays in the main process. """ import json import os from pa...
893
31,904
cognee
cognee/tests/integration/infrastructure/graph/test_ladybug_provenance_storage.py
.py
"""Ladybug/Kuzu-specific graph-provenance storage-shape tests.""" from __future__ import annotations from uuid import uuid4 import pytest from cognee.infrastructure.databases.provenance import EdgeIdentity, make_source_ref_key from cognee.infrastructure.engine import DataPoint try: from cognee.infrastructure.d...
173
5,288
cognee
cognee/tests/integration/infrastructure/graph/test_kuzu_neo4j_neighbors.py
.py
import json import os from pathlib import Path import pytest import cognee from cognee.shared.data_models import KnowledgeGraph from cognee.infrastructure.databases.graph.ladybug.adapter import LadybugAdapter from cognee.infrastructure.databases.graph.neo4j_driver.adapter import Neo4jAdapter DEMO_KG_PATH = os.path....
112
3,493
cognee
cognee/tests/integration/modules/agent_memory/test_agent_memory_integration.py
.py
"""Integration tests for the public cognee.agent_memory decorator behavior.""" import importlib from pathlib import Path from unittest.mock import AsyncMock, patch from uuid import uuid4 import pytest import pytest_asyncio import cognee from cognee.context_global_variables import graph_db_config, vector_db_config fr...
623
22,429
cognee
cognee/tests/integration/retrieval/test_brute_force_triplet_search_with_cognify.py
.py
import pathlib import pytest import pytest_asyncio import cognee from cognee.infrastructure.engine import DataPoint from cognee.modules.graph.cognee_graph.CogneeGraphElements import Edge from cognee.modules.retrieval.utils.brute_force_triplet_search import brute_force_triplet_search from cognee.low_level import setup...
155
5,784
cognee
cognee/tests/integration/retrieval/test_triplet_retriever.py
.py
import os import pytest import pathlib import pytest_asyncio import cognee from cognee.low_level import setup from cognee.tasks.storage import add_data_points from cognee.modules.retrieval.exceptions.exceptions import NoDataError from cognee.modules.retrieval.triplet_retriever import TripletRetriever from cognee.modul...
129
4,215
cognee
cognee/tests/integration/retrieval/test_structured_output.py
.py
import asyncio import os import pytest import pathlib import pytest_asyncio import cognee from pydantic import BaseModel from cognee.low_level import setup, DataPoint from cognee.tasks.storage import add_data_points from cognee.modules.chunking.models import DocumentChunk from cognee.modules.data.processing.document_t...
234
8,382
cognee
cognee/tests/integration/retrieval/test_graph_completion_decomposition_retriever.py
.py
import pathlib from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock, patch import pytest import pytest_asyncio import cognee from cognee.infrastructure.session.session_manager import SessionManager from cognee.low_level import DataPoint from cognee.low_level import setup as cognee_setup fr...
310
11,072
cognee
cognee/tests/integration/retrieval/test_temporal_retriever.py
.py
import os import pytest import pathlib import pytest_asyncio import cognee from cognee.low_level import setup, DataPoint from cognee.tasks.storage import add_data_points from cognee.modules.retrieval.temporal_retriever import TemporalRetriever from cognee.modules.engine.models.Event import Event from cognee.modules.en...
337
11,193
cognee
cognee/tests/integration/retrieval/test_summaries_retriever.py
.py
import os import pytest import pathlib import pytest_asyncio import cognee from cognee.low_level import setup from cognee.tasks.storage import add_data_points from cognee.infrastructure.databases.vector import get_vector_engine_async from cognee.modules.chunking.models import DocumentChunk from cognee.tasks.summarizat...
208
6,401
cognee
cognee/tests/integration/retrieval/test_graph_completion_retriever_context_extension.py
.py
import os import pytest import pathlib import pytest_asyncio from typing import Optional, Union import cognee from cognee.low_level import setup, DataPoint from cognee.tasks.storage import add_data_points from cognee.modules.graph.utils import resolve_edges_to_text from cognee.modules.retrieval.graph_completion_contex...
361
14,024
cognee
cognee/tests/integration/retrieval/test_rag_completion_retriever.py
.py
import os from typing import List import pytest import pathlib import pytest_asyncio import cognee from cognee.low_level import setup from cognee.tasks.storage import add_data_points from cognee.infrastructure.databases.vector import get_vector_engine_async from cognee.modules.chunking.models import DocumentChunk from...
336
10,754
cognee
cognee/tests/integration/retrieval/test_bm25_retriever.py
.py
import pytest import pathlib import pytest_asyncio import cognee from cognee.low_level import setup as setup_databases from cognee.tasks.storage import add_data_points from cognee.modules.chunking.models import DocumentChunk from cognee.modules.data.processing.document_types import TextDocument from cognee.modules.ret...
83
2,806
cognee
cognee/tests/integration/retrieval/test_chunks_retriever.py
.py
import os import pytest import pathlib import pytest_asyncio from typing import List import cognee from cognee.low_level import setup from cognee.tasks.storage import add_data_points from cognee.infrastructure.databases.vector import get_vector_engine_async from cognee.modules.chunking.models import DocumentChunk from...
352
11,926
cognee
cognee/tests/integration/retrieval/test_graph_completion_retriever.py
.py
import os import pytest import pathlib import pytest_asyncio from typing import Optional, Union import cognee from cognee.low_level import setup, DataPoint from cognee.tasks.storage import add_data_points from cognee.modules.retrieval.graph_completion_retriever import GraphCompletionRetriever def _detailed_context_c...
377
14,430
cognee
cognee/tests/integration/retrieval/test_graph_completion_retriever_cot.py
.py
import pytest import pathlib import pytest_asyncio from typing import Optional, Union import cognee from cognee.exceptions import CogneeValidationError from cognee.low_level import setup, DataPoint from cognee.tasks.storage import add_data_points from cognee.modules.retrieval.graph_completion_cot_retriever import Grap...
329
12,669
cognee
cognee/tests/backwards_compatibility/phase2_verify.py
.py
""" Backwards Compatibility Test Phase 1 - run with a legacy cognee version Seeds the database with Lorem Ipsum data: add → cognify → search. Phase 2 - run with current Cognee branch Runs startup migrations (relational + graph + vector), then verifies that the legacy-seeded graph, vector AND relational-ledger data...
883
41,101
cognee
cognee/tests/backwards_compatibility/phase1_seed.py
.py
""" Backwards Compatibility Test Phase 1 - run with a legacy cognee version Seeds the database with Lorem Ipsum data: add → cognify → search. Also seeds a session (two entries via session-mode remember) and bridges it into the graph via improve() — leaving a genuine pre-watermark session cache for Phase 2 to take ov...
166
7,109
cognee
cognee/tests/subprocesses/writer.py
.py
import asyncio import time import uuid from cognee.infrastructure.databases.graph.ladybug.adapter import LadybugAdapter from cognee.modules.data.processing.document_types import PdfDocument from common import get_kuzu_db_path def create_node(name): return PdfDocument( id=uuid.uuid4(), name=name, ...
33
740
cognee
cognee/tests/subprocesses/simple_cognify_2.py
.py
import asyncio import cognee from cognee.api.v1.search import SearchType from cognee.shared.logging_utils import INFO, setup_logging from common import configure_cognee_for_subprocess async def main(): configure_cognee_for_subprocess(cognee) await cognee.cognify(datasets=["second_cognify_dataset"]) que...
36
960
cognee
cognee/tests/subprocesses/simple_cognify_1.py
.py
import asyncio import cognee from cognee.api.v1.search import SearchType from cognee.shared.logging_utils import INFO, setup_logging from common import configure_cognee_for_subprocess async def main(): configure_cognee_for_subprocess(cognee) await cognee.cognify(datasets=["first_cognify_dataset"]) quer...
36
957
cognee
cognee/tests/subprocesses/common.py
.py
import os def configure_cognee_for_subprocess(cognee): data_root_directory = os.getenv("COGNEE_TEST_DATA_ROOT") system_root_directory = os.getenv("COGNEE_TEST_SYSTEM_ROOT") if data_root_directory: cognee.config.data_root_directory(data_root_directory) if system_root_directory: cognee....
16
465
cognee
cognee/tests/subprocesses/reader.py
.py
import asyncio from cognee.infrastructure.databases.graph.ladybug.adapter import LadybugAdapter from common import get_kuzu_db_path async def main(): adapter = LadybugAdapter(get_kuzu_db_path()) for _ in range(5): result = await adapter.query("MATCH (n:Node) RETURN COUNT(n)") print(f"Reader:...
20
514
cognee
cognee/tests/cli_tests/cli_integration_tests/test_cli_integration.py
.py
""" Integration tests for CLI commands that test end-to-end functionality. """ import tempfile import os import sys import subprocess from pathlib import Path from unittest.mock import patch, MagicMock class TestCliIntegration: """Integration tests for CLI commands""" def test_cli_help(self): """Tes...
324
11,040
cognee
cognee/tests/cli_tests/cli_integration_tests/__init__.py
.py
""" CLI integration tests package. """
4
39
cognee
cognee/tests/cli_tests/cli_unit_tests/test_cli_runner.py
.py
""" Test runner and utilities for CLI tests. """ import pytest import sys from pathlib import Path def run_cli_tests(): """Run all CLI tests""" test_dir = Path(__file__).parent integration_dir = test_dir.parent.parent / "integration" / "cli" cli_unit_test_files = [ "test_cli_main.py", ...
63
1,497
cognee
cognee/tests/cli_tests/cli_unit_tests/test_cli_commands.py
.py
""" Tests for individual CLI commands with proper mocking and coroutine handling. """ import os import pytest import sys import argparse import asyncio from uuid import uuid4 from unittest.mock import patch, MagicMock, AsyncMock, ANY import cognee from cognee.cli.commands.add_command import AddCommand from cognee.cli....
750
28,215
cognee
cognee/tests/cli_tests/cli_unit_tests/test_user_resolution.py
.py
"""Unit tests for cognee.cli.user_resolution.""" import asyncio from unittest.mock import AsyncMock, patch, MagicMock import pytest from cognee.cli.user_resolution import resolve_cli_user from cognee.infrastructure.databases.exceptions import EntityNotFoundError class TestResolveCliUser: def test_none_returns_...
52
2,263
cognee
cognee/tests/cli_tests/cli_unit_tests/test_api_dispatch.py
.py
"""Unit tests for cognee.cli.api_dispatch.""" import argparse from unittest.mock import MagicMock, patch import pytest from cognee.cli.api_dispatch import can_dispatch, dispatch, SUPPORTED_COMMANDS class TestCanDispatch: def test_false_when_no_api_url(self): args = argparse.Namespace(api_url=None, comm...
180
6,854
cognee
cognee/tests/cli_tests/cli_unit_tests/test_cli_utils.py
.py
""" Tests for CLI utility functions and helper modules. """ from cognee.cli import debug from cognee.cli.config import ( CLI_DESCRIPTION, DEFAULT_DOCS_URL, COMMAND_DESCRIPTIONS, SEARCH_TYPE_CHOICES, CHUNKER_CHOICES, OUTPUT_FORMAT_CHOICES, ) from cognee.cli._cognee import _discover_commands cl...
127
4,299
cognee
cognee/tests/cli_tests/cli_unit_tests/__init__.py
.py
""" CLI unit tests package. """
4
32
cognee
cognee/tests/cli_tests/cli_unit_tests/test_hints.py
.py
"""Unit tests for CLI next-step hint helpers. The hints module renders the "Next: ..." line after each primary command. These tests pin the exact copy so a reword is a deliberate change, and that the empty-recall hint points the user back at ``remember``. """ import pytest from cognee.cli import hints @pytest.fixt...
36
1,065
cognee
cognee/tests/cli_tests/cli_unit_tests/test_api_client.py
.py
"""Unit tests for cognee.cli.api_client.""" import io import os import tempfile from unittest.mock import MagicMock, patch import pytest from cognee.cli.api_client import CogneeApiClient, is_connection_error class TestCogneeApiClientInit: """Test client construction and URL helpers.""" def test_base_url_t...
218
8,900
cognee
cognee/tests/cli_tests/cli_unit_tests/test_push_command.py
.py
""" Tests for the push CLI command with proper mocking and coroutine handling. """ import argparse import asyncio from uuid import uuid4 from unittest.mock import patch, MagicMock, AsyncMock import pytest from cognee.api.v1.push.push import PushResult from cognee.cli.commands.push_command import PushCommand from cog...
253
9,271
cognee
cognee/tests/cli_tests/cli_unit_tests/test_cli_edge_cases.py
.py
""" Tests for CLI edge cases and error scenarios with proper mocking. """ import os import pytest import sys import asyncio import argparse from uuid import uuid4 from unittest.mock import patch, MagicMock, AsyncMock, ANY import cognee from cognee.cli.commands.add_command import AddCommand from cognee.cli.commands.se...
668
24,945
cognee
cognee/tests/cli_tests/cli_unit_tests/test_remediation.py
.py
"""Unit tests for the CLI first-run remediation table. Behaviour under test: for each documented failure mode, the substring match resolves to the correct actionable hint. The messages here are the real strings the runtime produces (or the ``str()`` of the real raised exception), not synthetic stand-ins — a needle tha...
98
3,551
cognee
cognee/tests/cli_tests/cli_unit_tests/test_cli_main.py
.py
""" Tests for the main CLI entry point and command discovery. """ import pytest import argparse from unittest.mock import patch, MagicMock from cognee.cli._cognee import main, _discover_commands, _create_parser from cognee.cli.exceptions import CliCommandException, CliCommandInnerException class TestCliMain: """...
174
6,143
cognee
cognee/tests/api/test_conditional_authentication_endpoints.py
.py
import pytest from unittest.mock import patch, AsyncMock, MagicMock from uuid import uuid4 from fastapi.testclient import TestClient from types import SimpleNamespace import importlib with patch("dotenv.load_dotenv"): # This prevents the .env file from ever loading during tests import os os.environ["REQU...
257
10,712
cognee
cognee/tests/api/test_multi_tenant_access_control_e2e.py
.py
"""Multi-tenant access-control end-to-end API tests (#3369). Proves tenant isolation end-to-end with ENABLE_BACKEND_ACCESS_CONTROL=true against the Cognee API using FastAPI's TestClient. Acceptance criteria from the issue: - Two users, each with their own dataset. - User B cannot read / search / delete User A's d...
287
10,633
cognee
cognee/tests/api/test_settings_authorization.py
.py
import os import pytest from unittest.mock import patch with patch("dotenv.load_dotenv"): os.environ["REQUIRE_AUTHENTICATION"] = "true" os.environ["ENABLE_BACKEND_ACCESS_CONTROL"] = "false" os.environ["HASH_API_KEY"] = "false" from fastapi.testclient import TestClient TEST_USER_EMAIL = "settings_tes...
86
2,885
cognee
cognee/tests/api/test_backend_auth.py
.py
import os import uuid import asyncio import pytest from unittest.mock import patch with patch("dotenv.load_dotenv"): os.environ["REQUIRE_AUTHENTICATION"] = "true" os.environ["ENABLE_BACKEND_ACCESS_CONTROL"] = "false" os.environ["HASH_API_KEY"] = "false" from fastapi.testclient import TestClient TEST...
164
6,260
cognee
cognee/tests/api/test_agents_e2e.py
.py
"""End-to-end tests for all /api/v1/agents/* endpoints. Exercises every route in the merged agents router against a real FastAPI TestClient with authentication enabled. The operations layer is patched only where it reaches into session-trace infrastructure that isn't available in a lightweight test context — everythi...
1,096
43,689
cognee
cognee/tests/api/test_agent_endpoints.py
.py
import os import uuid import pytest from unittest.mock import patch with patch("dotenv.load_dotenv"): os.environ["REQUIRE_AUTHENTICATION"] = "true" os.environ["ENABLE_BACKEND_ACCESS_CONTROL"] = "false" os.environ["HASH_API_KEY"] = "false" from fastapi.testclient import TestClient RUN_ID = uuid.uuid4(...
111
3,546
cognee
cognee/tests/api/test_agent_mode.py
.py
import os import uuid import pytest from unittest.mock import patch, MagicMock with patch("dotenv.load_dotenv"): os.environ["REQUIRE_AUTHENTICATION"] = "true" os.environ["ENABLE_BACKEND_ACCESS_CONTROL"] = "false" os.environ["COGNEE_AGENT_MODE"] = "true" from fastapi.testclient import TestClient from ...
173
6,289
cognee
cognee/tests/unit/test_litellm_embedding_sanitize.py
.py
from types import SimpleNamespace from unittest.mock import AsyncMock, Mock, patch import pytest from cognee.infrastructure.databases.vector.embeddings.LiteLLMEmbeddingEngine import ( LiteLLMEmbeddingEngine, ) @pytest.mark.asyncio async def test_embed_text_filters_invalid_inputs(monkeypatch): # Use monkeypa...
127
4,311
cognee
cognee/tests/unit/test_litellm_embedding_auth_fastfail.py
.py
"""Regression test: the embedding engine must NOT retry on auth failures. Rationale: prior to the fix, the tenacity ``retry`` decorator only skipped ``NotFoundError`` and ``CancelledError``. On an invalid ``LLM_API_KEY`` litellm raised ``AuthenticationError`` and the engine walked the full 8s -> 128s exponential backo...
103
3,359
cognee
cognee/tests/unit/test_add_parent_user_id_migration.py
.py
import importlib.util from pathlib import Path from types import SimpleNamespace from unittest.mock import MagicMock _MIGRATION_PATH = ( Path(__file__).resolve().parents[2] / "alembic" / "versions" / "7c5d4e2f8a91_add_parent_user_id_to_users.py" ) _SPEC = importlib.util.spec_from_file_location("parent...
73
2,538
cognee
cognee/tests/unit/test_run_migrations.py
.py
"""Tests for startup migrations (cognee/modules/migrations/startup.py + runner). Originally written against cognee/run_migrations.py; the implementation moved to cognee.modules.migrations.{startup,runner} (run_migrations.py is now a thin shim). The original intents are preserved: * Alembic runs IN-PROCESS so progra...
338
14,697
cognee
cognee/tests/unit/test_context_global_variables.py
.py
from types import SimpleNamespace from uuid import uuid4 import pytest from cognee.context_global_variables import ( current_dataset_id, embedding_config, graph_db_config, llm_config, set_database_global_context_variables, vector_db_config, ) from cognee.infrastructure.databases.vector.embeddi...
165
5,884