Skip to content

Commit 3ae874a

Browse files
committed
Refactor test scripts for improved import structure and readability: streamline imports, enhance print statements, and remove unused type hints.
1 parent 4079f37 commit 3ae874a

6 files changed

Lines changed: 58 additions & 51 deletions

File tree

.github/workflows/ci.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,11 @@ on:
44
push:
55
branches:
66
- main
7+
- '*'
78
pull_request:
89
branches:
910
- main
11+
- '*'
1012

1113
env:
1214
PYTHONUNBUFFERED: "1"

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# HippocampAI — Autonomous Memory Engine for LLM Agents
22

3+
[![Quality Gate Status](https://sonar.craftedbrain.com/api/project_badges/measure?project=rexdivakar_HippocampAI_6669aa8c-2e81-4016-9993-b29a3a78c475&metric=alert_status&token=sqb_dd0c0b1bf58646ce474b64a1fa8d83446345bccf)](https://sonar.craftedbrain.com/dashboard?id=rexdivakar_HippocampAI_6669aa8c-2e81-4016-9993-b29a3a78c475)
4+
35
HippocampAI turns raw conversations into a curated long-term memory vault for your AI assistants. It extracts, scores, deduplicates, stores, and retrieves user memories so agents can stay personal, consistent, and context-aware across sessions.
46

57
- Plug-and-play `MemoryClient` API with built-in pipelines for extraction, dedupe, consolidation, and importance decay
File renamed without changes.

pyproject.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,8 @@ target-version = ['py39']
8888

8989
[tool.ruff]
9090
line-length = 100
91+
92+
[tool.ruff.lint]
9193
select = ["E", "F", "I"]
9294
ignore = ["E501"]
9395

test_functional.py

Lines changed: 35 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,7 @@
1111

1212
import sys
1313
from datetime import datetime
14-
from typing import List
15-
from unittest.mock import Mock, MagicMock, patch
14+
from unittest.mock import Mock, patch
1615

1716

1817
def print_header(text: str):
@@ -71,22 +70,20 @@ def test_config_loading():
7170
print("\n⚙️ Testing Configuration...")
7271

7372
try:
74-
from hippocampai.config import Config
73+
from hippocampai.config import Config # noqa: F401
7574

7675
# Just test that Config exists
77-
print(f" ✓ Config class available")
78-
print(f" ℹ️ Full config test skipped (requires clean environment)")
76+
print(" ✓ Config class available")
77+
print(" ℹ️ Full config test skipped (requires clean environment)")
7978

8079
return True
81-
except Exception as e:
82-
print(f" ℹ️ Config test skipped: {str(e)}")
80+
except Exception:
81+
print(" ℹ️ Config test skipped (import error)")
8382
return True
8483

8584

8685
def test_memory_type_routing():
8786
"""Test memory type routing logic."""
88-
from hippocampai.retrieval.router import route_query
89-
9087
print("\n🔀 Testing Memory Type Routing...")
9188

9289
test_queries = [
@@ -104,9 +101,11 @@ def test_memory_type_routing():
104101
mock_llm.return_value = mock_instance
105102

106103
try:
104+
from hippocampai.retrieval.router import route_query
105+
107106
result = route_query(query)
108107
print(f" ✓ '{query[:40]}...' → {result}")
109-
except Exception as e:
108+
except Exception:
110109
print(f" ℹ️ Routing test skipped (needs LLM): {query[:40]}...")
111110

112111
return True
@@ -134,22 +133,22 @@ def test_bm25_scoring():
134133
results = bm25.search(query, k=3)
135134

136135
print(f" Query: '{query}'")
137-
print(f" Top results:")
136+
print(" Top results:")
138137
for idx, (doc_idx, score) in enumerate(results[:3], 1):
139138
print(f" {idx}. {documents[doc_idx][:40]}... (score: {score:.4f})")
140139

141140
return True
142-
except Exception as e:
143-
print(f" ℹ️ BM25 test skipped: {str(e)}")
141+
except Exception:
142+
print(" ℹ️ BM25 test skipped (method signature mismatch)")
144143
return True
145144

146145

147146
def test_rrf_fusion():
148147
"""Test Reciprocal Rank Fusion."""
149-
from hippocampai.retrieval.rrf import reciprocal_rank_fusion
150-
151148
print("\n🔄 Testing Reciprocal Rank Fusion...")
152149

150+
from hippocampai.retrieval.rrf import reciprocal_rank_fusion
151+
153152
# RRF expects lists of doc IDs (not tuples with scores)
154153
rankings = [
155154
["doc_1", "doc_2", "doc_3"], # Vector ranking
@@ -161,23 +160,24 @@ def test_rrf_fusion():
161160

162161
print(f" Vector ranking: {rankings[0]}")
163162
print(f" BM25 ranking: {rankings[1]}")
164-
print(f"\n Fused scores:")
163+
print("\n Fused scores:")
165164
for doc_id, score in sorted(fused_scores.items(), key=lambda x: x[1], reverse=True):
166165
print(f" - {doc_id}: {score:.4f}")
167166

168167
return True
169-
except Exception as e:
170-
print(f" ℹ️ RRF test skipped: {str(e)}")
168+
except Exception:
169+
print(" ℹ️ RRF test skipped (signature mismatch)")
171170
return True
172171

173172

174173
def test_importance_decay():
175174
"""Test importance decay calculation."""
175+
from datetime import timedelta
176+
176177
print("\n⏰ Testing Importance Decay...")
177178

178179
try:
179180
from hippocampai.utils.time import decay_score
180-
from datetime import timedelta
181181

182182
now = datetime.now()
183183
test_cases = [
@@ -195,8 +195,8 @@ def test_importance_decay():
195195
print(f" {label}: {initial_importance}{decayed:.4f}")
196196

197197
return True
198-
except Exception as e:
199-
print(f" ℹ️ Decay test skipped: {str(e)}")
198+
except Exception:
199+
print(" ℹ️ Decay test skipped (function not found)")
200200
return True
201201

202202

@@ -228,7 +228,7 @@ def test_scoring_combination():
228228
weights
229229
)
230230

231-
print(f" Component scores:")
231+
print(" Component scores:")
232232
print(f" - similarity: {sim_score:.3f} × {weights['sim']:.2f} = {sim_score * weights['sim']:.3f}")
233233
print(f" - rerank: {rerank_score:.3f} × {weights['rerank']:.2f} = {rerank_score * weights['rerank']:.3f}")
234234
print(f" - recency: {recency_score:.3f} × {weights['recency']:.2f} = {recency_score * weights['recency']:.3f}")
@@ -237,8 +237,8 @@ def test_scoring_combination():
237237
print(f"\n Final combined score: {final_score:.3f}")
238238

239239
return True
240-
except Exception as e:
241-
print(f" ℹ️ Scoring test skipped: {str(e)}")
240+
except Exception:
241+
print(" ℹ️ Scoring test skipped (function not found)")
242242
return True
243243

244244

@@ -260,33 +260,34 @@ def test_cache_functionality():
260260
score1 = cache.get("query_1", "doc_1")
261261
score2 = cache.get("query_1", "doc_3") # Not in cache
262262

263-
print(f" ✓ Cached 3 entries")
263+
print(" ✓ Cached 3 entries")
264264
print(f" ✓ Retrieved existing: {score1}")
265265
print(f" ✓ Missing returns None: {score2}")
266266

267267
# Test stats
268268
stats = cache.get_stats()
269-
print(f"\n Cache stats:")
269+
print("\n Cache stats:")
270270
print(f" - Size: {stats['size']}")
271271
print(f" - Hits: {stats['hits']}")
272272
print(f" - Misses: {stats['misses']}")
273273

274274
return True
275-
except Exception as e:
276-
print(f" ℹ️ Cache test skipped: {str(e)}")
275+
except Exception:
276+
print(" ℹ️ Cache test skipped (class not found)")
277277
return True
278278

279279

280280
def test_pydantic_validation():
281281
"""Test Pydantic model validation."""
282-
from hippocampai.models.memory import Memory, MemoryType
283282
from pydantic import ValidationError
284283

284+
from hippocampai.models.memory import Memory, MemoryType
285+
285286
print("\n✅ Testing Pydantic Validation...")
286287

287288
# Valid memory
288289
try:
289-
valid_mem = Memory(
290+
Memory(
290291
id="test_1",
291292
user_id="user_1",
292293
session_id="session_1",
@@ -295,14 +296,14 @@ def test_pydantic_validation():
295296
timestamp=datetime.now(),
296297
importance=0.5
297298
)
298-
print(f" ✓ Valid memory created")
299+
print(" ✓ Valid memory created")
299300
except ValidationError as e:
300301
print(f" ✗ Unexpected validation error: {e}")
301302
return False
302303

303304
# Test validation with invalid importance
304305
try:
305-
invalid_mem = Memory(
306+
Memory(
306307
id="test_2",
307308
user_id="user_1",
308309
session_id="session_1",
@@ -311,9 +312,9 @@ def test_pydantic_validation():
311312
timestamp=datetime.now(),
312313
importance=1.5 # Should be 0-1
313314
)
314-
print(f" ⚠️ Invalid importance accepted (validation may be loose)")
315+
print(" ⚠️ Invalid importance accepted (validation may be loose)")
315316
except ValidationError:
316-
print(f" ✓ Invalid importance rejected")
317+
print(" ✓ Invalid importance rejected")
317318

318319
return True
319320

test_install.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
import sys
1414
import traceback
15-
from typing import List, Tuple
15+
from typing import List
1616

1717

1818
class TestResult:
@@ -40,7 +40,8 @@ def run_test(test_name: str, test_func) -> TestResult:
4040

4141
def test_basic_imports():
4242
"""Test basic package imports."""
43-
from hippocampai import MemoryClient, Memory, MemoryType
43+
from hippocampai import Memory, MemoryClient, MemoryType
44+
4445
assert MemoryClient is not None
4546
assert Memory is not None
4647
assert MemoryType is not None
@@ -67,9 +68,10 @@ def test_memory_type_enum():
6768

6869
def test_memory_model():
6970
"""Test Memory model creation."""
70-
from hippocampai.models.memory import Memory, MemoryType
7171
from datetime import datetime
7272

73+
from hippocampai.models.memory import Memory, MemoryType
74+
7375
memory = Memory(
7476
id="test_123",
7577
user_id="user_456",
@@ -90,17 +92,16 @@ def test_memory_model():
9092

9193
def test_config_import():
9294
"""Test configuration module."""
93-
from hippocampai.config import Config
95+
from hippocampai.config import Config # noqa: F401
9496

9597
# Just test that Config class exists and can be imported
96-
assert Config is not None
97-
print(f" Config class imported successfully")
98+
print(" Config class imported successfully")
9899

99100

100101
def test_cli_imports():
101102
"""Test CLI module imports."""
102-
from hippocampai.cli import main
103-
assert main is not None
103+
from hippocampai.cli import main # noqa: F401
104+
104105
print(" CLI module imported successfully")
105106

106107

@@ -113,7 +114,7 @@ def test_api_imports():
113114

114115
def test_pipeline_imports():
115116
"""Test pipeline modules."""
116-
from hippocampai.pipeline import extractor, dedup, consolidate, importance
117+
from hippocampai.pipeline import consolidate, dedup, extractor, importance
117118

118119
assert extractor is not None
119120
assert dedup is not None
@@ -176,12 +177,11 @@ def test_utils_imports():
176177

177178
def test_memory_client_creation():
178179
"""Test MemoryClient class availability."""
179-
from hippocampai import MemoryClient
180+
from hippocampai import MemoryClient # noqa: F401
180181

181182
# Just test that the class exists
182-
assert MemoryClient is not None
183-
print(f" MemoryClient class imported successfully")
184-
print(f" (Note: Full instantiation requires Qdrant connection)")
183+
print(" MemoryClient class imported successfully")
184+
print(" (Note: Full instantiation requires Qdrant connection)")
185185

186186

187187
def test_package_metadata():
@@ -212,11 +212,11 @@ def test_dependencies():
212212
]
213213

214214
missing = []
215-
for module_name, display_name in dependencies:
215+
for module_name, _display_name in dependencies:
216216
try:
217217
__import__(module_name)
218218
except ImportError:
219-
missing.append(display_name)
219+
missing.append(_display_name)
220220

221221
if missing:
222222
raise ImportError(f"Missing dependencies: {', '.join(missing)}")
@@ -300,7 +300,7 @@ def main():
300300
except KeyboardInterrupt:
301301
print("\n\nTests interrupted by user")
302302
sys.exit(1)
303-
except Exception as e:
304-
print(f"\n\nFatal error during testing:")
303+
except Exception:
304+
print("\n\nFatal error during testing:")
305305
traceback.print_exc()
306306
sys.exit(1)

0 commit comments

Comments
 (0)