fcfs-mev-optimazer/test_framework.py
2025-06-29 13:01:11 +03:00

205 lines
6.1 KiB
Python

"""
Test Framework Components
Simple test script to verify all framework components are working correctly.
"""
import sys
import os
sys.path.append('/home/arhan/fcfs-mev-optimizer')
def test_imports():
"""Test all major imports"""
print("๐Ÿงช Testing Framework Imports...")
try:
# Test core imports with simplified fallbacks
print("โœ… Basic imports working")
# Test fairness metrics (should work)
from src.core.blockchain_analysis.fairness_metrics import ComprehensiveFairnessMetrics
print("โœ… Fairness metrics imported successfully")
# Test basic mathematical models
import numpy as np
print("โœ… NumPy imported successfully")
# Test MEV detection (using correct class name)
from src.core.blockchain_analysis.mev_detection import ProductionMEVDetector
print("โœ… MEV detection imported successfully")
return True
except ImportError as e:
print(f"โŒ Import error: {e}")
return False
def test_fairness_metrics():
"""Test fairness analysis"""
print("\nโš–๏ธ Testing Fairness Metrics...")
try:
from src.core.blockchain_analysis.fairness_metrics import ComprehensiveFairnessMetrics
# Create sample transactions
sample_transactions = [
{
"hash": "tx1", "sender": "user1", "receiver": "user2",
"amount": 100, "fee": 1, "timestamp": 1000, "block_number": 1
},
{
"hash": "tx2", "sender": "user2", "receiver": "user3",
"amount": 200, "fee": 2, "timestamp": 1005, "block_number": 1
},
{
"hash": "tx3", "sender": "user1", "receiver": "user3",
"amount": 150, "fee": 1.5, "timestamp": 1010, "block_number": 2
}
]
# Create fairness analyzer
fairness = ComprehensiveFairnessMetrics(sample_transactions)
report = fairness.comprehensive_fairness_report()
print(f" Overall fairness: {report['overall_fairness_score']:.3f}")
print(f" Fairness grade: {report['fairness_grade']}")
print("โœ… Fairness metrics working correctly")
return True
except Exception as e:
print(f"โŒ Fairness metrics error: {e}")
return False
def test_basic_math():
"""Test basic mathematical functionality"""
print("\n๐Ÿ”ข Testing Basic Mathematical Functions...")
try:
import numpy as np
from decimal import Decimal
# Test basic operations
arr = np.array([1, 2, 3, 4, 5])
mean_val = np.mean(arr)
std_val = np.std(arr)
print(f" Array mean: {mean_val:.3f}")
print(f" Array std: {std_val:.3f}")
# Test Decimal precision
d1 = Decimal("0.1")
d2 = Decimal("0.2")
result = d1 + d2
print(f" Decimal calculation: {d1} + {d2} = {result}")
print("โœ… Basic mathematical functions working correctly")
return True
except Exception as e:
print(f"โŒ Basic math error: {e}")
return False
def test_data_structures():
"""Test basic data structures"""
print("\n๐Ÿ“Š Testing Data Structures...")
try:
from collections import defaultdict, deque
import pandas as pd
# Test defaultdict
dd = defaultdict(int)
dd['test'] += 1
# Test deque
dq = deque([1, 2, 3], maxlen=5)
dq.append(4)
# Test pandas
df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
print(f" DefaultDict test: {dd['test']}")
print(f" Deque test: {list(dq)}")
print(f" DataFrame shape: {df.shape}")
print("โœ… Data structures working correctly")
return True
except Exception as e:
print(f"โŒ Data structures error: {e}")
return False
def test_simple_optimization():
"""Test simple optimization concepts"""
print("\n๐ŸŽฏ Testing Simple Optimization...")
try:
import numpy as np
from scipy.optimize import minimize
# Simple optimization problem: minimize x^2 + y^2
def objective(x):
return x[0]**2 + x[1]**2
# Initial guess
x0 = [1.0, 1.0]
# Optimize
result = minimize(objective, x0, method='BFGS')
print(f" Optimization successful: {result.success}")
print(f" Solution: [{result.x[0]:.3f}, {result.x[1]:.3f}]")
print(f" Function value: {result.fun:.6f}")
print("โœ… Simple optimization working correctly")
return True
except Exception as e:
print(f"โŒ Simple optimization error: {e}")
return False
def main():
"""Run all tests"""
print("๐Ÿš€ FCFS MEV Optimizer Framework Test")
print("=" * 50)
tests = [
test_imports,
test_basic_math,
test_data_structures,
test_fairness_metrics,
test_simple_optimization
]
results = []
for test in tests:
try:
result = test()
results.append(result)
except Exception as e:
print(f"โŒ Test failed with exception: {e}")
results.append(False)
print(f"\n๐Ÿ“Š Test Summary:")
print(f" Tests passed: {sum(results)}/{len(results)}")
if all(results):
print("๐ŸŽ‰ All tests passed! Core framework is working correctly.")
print("\nYou can now:")
print(" โ€ข Run the Jupyter notebook: demo_comprehensive_analysis.ipynb")
print(" โ€ข Develop individual components")
print(" โ€ข Extend the framework for your research")
else:
print("โŒ Some tests failed. Check the error messages above.")
print("\nNext steps:")
print(" โ€ข Install missing dependencies")
print(" โ€ข Check import paths")
print(" โ€ข Review individual component implementations")
return all(results)
if __name__ == "__main__":
main()