"""Tests for SqliteNetDB — persistent RouterInfo storage.""" import os import tempfile import time import pytest from i2p_netdb.sqlite_netdb import SqliteNetDB @pytest.fixture def db(tmp_path): """Create a SqliteNetDB in a temp directory.""" ndb = SqliteNetDB(str(tmp_path)) yield ndb ndb.close() class TestSqliteNetDBStore: def test_store_and_count(self, db): db.store(b"\x01" * 32, b"routerinfo1") assert db.count() == 1 def test_store_multiple(self, db): for i in range(5): db.store(bytes([i]) * 32, f"data{i}".encode()) assert db.count() == 5 def test_store_replace(self, db): key = b"\xaa" * 32 db.store(key, b"old") db.store(key, b"new") assert db.count() == 1 rows = db.load_all() assert rows[0][1] == b"new" class TestSqliteNetDBLoad: def test_load_all_empty(self, db): assert db.load_all() == [] def test_load_all_returns_non_expired(self, db): key = b"\x01" * 32 db.store(key, b"data", ttl_ms=86_400_000) # 24h TTL rows = db.load_all() assert len(rows) == 1 assert rows[0][0] == key assert rows[0][1] == b"data" def test_load_excludes_expired(self, db): key = b"\x02" * 32 db.store(key, b"expired", ttl_ms=0) # already expired # wait a tiny bit so expires_at < now time.sleep(0.01) rows = db.load_all() assert len(rows) == 0 class TestSqliteNetDBEvict: def test_evict_expired(self, db): db.store(b"\x01" * 32, b"expired", ttl_ms=0) time.sleep(0.01) db.store(b"\x02" * 32, b"fresh", ttl_ms=86_400_000) evicted = db.evict_expired() assert evicted == 1 assert db.count() == 1 def test_evict_nothing(self, db): db.store(b"\x01" * 32, b"fresh", ttl_ms=86_400_000) assert db.evict_expired() == 0 def test_evict_all(self, db): for i in range(3): db.store(bytes([i]) * 32, b"x", ttl_ms=0) time.sleep(0.01) evicted = db.evict_expired() assert evicted == 3 assert db.count() == 0 class TestSqliteNetDBLifecycle: def test_creates_db_file(self, tmp_path): db = SqliteNetDB(str(tmp_path)) db.store(b"\x01" * 32, b"data") db.close() assert (tmp_path / "netdb.sqlite3").exists() def test_creates_parent_dirs(self, tmp_path): nested = tmp_path / "a" / "b" / "c" db = SqliteNetDB(str(nested)) db.store(b"\x01" * 32, b"data") db.close() assert (nested / "netdb.sqlite3").exists() def test_persists_across_open_close(self, tmp_path): db1 = SqliteNetDB(str(tmp_path)) db1.store(b"\x01" * 32, b"persist") db1.close() db2 = SqliteNetDB(str(tmp_path)) rows = db2.load_all() assert len(rows) == 1 assert rows[0][1] == b"persist" db2.close()