-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth_selenium_tests.py
More file actions
562 lines (460 loc) · 25.5 KB
/
auth_selenium_tests.py
File metadata and controls
562 lines (460 loc) · 25.5 KB
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
import time
import random
import string
import sys
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from colorama import Fore, Style, init
# Initialize colorama for colored output
init(autoreset=True)
class AuthTester:
def __init__(self):
chrome_options = Options()
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--log-level=3") # Suppress console logs
chrome_options.add_experimental_option('excludeSwitches', ['enable-logging']) # Suppress DevTools
self.driver = webdriver.Chrome(options=chrome_options)
self.driver.implicitly_wait(10)
self.base_url = "http://localhost:3000"
self.test_results = []
self.passed_count = 0
self.failed_count = 0
def print_header(self):
"""Print a nice header for the test suite"""
print("\n" + "=" * 70)
print(f"{Fore.CYAN}{'AUTHENTICATION TEST SUITE':^70}")
print("=" * 70 + "\n")
def print_test_header(self, test_name):
"""Print header for each test"""
print(f"\n{Fore.YELLOW}▶ Running: {test_name}")
print(f"{Fore.YELLOW}{'─' * 70}")
def log_result(self, test_name, passed, message=""):
"""Log test result with improved formatting"""
if passed:
status_icon = "✓"
status_color = Fore.GREEN
status_text = "PASS"
self.passed_count += 1
else:
status_icon = "✗"
status_color = Fore.RED
status_text = "FAIL"
self.failed_count += 1
result = {
'name': test_name,
'passed': passed,
'message': message
}
self.test_results.append(result)
# Print immediate result
print(f"{status_color}{status_icon} {status_text}: {message if message else test_name}")
def generate_random_email(self):
random_string = ''.join(random.choices(string.ascii_lowercase + string.digits, k=8))
return f"test_{random_string}@example.com"
def generate_random_username(self):
return f"user_{random.randint(1000, 9999)}"
def generate_strong_password(self):
return f"StrongPass{random.randint(100, 999)}!"
def wait_for_element(self, by, value, timeout=10):
try:
return WebDriverWait(self.driver, timeout).until(
EC.presence_of_element_located((by, value))
)
except TimeoutException:
return None
def test_signup_valid_user(self):
test_name = "Signup with Valid User"
self.print_test_header(test_name)
try:
self.driver.get(self.base_url)
email = self.generate_random_email()
username = self.generate_random_username()
first_name = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-firstname"]')
last_name = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-lastname"]')
username_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-username"]')
email_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-email"]')
password_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-password"]')
confirm_password_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-confirm-password"]')
submit_btn = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-submit-btn"]')
if not all([first_name, last_name, username_field, email_field, password_field, confirm_password_field, submit_btn]):
self.log_result(test_name, False, "Required form elements not found")
return False
strong_password = self.generate_strong_password()
first_name.send_keys("John")
last_name.send_keys("Doe")
username_field.send_keys(username)
email_field.send_keys(email)
password_field.send_keys(strong_password)
confirm_password_field.send_keys(strong_password)
submit_btn.click()
time.sleep(3)
current_url = self.driver.current_url
if "/components/Login" in current_url:
self.log_result(test_name, True, f"User '{username}' created successfully")
return True
else:
error_msg = self.driver.find_elements(By.CSS_SELECTOR, '[data-testid="signup-error-msg"]')
error_text = error_msg[0].text if error_msg else "Unknown error"
self.log_result(test_name, False, f"Signup failed: {error_text}")
return False
except Exception as e:
self.log_result(test_name, False, f"Unexpected error: {str(e)[:100]}")
return False
def test_signup_short_password(self):
test_name = "Signup with Short Password"
self.print_test_header(test_name)
try:
self.driver.get(self.base_url)
email = self.generate_random_email()
username = self.generate_random_username()
first_name = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-firstname"]')
last_name = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-lastname"]')
username_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-username"]')
email_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-email"]')
password_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-password"]')
confirm_password_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-confirm-password"]')
submit_btn = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-submit-btn"]')
first_name.send_keys("Jane")
last_name.send_keys("Doe")
username_field.send_keys(username)
email_field.send_keys(email)
password_field.send_keys("12345")
confirm_password_field.send_keys("12345")
submit_btn.click()
time.sleep(2)
error_msg = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-error-msg"]')
if error_msg and "at least 6 characters" in error_msg.text:
self.log_result(test_name, True, "Short password correctly rejected")
return True
else:
self.log_result(test_name, False, "Short password was not rejected")
return False
except Exception as e:
self.log_result(test_name, False, f"Unexpected error: {str(e)[:100]}")
return False
def test_signup_mismatched_passwords(self):
test_name = "Signup with Mismatched Passwords"
self.print_test_header(test_name)
try:
self.driver.get(self.base_url)
email = self.generate_random_email()
username = self.generate_random_username()
first_name = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-firstname"]')
last_name = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-lastname"]')
username_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-username"]')
email_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-email"]')
password_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-password"]')
confirm_password_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-confirm-password"]')
submit_btn = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-submit-btn"]')
first_name.send_keys("Bob")
last_name.send_keys("Smith")
username_field.send_keys(username)
email_field.send_keys(email)
password_field.send_keys("password123")
confirm_password_field.send_keys("differentpassword")
submit_btn.click()
time.sleep(2)
error_msg = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-error-msg"]')
if error_msg and "do not match" in error_msg.text:
self.log_result(test_name, True, "Mismatched passwords correctly rejected")
return True
else:
self.log_result(test_name, False, "Mismatched passwords were not rejected")
return False
except Exception as e:
self.log_result(test_name, False, f"Unexpected error: {str(e)[:100]}")
return False
def test_signup_duplicate_user(self):
test_name = "Signup with Duplicate User"
self.print_test_header(test_name)
try:
email = "duplicate@example.com"
username = "duplicateuser"
strong_password = self.generate_strong_password()
for attempt in range(2):
self.driver.get(self.base_url)
first_name = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-firstname"]')
last_name = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-lastname"]')
username_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-username"]')
email_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-email"]')
password_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-password"]')
confirm_password_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-confirm-password"]')
submit_btn = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-submit-btn"]')
first_name.send_keys("Duplicate")
last_name.send_keys("User")
username_field.send_keys(username)
email_field.send_keys(email)
password_field.send_keys(strong_password)
confirm_password_field.send_keys(strong_password)
submit_btn.click()
time.sleep(3)
if attempt == 0:
current_url = self.driver.current_url
if "/components/Login" not in current_url:
error_msg = self.driver.find_elements(By.CSS_SELECTOR, '[data-testid="signup-error-msg"]')
error_text = error_msg[0].text if error_msg else "Unknown error"
self.log_result(test_name, False, f"First signup failed: {error_text}")
return False
else:
error_msg = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-error-msg"]')
if error_msg and ("already exists" in error_msg.text.lower() or "already taken" in error_msg.text.lower() or "user with" in error_msg.text.lower()):
self.log_result(test_name, True, "Duplicate user correctly rejected")
return True
else:
self.log_result(test_name, False, "Duplicate user was not rejected")
return False
except Exception as e:
self.log_result(test_name, False, f"Unexpected error: {str(e)[:100]}")
return False
def test_login_valid_credentials(self):
test_name = "Login with Valid Credentials"
self.print_test_header(test_name)
try:
email = self.generate_random_email()
username = self.generate_random_username()
password = self.generate_strong_password()
# Create user first
self.driver.get(self.base_url)
first_name = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-firstname"]')
last_name = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-lastname"]')
username_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-username"]')
email_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-email"]')
password_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-password"]')
confirm_password_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-confirm-password"]')
submit_btn = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-submit-btn"]')
first_name.send_keys("Test")
last_name.send_keys("User")
username_field.send_keys(username)
email_field.send_keys(email)
password_field.send_keys(password)
confirm_password_field.send_keys(password)
submit_btn.click()
time.sleep(3)
current_url = self.driver.current_url
if "/components/Login" not in current_url:
self.log_result(test_name, False, "User creation failed during setup")
return False
# Now test login
login_email = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="login-email"]')
login_password = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="login-password"]')
login_submit = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="login-submit-btn"]')
login_email.send_keys(email)
login_password.send_keys(password)
login_submit.click()
time.sleep(3)
current_url = self.driver.current_url
if "/components/DepartmentConfig" in current_url:
self.log_result(test_name, True, "Login successful")
return True
else:
error_msg = self.driver.find_elements(By.CSS_SELECTOR, '[data-testid="login-error-msg"]')
error_text = error_msg[0].text if error_msg else "Unknown error"
self.log_result(test_name, False, f"Login failed: {error_text}")
return False
except Exception as e:
self.log_result(test_name, False, f"Unexpected error: {str(e)[:100]}")
return False
def test_login_invalid_email(self):
test_name = "Login with Invalid Email"
self.print_test_header(test_name)
try:
self.driver.get(f"{self.base_url}/components/Login")
login_email = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="login-email"]')
login_password = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="login-password"]')
login_submit = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="login-submit-btn"]')
login_email.send_keys("nonexistent@example.com")
login_password.send_keys(self.generate_strong_password())
login_submit.click()
time.sleep(2)
error_msg = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="login-error-msg"]')
if error_msg and ("invalid" in error_msg.text.lower() or "credential" in error_msg.text.lower() or "authentication" in error_msg.text.lower()):
self.log_result(test_name, True, "Invalid email correctly rejected")
return True
else:
self.log_result(test_name, False, "Invalid email was not rejected")
return False
except Exception as e:
self.log_result(test_name, False, f"Unexpected error: {str(e)[:100]}")
return False
def test_login_wrong_password(self):
test_name = "Login with Wrong Password"
self.print_test_header(test_name)
try:
email = self.generate_random_email()
username = self.generate_random_username()
correct_password = self.generate_strong_password()
wrong_password = self.generate_strong_password()
# Create user first
self.driver.get(self.base_url)
first_name = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-firstname"]')
last_name = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-lastname"]')
username_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-username"]')
email_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-email"]')
password_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-password"]')
confirm_password_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-confirm-password"]')
submit_btn = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-submit-btn"]')
first_name.send_keys("Wrong")
last_name.send_keys("Password")
username_field.send_keys(username)
email_field.send_keys(email)
password_field.send_keys(correct_password)
confirm_password_field.send_keys(correct_password)
submit_btn.click()
time.sleep(3)
current_url = self.driver.current_url
if "/components/Login" not in current_url:
self.log_result(test_name, False, "User creation failed during setup")
return False
# Test login with wrong password
login_email = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="login-email"]')
login_password = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="login-password"]')
login_submit = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="login-submit-btn"]')
login_email.send_keys(email)
login_password.send_keys(wrong_password)
login_submit.click()
time.sleep(2)
error_msg = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="login-error-msg"]')
if error_msg and ("invalid" in error_msg.text.lower() or "credential" in error_msg.text.lower() or "authentication" in error_msg.text.lower() or "password" in error_msg.text.lower()):
self.log_result(test_name, True, "Wrong password correctly rejected")
return True
else:
self.log_result(test_name, False, "Wrong password was not rejected")
return False
except Exception as e:
self.log_result(test_name, False, f"Unexpected error: {str(e)[:100]}")
return False
def test_login_empty_fields(self):
test_name = "Login with Empty Fields"
self.print_test_header(test_name)
try:
self.driver.get(f"{self.base_url}/components/Login")
login_submit = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="login-submit-btn"]')
login_submit.click()
time.sleep(2)
current_url = self.driver.current_url
if "/components/Login" in current_url:
self.log_result(test_name, True, "Empty fields correctly prevented login")
return True
else:
self.log_result(test_name, False, "Empty fields were not validated")
return False
except Exception as e:
self.log_result(test_name, False, f"Unexpected error: {str(e)[:100]}")
return False
def test_signup_invalid_email_format(self):
test_name = "Signup with Invalid Email Format"
self.print_test_header(test_name)
try:
self.driver.get(self.base_url)
username = self.generate_random_username()
first_name = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-firstname"]')
last_name = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-lastname"]')
username_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-username"]')
email_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-email"]')
password_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-password"]')
confirm_password_field = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-confirm-password"]')
submit_btn = self.wait_for_element(By.CSS_SELECTOR, '[data-testid="signup-submit-btn"]')
strong_password = self.generate_strong_password()
first_name.send_keys("Invalid")
last_name.send_keys("Email")
username_field.send_keys(username)
email_field.send_keys("invalid-email-format")
password_field.send_keys(strong_password)
confirm_password_field.send_keys(strong_password)
submit_btn.click()
time.sleep(2)
current_url = self.driver.current_url
error_msg = self.driver.find_elements(By.CSS_SELECTOR, '[data-testid="signup-error-msg"]')
if "/components/Login" not in current_url or error_msg:
self.log_result(test_name, True, "Invalid email format correctly rejected")
return True
else:
self.log_result(test_name, False, "Invalid email format was not rejected")
return False
except Exception as e:
self.log_result(test_name, False, f"Unexpected error: {str(e)[:100]}")
return False
def print_summary(self):
"""Print a comprehensive summary of test results"""
total = len(self.test_results)
print("\n" + "=" * 70)
print(f"{Fore.CYAN}{'TEST SUMMARY':^70}")
print("=" * 70)
# Calculate success rate
success_rate = (self.passed_count / total * 100) if total > 0 else 0
# Choose color based on success rate
if success_rate == 100:
rate_color = Fore.GREEN
elif success_rate >= 70:
rate_color = Fore.YELLOW
else:
rate_color = Fore.RED
print(f"\n{Fore.WHITE}Total Tests: {Fore.CYAN}{total}")
print(f"{Fore.WHITE}Passed: {Fore.GREEN}{self.passed_count}")
print(f"{Fore.WHITE}Failed: {Fore.RED}{self.failed_count}")
print(f"{Fore.WHITE}Success Rate: {rate_color}{success_rate:.1f}%")
# Print detailed results
if self.failed_count > 0:
print(f"\n{Fore.RED}Failed Tests:")
print(f"{Fore.RED}{'─' * 70}")
for result in self.test_results:
if not result['passed']:
print(f"{Fore.RED} ✗ {result['name']}")
if result['message']:
print(f"{Fore.WHITE} └─ {result['message']}")
if self.passed_count > 0:
print(f"\n{Fore.GREEN}Passed Tests:")
print(f"{Fore.GREEN}{'─' * 70}")
for result in self.test_results:
if result['passed']:
print(f"{Fore.GREEN} ✓ {result['name']}")
if result['message']:
print(f"{Fore.WHITE} └─ {result['message']}")
print("\n" + "=" * 70 + "\n")
def run_all_tests(self):
"""Run all authentication tests"""
self.print_header()
tests = [
self.test_signup_valid_user,
self.test_signup_short_password,
self.test_signup_mismatched_passwords,
self.test_signup_duplicate_user,
self.test_login_valid_credentials,
self.test_login_invalid_email,
self.test_login_wrong_password,
self.test_login_empty_fields,
self.test_signup_invalid_email_format
]
for i, test in enumerate(tests, 1):
try:
print(f"\n{Fore.CYAN}[{i}/{len(tests)}]", end=" ")
test()
except Exception as e:
print(f"{Fore.RED}✗ Test crashed: {str(e)[:100]}")
time.sleep(1)
self.print_summary()
def cleanup(self):
"""Clean up browser resources"""
try:
if self.driver:
self.driver.quit()
print(f"{Fore.CYAN}Browser closed successfully.")
except Exception as e:
print(f"{Fore.RED}Error during cleanup: {e}")
if __name__ == "__main__":
print(f"\n{Fore.CYAN}Initializing test environment...")
tester = AuthTester()
try:
tester.run_all_tests()
except KeyboardInterrupt:
print(f"\n\n{Fore.YELLOW}Tests interrupted by user.")
except Exception as e:
print(f"\n\n{Fore.RED}Fatal error: {e}")
finally:
tester.cleanup()