attstore / scripts /test_tenant_management.py
dn-scribe's picture
feat: support tenant deletion
38536e2
Raw History Blame Contribute Delete
7.72 kB
#!/usr/bin/env python3
"""
Test script for tenant management endpoints
This script tests the tenant CRUD operations including the new delete endpoint.
Run this after starting the application to verify the tenant management features.
Usage:
python3 test_tenant_management.py [API_URL] [USERNAME] [PASSWORD]
Or set environment variables:
export API_URL="http://localhost:5555"
export ADMIN_USERNAME="admin"
export ADMIN_PASSWORD="admin"
python3 test_tenant_management.py
"""
import requests
import sys
import json
import os
# Get configuration from command line args or environment variables
if len(sys.argv) > 1:
API_URL = sys.argv[1]
USERNAME = sys.argv[2] if len(sys.argv) > 2 else "admin"
PASSWORD = sys.argv[3] if len(sys.argv) > 3 else "admin"
else:
API_URL = os.environ.get("API_URL", "http://localhost:5555")
USERNAME = os.environ.get("ADMIN_USERNAME", "admin")
PASSWORD = os.environ.get("ADMIN_PASSWORD", "admin")
def get_auth_token():
"""Authenticate and get JWT token"""
print(f" Attempting login with username: {USERNAME} to {API_URL}/v1/login")
response = requests.post(
f"{API_URL}/v1/login",
json={"username": USERNAME, "password": PASSWORD}
)
print(f" Response status: {response.status_code}")
if response.status_code != 200:
print(f"❌ Authentication failed (status {response.status_code}): {response.text}")
sys.exit(1)
token = response.json().get("access_token")
if not token:
print(f"❌ No access token in response: {response.json()}")
sys.exit(1)
print(f" Token received: {token[:30]}...")
return token
def test_list_tenants(token):
"""Test listing tenants"""
print("\nπŸ“‹ Testing: List Tenants")
response = requests.get(
f"{API_URL}/api/saml/tenants",
headers={"Authorization": f"Bearer {token}"}
)
if response.status_code == 200:
tenants = response.json()
print(f"βœ… Successfully retrieved {len(tenants)} tenant(s)")
for tenant in tenants:
print(f" - {tenant['name']} (slug: {tenant['slug']}, id: {tenant['id']})")
return tenants
else:
print(f"❌ Failed to list tenants: {response.text}")
return []
def test_create_tenant(token):
"""Test creating a tenant"""
print("\nβž• Testing: Create Tenant")
tenant_data = {
"name": "Test Tenant for Deletion",
"slug": "test-tenant-delete",
"description": "This is a test tenant that will be deleted",
"active": True,
"allow_password_auth": True
}
response = requests.post(
f"{API_URL}/api/saml/tenants",
headers={"Authorization": f"Bearer {token}"},
json=tenant_data
)
if response.status_code == 201:
tenant = response.json()
print(f"βœ… Successfully created tenant: {tenant['name']} (ID: {tenant['id']})")
return tenant
else:
print(f"❌ Failed to create tenant: {response.text}")
return None
def test_delete_tenant(token, tenant_id):
"""Test deleting a tenant"""
print(f"\nπŸ—‘οΈ Testing: Delete Tenant (ID: {tenant_id})")
response = requests.delete(
f"{API_URL}/api/saml/tenants/{tenant_id}",
headers={"Authorization": f"Bearer {token}"}
)
if response.status_code == 200:
result = response.json()
print(f"βœ… Successfully deleted tenant")
print(f" - Message: {result['message']}")
print(f" - Users affected: {result['users_affected']}")
print(f" - SAML configs deleted: {result['saml_configs_deleted']}")
return True
else:
print(f"❌ Failed to delete tenant: {response.text}")
return False
def test_delete_nonexistent_tenant(token):
"""Test deleting a non-existent tenant"""
print("\nπŸ” Testing: Delete Non-existent Tenant")
print(f" Using token: {token[:20]}..." if token else " Token is None/empty!")
response = requests.delete(
f"{API_URL}/api/saml/tenants/999999",
headers={"Authorization": f"Bearer {token}"}
)
print(f" Response status: {response.status_code}")
if response.status_code == 404:
print("βœ… Correctly returned 404 for non-existent tenant")
return True
elif response.status_code == 401:
print(f"⚠️ Got 401 Unauthorized instead of 404")
print(f" This suggests the authentication token is invalid or expired")
print(f" Response: {response.text}")
return False
else:
print(f"❌ Expected 404 but got {response.status_code}: {response.text}")
return False
def main():
print("=" * 60)
print("Tenant Management Endpoint Tests")
print("=" * 60)
print(f"API URL: {API_URL}")
print(f"Username: {USERNAME}")
print(f"Password: {'*' * len(PASSWORD)}")
print()
# Authenticate
print("πŸ” Authenticating...")
token = get_auth_token()
print("βœ… Authentication successful")
# Test list tenants (before)
initial_tenants = test_list_tenants(token)
# Test create tenant
new_tenant = test_create_tenant(token)
if not new_tenant:
print("\n❌ Cannot continue tests without creating a tenant")
sys.exit(1)
# Test list tenants (after creation)
test_list_tenants(token)
# Test delete tenant
success = test_delete_tenant(token, new_tenant['id'])
# Test list tenants (after deletion)
final_tenants = test_list_tenants(token)
# Get a fresh token for the 404 test (in case the previous token expired)
print("\nπŸ”„ Refreshing authentication token...")
try:
token = get_auth_token()
print("βœ… Token refreshed successfully")
# Immediately test if the token works by listing tenants
print(" Verifying token works...")
verify_response = requests.get(
f"{API_URL}/api/saml/tenants",
headers={"Authorization": f"Bearer {token}"}
)
if verify_response.status_code == 200:
print(" βœ… Token verified - it works for listing tenants")
else:
print(f" ❌ Token verification failed: {verify_response.status_code} - {verify_response.text}")
print(" This is a bug - newly minted token should work!")
except Exception as e:
print(f"❌ Failed to refresh token: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
# Test delete non-existent tenant
not_found_success = test_delete_nonexistent_tenant(token)
# Summary
print("\n" + "=" * 60)
print("Test Summary")
print("=" * 60)
if success and not_found_success and len(final_tenants) == len(initial_tenants):
print("βœ… All tests passed!")
print(f" - Created and deleted test tenant successfully")
print(f" - Tenant count returned to original: {len(initial_tenants)}")
print(f" - 404 error handling works correctly")
else:
print("❌ Some tests failed. Please review the output above.")
sys.exit(1)
if __name__ == "__main__":
try:
main()
except requests.exceptions.ConnectionError:
print(f"\n❌ Could not connect to API at {API_URL}")
print(" Please make sure the application is running.")
sys.exit(1)
except KeyboardInterrupt:
print("\n\n⚠️ Tests interrupted by user")
sys.exit(1)
except Exception as e:
print(f"\n❌ Unexpected error: {e}")
import traceback
traceback.print_exc()
sys.exit(1)