test_hooks.py•7.5 kB
#!/usr/bin/env python3
"""
Git Hook和错误捕获功能测试脚本
测试post-commit hook和error_catcher的功能
"""
import sys
import os
import subprocess
import tempfile
from pathlib import Path
from datetime import datetime
# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
try:
from simple_memory_ops_sdk import SimpleMemoryOps
except ImportError:
try:
from memory_ops_sdk import MemoryOps as SimpleMemoryOps
except ImportError:
print("❌ Error: Cannot import memory ops SDK")
sys.exit(1)
def test_memory_ops_sdk():
"""测试Memory Ops SDK基本功能"""
print("🧪 Testing Memory Ops SDK...")
try:
mem = SimpleMemoryOps(verbose=True)
# 测试添加记忆
success = mem.add(
text="Test memory for hook testing",
memory_type='general_mem',
tags=["test", "hook"],
metadata={"test": True, "timestamp": datetime.now().isoformat()}
)
if success:
print("✅ Memory Ops SDK is working")
else:
print("❌ Memory Ops SDK add failed")
return False
# 测试查询记忆
results = mem.query("hook testing", limit=1)
if results:
print(f"✅ Memory Ops SDK query returned {len(results)} results")
else:
print("⚠️ Memory Ops SDK query returned no results")
mem.close()
return True
except Exception as e:
print(f"❌ Memory Ops SDK test failed: {e}")
return False
def test_record_commit_script():
"""测试record_commit.py脚本"""
print("\n🧪 Testing record_commit.py script...")
script_path = project_root / "scripts" / "record_commit.py"
if not script_path.exists():
print(f"❌ record_commit.py not found at {script_path}")
return False
# 模拟commit参数
test_args = [
"abc123def456", # commit_hash
"Test commit message for hook testing", # commit_msg
"Test Author", # commit_author
"test@example.com", # commit_email
"2025-07-16 18:45:00 +0800", # commit_date
"test_file.py,README.md" # changed_files
]
try:
# 运行脚本
result = subprocess.run(
[sys.executable, str(script_path)] + test_args,
capture_output=True,
text=True,
cwd=str(project_root)
)
if result.returncode == 0:
print("✅ record_commit.py executed successfully")
if result.stdout:
print(f" Output: {result.stdout.strip()}")
return True
else:
print(f"❌ record_commit.py failed with return code {result.returncode}")
if result.stderr:
print(f" Error: {result.stderr.strip()}")
return False
except Exception as e:
print(f"❌ Error running record_commit.py: {e}")
return False
def test_error_catcher():
"""测试error_catcher.py"""
print("\n🧪 Testing error_catcher.py...")
try:
# 导入error_catcher模块
sys.path.insert(0, str(project_root / "scripts"))
import error_catcher
# 测试记录错误功能
try:
# 故意触发一个错误
1 / 0
except ZeroDivisionError as e:
# 手动调用错误记录函数
error_catcher.record_error(
type(e),
e,
e.__traceback__,
"Test error from test_hooks.py"
)
print("✅ Error catcher recorded test error")
return True
except Exception as e:
print(f"❌ Error catcher test failed: {e}")
return False
def test_git_hook_installation():
"""测试Git Hook是否正确安装"""
print("\n🧪 Testing Git Hook installation...")
hook_path = project_root / ".git" / "hooks" / "post-commit"
if not hook_path.exists():
print("❌ post-commit hook not installed")
print(" Run 'bash scripts/install_hooks.sh' to install")
return False
if not os.access(hook_path, os.X_OK):
print("❌ post-commit hook is not executable")
return False
print("✅ post-commit hook is installed and executable")
# 检查hook内容
try:
with open(hook_path, 'r') as f:
content = f.read()
if "record_commit.py" in content:
print("✅ post-commit hook contains record_commit.py call")
else:
print("⚠️ post-commit hook may not call record_commit.py")
except Exception as e:
print(f"⚠️ Could not read hook content: {e}")
return True
def test_memory_types():
"""测试Memory类型是否包含git_commit_mem和error_log_mem"""
print("\n🧪 Testing Memory types...")
try:
mem = SimpleMemoryOps(verbose=False)
types = mem.list_memory_types()
print(f"Available memory types: {list(types.keys())}")
if 'git_commit_mem' in types:
print("✅ git_commit_mem type is available")
else:
print("⚠️ git_commit_mem type not available, will use general_mem")
if 'error_log_mem' in types:
print("✅ error_log_mem type is available")
else:
print("⚠️ error_log_mem type not available, will use general_mem")
mem.close()
return True
except Exception as e:
print(f"❌ Memory types test failed: {e}")
return False
def main():
"""主测试函数"""
print("🚀 MemOS Git Hook and Error Catcher Test Suite")
print("=" * 60)
tests = [
("Memory Ops SDK", test_memory_ops_sdk),
("Memory Types", test_memory_types),
("record_commit.py Script", test_record_commit_script),
("Error Catcher", test_error_catcher),
("Git Hook Installation", test_git_hook_installation),
]
passed = 0
total = len(tests)
for test_name, test_func in tests:
print(f"\n{'='*20} {test_name} {'='*20}")
try:
if test_func():
passed += 1
print(f"✅ {test_name} PASSED")
else:
print(f"❌ {test_name} FAILED")
except Exception as e:
print(f"❌ {test_name} ERROR: {e}")
print(f"\n{'='*60}")
print(f"📊 Test Results: {passed}/{total} tests passed")
if passed == total:
print("🎉 All tests passed! Git Hook and Error Catcher are ready to use.")
print("\n📋 Next steps:")
print("1. Make a test commit to see the hook in action")
print("2. Import error_catcher in your Python scripts")
print("3. Check memory system for recorded data")
else:
print("⚠️ Some tests failed. Please check the issues above.")
print("\n🔧 Troubleshooting:")
print("1. Ensure you're in the MemOS project directory")
print("2. Run 'bash scripts/install_hooks.sh' to install hooks")
print("3. Check that Memory Ops SDK is working properly")
return passed == total
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1)