File size: 10,060 Bytes
95e10ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

Post-deployment test script for HealthGuard-AI.

This script tests the deployed application to ensure everything is working correctly.

"""

import os
import requests
import time
import sys
from datetime import datetime

class HealthGuardTester:
    def __init__(self, base_url):
        self.base_url = base_url.rstrip('/')
        self.session = requests.Session()
        self.test_results = []
    
    def log_result(self, test_name, success, details=""):
        """Log a test result."""
        status = "PASS" if success else "FAIL"
        result = f"[{status}] {test_name}"
        if details:
            result += f" - {details}"
        print(result)
        self.test_results.append((test_name, success, details))
        return success
    
    def test_home_page(self):
        """Test if home page loads."""
        try:
            response = self.session.get(self.base_url, timeout=10)
            success = response.status_code == 200
            details = f"Status: {response.status_code}, Length: {len(response.text)} chars"
            return self.log_result("Home Page Load", success, details)
        except Exception as e:
            return self.log_result("Home Page Load", False, f"Error: {e}")
    
    def test_login_page(self):
        """Test if login page loads."""
        try:
            response = self.session.get(f"{self.base_url}/login", timeout=10)
            success = response.status_code == 200
            details = f"Status: {response.status_code}, Length: {len(response.text)} chars"
            return self.log_result("Login Page Load", success, details)
        except Exception as e:
            return self.log_result("Login Page Load", False, f"Error: {e}")
    
    def test_debug_endpoints(self):
        """Test debug endpoints."""
        endpoints = [
            "/debug/login-status",
            "/debug/test-session",
            "/debug/clear-session"
        ]
        
        all_success = True
        for endpoint in endpoints:
            try:
                response = self.session.get(f"{self.base_url}{endpoint}", timeout=10)
                success = response.status_code in [200, 404]  # 404 might be OK if not implemented
                details = f"Status: {response.status_code}"
                if response.status_code == 200:
                    try:
                        data = response.json()
                        details += f", Data keys: {list(data.keys())}"
                    except:
                        details += f", Response: {response.text[:100]}..."
                endpoint_success = self.log_result(f"Debug Endpoint {endpoint}", success, details)
                all_success = all_success and endpoint_success
            except Exception as e:
                endpoint_success = self.log_result(f"Debug Endpoint {endpoint}", False, f"Error: {e}")
                all_success = all_success and endpoint_success
        
        return all_success
    
    def test_session_functionality(self):
        """Test session functionality."""
        try:
            # Clear session first
            self.session.get(f"{self.base_url}/debug/clear-session", timeout=10)
            
            # Set session
            response = self.session.get(f"{self.base_url}/debug/test-session", timeout=10)
            if response.status_code == 200:
                data = response.json()
                session_set = "test" in data.get("session_data", {})
                details = f"Session set: {session_set}"
                if session_set:
                    details += f", Session data: {data['session_data']}"
                return self.log_result("Session Functionality", session_set, details)
            else:
                return self.log_result("Session Functionality", False, f"Status: {response.status_code}")
        except Exception as e:
            return self.log_result("Session Functionality", False, f"Error: {e}")
    
    def test_user_lookup(self, email=None):
        """Test user lookup functionality."""
        if not email:
            # Try to get a user email from environment or use a test one
            email = os.getenv("TEST_USER_EMAIL", "test@example.com")
        
        try:
            response = self.session.get(f"{self.base_url}/debug/user/{email}", timeout=10)
            success = response.status_code in [200, 404]
            details = f"Status: {response.status_code}"
            if response.status_code == 200:
                try:
                    data = response.json()
                    details += f", User found: {data.get('status') == 'User found'}"
                except:
                    details += f", Response: {response.text[:100]}..."
            elif response.status_code == 404:
                details += ", User not found (this may be OK)"
            return self.log_result("User Lookup", success, details)
        except Exception as e:
            return self.log_result("User Lookup", False, f"Error: {e}")
    
    def simulate_login_flow(self, email=None, password=None):
        """Simulate the complete login flow."""
        if not email or not password:
            print("Skipping login flow test - credentials not provided")
            return True
        
        try:
            # 1. Get login page
            response = self.session.get(f"{self.base_url}/login", timeout=10)
            if response.status_code != 200:
                return self.log_result("Login Flow", False, f"Failed to load login page: {response.status_code}")
            
            # 2. Check pre-login status
            response = self.session.get(f"{self.base_url}/debug/login-status", timeout=10)
            pre_login_status = {}
            if response.status_code == 200:
                pre_login_status = response.json()
            
            # 3. Perform login
            login_data = {
                'email': email,
                'password': password
            }
            response = self.session.post(f"{self.base_url}/login", data=login_data, timeout=10, allow_redirects=False)
            
            # 4. Check post-login status
            response2 = self.session.get(f"{self.base_url}/debug/login-status", timeout=10)
            post_login_status = {}
            if response2.status_code == 200:
                post_login_status = response2.json()
            
            # 5. Try to access dashboard
            response3 = self.session.get(f"{self.base_url}/user/dashboard", timeout=10, allow_redirects=False)
            dashboard_status = response3.status_code
            
            # Analyze results
            logged_in = 'user_id' in post_login_status.get('session_data', {})
            redirected_to_dashboard = response.status_code in [301, 302, 303, 307, 308] and '/dashboard' in response.headers.get('Location', '')
            dashboard_accessible = dashboard_status == 200
            
            success = logged_in and (redirected_to_dashboard or dashboard_accessible)
            details = f"Logged in: {logged_in}, Redirected: {redirected_to_dashboard}, Dashboard: {dashboard_status}"
            details += f", Pre-login: {pre_login_status.get('user_logged_in', False)}, Post-login: {post_login_status.get('user_logged_in', False)}"
            
            return self.log_result("Login Flow", success, details)
        except Exception as e:
            return self.log_result("Login Flow", False, f"Error: {e}")
    
    def run_all_tests(self, email=None, password=None):
        """Run all tests."""
        print(f"HealthGuard-AI Post-Deployment Test")
        print(f"Testing against: {self.base_url}")
        print(f"Time: {datetime.now()}")
        print("=" * 50)
        
        tests = [
            self.test_home_page,
            self.test_login_page,
            self.test_debug_endpoints,
            self.test_session_functionality,
            lambda: self.test_user_lookup(email),
            lambda: self.simulate_login_flow(email, password)
        ]
        
        for test in tests:
            test()
            print()  # Empty line for readability
        
        # Summary
        print("=" * 50)
        print("TEST SUMMARY")
        print("=" * 50)
        
        passed = sum(1 for _, success, _ in self.test_results if success)
        total = len(self.test_results)
        
        for test_name, success, details in self.test_results:
            status = "PASS" if success else "FAIL"
            print(f"[{status}] {test_name}")
            if details:
                print(f"      {details}")
        
        print(f"\nOverall: {passed}/{total} tests passed")
        
        if passed == total:
            print("✓ All tests passed! Application appears to be working correctly.")
            return True
        else:
            print("✗ Some tests failed. Please check the output above.")
            return False

def main():
    """Main function."""
    print("HealthGuard-AI Post-Deployment Tester")
    print("=" * 40)
    
    # Get base URL from command line or environment
    if len(sys.argv) > 1:
        base_url = sys.argv[1]
    else:
        base_url = os.getenv('APP_URL', 'http://localhost:7860')
    
    # Get credentials if provided
    email = os.getenv('TEST_USER_EMAIL')
    password = os.getenv('TEST_USER_PASSWORD')
    
    if not email:
        email = input("Enter test user email (or press Enter to skip login test): ").strip()
    
    if email and not password:
        password = input("Enter test user password: ").strip()
    
    if not email:
        email = None
        password = None
    
    # Create tester and run tests
    tester = HealthGuardTester(base_url)
    success = tester.run_all_tests(email, password)
    
    sys.exit(0 if success else 1)

if __name__ == "__main__":
    main()