Spaces:
Sleeping
Sleeping
File size: 6,105 Bytes
18c9405 | 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 | import os
import requests
import json
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Base URL for API
BASE_URL = "http://localhost:5000/api"
# Global variables to store data between tests
department_data = None
admin_user = None
token = None
def test_create_department():
"""Test creating a new department with an admin user"""
global department_data, admin_user
# Department data
department_data = {
"name": "Auth Test Department",
"address": "456 Auth Street, Test City, TS 67890",
"website": "https://auth-test.example.com",
"admin_email": "admin@auth-test.example.com",
"admin_name": "Auth Admin",
"admin_password": "SecureTestPassword123"
}
# Make POST request to create department
response = requests.post(f"{BASE_URL}/departments", json=department_data)
# Print response details
print(f"Status Code: {response.status_code}")
print("Response:")
print(json.dumps(response.json(), indent=2))
# Store created department and admin user
result = response.json()
if result.get('department') and result.get('admin_user'):
department_data = result['department']
admin_user = result['admin_user']
print("\n=== Department Created Successfully ===")
print(f"Department ID: {department_data['_id']}")
print(f"Admin Email: {admin_user['email']}")
return True
return False
def test_login():
"""Test admin login"""
global token
if not admin_user:
print("Error: No admin user available. Run test_create_department first.")
return False
# Login data
login_data = {
"email": department_data["admin_email"],
"password": department_data["admin_password"]
}
# Make POST request to login
response = requests.post(f"{BASE_URL}/auth/login", json=login_data)
# Print response details
print("\n=== Testing Admin Login ===")
print(f"Status Code: {response.status_code}")
print("Response:")
print(json.dumps(response.json(), indent=2))
# Store token
result = response.json()
if result.get('token'):
token = result['token']
print("\n=== Login Successful ===")
print(f"Token: {token[:20]}...")
return True
return False
def test_get_current_user():
"""Test getting current user information"""
if not token:
print("Error: No token available. Run test_login first.")
return False
# Set up headers with token
headers = {
"Authorization": f"Bearer {token}"
}
# Make GET request to get current user
response = requests.get(f"{BASE_URL}/auth/me", headers=headers)
# Print response details
print("\n=== Testing Get Current User ===")
print(f"Status Code: {response.status_code}")
print("Response:")
print(json.dumps(response.json(), indent=2))
# Check if successful
result = response.json()
if result.get('user'):
print("\n=== Get Current User Successful ===")
return True
return False
def test_update_profile():
"""Test updating user profile"""
if not token:
print("Error: No token available. Run test_login first.")
return False
# Set up headers with token
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
# Profile update data
profile_data = {
"name": "Updated Admin Name",
"position": "Chief Administrator"
}
# Make PUT request to update profile
response = requests.put(f"{BASE_URL}/auth/profile", headers=headers, json=profile_data)
# Print response details
print("\n=== Testing Update Profile ===")
print(f"Status Code: {response.status_code}")
print("Response:")
print(json.dumps(response.json(), indent=2))
# Check if successful
result = response.json()
if result.get('message') == 'Profile updated successfully':
print("\n=== Profile Update Successful ===")
return True
return False
def test_update_password():
"""Test updating user password"""
if not token:
print("Error: No token available. Run test_login first.")
return False
# Set up headers with token
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
# Password update data
password_data = {
"current_password": department_data["admin_password"],
"new_password": "NewSecurePassword456"
}
# Update the stored password for future tests
department_data["admin_password"] = password_data["new_password"]
# Make PUT request to update password
response = requests.put(f"{BASE_URL}/auth/password", headers=headers, json=password_data)
# Print response details
print("\n=== Testing Update Password ===")
print(f"Status Code: {response.status_code}")
print("Response:")
print(json.dumps(response.json(), indent=2))
# Check if successful
result = response.json()
if result.get('message') == 'Password updated successfully':
print("\n=== Password Update Successful ===")
return True
return False
def main():
"""Run test functions in sequence"""
# Step 1: Create department with admin user
if not test_create_department():
print("Failed to create department. Exiting tests.")
return
# Step 2: Login as admin
if not test_login():
print("Failed to login. Exiting tests.")
return
# Step 3: Get current user
test_get_current_user()
# Step 4: Update profile
test_update_profile()
# Step 5: Update password
test_update_password()
# Step 6: Login with new password to verify
print("\n=== Verifying login with new password ===")
test_login()
print("\n=== All authentication tests completed ===")
if __name__ == "__main__":
main() |