Spaces:
Running
Running
File size: 23,277 Bytes
05a3c8b aac729b 05a3c8b aac729b 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 05a3c8b 5402d17 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 | # OrKa: Orchestrator Kit Agents
# Copyright Β© 2025 Marco Somma
#
# This file is part of OrKa β https://github.com/marcosomma/orka-reasoning
#
# Licensed under the Apache License, Version 2.0 (Apache 2.0).
# You may not use this file for commercial purposes without explicit permission.
#
# Full license: https://www.apache.org/licenses/LICENSE-2.0
# For commercial use, contact: marcosomma.work@gmail.com
#
# Required attribution: OrKa by Marco Somma β https://github.com/marcosomma/orka-reasoning
"""
Test CLI Memory Commands
========================
Tests for memory management CLI commands including statistics, cleanup, and configuration.
"""
import json
import logging
import os
from argparse import Namespace
from io import StringIO
from unittest.mock import MagicMock, patch
from orka.cli.memory.commands import memory_cleanup, memory_configure, memory_stats
class LogCaptureHandler(logging.StreamHandler):
"""Custom handler that captures log output for testing."""
def __init__(self):
super().__init__()
self.stream = StringIO()
self.setFormatter(logging.Formatter("%(message)s"))
def get_output(self):
"""Get the captured output."""
return self.stream.getvalue()
def reset(self):
"""Reset the capture buffer."""
self.stream = StringIO()
import pytest
@pytest.fixture(autouse=True)
def setup_logging():
"""Set up logging capture for tests."""
# Create and configure handler
handler = LogCaptureHandler()
logger = logging.getLogger("orka.cli.memory.commands")
logger.addHandler(handler)
logger.setLevel(logging.INFO)
# Yield the handler for test use
yield handler
# Cleanup
logger.removeHandler(handler)
handler.close()
class TestMemoryStats:
"""Test cases for memory_stats command."""
def test_memory_stats_success(self, setup_logging):
"""Test memory_stats with successful execution."""
args = Namespace(backend="redis", json=False)
mock_memory = MagicMock()
mock_stats = {
"backend": "redis",
"decay_enabled": True,
"total_streams": 10,
"total_entries": 100,
"expired_entries": 5,
}
mock_memory.get_memory_stats.return_value = mock_stats
with patch("orka.cli.memory.commands.create_memory_logger", return_value=mock_memory):
result = memory_stats(args)
assert result == 0
output = setup_logging.get_output()
assert "=== OrKa Memory Statistics ===" in output
assert "Backend: redis" in output
assert "Total Entries: 100" in output
def test_memory_stats_json_format(self, setup_logging):
"""Test memory_stats with JSON output."""
args = Namespace(backend="redis", json=True)
mock_memory = MagicMock()
mock_stats = {"backend": "redis", "total_entries": 50}
mock_memory.get_memory_stats.return_value = mock_stats
with patch("orka.cli.memory.commands.create_memory_logger", return_value=mock_memory):
result = memory_stats(args)
assert result == 0
output = setup_logging.get_output()
json_output = json.loads(output)
assert json_output["stats"]["backend"] == "redis"
assert json_output["stats"]["total_entries"] == 50
def test_memory_stats_error(self, setup_logging):
"""Test memory_stats with error handling."""
args = Namespace(backend="redis", json=False)
with patch("orka.cli.memory.commands.create_memory_logger") as mock_create:
mock_create.side_effect = Exception("Connection failed")
result = memory_stats(args)
assert result == 1
output = setup_logging.get_output()
assert "Error getting memory statistics: Connection failed" in output
def test_memory_stats_comprehensive_output(self, setup_logging):
"""Test memory_stats with comprehensive stats output."""
args = Namespace(backend="redis", json=False)
mock_memory = MagicMock()
mock_stats = {
"backend": "redis",
"decay_enabled": True,
"total_streams": 10,
"total_entries": 100,
"expired_entries": 5,
"entries_by_type": {"event": 50, "decision": 30, "output": 20},
"entries_by_memory_type": {"short_term": 70, "long_term": 30},
"entries_by_category": {"planning": 40, "execution": 35, "monitoring": 25},
"decay_config": {
"short_term_hours": 1.0,
"long_term_hours": 24.0,
"check_interval_minutes": 30,
"last_decay_check": "2024-01-01T12:00:00Z",
},
}
mock_memory.get_memory_stats.return_value = mock_stats
with patch("orka.cli.memory.commands.create_memory_logger", return_value=mock_memory):
result = memory_stats(args)
assert result == 0
output = setup_logging.get_output()
assert "Entries by Type:" in output
assert "event: 50" in output
assert "Entries by Memory Type:" in output
assert "short_term: 70" in output
assert "Entries by Category:" in output
assert "planning: 40" in output
assert "Decay Configuration:" in output
assert "Short-term retention: 1.0h" in output
assert "Last cleanup: 2024-01-01T12:00:00Z" in output
def test_memory_stats_no_backend_args(self, setup_logging):
"""Test memory_stats with no backend attribute in args."""
args = Namespace(json=False) # No backend attribute
mock_memory = MagicMock()
mock_stats = {"backend": "redisstack", "total_entries": 75}
mock_memory.get_memory_stats.return_value = mock_stats
with (
patch("orka.cli.memory.commands.create_memory_logger", return_value=mock_memory),
patch.dict(os.environ, {"ORKA_MEMORY_BACKEND": "redisstack"}),
):
result = memory_stats(args)
assert result == 0
output = setup_logging.get_output()
assert "Backend: redisstack" in output
assert "Total Entries: 75" in output
def test_memory_stats_redisstack_fallback(self, setup_logging):
"""Test memory_stats with redisstack fallback to redis."""
args = Namespace(backend="redisstack", json=False)
mock_memory = MagicMock()
mock_stats = {"backend": "redis", "total_entries": 25}
mock_memory.get_memory_stats.return_value = mock_stats
with patch("orka.cli.memory.commands.create_memory_logger") as mock_create:
# First call raises ImportError, second succeeds
mock_create.side_effect = [ImportError("RedisStack not available"), mock_memory]
result = memory_stats(args)
assert result == 0
output = setup_logging.get_output()
assert "RedisStack not available" in output
assert "falling back to Redis" in output
assert mock_create.call_count == 2
assert "Backend: redis" in output
assert "Total Entries: 25" in output
class TestMemoryCleanup:
"""Test cases for memory_cleanup command."""
def test_memory_cleanup_success(self, setup_logging):
"""Test memory_cleanup with successful execution."""
args = Namespace(backend="redis", dry_run=False, json=False, verbose=False)
mock_memory = MagicMock()
mock_result = {
"status": "completed",
"deleted_count": 15,
"streams_processed": 5,
"total_entries_checked": 100,
}
mock_memory.cleanup_expired_memories.return_value = mock_result
with patch("orka.cli.memory.commands.create_memory_logger", return_value=mock_memory):
result = memory_cleanup(args)
assert result == 0
output = setup_logging.get_output()
assert "=== Memory Cleanup ===" in output
assert "Deleted Entries: 15" in output
assert "Streams Processed: 5" in output
assert "Total Entries Checked: 100" in output
def test_memory_cleanup_dry_run(self, setup_logging):
"""Test memory_cleanup with dry run mode."""
args = Namespace(backend="redis", dry_run=True, json=False, verbose=False)
mock_memory = MagicMock()
mock_result = {"status": "dry_run", "deleted_count": 0}
mock_memory.cleanup_expired_memories.return_value = mock_result
with patch("orka.cli.memory.commands.create_memory_logger", return_value=mock_memory):
result = memory_cleanup(args)
assert result == 0
output = setup_logging.get_output()
assert "=== Dry Run: Memory Cleanup Preview ===" in output
assert "Status: dry_run" in output
assert "Deleted Entries: 0" in output
def test_memory_cleanup_json_output(self, setup_logging):
"""Test memory_cleanup with JSON output."""
args = Namespace(backend="redis", dry_run=False, json=True, verbose=False)
mock_memory = MagicMock()
mock_result = {"status": "completed", "deleted_count": 10}
mock_memory.cleanup_expired_memories.return_value = mock_result
with patch("orka.cli.memory.commands.create_memory_logger", return_value=mock_memory):
result = memory_cleanup(args)
assert result == 0
output = setup_logging.get_output()
# Find the JSON part of the output
json_str = output.split("=== Memory Cleanup ===\n")[1].strip()
json_output = json.loads(json_str)
assert "cleanup_result" in json_output
assert json_output["cleanup_result"]["status"] == "completed"
assert json_output["cleanup_result"]["deleted_count"] == 10
def test_memory_cleanup_with_errors(self, setup_logging):
"""Test memory_cleanup with error count."""
args = Namespace(backend="redis", dry_run=False, json=False, verbose=False)
mock_memory = MagicMock()
mock_result = {
"status": "completed",
"deleted_count": 5,
"error_count": 2,
"duration_seconds": 3.5,
}
mock_memory.cleanup_expired_memories.return_value = mock_result
with patch("orka.cli.memory.commands.create_memory_logger", return_value=mock_memory):
result = memory_cleanup(args)
assert result == 0
output = setup_logging.get_output()
assert "Errors: 2" in output
assert "Duration: 3.50s" in output
def test_memory_cleanup_verbose(self, setup_logging):
"""Test memory_cleanup with verbose output."""
args = Namespace(backend="redis", dry_run=False, json=False, verbose=True)
mock_memory = MagicMock()
mock_result = {
"status": "completed",
"deleted_count": 3,
"deleted_entries": [
{"agent_id": "agent1", "event_type": "event", "stream": "stream1"},
{"agent_id": "agent2", "event_type": "decision", "stream": "stream2"},
{"agent_id": "agent3", "event_type": "output"},
],
}
mock_memory.cleanup_expired_memories.return_value = mock_result
with patch("orka.cli.memory.commands.create_memory_logger", return_value=mock_memory):
result = memory_cleanup(args)
assert result == 0
output = setup_logging.get_output()
assert "Deleted Entries:" in output
assert "stream1: agent1 - event" in output
assert "stream2: agent2 - decision" in output
assert "agent3 - output" in output
def test_memory_cleanup_verbose_many_entries(self, setup_logging):
"""Test memory_cleanup with verbose output and many entries."""
args = Namespace(backend="redis", dry_run=False, json=False, verbose=True)
mock_memory = MagicMock()
deleted_entries = [
{"agent_id": f"agent{i}", "event_type": "event", "stream": f"stream{i}"}
for i in range(15)
]
mock_result = {
"status": "completed",
"deleted_count": 15,
"deleted_entries": deleted_entries,
}
mock_memory.cleanup_expired_memories.return_value = mock_result
with patch("orka.cli.memory.commands.create_memory_logger", return_value=mock_memory):
result = memory_cleanup(args)
assert result == 0
output = setup_logging.get_output()
assert "Deleted Entries:" in output
assert "stream0: agent0 - event" in output
assert "stream9: agent9 - event" in output
assert "... and 5 more" in output
def test_memory_cleanup_fallback_to_redis(self, setup_logging):
"""Test memory_cleanup with fallback from redisstack to redis."""
args = Namespace(backend="redisstack", dry_run=False, json=False, verbose=False)
mock_memory = MagicMock()
mock_result = {"status": "completed", "deleted_count": 5}
mock_memory.cleanup_expired_memories.return_value = mock_result
with patch("orka.cli.memory.commands.create_memory_logger") as mock_create:
mock_create.side_effect = [ImportError("RedisStack not available"), mock_memory]
result = memory_cleanup(args)
assert result == 0
output = setup_logging.get_output()
assert "RedisStack not available" in output
assert "falling back to Redis" in output
assert "Backend: redis" in output
assert "Deleted Entries: 5" in output
def test_memory_cleanup_error_handling(self, setup_logging):
"""Test memory_cleanup with error handling."""
args = Namespace(backend="redis", dry_run=False, json=False, verbose=False)
with patch("orka.cli.memory.commands.create_memory_logger") as mock_create:
mock_create.side_effect = Exception("Connection failed")
result = memory_cleanup(args)
assert result == 1
output = setup_logging.get_output()
assert "Error during memory cleanup: Connection failed" in output
class TestMemoryConfigure:
"""Test cases for memory_configure command."""
def test_memory_configure_success(self, setup_logging):
"""Test memory_configure with successful execution."""
args = Namespace(backend="redis")
mock_memory = MagicMock()
mock_memory.decay_config = {"enabled": True}
mock_memory.get_memory_stats.return_value = {"total_entries": 100}
with patch("orka.cli.memory.commands.create_memory_logger", return_value=mock_memory):
result = memory_configure(args)
assert result == 0
output = setup_logging.get_output()
assert "=== OrKa Memory Configuration Test ===" in output
assert "Backend: redis" in output
assert "β
Decay Config: Enabled" in output
assert "Total entries: 100" in output
assert "Backend: redis" in output
def test_memory_configure_redis_detailed(self, setup_logging):
"""Test memory_configure with Redis backend detailed tests."""
args = Namespace(backend="redis")
mock_memory = MagicMock()
mock_memory.decay_config = {
"enabled": True,
"default_short_term_hours": 1.0,
"default_long_term_hours": 24.0,
"check_interval_minutes": 30,
}
mock_memory.client = MagicMock()
mock_memory.client.ping.return_value = True
mock_memory.cleanup_expired_memories.return_value = {"total_entries_checked": 50}
mock_memory.get_memory_stats.return_value = {
"total_entries": 100,
"entries_by_memory_type": {"short_term": 70},
}
with patch("orka.cli.memory.commands.create_memory_logger", return_value=mock_memory):
result = memory_configure(args)
assert result == 0
output = setup_logging.get_output()
assert "β
Decay Config: Enabled" in output
assert "Short-term: 1.0h" in output
assert "Long-term: 24.0h" in output
assert "Check interval: 30min" in output
assert "β
Redis Connection: Active" in output
assert "β
Decay Cleanup: Available" in output
assert "Checked: 50 entries" in output
assert "Total entries: 100" in output
assert "π§ Redis-Specific Tests:" in output
assert "β
Redis Connection: Active" in output
assert "β
Decay Cleanup: Available" in output
assert "Checked: 50 entries" in output
def test_memory_configure_redisstack_detailed(self, setup_logging):
"""Test memory_configure with RedisStack backend detailed tests."""
args = Namespace(backend="redisstack")
mock_memory = MagicMock()
mock_memory.decay_config = {"enabled": False}
mock_memory.client = MagicMock()
mock_index_info = {"num_docs": 150, "indexing": True}
mock_memory.client.ft.return_value.info.return_value = mock_index_info
mock_memory.get_memory_stats.return_value = {"total_entries": 150, "decay_enabled": False}
with patch("orka.cli.memory.commands.create_memory_logger", return_value=mock_memory):
result = memory_configure(args)
assert result == 0
output = setup_logging.get_output()
assert "β
Decay Config: Disabled" in output
assert "π RedisStack-Specific Tests:" in output
assert "β
HNSW Index: Available" in output
assert "Documents: 150" in output
assert "Indexing: Yes" in output
assert "Total entries: 150" in output
assert "π RedisStack-Specific Tests:" in output
assert "β
HNSW Index: Available" in output
assert "Documents: 150" in output
assert "Indexing: Yes" in output
def test_memory_configure_no_decay_config(self, setup_logging):
"""Test memory_configure with no decay config."""
args = Namespace(backend="redis")
mock_memory = MagicMock()
# Simulate AttributeError when decay_config is accessed
type(mock_memory).decay_config = None
with patch("orka.cli.memory.commands.create_memory_logger", return_value=mock_memory):
result = memory_configure(args)
assert result == 1
output = setup_logging.get_output()
assert "=== OrKa Memory Configuration Test ===" in output
assert "Backend: redis" in output
assert "β Configuration test failed" in output
def test_memory_configure_redis_connection_error(self, setup_logging):
"""Test memory_configure with Redis connection error."""
args = Namespace(backend="redis")
mock_memory = MagicMock()
mock_memory.decay_config = {"enabled": True}
mock_memory.client = MagicMock()
mock_memory.client.ping.side_effect = Exception("Connection refused")
mock_memory.get_memory_stats.return_value = {"total_entries": 0}
with patch("orka.cli.memory.commands.create_memory_logger", return_value=mock_memory):
result = memory_configure(args)
assert result == 0
output = setup_logging.get_output()
assert "=== OrKa Memory Configuration Test ===" in output
assert "Backend: redis" in output
assert "β
Decay Config: Enabled" in output
assert "β Redis Connection: Error - Connection refused" in output
def test_memory_configure_redisstack_index_error(self, setup_logging):
"""Test memory_configure with RedisStack index error."""
args = Namespace(backend="redisstack")
mock_memory = MagicMock()
mock_memory.decay_config = {"enabled": True}
mock_memory.client = MagicMock()
mock_memory.client.ft.return_value.info.side_effect = Exception("Index not found")
mock_memory.get_memory_stats.return_value = {"total_entries": 0}
with patch("orka.cli.memory.commands.create_memory_logger", return_value=mock_memory):
result = memory_configure(args)
assert result == 0
output = setup_logging.get_output()
assert "=== OrKa Memory Configuration Test ===" in output
assert "Backend: redisstack" in output
assert "β
Decay Config: Enabled" in output
assert "β HNSW Index: Not available - Index not found" in output
def test_memory_configure_memory_stats_error(self, setup_logging):
"""Test memory_configure with memory stats error."""
args = Namespace(backend="redis")
mock_memory = MagicMock()
mock_memory.decay_config = {"enabled": True}
mock_memory.get_memory_stats.side_effect = Exception("Stats unavailable")
with patch("orka.cli.memory.commands.create_memory_logger", return_value=mock_memory):
result = memory_configure(args)
assert result == 0
output = setup_logging.get_output()
assert "=== OrKa Memory Configuration Test ===" in output
assert "Backend: redis" in output
assert "β
Decay Config: Enabled" in output
assert "β Memory Stats: Error - Stats unavailable" in output
def test_memory_configure_configuration_test_error(self, setup_logging):
"""Test memory_configure with configuration test error."""
args = Namespace(backend="redis")
mock_memory = MagicMock()
mock_memory.decay_config = {"enabled": True}
mock_memory.get_memory_stats.side_effect = Exception("Configuration test failed")
with patch("orka.cli.memory.commands.create_memory_logger", return_value=mock_memory):
result = memory_configure(args)
# Memory stats error doesn't cause function to return 1
assert result == 0
output = setup_logging.get_output()
assert "=== OrKa Memory Configuration Test ===" in output
assert "Backend: redis" in output
assert "β
Decay Config: Enabled" in output
assert "β Memory Stats: Error - Configuration test failed" in output
def test_memory_configure_create_memory_logger_error(self, setup_logging):
"""Test memory_configure with create_memory_logger error."""
args = Namespace(backend="redis")
with patch("orka.cli.memory.commands.create_memory_logger") as mock_create:
mock_create.side_effect = Exception("Logger creation failed")
result = memory_configure(args)
assert result == 1
output = setup_logging.get_output()
assert "=== OrKa Memory Configuration Test ===" in output
assert "Backend: redis" in output
assert "β Configuration test failed: Logger creation failed" in output
|