173 lines
5.7 KiB
Python
173 lines
5.7 KiB
Python
#!/usr/bin/env python
|
|
"""
|
|
Test script to verify user account creation works correctly
|
|
"""
|
|
import os
|
|
import django
|
|
|
|
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
|
|
django.setup()
|
|
|
|
from apps.organizations.models import Staff, Hospital, Department
|
|
from apps.organizations.services import StaffService
|
|
from apps.accounts.models import User
|
|
|
|
def test_user_account_creation():
|
|
"""Test that user account creation works with the updated StaffService"""
|
|
print("\n" + "="*60)
|
|
print("Testing User Account Creation")
|
|
print("="*60 + "\n")
|
|
|
|
# Get a hospital
|
|
hospital = Hospital.objects.filter(status='active').first()
|
|
if not hospital:
|
|
print("❌ No hospital found. Please create a hospital first.")
|
|
return False
|
|
|
|
# Get a department
|
|
department = Department.objects.filter(hospital=hospital).first()
|
|
|
|
# Create a test staff member
|
|
print("1. Creating test staff member...")
|
|
staff = Staff.objects.create(
|
|
first_name="Test",
|
|
last_name="User",
|
|
first_name_ar="اختبار",
|
|
last_name_ar="مستخدم",
|
|
email="test.user@example.com",
|
|
staff_type=Staff.StaffType.PHYSICIAN,
|
|
job_title="Test Doctor",
|
|
specialization="General Medicine",
|
|
employee_id="TEST-001",
|
|
hospital=hospital,
|
|
department=department,
|
|
status='active'
|
|
)
|
|
print(f" ✓ Created staff: {staff.get_full_name()} (ID: {staff.id})")
|
|
|
|
# Create mock request
|
|
class MockRequest:
|
|
META = {
|
|
'HTTP_X_FORWARDED_FOR': '127.0.0.1',
|
|
'REMOTE_ADDR': '127.0.0.1'
|
|
}
|
|
|
|
def build_absolute_uri(self, location=''):
|
|
return f"http://localhost:8000{location}"
|
|
|
|
class MockUser:
|
|
is_authenticated = False
|
|
|
|
user = MockUser()
|
|
|
|
request = MockRequest()
|
|
|
|
# Test user account creation
|
|
print("\n2. Creating user account...")
|
|
try:
|
|
role = StaffService.get_staff_type_role(staff.staff_type)
|
|
print(f" Determined role: {role}")
|
|
|
|
user, was_created, password = StaffService.create_user_for_staff(
|
|
staff,
|
|
role=role,
|
|
request=request
|
|
)
|
|
|
|
if was_created:
|
|
print(f" ✓ Created new user account")
|
|
print(f" ✓ Username: {user.username}")
|
|
print(f" ✓ Email: {user.email}")
|
|
print(f" ✓ Generated password: {password}")
|
|
print(f" ✓ Role: {user.role}")
|
|
print(f" ✓ Is active: {user.is_active}")
|
|
|
|
# Verify staff is linked
|
|
staff.refresh_from_db()
|
|
if staff.user == user:
|
|
print(f" ✓ Staff linked to user account")
|
|
else:
|
|
print(f" ❌ Staff NOT linked to user account")
|
|
return False
|
|
|
|
else:
|
|
print(f" ✓ Linked existing user account")
|
|
print(f" ✓ Username: {user.username}")
|
|
print(f" ✓ Email: {user.email}")
|
|
|
|
if not password:
|
|
print(f" ✓ No password generated (existing user)")
|
|
else:
|
|
print(f" ✓ Generated password: {password}")
|
|
|
|
# Test that we can't create another user for the same staff
|
|
print("\n3. Testing duplicate prevention...")
|
|
try:
|
|
user2, was_created2, password2 = StaffService.create_user_for_staff(
|
|
staff,
|
|
role=role,
|
|
request=request
|
|
)
|
|
print(f" ❌ Should have raised ValueError for duplicate user")
|
|
return False
|
|
except ValueError as e:
|
|
if "already has a user account" in str(e):
|
|
print(f" ✓ Correctly prevented duplicate user creation")
|
|
print(f" ✓ Error message: {e}")
|
|
else:
|
|
print(f" ❌ Unexpected error: {e}")
|
|
return False
|
|
|
|
# Test with staff that already has a user
|
|
print("\n4. Testing with staff that already has a user...")
|
|
staff_with_user = Staff.objects.filter(user__isnull=False).first()
|
|
if staff_with_user:
|
|
try:
|
|
user3, was_created3, password3 = StaffService.create_user_for_staff(
|
|
staff_with_user,
|
|
role=role,
|
|
request=request
|
|
)
|
|
print(f" ❌ Should have raised ValueError for staff with existing user")
|
|
return False
|
|
except ValueError as e:
|
|
if "already has a user account" in str(e):
|
|
print(f" ✓ Correctly prevented creating user for staff with existing user")
|
|
print(f" ✓ Error message: {e}")
|
|
else:
|
|
print(f" ❌ Unexpected error: {e}")
|
|
return False
|
|
else:
|
|
print(f" ⚠ No staff with existing user found to test")
|
|
|
|
# Clean up
|
|
print("\n5. Cleaning up...")
|
|
staff.delete()
|
|
if was_created:
|
|
user.delete()
|
|
print(f" ✓ Cleaned up test data")
|
|
|
|
print("\n" + "="*60)
|
|
print("✅ All tests passed!")
|
|
print("="*60 + "\n")
|
|
return True
|
|
|
|
except Exception as e:
|
|
print(f" ❌ Error: {str(e)}")
|
|
import traceback
|
|
traceback.print_exc()
|
|
|
|
# Clean up on error
|
|
try:
|
|
staff.delete()
|
|
except:
|
|
pass
|
|
|
|
print("\n" + "="*60)
|
|
print("❌ Test failed")
|
|
print("="*60 + "\n")
|
|
return False
|
|
|
|
if __name__ == '__main__':
|
|
test_user_account_creation()
|