#!/usr/bin/env python """ Test script to demonstrate the improved login error handling """ import os import django # Setup Django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.develop') django.setup() from django.test import RequestFactory from apps.account.views.user import UserLoginView from rest_framework.exceptions import ValidationError from django.contrib.auth.models import User as DjangoUser def test_login_errors(): """Test the different login error scenarios""" factory = RequestFactory() view = UserLoginView() print("๐Ÿงช Testing Login Error Handling") print("=" * 40) # Test Case 1: Non-existent email print("\n1๏ธโƒฃ Testing non-existent email:") try: request = factory.post('/api/account/login/', { 'email': 'nonexistent@example.com', 'password': 'somepassword' }, content_type='application/json') view.request = request response = view.create(request) print("โŒ Should have raised ValidationError") except ValidationError as e: print(f"โœ… Correctly caught ValidationError: {e.detail}") except Exception as e: print(f"โŒ Unexpected error: {e}") # Test Case 2: Wrong password for existing user print("\n2๏ธโƒฃ Testing wrong password for existing user:") try: # First, let's create a test user if it doesn't exist test_email = 'test@example.com' test_password = 'correctpassword' if not DjangoUser.objects.filter(email=test_email).exists(): DjangoUser.objects.create_user( username=test_email, email=test_email, password=test_password ) print(f" Created test user: {test_email}") # Now test wrong password request = factory.post('/api/account/login/', { 'email': test_email, 'password': 'wrongpassword' }, content_type='application/json') view.request = request response = view.create(request) print("โŒ Should have raised ValidationError") except ValidationError as e: print(f"โœ… Correctly caught ValidationError: {e.detail}") except Exception as e: print(f"โŒ Unexpected error: {e}") # Test Case 3: Correct login (should succeed if user exists) print("\n3๏ธโƒฃ Testing correct login:") try: request = factory.post('/api/account/login/', { 'email': test_email, 'password': test_password }, content_type='application/json') view.request = request response = view.create(request) if response.status_code == 201: print("โœ… Login successful (as expected)") else: print(f"โŒ Login failed with status: {response.status_code}") except ValidationError as e: print(f"โ„น๏ธ ValidationError (might be expected): {e.detail}") except Exception as e: print(f"โŒ Unexpected error: {e}") print("\n" + "=" * 40) print("๐ŸŽฏ SUMMARY:") print("- Non-existent email โ†’ 'user not exists with this email'") print("- Wrong password โ†’ 'password is incorrect'") print("- Correct credentials โ†’ Successful login") if __name__ == "__main__": test_login_errors()