File size: 9,280 Bytes
11898c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
ο»Ώ# scripts/comprehensive_test.py
"""
Comprehensive test suite for the complete Self-Healing ML Pipelines system.
"""

import sys
import os
import json
from pathlib import Path
from datetime import datetime

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))


def test_module_imports():
    """Test that all critical modules can be imported."""
    print("πŸ§ͺ Testing module imports...")
    
    modules_to_test = [
        ("utils.config_loader", "ConfigLoader"),
        ("monitoring.data_drift", "DataDriftDetector"),
        ("decision_engine.policy_engine", "PolicyEngine"),
        ("healing.healing_actions", "HealingActions"),
        ("orchestration.controller", "SelfHealingController"),
        ("adaptive.adaptive_controller", "AdaptiveHealingController"),
        ("adaptive_integration", "IntegratedHealingController"),
        ("orchestration.sla_simulator", "SLASimulator"),
        ("orchestration.canary_controller", "CanaryController"),
        ("adaptive.learning.shadow_learner", "ShadowLearner"),
    ]
    
    all_passed = True
    for module_path, class_name in modules_to_test:
        try:
            module = __import__(module_path, fromlist=[class_name])
            getattr(module, class_name)
            print(f"  βœ… {module_path}.{class_name}")
        except Exception as e:
            print(f"  ❌ {module_path}.{class_name}: {e}")
            all_passed = False
    
    return all_passed


def test_config_files():
    """Test that all configuration files exist and are valid."""
    print("\nπŸ“‹ Testing configuration files...")
    
    config_files = [
        "configs/pipeline.yaml",
        "configs/healing_policies.yaml", 
        "configs/cost_model.yaml",
        "configs/sla_config.yaml",
        "configs/canary_config.yaml",
        "adaptive/cost_model/action_costs.yaml"
    ]
    
    all_passed = True
    for config_file in config_files:
        if os.path.exists(config_file):
            try:
                # Try to read the file
                with open(config_file, 'r') as f:
                    content = f.read()
                if len(content) > 10:
                    print(f"  βœ… {config_file}")
                else:
                    print(f"  ⚠️  {config_file}: File too small")
                    all_passed = False
            except Exception as e:
                print(f"  ❌ {config_file}: Read error - {e}")
                all_passed = False
        else:
            print(f"  ❌ {config_file}: Missing")
            all_passed = False
    
    return all_passed


def test_data_files():
    """Test that required data files exist."""
    print("\nπŸ“Š Testing data files...")
    
    data_files = [
        "adaptive/memory/experiences.json",
        "models/current_model.joblib",
        "models/current_metadata.json",
        "models/fallback/rule_based.joblib"
    ]
    
    all_passed = True
    for data_file in data_files:
        if os.path.exists(data_file):
            size = os.path.getsize(data_file)
            if size > 0:
                print(f"  βœ… {data_file} ({size} bytes)")
            else:
                print(f"  ⚠️  {data_file}: Empty file")
                all_passed = False
        else:
            print(f"  ❌ {data_file}: Missing")
            all_passed = False
    
    return all_passed


def test_system_integration():
    """Test the integrated system components."""
    print("\nπŸ”— Testing system integration...")
    
    from utils.config_loader import ConfigLoader
    from monitoring.data_drift import DataDriftDetector
    from decision_engine.policy_engine import PolicyEngine
    from healing.healing_actions import HealingActions
    
    all_passed = True
    
    try:
        # Test ConfigLoader
        config = ConfigLoader().load_config()
        if config and 'pipeline' in config:
            print("  βœ… ConfigLoader: Loaded configuration")
        else:
            print("  ❌ ConfigLoader: Failed to load config")
            all_passed = False
        
        # Test DataDriftDetector
        detector = DataDriftDetector()
        drift_result = detector.check_drift([0.1, 0.2, 0.3], [0.15, 0.25, 0.35])
        if drift_result is not None:
            print(f"  βœ… DataDriftDetector: drift_score={drift_result.get('drift_score', 'N/A')}")
        else:
            print("  ❌ DataDriftDetector: Failed")
            all_passed = False
        
        # Test PolicyEngine
        policy_engine = PolicyEngine()
        decision = policy_engine.evaluate({'data_drift': 0.25})
        if decision:
            print(f"  βœ… PolicyEngine: decision={decision.get('action', 'N/A')}")
        else:
            print("  ❌ PolicyEngine: Failed")
            all_passed = False
        
        # Test HealingActions
        healing = HealingActions()
        print(f"  βœ… HealingActions: Initialized")
        
    except Exception as e:
        print(f"  ❌ Integration test failed: {e}")
        all_passed = False
    
    return all_passed


def test_adaptive_system():
    """Test the adaptive learning components."""
    print("\n🧠 Testing adaptive system...")
    
    all_passed = True
    
    try:
        # Check experiences
        exp_path = "adaptive/memory/experiences.json"
        if os.path.exists(exp_path):
            with open(exp_path, 'r') as f:
                experiences = json.load(f)
            print(f"  βœ… Experiences: {len(experiences)} entries")
        else:
            print("  ⚠️  No experiences file")
            all_passed = False
        
        # Test Adaptive Controller
        from adaptive.adaptive_controller import AdaptiveHealingController
        adaptive = AdaptiveHealingController()
        context = {'data_drift': 0.15, 'anomaly_rate': 0.05}
        decision = adaptive.decide(context)
        if decision:
            print(f"  βœ… AdaptiveController: decision={decision}")
        else:
            print("  ❌ AdaptiveController: Failed")
            all_passed = False
        
        # Test Integrated Controller
        from adaptive_integration import IntegratedHealingController
        integrated = IntegratedHealingController()
        print(f"  βœ… IntegratedController: mode={integrated.mode}")
        
    except Exception as e:
        print(f"  ❌ Adaptive test failed: {e}")
        all_passed = False
    
    return all_passed


def test_phase3_features():
    """Test Phase 3 enterprise features."""
    print("\n🏒 Testing Phase 3 features...")
    
    all_passed = True
    
    try:
        # Test SLA Simulator
        from orchestration.sla_simulator import SLASimulator
        from datetime import datetime, timedelta
        
        sla = SLASimulator()
        outcome = {'performance_change': -0.1, 'recovery_time': 150.0}
        impact = sla.simulate_sla_impact(
            action='retrain',
            outcome=outcome,
            start_time=datetime.now() - timedelta(minutes=5),
            end_time=datetime.now()
        )
        print(f"  βœ… SLASimulator: {impact.get('action', 'N/A')}")
        
        # Test Canary Controller
        from orchestration.canary_controller import CanaryController
        
        canary = CanaryController()
        status = canary.get_rollout_status()
        print(f"  βœ… CanaryController: stage={status.get('current_stage', 'N/A')}")
        
        # Test Shadow Learner
        from adaptive.learning.shadow_learner import ShadowLearner
        
        shadow = ShadowLearner()
        context = {'data_drift': 0.25}
        shadow_exp = shadow.simulate_decision(context, 'retrain', 'fallback')
        print(f"  βœ… ShadowLearner: created experience")
        
        # Test Portfolio Demo
        from portfolio.interview_demo import demonstrate_system_capabilities
        print(f"  βœ… Portfolio demo: import successful")
        
    except Exception as e:
        print(f"  ❌ Phase 3 test failed: {e}")
        all_passed = False
    
    return all_passed


def run_comprehensive_test():
    """Run all comprehensive tests."""
    print("=" * 80)
    print("πŸ§ͺ COMPREHENSIVE TEST SUITE - SELF-HEALING ML PIPELINES")
    print("=" * 80)
    
    results = {}
    
    # Run all tests
    results['imports'] = test_module_imports()
    results['configs'] = test_config_files()
    results['data'] = test_data_files()
    results['integration'] = test_system_integration()
    results['adaptive'] = test_adaptive_system()
    results['phase3'] = test_phase3_features()
    
    # Summary
    print("\n" + "=" * 80)
    print("πŸ“Š TEST SUMMARY")
    print("=" * 80)
    
    passed = sum(results.values())
    total = len(results)
    
    for test_name, result in results.items():
        status = "βœ… PASS" if result else "❌ FAIL"
        print(f"{status} {test_name}")
    
    print(f"\nπŸ“ˆ Overall: {passed}/{total} tests passed ({passed/total*100:.1f}%)")
    
    if passed == total:
        print("\nπŸŽ‰ ALL TESTS PASSED! System is ready for production.")
        return True
    else:
        print(f"\n⚠️  {total - passed} tests failed. Review issues above.")
        return False


if __name__ == "__main__":
    success = run_comprehensive_test()
    sys.exit(0 if success else 1)