File size: 8,533 Bytes
81923e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Test script for WhatsApp-like chat application
Demonstrates: Register β†’ Login β†’ Add Contact β†’ Send Message β†’ Status Updates
"""

import requests
import time
import json
from socketio import SimpleClient

BASE_URL = 'http://localhost:5000'

def print_step(step, message):
    print(f"\n{'='*60}")
    print(f"STEP {step}: {message}")
    print('='*60)

def test_registration():
    print_step(1, "Testing User Registration")
    
    user1_data = {
        'name': 'Test User 1',
        'email': f'testuser1_{int(time.time())}@test.com'
    }
    
    user2_data = {
        'name': 'Test User 2',
        'email': f'testuser2_{int(time.time())}@test.com'
    }
    
    print("\nπŸ“ Registering User 1...")
    response1 = requests.post(f'{BASE_URL}/api/register', json=user1_data)
    user1 = response1.json()
    print(f"βœ… User 1 registered successfully!")
    print(f"   Name: {user1['name']}")
    print(f"   ID: {user1['user_id']}")
    print(f"   Token: {user1['token'][:20]}...")
    
    print("\nπŸ“ Registering User 2...")
    response2 = requests.post(f'{BASE_URL}/api/register', json=user2_data)
    user2 = response2.json()
    print(f"βœ… User 2 registered successfully!")
    print(f"   Name: {user2['name']}")
    print(f"   ID: {user2['user_id']}")
    print(f"   Token: {user2['token'][:20]}...")
    
    return user1, user2

def test_login(user):
    print_step(2, "Testing User Login")
    
    login_data = {
        'user_id': user['user_id'],
        'token': user['token']
    }
    
    print(f"\nπŸ” Logging in as {user['name']}...")
    response = requests.post(f'{BASE_URL}/api/login', json=login_data)
    result = response.json()
    
    if response.status_code == 200:
        print(f"βœ… Login successful!")
        print(f"   User: {result['name']}")
        print(f"   Email: {result['email']}")
        return True
    else:
        print(f"❌ Login failed: {result.get('error')}")
        return False

def test_add_contact(user1, user2):
    print_step(3, "Testing Add Contact")
    
    contact_data = {
        'token': user1['token'],
        'contact_id': user2['user_id']
    }
    
    print(f"\nπŸ‘₯ {user1['name']} adding {user2['name']} as contact...")
    response = requests.post(f'{BASE_URL}/api/contacts/add', json=contact_data)
    
    if response.status_code == 200:
        result = response.json()
        print(f"βœ… Contact added successfully!")
        print(f"   Contact Name: {result['name']}")
        print(f"   Contact ID: {result['contact_id']}")
        return True
    else:
        error = response.json().get('error')
        print(f"❌ Failed to add contact: {error}")
        return False

def test_get_contacts(user):
    print_step(4, "Testing Get Contacts")
    
    print(f"\nπŸ“‹ Getting contacts for {user['name']}...")
    response = requests.post(f'{BASE_URL}/api/contacts', 
                            json={'token': user['token']})
    
    if response.status_code == 200:
        result = response.json()
        contacts = result['contacts']
        print(f"βœ… Retrieved {len(contacts)} contact(s):")
        for contact in contacts:
            print(f"   - {contact['name']} (ID: {contact['user_id']})")
        return contacts
    else:
        print(f"❌ Failed to get contacts")
        return []

def test_websocket_messaging(user1, user2):
    print_step(5, "Testing WebSocket Real-time Messaging")
    
    print("\nπŸ”Œ Connecting User 1 via WebSocket...")
    client1 = SimpleClient()
    client1.connect(BASE_URL)
    client1.emit('authenticate', {'token': user1['token']})
    
    event = client1.receive(timeout=5)
    if event[0] == 'authenticated' and event[1]['success']:
        print("βœ… User 1 authenticated via WebSocket")
    
    print("\nπŸ”Œ Connecting User 2 via WebSocket...")
    client2 = SimpleClient()
    client2.connect(BASE_URL)
    client2.emit('authenticate', {'token': user2['token']})
    
    event = client2.receive(timeout=5)
    if event[0] == 'authenticated' and event[1]['success']:
        print("βœ… User 2 authenticated via WebSocket")
    
    print("\nπŸ’¬ User 1 sending message to User 2...")
    test_message = "Hello from automated test! πŸ‘‹"
    client1.emit('send_message', {
        'token': user1['token'],
        'to': user2['user_id'],
        'message': test_message
    })
    
    time.sleep(1)
    
    print("\nπŸ“¨ Checking for received messages...")
    received_messages = []
    
    try:
        while True:
            event = client2.receive(timeout=2)
            print(f"   Received event: {event[0]}")
            
            if event[0] == 'new_message':
                msg = event[1]
                received_messages.append(msg)
                print(f"βœ… Message received!")
                print(f"   From: {msg['from']}")
                print(f"   Message: {msg['message']}")
                print(f"   Status: {msg['status']}")
                
                print(f"\nπŸ“– User 2 marking message as read...")
                client2.emit('mark_conversation_read', {
                    'token': user2['token'],
                    'contact_id': user1['user_id']
                })
                break
    except:
        pass
    
    time.sleep(1)
    
    print("\nπŸ”„ Checking for status updates on User 1's side...")
    try:
        while True:
            event = client1.receive(timeout=2)
            if event[0] == 'message_status_update':
                status_update = event[1]
                print(f"βœ… Status update received!")
                print(f"   Message ID: {status_update['message_id']}")
                print(f"   New Status: {status_update['status']}")
                if status_update['status'] == 'read':
                    print("\n✨ Message lifecycle complete: sent β†’ delivered β†’ read")
                    break
    except:
        pass
    
    print("\nπŸ”Œ Disconnecting clients...")
    client1.disconnect()
    client2.disconnect()
    
    return len(received_messages) > 0

def test_message_persistence(user1, user2):
    print_step(6, "Testing Message Persistence")
    
    print(f"\nπŸ“š Loading message history...")
    response = requests.post(f'{BASE_URL}/api/messages', 
                            json={
                                'token': user1['token'],
                                'contact_id': user2['user_id']
                            })
    
    if response.status_code == 200:
        result = response.json()
        messages = result['messages']
        print(f"βœ… Retrieved {len(messages)} message(s) from JSON storage:")
        for msg in messages[-3:]:
            print(f"   [{msg['status']}] {msg['from'][:8]}... β†’ {msg['to'][:8]}...: {msg['message'][:30]}")
        return True
    else:
        print(f"❌ Failed to load messages")
        return False

def main():
    print("\n" + "="*60)
    print("WhatsApp-like Chat Application - Automated Test Suite")
    print("="*60)
    
    try:
        user1, user2 = test_registration()
        time.sleep(1)
        
        test_login(user1)
        time.sleep(1)
        
        test_add_contact(user1, user2)
        test_add_contact(user2, user1)
        time.sleep(1)
        
        test_get_contacts(user1)
        time.sleep(1)
        
        test_websocket_messaging(user1, user2)
        time.sleep(1)
        
        test_message_persistence(user1, user2)
        
        print("\n" + "="*60)
        print("βœ… ALL TESTS COMPLETED SUCCESSFULLY!")
        print("="*60)
        print("\nπŸ“‹ Test Summary:")
        print("   βœ… User Registration")
        print("   βœ… User Login")
        print("   βœ… Add Contact")
        print("   βœ… Get Contacts")
        print("   βœ… Real-time Messaging via WebSocket")
        print("   βœ… Message Status Lifecycle (sent β†’ delivered β†’ read)")
        print("   βœ… Message Persistence in JSON")
        print("\nπŸ’‘ You can now login with these test credentials:")
        print(f"   User 1 ID: {user1['user_id']}")
        print(f"   User 1 Token: {user1['token']}")
        print(f"   User 2 ID: {user2['user_id']}")
        print(f"   User 2 Token: {user2['token']}")
        
    except Exception as e:
        print(f"\n❌ Test failed with error: {str(e)}")
        import traceback
        traceback.print_exc()

if __name__ == '__main__':
    print("\n⚠️  Make sure the server is running on http://localhost:5000")
    print("Starting tests in 3 seconds...\n")
    time.sleep(3)
    main()