import pytest
import threading
from pathlib import Path
from project_brain.graph.sqlite_store import SqliteStore
from project_brain.graph.models import Edge
@pytest.fixture
def store(tmp_dir):
s = SqliteStore(tmp_dir / "db")
yield s
s.close()
def test_add_and_get_node(store):
store.add_node({"id": "fn_1", "type": "function", "name": "foo"})
node = store.get_node("fn_1")
assert node is not None
assert node["name"] == "foo"
def test_get_node_not_found(store):
assert store.get_node("nonexistent") is None
def test_get_nodes_by_type(store):
store.add_node({"id": "fn_1", "type": "function", "name": "foo"})
store.add_node({"id": "fn_2", "type": "function", "name": "bar"})
store.add_node({"id": "cls_1", "type": "class", "name": "Baz"})
assert len(store.get_nodes_by_type("function")) == 2
assert len(store.get_nodes_by_type("class")) == 1
def test_update_node(store):
store.add_node({"id": "fn_1", "type": "function", "name": "foo"})
store.update_node("fn_1", {"name": "bar"})
assert store.get_node("fn_1")["name"] == "bar"
def test_delete_node(store):
store.add_node({"id": "fn_1", "type": "function", "name": "foo"})
store.delete_node("fn_1")
assert store.get_node("fn_1") is None
def test_add_and_get_edges(store):
store.add_edge(Edge(id="e1", type="CALL", source="fn_1", target="fn_2"))
out_edges = store.get_edges("fn_1", direction="out")
assert len(out_edges) == 1
assert out_edges[0].target == "fn_2"
in_edges = store.get_edges("fn_2", direction="in")
assert len(in_edges) == 1
def test_get_edges_filter_type(store):
store.add_edge(Edge(id="e1", type="CALL", source="fn_1", target="fn_2"))
store.add_edge(Edge(id="e2", type="DEPEND", source="fn_1", target="mod_1"))
assert len(store.get_edges("fn_1", edge_type="CALL", direction="out")) == 1
assert len(store.get_edges("fn_1", edge_type="DEPEND", direction="out")) == 1
def test_delete_edges(store):
store.add_edge(Edge(id="e1", type="CALL", source="fn_1", target="fn_2"))
store.delete_edges("fn_1")
assert len(store.get_edges("fn_1", direction="out")) == 0
def test_get_neighbors(store):
store.add_node({"id": "fn_1", "type": "function", "name": "foo"})
store.add_node({"id": "fn_2", "type": "function", "name": "bar"})
store.add_edge(Edge(id="e1", type="CALL", source="fn_1", target="fn_2"))
neighbors = store.get_neighbors("fn_1", direction="out")
assert len(neighbors) == 1
assert neighbors[0]["id"] == "fn_2"
def test_save_and_load(tmp_dir):
store1 = SqliteStore(tmp_dir)
store1.add_node({"id": "fn_1", "type": "function", "name": "foo"})
store1.add_edge(Edge(id="e1", type="CALL", source="fn_1", target="fn_2"))
store1.save(str(tmp_dir))
store1.close()
store2 = SqliteStore(tmp_dir)
store2.load(str(tmp_dir))
assert store2.get_node("fn_1") is not None
assert len(store2.get_edges("fn_1", direction="out")) == 1
store2.close()
def test_store_can_be_updated_from_watcher_thread(tmp_dir):
store = SqliteStore(tmp_dir / "threaded")
errors = []
def write():
try:
store.add_node({"id": "thread_node", "type": "file", "path": "x.py"})
except Exception as exc:
errors.append(exc)
thread = threading.Thread(target=write)
thread.start()
thread.join(timeout=5)
assert not errors
assert store.get_node("thread_node") is not None
store.close()
def test_both_direction_respects_edge_type(store):
store.add_edge(Edge(id="call", type="CALL", source="a", target="b"))
store.add_edge(Edge(id="contain", type="CONTAIN", source="a", target="c"))
edges = store.get_edges("a", edge_type="CALL", direction="both")
assert [edge.id for edge in edges] == ["call"]
def test_transaction_rolls_back_batch(store):
store.add_node({"id": "before", "type": "file"})
with pytest.raises(RuntimeError):
with store.transaction():
store.delete_node("before")
store.add_node({"id": "partial", "type": "file"})
raise RuntimeError("rollback")
assert store.get_node("before") is not None
assert store.get_node("partial") is None
def test_transaction_rolls_back_metadata(store):
store.set_metadata("generation", {"id": "before"})
with pytest.raises(RuntimeError):
with store.transaction():
store.set_metadata("generation", {"id": "partial"})
store.set_metadata("new-key", [1, 2, 3])
raise RuntimeError("rollback")
assert store.get_metadata("generation") == {"id": "before"}
assert store.get_metadata("new-key") is None
def test_transaction_rolls_back_base_exception_and_restores_state(store):
store.add_node({"id": "before", "type": "file"})
with pytest.raises(KeyboardInterrupt):
with store.transaction():
store.delete_node("before")
store.add_node({"id": "partial", "type": "file"})
raise KeyboardInterrupt
assert store._transaction_depth == 0
assert not store.conn.in_transaction
assert store.get_node("before") is not None
assert store.get_node("partial") is None
with store.transaction():
store.add_node({"id": "after", "type": "file"})
assert store._transaction_depth == 0
assert store.get_node("after") is not None
def test_nested_transaction_uses_outer_commit_boundary(store):
with store.transaction():
assert store._transaction_depth == 1
store.add_node({"id": "outer", "type": "file"})
with store.transaction():
assert store._transaction_depth == 2
store.add_node({"id": "inner", "type": "file"})
assert store._transaction_depth == 1
assert store.conn.in_transaction
assert store._transaction_depth == 0
assert not store.conn.in_transaction
assert store.get_node("outer") is not None
assert store.get_node("inner") is not None
class _FailOnceCommitConnection:
"""Delegate SQLite operations while injecting one outer commit failure."""
def __init__(self, wrapped):
self.wrapped = wrapped
self.commit_calls = 0
self.rollback_calls = 0
self.fail_next_commit = True
def __getattr__(self, name):
return getattr(self.wrapped, name)
def commit(self):
self.commit_calls += 1
if self.fail_next_commit:
self.fail_next_commit = False
raise RuntimeError("injected commit failure")
return self.wrapped.commit()
def rollback(self):
self.rollback_calls += 1
return self.wrapped.rollback()
def test_outer_commit_failure_rolls_back_and_restores_transaction_depth(store):
store.set_metadata("generation", "before")
connection = _FailOnceCommitConnection(store.conn)
store.conn = connection
with pytest.raises(RuntimeError, match="injected commit failure"):
with store.transaction():
store.set_metadata("generation", "partial")
assert connection.commit_calls == 1
assert connection.rollback_calls == 1
assert store._transaction_depth == 0
assert store.get_metadata("generation") == "before"
with store.transaction():
store.set_metadata("generation", "after")
assert connection.commit_calls == 2
assert store._transaction_depth == 0
assert store.get_metadata("generation") == "after"
def test_autocommit_failure_rolls_back_connection(store):
connection = _FailOnceCommitConnection(store.conn)
store.conn = connection
with pytest.raises(RuntimeError, match="injected commit failure"):
store.add_node({"id": "partial", "type": "file"})
assert connection.rollback_calls == 1
assert not store.conn.in_transaction
assert store.get_node("partial") is None
store.add_node({"id": "after", "type": "file"})
assert store.get_node("after") is not None
def test_delete_edges_by_type(store):
store.add_edge(Edge(id="call", type="CALL", source="a", target="b"))
store.add_edge(Edge(id="contain", type="CONTAIN", source="a", target="c"))
store.delete_edges_by_type({"CALL"})
assert [edge.id for edge in store.get_all_edges()] == ["contain"]