Files
hive/backend/test_ucxl_integration.py
anthonyrawlins 268214d971 Major WHOOSH system refactoring and feature enhancements
- Migrated from HIVE branding to WHOOSH across all components
- Enhanced backend API with new services: AI models, BZZZ integration, templates, members
- Added comprehensive testing suite with security, performance, and integration tests
- Improved frontend with new components for project setup, AI models, and team management
- Updated MCP server implementation with WHOOSH-specific tools and resources
- Enhanced deployment configurations with production-ready Docker setups
- Added comprehensive documentation and setup guides
- Implemented age encryption service and UCXL integration

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-08-27 08:34:48 +10:00

255 lines
9.8 KiB
Python

#!/usr/bin/env python3
"""
Test UCXL Integration Service
Verify integration with existing UCXL addressing system
"""
import asyncio
import json
import sys
from datetime import datetime
from app.services.ucxl_integration_service import UCXLIntegrationService, UCXLAddress
async def test_ucxl_integration():
"""Test UCXL integration functionality"""
print("📦 Testing UCXL Integration Service")
print("=" * 60)
# Initialize service
service = UCXLIntegrationService()
try:
# Test initialization
print("\n1. Testing Service Initialization...")
initialized = await service.initialize()
print(f" Initialization result: {'✅ Success' if initialized else '❌ Failed'}")
if not initialized:
print(" ⚠️ Cannot continue without successful initialization")
return
# Test system status
print("\n2. Testing System Status...")
status = await service.get_system_status()
print(f" UCXL endpoints: {status.get('ucxl_endpoints', 0)}")
print(f" DHT nodes: {status.get('dht_nodes', 0)}")
print(f" BZZZ gateways: {status.get('bzzz_gateways', 0)}")
print(f" Cached artifacts: {status.get('cached_artifacts', 0)}")
print(f" System health: {status.get('system_health', 0):.2%}")
# Test UCXL address parsing
print("\n3. Testing UCXL Address Parsing...")
test_addresses = [
"ucxl://any:any@WHOOSH:BACKEND/src/main.py",
"ucxl://user@PROJECT:COMPONENT/path/to/file",
"ucxls://secure:pass@BZZZ:RUSTLE/config.yaml",
]
for addr in test_addresses:
try:
parsed = UCXLAddress.parse(addr)
reconstructed = parsed.to_string()
print(f"{addr}")
print(f" → Project: {parsed.project}, Component: {parsed.component}")
print(f" → Path: {parsed.path}, Protocol: {parsed.protocol.value}")
print(f" → Reconstructed: {reconstructed}")
except Exception as e:
print(f" ❌ Failed to parse {addr}: {e}")
# Test artifact storage
print("\n4. Testing Artifact Storage...")
test_content = {
"message": "Hello from WHOOSH UCXL Integration",
"timestamp": datetime.utcnow().isoformat(),
"test_data": {
"numbers": [1, 2, 3, 4, 5],
"nested": {"key": "value"}
}
}
address = await service.store_artifact(
project="WHOOSH",
component="TEST",
path="test_artifact.json",
content=json.dumps(test_content, indent=2),
content_type="application/json",
metadata={
"test_type": "integration_test",
"created_by": "WHOOSH",
"purpose": "testing UCXL storage functionality"
}
)
if address:
print(f" ✅ Artifact stored: {address}")
# Test artifact retrieval
print("\n5. Testing Artifact Retrieval...")
retrieved = await service.retrieve_artifact(address)
if retrieved:
print(f" ✅ Artifact retrieved successfully")
print(f" → Content hash: {retrieved.get('content_hash', 'unknown')}")
print(f" → Size: {retrieved.get('size', 0)} bytes")
print(f" → Content type: {retrieved.get('content_type', 'unknown')}")
print(f" → Cached: {retrieved.get('cached', False)}")
else:
print(" ❌ Failed to retrieve stored artifact")
else:
print(" ❌ Failed to store test artifact")
# Test project context creation
print("\n6. Testing Project Context Creation...")
project_address = await service.create_project_context(
project_name="WHOOSH_TEST",
description="Test project for WHOOSH UCXL integration",
components=["BACKEND", "FRONTEND", "API", "STORAGE"],
metadata={
"version": "1.0",
"created_by": "UCXL Integration Test",
"purpose": "testing project context functionality"
}
)
if project_address:
print(f" ✅ Project context created: {project_address}")
else:
print(" ❌ Failed to create project context")
# Test artifact listing
print("\n7. Testing Artifact Listing...")
artifacts = await service.list_artifacts(project="WHOOSH", limit=10)
print(f" Found {len(artifacts)} artifacts in WHOOSH project:")
for artifact in artifacts[:5]: # Show first 5
addr = artifact.get("address", "unknown")
size = artifact.get("size", 0)
ctype = artifact.get("content_type", "unknown")
print(f" - {addr} ({size} bytes, {ctype})")
# Test artifact linking (if we have artifacts)
if address and project_address:
print("\n8. Testing Artifact Linking...")
link_success = await service.link_artifacts(
source_address=address,
target_address=project_address,
relationship="belongs_to",
metadata={
"link_type": "membership",
"created_by": "integration_test"
}
)
if link_success:
print(f" ✅ Artifacts linked: {address} belongs_to {project_address}")
# Test getting artifact links
print("\n9. Testing Link Retrieval...")
links = await service.get_artifact_links(address)
print(f" Found {len(links)} links for test artifact:")
for link in links:
rel = link.get("relationship", "unknown")
target = link.get("target", "unknown")
print(f" - {rel}{target}")
else:
print(" ❌ Failed to create artifact link")
# Test temporal resolution (even if backend doesn't support it yet)
if address:
print("\n10. Testing Temporal Resolution...")
temporal_result = await service.resolve_temporal_address(
address,
datetime.utcnow()
)
if temporal_result:
print(f" ✅ Temporal resolution successful")
print(f" → Address: {temporal_result.get('address', 'unknown')}")
else:
print(" ⚠️ Temporal resolution not available (fallback to current)")
print("\n✅ UCXL Integration Test Completed!")
except Exception as e:
print(f"❌ Test failed with error: {e}")
import traceback
traceback.print_exc()
finally:
# Cleanup
await service.cleanup()
print("\n🧹 Service cleanup completed")
async def test_address_manipulation():
"""Test UCXL address parsing and generation"""
print("\n" + "=" * 60)
print("🔍 Testing UCXL Address Manipulation")
print("=" * 60)
test_cases = [
{
"address": "ucxl://any:any@WHOOSH:BACKEND/src/main.py",
"description": "Standard WHOOSH backend file"
},
{
"address": "ucxl://developer@PROJECT:COMPONENT/path/to/resource",
"description": "User-specific access"
},
{
"address": "ucxls://secure:password@SENSITIVE:DATA/config.json",
"description": "Secure protocol with credentials"
},
{
"address": "ucxl://PROJECT:COMPONENT",
"description": "Component-level address"
},
{
"address": "ucxl://PROJECT",
"description": "Project-level address"
}
]
for i, test_case in enumerate(test_cases, 1):
print(f"\n{i}. Testing: {test_case['description']}")
print(f" Address: {test_case['address']}")
try:
# Parse the address
parsed = UCXLAddress.parse(test_case['address'])
print(f" ✅ Parsed successfully:")
print(f" → Protocol: {parsed.protocol.value}")
print(f" → User: {parsed.user or 'None'}")
print(f" → Project: {parsed.project or 'None'}")
print(f" → Component: {parsed.component or 'None'}")
print(f" → Path: {parsed.path or 'None'}")
# Reconstruct the address
reconstructed = parsed.to_string()
print(f" → Reconstructed: {reconstructed}")
# Verify reconstruction matches
if reconstructed == test_case['address']:
print(f" ✅ Reconstruction matches original")
else:
print(f" ⚠️ Reconstruction differs from original")
except Exception as e:
print(f" ❌ Failed to parse: {e}")
if __name__ == "__main__":
print("🚀 Starting UCXL Integration Tests")
print(f"🕐 Test started at: {datetime.utcnow().isoformat()}")
try:
# Run address manipulation tests
asyncio.run(test_address_manipulation())
# Run main integration test
asyncio.run(test_ucxl_integration())
print(f"\n🏁 All tests completed at: {datetime.utcnow().isoformat()}")
except KeyboardInterrupt:
print("\n⚠️ Tests interrupted by user")
sys.exit(1)
except Exception as e:
print(f"\n❌ Test suite failed: {e}")
sys.exit(1)