File size: 13,841 Bytes
2469150
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Enterprise-grade test runner for FRED ML
Consolidates all testing functionality into a single, comprehensive test suite
"""

import sys
import os
import subprocess
import argparse
import time
import json
from pathlib import Path
from typing import Dict, List, Optional, Tuple

# Add project root to path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))


class TestRunner:
    """Enterprise-grade test runner for FRED ML"""
    
    def __init__(self):
        self.project_root = Path(__file__).parent.parent
        self.test_results = {}
        self.start_time = time.time()
        
    def run_command(self, command: List[str], capture_output: bool = True) -> Tuple[int, str, str]:
        """Run a command and return results"""
        try:
            result = subprocess.run(
                command,
                capture_output=capture_output,
                text=True,
                cwd=self.project_root
            )
            return result.returncode, result.stdout, result.stderr
        except Exception as e:
            return 1, "", str(e)
    
    def run_unit_tests(self) -> Dict:
        """Run unit tests"""
        print("πŸ§ͺ Running Unit Tests...")
        print("=" * 50)
        
        start_time = time.time()
        returncode, stdout, stderr = self.run_command([
            "python", "-m", "pytest", "tests/unit/", "-v", "--tb=short"
        ])
        end_time = time.time()
        
        result = {
            "success": returncode == 0,
            "returncode": returncode,
            "stdout": stdout,
            "stderr": stderr,
            "duration": end_time - start_time
        }
        
        if result["success"]:
            print("βœ… Unit tests passed")
        else:
            print("❌ Unit tests failed")
            if stderr:
                print(f"Error: {stderr}")
        
        return result
    
    def run_integration_tests(self) -> Dict:
        """Run integration tests"""
        print("\nπŸ”— Running Integration Tests...")
        print("=" * 50)
        
        start_time = time.time()
        returncode, stdout, stderr = self.run_command([
            "python", "-m", "pytest", "tests/integration/", "-v", "--tb=short"
        ])
        end_time = time.time()
        
        result = {
            "success": returncode == 0,
            "returncode": returncode,
            "stdout": stdout,
            "stderr": stderr,
            "duration": end_time - start_time
        }
        
        if result["success"]:
            print("βœ… Integration tests passed")
        else:
            print("❌ Integration tests failed")
            if stderr:
                print(f"Error: {stderr}")
        
        return result
    
    def run_e2e_tests(self) -> Dict:
        """Run end-to-end tests"""
        print("\nπŸš€ Running End-to-End Tests...")
        print("=" * 50)
        
        start_time = time.time()
        returncode, stdout, stderr = self.run_command([
            "python", "-m", "pytest", "tests/e2e/", "-v", "--tb=short"
        ])
        end_time = time.time()
        
        result = {
            "success": returncode == 0,
            "returncode": returncode,
            "stdout": stdout,
            "stderr": stderr,
            "duration": end_time - start_time
        }
        
        if result["success"]:
            print("βœ… End-to-end tests passed")
        else:
            print("❌ End-to-end tests failed")
            if stderr:
                print(f"Error: {stderr}")
        
        return result
    
    def run_import_tests(self) -> Dict:
        """Test module imports"""
        print("\nπŸ“¦ Testing Module Imports...")
        print("=" * 50)
        
        start_time = time.time()
        
        # Test core imports
        import_tests = [
            ("src.core.enhanced_fred_client", "EnhancedFREDClient"),
            ("src.analysis.comprehensive_analytics", "ComprehensiveAnalytics"),
            ("src.analysis.economic_forecasting", "EconomicForecaster"),
            ("src.analysis.economic_segmentation", "EconomicSegmentation"),
            ("src.analysis.statistical_modeling", "StatisticalModeling"),
            ("src.analysis.mathematical_fixes", "MathematicalFixes"),
        ]
        
        failed_imports = []
        successful_imports = []
        
        for module, class_name in import_tests:
            try:
                module_obj = __import__(module, fromlist=[class_name])
                class_obj = getattr(module_obj, class_name)
                successful_imports.append(f"{module}.{class_name}")
                print(f"βœ… {module}.{class_name}")
            except ImportError as e:
                failed_imports.append(f"{module}.{class_name} ({str(e)})")
                print(f"❌ {module}.{class_name} - {e}")
            except Exception as e:
                failed_imports.append(f"{module}.{class_name} ({str(e)})")
                print(f"❌ {module}.{class_name} - {e}")
        
        end_time = time.time()
        
        result = {
            "success": len(failed_imports) == 0,
            "successful_imports": successful_imports,
            "failed_imports": failed_imports,
            "duration": end_time - start_time
        }
        
        if result["success"]:
            print("βœ… All imports successful")
        else:
            print(f"❌ {len(failed_imports)} imports failed")
        
        return result
    
    def run_code_quality_tests(self) -> Dict:
        """Run code quality checks"""
        print("\nπŸ” Running Code Quality Checks...")
        print("=" * 50)
        
        start_time = time.time()
        
        # Check for common issues
        issues = []
        
        # Check for debug statements
        debug_files = []
        for root, dirs, files in os.walk(self.project_root):
            if "tests" in root or ".git" in root or "__pycache__" in root:
                continue
            for file in files:
                if file.endswith('.py'):
                    file_path = os.path.join(root, file)
                    try:
                        with open(file_path, 'r') as f:
                            content = f.read()
                            if 'print(' in content and 'DEBUG:' in content:
                                debug_files.append(file_path)
                    except Exception:
                        pass
        
        if debug_files:
            issues.append(f"Debug statements found in {len(debug_files)} files")
        
        # Check for TODO comments
        todo_files = []
        for root, dirs, files in os.walk(self.project_root):
            if "tests" in root or ".git" in root or "__pycache__" in root:
                continue
            for file in files:
                if file.endswith('.py'):
                    file_path = os.path.join(root, file)
                    try:
                        with open(file_path, 'r') as f:
                            content = f.read()
                            if 'TODO:' in content or 'FIXME:' in content:
                                todo_files.append(file_path)
                    except Exception:
                        pass
        
        if todo_files:
            issues.append(f"TODO/FIXME comments found in {len(todo_files)} files")
        
        end_time = time.time()
        
        result = {
            "success": len(issues) == 0,
            "issues": issues,
            "debug_files": debug_files,
            "todo_files": todo_files,
            "duration": end_time - start_time
        }
        
        if result["success"]:
            print("βœ… Code quality checks passed")
        else:
            print("⚠️ Code quality issues found:")
            for issue in issues:
                print(f"  - {issue}")
        
        return result
    
    def run_performance_tests(self) -> Dict:
        """Run performance tests"""
        print("\n⚑ Running Performance Tests...")
        print("=" * 50)
        
        start_time = time.time()
        
        # Basic performance tests
        import time
        import pandas as pd
        import numpy as np
        
        performance_results = {}
        
        # Test data processing performance
        data_start = time.time()
        large_data = pd.DataFrame({
            'GDPC1': np.random.normal(22000, 1000, 1000),
            'INDPRO': np.random.normal(100, 5, 1000),
            'CPIAUCSL': np.random.normal(250, 10, 1000)
        })
        data_end = time.time()
        performance_results['data_creation'] = data_end - data_start
        
        # Test computation performance
        comp_start = time.time()
        large_data.describe()
        large_data.corr()
        comp_end = time.time()
        performance_results['computation'] = comp_end - comp_start
        
        end_time = time.time()
        
        result = {
            "success": performance_results['computation'] < 5.0,  # Should complete within 5 seconds
            "performance_results": performance_results,
            "duration": end_time - start_time
        }
        
        if result["success"]:
            print("βœ… Performance tests passed")
            print(f"  - Data creation: {performance_results['data_creation']:.3f}s")
            print(f"  - Computation: {performance_results['computation']:.3f}s")
        else:
            print("❌ Performance tests failed - computation too slow")
        
        return result
    
    def generate_report(self) -> Dict:
        """Generate comprehensive test report"""
        total_duration = time.time() - self.start_time
        
        report = {
            "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
            "total_duration": total_duration,
            "results": self.test_results,
            "summary": {
                "total_tests": len(self.test_results),
                "passed_tests": sum(1 for r in self.test_results.values() if r.get("success", False)),
                "failed_tests": sum(1 for r in self.test_results.values() if not r.get("success", True))
            }
        }
        
        return report
    
    def print_summary(self, report: Dict):
        """Print test summary"""
        print("\n" + "=" * 60)
        print("πŸ“Š TEST SUMMARY")
        print("=" * 60)
        
        summary = report["summary"]
        print(f"Total Tests: {summary['total_tests']}")
        print(f"Passed: {summary['passed_tests']}")
        print(f"Failed: {summary['failed_tests']}")
        print(f"Success Rate: {(summary['passed_tests'] / summary['total_tests'] * 100):.1f}%")
        print(f"Total Duration: {report['total_duration']:.2f}s")
        
        print("\nπŸ“‹ Detailed Results:")
        for test_name, result in report["results"].items():
            status = "βœ… PASS" if result.get("success", False) else "❌ FAIL"
            duration = f"{result.get('duration', 0):.2f}s"
            print(f"  {test_name}: {status} ({duration})")
        
        if summary['failed_tests'] == 0:
            print("\nπŸŽ‰ All tests passed! The system is ready for production.")
        else:
            print(f"\n⚠️ {summary['failed_tests']} test(s) failed. Please review the results above.")
    
    def save_report(self, report: Dict, filename: str = "test_report.json"):
        """Save test report to file"""
        report_path = self.project_root / filename
        try:
            with open(report_path, 'w') as f:
                json.dump(report, f, indent=2, default=str)
            print(f"\nπŸ“„ Test report saved to: {report_path}")
        except Exception as e:
            print(f"\n❌ Failed to save test report: {e}")
    
    def run_all_tests(self, save_report: bool = True) -> Dict:
        """Run all tests and generate report"""
        print("πŸš€ FRED ML - Enterprise Test Suite")
        print("=" * 60)
        
        # Run all test categories
        self.test_results["unit_tests"] = self.run_unit_tests()
        self.test_results["integration_tests"] = self.run_integration_tests()
        self.test_results["e2e_tests"] = self.run_e2e_tests()
        self.test_results["import_tests"] = self.run_import_tests()
        self.test_results["code_quality"] = self.run_code_quality_tests()
        self.test_results["performance_tests"] = self.run_performance_tests()
        
        # Generate and display report
        report = self.generate_report()
        self.print_summary(report)
        
        if save_report:
            self.save_report(report)
        
        return report


def main():
    """Main entry point"""
    parser = argparse.ArgumentParser(description="FRED ML Test Runner")
    parser.add_argument("--no-report", action="store_true", help="Don't save test report")
    parser.add_argument("--unit-only", action="store_true", help="Run only unit tests")
    parser.add_argument("--integration-only", action="store_true", help="Run only integration tests")
    parser.add_argument("--e2e-only", action="store_true", help="Run only end-to-end tests")
    
    args = parser.parse_args()
    
    runner = TestRunner()
    
    if args.unit_only:
        runner.test_results["unit_tests"] = runner.run_unit_tests()
    elif args.integration_only:
        runner.test_results["integration_tests"] = runner.run_integration_tests()
    elif args.e2e_only:
        runner.test_results["e2e_tests"] = runner.run_e2e_tests()
    else:
        runner.run_all_tests(save_report=not args.no_report)
    
    # Exit with appropriate code
    total_failed = sum(1 for r in runner.test_results.values() if not r.get("success", True))
    sys.exit(1 if total_failed > 0 else 0)


if __name__ == "__main__":
    main()