File size: 7,209 Bytes
f84a02d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
ATOM Integration Test Suite
Tests all frontend-backend connections
"""

import json
import sys
import time
from typing import Any, Dict, List
import requests


class AtomIntegrationTester:
    def __init__(self):
        self.backend_url = "http://localhost:5058"
        self.results = {}
        
    def test_backend_health(self) -> Dict[str, Any]:
        """Test backend health endpoint"""
        try:
            response = requests.get(f"{self.backend_url}/healthz", timeout=5)
            return {
                "ok": response.status_code == 200,
                "status_code": response.status_code,
                "data": response.json() if response.headers.get('content-type', '').startswith('application/json') else response.text,
                "response_time": response.elapsed.total_seconds()
            }
        except Exception as e:
            return {
                "ok": False,
                "error": str(e),
                "response_time": 5.0
            }
    
    def test_service_integrations(self) -> Dict[str, Dict[str, Any]]:
        """Test all service integrations"""
        services = ['gmail', 'slack', 'asana', 'github', 'notion', 'trello', 'outlook']
        results = {}
        
        for service in services:
            try:
                start_time = time.time()
                response = requests.get(f"{self.backend_url}/api/{service}/health", timeout=10)
                end_time = time.time()
                
                results[service] = {
                    "ok": response.status_code == 200,
                    "status_code": response.status_code,
                    "response_time": end_time - start_time,
                    "data": response.json() if response.headers.get('content-type', '').startswith('application/json') else response.text
                }
            except Exception as e:
                results[service] = {
                    "ok": False,
                    "error": str(e),
                    "response_time": 10.0
                }
        
        return results
    
    def test_api_endpoints(self) -> Dict[str, Any]:
        """Test general API endpoints"""
        try:
            response = requests.get(f"{self.backend_url}/api/test", timeout=5)
            return {
                "ok": response.status_code == 200,
                "data": response.json() if response.headers.get('content-type', '').startswith('application/json') else response.text,
                "status_code": response.status_code
            }
        except Exception as e:
            return {
                "ok": False,
                "error": str(e)
            }
    
    def run_comprehensive_test(self) -> Dict[str, Any]:
        """Run all integration tests"""
        print("🚀 Starting ATOM Integration Tests...")
        print(f"📍 Testing backend at: {self.backend_url}")
        print("=" * 50)
        
        # Test backend health
        print("1. Testing backend health...")
        health_result = self.test_backend_health()
        self.results["health"] = health_result
        
        if health_result["ok"]:
            print(f"   ✅ Backend healthy (Response time: {health_result.get('response_time', 0):.2f}s)")
            print(f"   📊 Status: {health_result.get('data', {}).get('status', 'Unknown')}")
        else:
            print(f"   ❌ Backend unhealthy: {health_result.get('error', 'Unknown error')}")
            print("   ⚠️  Skipping other tests due to backend connection failure")
            return self.results
        
        # Test API endpoint
        print("\n2. Testing API endpoint...")
        api_result = self.test_api_endpoints()
        self.results["api"] = api_result
        
        if api_result["ok"]:
            print("   ✅ API endpoint working")
        else:
            print(f"   ❌ API endpoint failed: {api_result.get('error', 'Unknown error')}")
        
        # Test service integrations
        print("\n3. Testing service integrations...")
        service_results = self.test_service_integrations()
        self.results["services"] = service_results
        
        for service, result in service_results.items():
            if result["ok"]:
                print(f"   ✅ {service.capitalize()}: Connected ({result.get('response_time', 0):.2f}s)")
            else:
                print(f"   ❌ {service.capitalize()}: {result.get('error', 'Connection failed')}")
        
        return self.results
    
    def generate_report(self) -> str:
        """Generate integration test report"""
        if not self.results:
            return "No test results available. Run tests first."
        
        report = []
        report.append("ATOM INTEGRATION TEST REPORT")
        report.append("=" * 40)
        report.append(f"Timestamp: {time.strftime('%Y-%m-%d %H:%M:%S')}")
        report.append("")
        
        # Health status
        health = self.results.get("health", {})
        report.append("BACKEND HEALTH:")
        if health.get("ok"):
            report.append(f"  Status: ✅ HEALTHY")
            report.append(f"  Response Time: {health.get('response_time', 0):.2f}s")
        else:
            report.append(f"  Status: ❌ UNHEALTHY")
            report.append(f"  Error: {health.get('error', 'Unknown')}")
        report.append("")
        
        # Service integrations
        services = self.results.get("services", {})
        report.append("SERVICE INTEGRATIONS:")
        connected_count = sum(1 for s in services.values() if s.get("ok"))
        total_count = len(services)
        
        for service, result in services.items():
            status = "✅ CONNECTED" if result.get("ok") else "❌ FAILED"
            response_time = result.get("response_time", 0)
            report.append(f"  {service.capitalize()}: {status} ({response_time:.2f}s)")
        
        report.append(f"\nSummary: {connected_count}/{total_count} services connected")
        report.append("")
        
        # Overall status
        overall_healthy = health.get("ok") and connected_count > 0
        report.append(f"OVERALL STATUS: {'✅ HEALTHY' if overall_healthy else '❌ NEEDS ATTENTION'}")
        
        return "\n".join(report)

def main():
    """Main test execution"""
    tester = AtomIntegrationTester()
    
    try:
        results = tester.run_comprehensive_test()
        report = tester.generate_report()
        print("\n" + report)
        
        # Save report to file
        with open("integration_test_report.txt", "w") as f:
            f.write(report)
        
        print(f"\n📄 Report saved to: integration_test_report.txt")
        
        # Exit with appropriate code
        overall_healthy = results.get("health", {}).get("ok") and \
                         sum(1 for results in results.get("services", {}).values() if results.get("ok")) > 0
        
        sys.exit(0 if overall_healthy else 1)
        
    except KeyboardInterrupt:
        print("\n⚠️  Tests interrupted by user")
        sys.exit(1)
    except Exception as e:
        print(f"\n❌ Test suite error: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()