Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

6.0 KB
Raw Blame
"""Shared fixtures for Notes tests."""

import uuid

import pytest
from sqlalchemy import create_engine, event
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool

from local_deep_research.database.models import (
    Base,
    Document,
    SourceType,
    NoteLink,
    NoteVersion,
    Collection,
)


from tests.notes.helpers import _generate_hash


@pytest.fixture(autouse=True)
def _force_synchronous_summary_executor(monkeypatch):
    """update_note submits its LLM change-summary call to a thread pool so the
    HTTP request doesn't block on the LLM. Threading + in-memory SQLite +
    monkeypatched session helpers don't compose well in tests: worker fired
    from test A can race the setup of test B and flake the suite.

    Replace the executor with an inline shim for the whole notes test
    package. Production code path is unaffected.
    """

    class _InlineExecutor:
        def submit(self, fn, *args, **kwargs):
            try:
                fn(*args, **kwargs)
            except Exception:
                pass

            class _Done:
                def result(self_inner):
                    return None

            return _Done()

    monkeypatch.setattr(
        "local_deep_research.research_library.notes.services.note_service._get_summary_executor",
        lambda: _InlineExecutor(),
    )


@pytest.fixture
def in_memory_engine():
    """Create an in-memory SQLite database for testing."""
    # StaticPool + check_same_thread=False: the async notes surface offloads
    # DB work to worker threads (run_db_sync / _offload_db via
    # asyncio.to_thread); those threads must see the SAME in-memory database
    # as the test thread.
    engine = create_engine(
        "sqlite:///:memory:",
        connect_args={"check_same_thread": False},
        poolclass=StaticPool,
    )

    @event.listens_for(engine, "connect")
    def set_sqlite_pragma(dbapi_conn, connection_record):
        cursor = dbapi_conn.cursor()
        cursor.execute("PRAGMA foreign_keys=ON")
        cursor.close()

    Base.metadata.create_all(engine)
    try:
        yield engine
    finally:
        engine.dispose()


@pytest.fixture
def db_session(in_memory_engine):
    """Create a database session for testing."""
    Session = sessionmaker(bind=in_memory_engine)
    session = Session()
    yield session
    session.rollback()
    session.close()


@pytest.fixture
def note_source_type(db_session):
    """Create the 'note' source type for notes."""
    source_type = SourceType(
        id=str(uuid.uuid4()),
        name="note",
        display_name="Note",
        description="User-created notes",
        icon="sticky-note",
    )
    db_session.add(source_type)
    db_session.commit()
    return source_type


@pytest.fixture
def sample_note(db_session, note_source_type):
    """Create a sample note (document with source_type='note') for testing."""
    note_id = str(uuid.uuid4())
    content = "This is sample content for testing."
    note = Document(
        id=note_id,
        title="Sample Note",
        text_content=content,
        file_type="note",
        file_size=0,
        source_type_id=note_source_type.id,
        document_hash=_generate_hash(f"{note_id}:{content}"),
        tags=["test", "sample"],
        favorite=False,
    )
    db_session.add(note)
    db_session.commit()
    return note


@pytest.fixture
def sample_notes(db_session, note_source_type):
    """Create multiple sample notes for testing."""
    notes_data = [
        (
            "Machine Learning Basics",
            "Introduction to machine learning concepts.",
            ["ml", "ai"],
        ),
        (
            "Deep Learning",
            "Neural networks and deep learning.",
            ["dl", "neural-networks"],
        ),
        (
            "Python Programming",
            "Python basics and best practices.",
            ["python", "programming"],
        ),
    ]

    notes = []
    for title, content, tags in notes_data:
        note_id = str(uuid.uuid4())
        note = Document(
            id=note_id,
            title=title,
            text_content=content,
            file_type="note",
            file_size=0,
            source_type_id=note_source_type.id,
            document_hash=_generate_hash(f"{note_id}:{content}"),
            tags=tags,
        )
        notes.append(note)
        db_session.add(note)

    db_session.commit()
    return notes


@pytest.fixture
def linked_notes(db_session, sample_notes):
    """Create notes with wiki-style links between them."""
    source, target1, target2 = sample_notes

    # Create links
    link1 = NoteLink(
        source_document_id=source.id,
        target_document_id=target1.id,
        link_text="Deep Learning",
    )
    link2 = NoteLink(
        source_document_id=source.id,
        target_document_id=target2.id,
        link_text="Python Programming",
    )

    db_session.add_all([link1, link2])
    db_session.commit()

    return {
        "source": source,
        "targets": [target1, target2],
        "links": [link1, link2],
    }


@pytest.fixture
def note_with_versions(db_session, sample_note):
    """Create a note with version history."""
    versions = []
    for i in range(1, 4):
        version = NoteVersion(
            id=str(uuid.uuid4()),
            document_id=sample_note.id,
            title=f"Sample Note v{i}",
            content=f"Content at version {i}",
            tags=["test"],
            change_type="initial" if i == 1 else "manual_save",
            change_summary=f"Version {i}" if i > 1 else None,
            content_hash=f"hash{i}",
        )
        versions.append(version)
        db_session.add(version)

    db_session.commit()

    return {
        "note": sample_note,
        "versions": versions,
    }


@pytest.fixture
def sample_collection(db_session):
    """Create a sample collection."""
    collection = Collection(
        id=str(uuid.uuid4()),
        name="Notes",
        description="Default notes collection",
        collection_type="notes",
    )
    db_session.add(collection)
    db_session.commit()
    return collection