File size: 6,369 Bytes
3a32bd4 | 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 | """
Test script for batch certificate verification API
Tests both single and multiple certificate uploads
"""
import requests
import os
from pathlib import Path
# API endpoint
API_URL = "http://localhost:8000/api/verify"
def test_single_certificate():
"""Test single certificate upload"""
print("\n" + "="*60)
print("TEST 1: Single Certificate Upload")
print("="*60)
# Find a test certificate image
test_files = list(Path(".").glob("*.jpg")) + list(Path(".").glob("*.png"))
if not test_files:
print("β No test images found. Add a .jpg or .png certificate image.")
return
test_file = test_files[0]
print(f"π Testing with: {test_file.name}")
try:
with open(test_file, 'rb') as f:
files = {'files': (test_file.name, f, 'image/jpeg')}
response = requests.post(API_URL, files=files)
print(f"β
Status: {response.status_code}")
result = response.json()
print(f"\nπ Result:")
print(f" Decision: {result.get('decision')}")
print(f" Confidence: {result.get('confidence')}")
print(f" Reason: {result.get('reason')}")
print(f" Processing Time: {result.get('processing_time_seconds')}s")
except Exception as e:
print(f"β Error: {e}")
def test_batch_certificates():
"""Test batch certificate upload"""
print("\n" + "="*60)
print("TEST 2: Batch Certificate Upload")
print("="*60)
# Find multiple test images
test_files = list(Path(".").glob("*.jpg"))[:5] + list(Path(".").glob("*.png"))[:5]
if len(test_files) < 2:
print("β Need at least 2 test images for batch test.")
return
# Limit to 5 files for testing
test_files = test_files[:5]
print(f"π Testing with {len(test_files)} certificates:")
for f in test_files:
print(f" - {f.name}")
try:
# Prepare multiple files
files = []
file_handles = []
for test_file in test_files:
fh = open(test_file, 'rb')
file_handles.append(fh)
files.append(('files', (test_file.name, fh, 'image/jpeg')))
response = requests.post(API_URL, files=files)
# Close file handles
for fh in file_handles:
fh.close()
print(f"β
Status: {response.status_code}")
result = response.json()
if result.get('batch'):
print(f"\nπ Batch Results:")
print(f" Total: {result['total_certificates']}")
print(f" Processed: {result['processed']}")
print(f" Failed: {result['failed']}")
print(f" Total Time: {result['summary']['total_processing_time_seconds']}s")
print(f" Average Confidence: {result['summary']['average_confidence']}")
print(f"\nπ Summary:")
print(f" β
Authentic: {result['summary']['authentic_count']}")
print(f" β Fake: {result['summary']['fake_count']}")
print(f" β οΈ Suspicious: {result['summary']['suspicious_count']}")
print(f" π΄ Errors: {result['summary']['error_count']}")
print(f"\nπ Individual Results:")
for idx, res in enumerate(result['results'], 1):
status_icon = "β
" if res['success'] else "β"
decision = res.get('decision', 'ERROR')
confidence = res.get('confidence', 0)
time_taken = res.get('processing_time_seconds', 0)
print(f" {idx}. {status_icon} {res['filename']}")
print(f" Decision: {decision} ({confidence}) - {time_taken}s")
if res.get('error'):
print(f" Error: {res['error']}")
except Exception as e:
print(f"β Error: {e}")
def test_error_handling():
"""Test error cases"""
print("\n" + "="*60)
print("TEST 3: Error Handling")
print("="*60)
# Test 1: Too many files
print("\nπ Test 3a: Too many files (>10)")
try:
test_files = list(Path(".").glob("*.jpg"))[:11] # Try 11 files
if len(test_files) >= 11:
files = []
file_handles = []
for test_file in test_files:
fh = open(test_file, 'rb')
file_handles.append(fh)
files.append(('files', (test_file.name, fh, 'image/jpeg')))
response = requests.post(API_URL, files=files)
for fh in file_handles:
fh.close()
if response.status_code == 400:
print(f" β
Correctly rejected: {response.json().get('detail')}")
else:
print(f" β οΈ Unexpected response: {response.status_code}")
else:
print(f" βοΈ Skipped (not enough files)")
except Exception as e:
print(f" β Error: {e}")
# Test 2: Invalid file type
print("\nπ Test 3b: Invalid file type")
try:
# Try uploading this Python script as if it were an image
with open(__file__, 'rb') as f:
files = {'files': ('test.py', f, 'text/plain')}
response = requests.post(API_URL, files=files)
result = response.json()
if response.status_code == 400 or not result.get('success'):
print(f" β
Correctly rejected invalid file type")
else:
print(f" β οΈ Unexpected response: {response.status_code}")
except Exception as e:
print(f" β Error: {e}")
def main():
"""Run all tests"""
print("\n" + "="*60)
print("π§ͺ BATCH API TESTING SUITE")
print("="*60)
print(f"API Endpoint: {API_URL}")
# Check API is running
try:
response = requests.get("http://localhost:8000/health")
print(f"β
API is running")
except:
print(f"β API is not running. Start it with: python api.py")
return
# Run tests
test_single_certificate()
test_batch_certificates()
test_error_handling()
print("\n" + "="*60)
print("β
Testing Complete!")
print("="*60)
if __name__ == "__main__":
main()
|