|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +LicenseChain Python SDK - License Testing Script |
| 4 | +
|
| 5 | +This script tests license validation using the provided example licenses |
| 6 | +to ensure the SDK and API endpoints are working correctly. |
| 7 | +""" |
| 8 | + |
| 9 | +import asyncio |
| 10 | +import os |
| 11 | +import sys |
| 12 | +from datetime import datetime |
| 13 | +from typing import Dict, Any, List |
| 14 | + |
| 15 | +# Add the parent directory to the path so we can import the SDK |
| 16 | +sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) |
| 17 | + |
| 18 | +from licensechain.client import LicenseChainClient |
| 19 | +from licensechain.exceptions import ( |
| 20 | + AuthenticationError, |
| 21 | + ValidationError, |
| 22 | + NetworkError, |
| 23 | + LicenseChainException, |
| 24 | +) |
| 25 | + |
| 26 | + |
| 27 | +# Test license keys from the dashboard |
| 28 | +TEST_LICENSES = [ |
| 29 | + "LC-ZFVUPU-QR4DIU-4QPUFD", |
| 30 | + "LC-WGVCU0-MH6QO5-SJF7ZE", |
| 31 | + "LC-DBQ88O-M181MU-9RYRU7", |
| 32 | + "LC-MDC1AM-V1N53V-BUXIB0", |
| 33 | + "LC-08QGAA-RRCTZC-RWU6N7", |
| 34 | + "LC-U1N96E-T3RPVG-R7VT3D", |
| 35 | + "LC-CFYX1L-VCP9JD-KE7F06", |
| 36 | + "LC-AILF6U-4Z623N-B1JHSE", |
| 37 | +] |
| 38 | + |
| 39 | + |
| 40 | +async def test_license_validation(client: LicenseChainClient, license_key: str) -> Dict[str, Any]: |
| 41 | + """ |
| 42 | + Test validation of a single license key. |
| 43 | + |
| 44 | + Returns: |
| 45 | + Dictionary with test results |
| 46 | + """ |
| 47 | + result = { |
| 48 | + "license_key": license_key, |
| 49 | + "valid": False, |
| 50 | + "status": None, |
| 51 | + "error": None, |
| 52 | + "response_time": None, |
| 53 | + "details": None, |
| 54 | + } |
| 55 | + |
| 56 | + try: |
| 57 | + start_time = datetime.now() |
| 58 | + response = await client.validate_license(license_key=license_key) |
| 59 | + elapsed = (datetime.now() - start_time).total_seconds() |
| 60 | + |
| 61 | + result["response_time"] = elapsed |
| 62 | + result["valid"] = response.get("valid", False) |
| 63 | + result["status"] = response.get("status", "UNKNOWN") |
| 64 | + result["details"] = { |
| 65 | + "expiresAt": response.get("expiresAt"), |
| 66 | + "email": response.get("email"), |
| 67 | + "metadata": response.get("metadata"), |
| 68 | + } |
| 69 | + |
| 70 | + except ValidationError as e: |
| 71 | + result["error"] = f"ValidationError: {str(e)}" |
| 72 | + except AuthenticationError as e: |
| 73 | + result["error"] = f"AuthenticationError: {str(e)}" |
| 74 | + except NetworkError as e: |
| 75 | + result["error"] = f"NetworkError: {str(e)}" |
| 76 | + except LicenseChainException as e: |
| 77 | + result["error"] = f"LicenseChainException: {str(e)}" |
| 78 | + except Exception as e: |
| 79 | + result["error"] = f"Unexpected error: {type(e).__name__}: {str(e)}" |
| 80 | + |
| 81 | + return result |
| 82 | + |
| 83 | + |
| 84 | +async def test_all_licenses(client: LicenseChainClient) -> List[Dict[str, Any]]: |
| 85 | + """Test all provided license keys.""" |
| 86 | + print("🔍 Testing license validation for all provided licenses...\n") |
| 87 | + |
| 88 | + results = [] |
| 89 | + for i, license_key in enumerate(TEST_LICENSES, 1): |
| 90 | + print(f"[{i}/{len(TEST_LICENSES)}] Testing: {license_key}") |
| 91 | + result = await test_license_validation(client, license_key) |
| 92 | + results.append(result) |
| 93 | + |
| 94 | + if result["error"]: |
| 95 | + print(f" ❌ Error: {result['error']}") |
| 96 | + elif result["valid"]: |
| 97 | + print(f" ✅ Valid - Status: {result['status']}") |
| 98 | + if result["details"]["expiresAt"]: |
| 99 | + print(f" Expires: {result['details']['expiresAt']}") |
| 100 | + if result["details"]["email"]: |
| 101 | + print(f" Email: {result['details']['email']}") |
| 102 | + else: |
| 103 | + print(f" ❌ Invalid - Status: {result['status']}") |
| 104 | + print(f" ⏱️ Response time: {result['response_time']:.3f}s\n") |
| 105 | + |
| 106 | + return results |
| 107 | + |
| 108 | + |
| 109 | +async def print_summary(results: List[Dict[str, Any]]): |
| 110 | + """Print test summary.""" |
| 111 | + print("="*60) |
| 112 | + print("Test Summary") |
| 113 | + print("="*60) |
| 114 | + |
| 115 | + valid_count = sum(1 for r in results if r["valid"]) |
| 116 | + invalid_count = sum(1 for r in results if not r["valid"] and not r["error"]) |
| 117 | + error_count = sum(1 for r in results if r["error"]) |
| 118 | + |
| 119 | + print(f"Total Licenses Tested: {len(results)}") |
| 120 | + print(f"✅ Valid: {valid_count}") |
| 121 | + print(f"❌ Invalid: {invalid_count}") |
| 122 | + print(f"⚠️ Errors: {error_count}") |
| 123 | + |
| 124 | + if results: |
| 125 | + avg_response_time = sum(r["response_time"] or 0 for r in results) / len(results) |
| 126 | + print(f"⏱️ Average Response Time: {avg_response_time:.3f}s") |
| 127 | + |
| 128 | + print("\n" + "="*60) |
| 129 | + print("Detailed Results") |
| 130 | + print("="*60) |
| 131 | + |
| 132 | + for result in results: |
| 133 | + status_icon = "✅" if result["valid"] else ("⚠️" if result["error"] else "❌") |
| 134 | + print(f"\n{status_icon} {result['license_key']}") |
| 135 | + print(f" Status: {result['status'] or 'N/A'}") |
| 136 | + if result["error"]: |
| 137 | + print(f" Error: {result['error']}") |
| 138 | + if result["details"]["expiresAt"]: |
| 139 | + print(f" Expires: {result['details']['expiresAt']}") |
| 140 | + if result["details"]["email"]: |
| 141 | + print(f" Email: {result['details']['email']}") |
| 142 | + if result["response_time"]: |
| 143 | + print(f" Response Time: {result['response_time']:.3f}s") |
| 144 | + |
| 145 | + |
| 146 | +async def main(): |
| 147 | + """Main test function.""" |
| 148 | + print("="*60) |
| 149 | + print("LicenseChain Python SDK - License Testing") |
| 150 | + print("="*60) |
| 151 | + print(f"Timestamp: {datetime.now().isoformat()}\n") |
| 152 | + |
| 153 | + # Get API key from environment |
| 154 | + api_key = os.getenv("LICENSECHAIN_API_KEY") |
| 155 | + if not api_key: |
| 156 | + print("❌ ERROR: LICENSECHAIN_API_KEY environment variable not set") |
| 157 | + print("\nTo run this test:") |
| 158 | + print(" export LICENSECHAIN_API_KEY='your-api-key'") |
| 159 | + print(" python examples/test_licenses.py") |
| 160 | + return False |
| 161 | + |
| 162 | + # Optional: Get app ID |
| 163 | + app_id = os.getenv("LICENSECHAIN_APP_ID") |
| 164 | + |
| 165 | + # Initialize client |
| 166 | + client = LicenseChainClient( |
| 167 | + api_key=api_key, |
| 168 | + base_url="https://api.licensechain.app", |
| 169 | + timeout=30, |
| 170 | + ) |
| 171 | + |
| 172 | + try: |
| 173 | + # Test all licenses |
| 174 | + results = await test_all_licenses(client) |
| 175 | + |
| 176 | + # Print summary |
| 177 | + await print_summary(results) |
| 178 | + |
| 179 | + # Overall result |
| 180 | + all_passed = all(r["valid"] or r["error"] for r in results) |
| 181 | + if all_passed: |
| 182 | + print("\n✅ All licenses processed successfully!") |
| 183 | + return True |
| 184 | + else: |
| 185 | + print("\n⚠️ Some licenses failed validation") |
| 186 | + return False |
| 187 | + |
| 188 | + except Exception as e: |
| 189 | + print(f"\n❌ Test failed with error: {type(e).__name__}: {e}") |
| 190 | + import traceback |
| 191 | + traceback.print_exc() |
| 192 | + return False |
| 193 | + finally: |
| 194 | + await client.close() |
| 195 | + |
| 196 | + |
| 197 | +if __name__ == "__main__": |
| 198 | + success = asyncio.run(main()) |
| 199 | + sys.exit(0 if success else 1) |
0 commit comments