Files
whale-town-end/test-comprehensive.ps1
moyin 7429de3cf4 chore:整理API测试脚本
- 移除分散的旧测试脚本(test-api.ps1, test-api.sh, test-register-fix.ps1, test-throttle.ps1)
- 添加统一的综合测试脚本(test-comprehensive.ps1)
- 新脚本支持更多功能:跳过限流测试、自定义服务器地址等
- 提供更完整的API功能测试覆盖
2025-12-25 20:50:29 +08:00

333 lines
13 KiB
PowerShell
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Comprehensive API Test Script
# 综合API测试脚本 - 完整的后端功能测试
#
# 🧪 测试内容:
# 1. 基础API功能应用状态、注册、登录
# 2. 邮箱验证码流程(发送、验证、冲突检测)
# 3. 验证码冷却时间清除功能
# 4. 限流保护机制
# 5. 密码重置流程
# 6. 验证码登录功能
# 7. 错误处理和边界条件
#
# 🚀 使用方法:
# .\test-comprehensive.ps1 # 运行完整测试
# .\test-comprehensive.ps1 -SkipThrottleTest # 跳过限流测试
# .\test-comprehensive.ps1 -SkipCooldownTest # 跳过冷却测试
# .\test-comprehensive.ps1 -BaseUrl "https://your-server.com" # 测试远程服务器
param(
[string]$BaseUrl = "http://localhost:3000",
[switch]$SkipThrottleTest = $false,
[switch]$SkipCooldownTest = $false
)
$ErrorActionPreference = "Continue"
Write-Host "🧪 Comprehensive API Test Suite" -ForegroundColor Green
Write-Host "===============================" -ForegroundColor Green
Write-Host "Base URL: $BaseUrl" -ForegroundColor Yellow
Write-Host "Skip Throttle Test: $SkipThrottleTest" -ForegroundColor Yellow
Write-Host "Skip Cooldown Test: $SkipCooldownTest" -ForegroundColor Yellow
# Helper function to handle API responses
function Test-ApiCall {
param(
[string]$TestName,
[string]$Url,
[string]$Body,
[string]$Method = "POST",
[int]$ExpectedStatus = 200,
[switch]$Silent = $false
)
if (-not $Silent) {
Write-Host "`n📋 $TestName" -ForegroundColor Yellow
}
try {
$response = Invoke-RestMethod -Uri $Url -Method $Method -Body $Body -ContentType "application/json" -ErrorAction Stop
if (-not $Silent) {
Write-Host "✅ SUCCESS ($(if ($response.success) { 'true' } else { 'false' }))" -ForegroundColor Green
Write-Host "Message: $($response.message)" -ForegroundColor Cyan
}
return $response
} catch {
$statusCode = $_.Exception.Response.StatusCode.value__
if (-not $Silent) {
Write-Host "❌ FAILED ($statusCode)" -ForegroundColor $(if ($statusCode -eq $ExpectedStatus) { "Yellow" } else { "Red" })
}
if ($_.Exception.Response) {
$stream = $_.Exception.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($stream)
$responseBody = $reader.ReadToEnd()
$reader.Close()
$stream.Close()
if ($responseBody) {
try {
$errorResponse = $responseBody | ConvertFrom-Json
if (-not $Silent) {
Write-Host "Message: $($errorResponse.message)" -ForegroundColor Cyan
Write-Host "Error Code: $($errorResponse.error_code)" -ForegroundColor Gray
}
return $errorResponse
} catch {
if (-not $Silent) {
Write-Host "Raw Response: $responseBody" -ForegroundColor Gray
}
}
}
}
return $null
}
}
# Clear throttle first
Write-Host "`n🔄 Clearing throttle records..." -ForegroundColor Blue
try {
Invoke-RestMethod -Uri "$BaseUrl/auth/debug-clear-throttle" -Method POST | Out-Null
Write-Host "✅ Throttle cleared" -ForegroundColor Green
} catch {
Write-Host "⚠️ Could not clear throttle" -ForegroundColor Yellow
}
# Test Results Tracking
$testResults = @{
AppStatus = $false
BasicAPI = $false
EmailConflict = $false
VerificationCodeLogin = $false
CooldownClearing = $false
ThrottleProtection = $false
PasswordReset = $false
}
Write-Host "`n" + "="*60 -ForegroundColor Cyan
Write-Host "🧪 Test Suite 0: Application Status" -ForegroundColor Cyan
Write-Host "="*60 -ForegroundColor Cyan
# Test application status
$result0 = Test-ApiCall -TestName "Check application status" -Url "$BaseUrl" -Method "GET" -Body ""
if ($result0 -and $result0.service -eq "Pixel Game Server") {
$testResults.AppStatus = $true
Write-Host "✅ PASS: Application is running" -ForegroundColor Green
Write-Host " Service: $($result0.service)" -ForegroundColor Cyan
Write-Host " Version: $($result0.version)" -ForegroundColor Cyan
Write-Host " Environment: $($result0.environment)" -ForegroundColor Cyan
} else {
Write-Host "❌ FAIL: Application status check failed" -ForegroundColor Red
}
Write-Host "`n" + "="*60 -ForegroundColor Cyan
Write-Host "🧪 Test Suite 1: Basic API Functionality" -ForegroundColor Cyan
Write-Host "="*60 -ForegroundColor Cyan
# Generate unique test data
$testEmail = "comprehensive_test_$(Get-Random)@example.com"
$testUsername = "comp_test_$(Get-Random)"
# Test 1: Send verification code
$result1 = Test-ApiCall -TestName "Send email verification code" -Url "$BaseUrl/auth/send-email-verification" -Body (@{
email = $testEmail
} | ConvertTo-Json)
if ($result1 -and $result1.data.verification_code) {
$verificationCode = $result1.data.verification_code
Write-Host "Got verification code: $verificationCode" -ForegroundColor Green
# Test 2: Register user
$result2 = Test-ApiCall -TestName "Register new user" -Url "$BaseUrl/auth/register" -Body (@{
username = $testUsername
password = "password123"
nickname = "Comprehensive Test User"
email = $testEmail
email_verification_code = $verificationCode
} | ConvertTo-Json)
if ($result2 -and $result2.success) {
# Test 3: Login user
$result3 = Test-ApiCall -TestName "Login with registered user" -Url "$BaseUrl/auth/login" -Body (@{
identifier = $testUsername
password = "password123"
} | ConvertTo-Json)
if ($result3 -and $result3.success) {
$testResults.BasicAPI = $true
Write-Host "✅ PASS: Basic API functionality working" -ForegroundColor Green
}
}
}
Write-Host "`n" + "="*60 -ForegroundColor Cyan
Write-Host "🧪 Test Suite 2: Email Conflict Detection" -ForegroundColor Cyan
Write-Host "="*60 -ForegroundColor Cyan
# Test email conflict detection
$result4 = Test-ApiCall -TestName "Test email conflict detection" -Url "$BaseUrl/auth/send-email-verification" -Body (@{
email = $testEmail
} | ConvertTo-Json) -ExpectedStatus 409
if ($result4 -and $result4.message -like "*已被注册*") {
$testResults.EmailConflict = $true
Write-Host "✅ PASS: Email conflict detection working" -ForegroundColor Green
} else {
Write-Host "❌ FAIL: Email conflict detection not working" -ForegroundColor Red
}
Write-Host "`n" + "="*60 -ForegroundColor Cyan
Write-Host "🧪 Test Suite 3: Verification Code Login" -ForegroundColor Cyan
Write-Host "="*60 -ForegroundColor Cyan
# Test verification code login
if ($result2 -and $result2.success) {
$userEmail = $result2.data.user.email
# Send login verification code
$result4a = Test-ApiCall -TestName "Send login verification code" -Url "$BaseUrl/auth/send-login-verification-code" -Body (@{
identifier = $userEmail
} | ConvertTo-Json)
if ($result4a -and $result4a.data.verification_code) {
$loginCode = $result4a.data.verification_code
# Login with verification code
$result4b = Test-ApiCall -TestName "Login with verification code" -Url "$BaseUrl/auth/verification-code-login" -Body (@{
identifier = $userEmail
verification_code = $loginCode
} | ConvertTo-Json)
if ($result4b -and $result4b.success) {
$testResults.VerificationCodeLogin = $true
Write-Host "✅ PASS: Verification code login working" -ForegroundColor Green
} else {
Write-Host "❌ FAIL: Verification code login failed" -ForegroundColor Red
}
}
}
if (-not $SkipCooldownTest) {
Write-Host "`n" + "="*60 -ForegroundColor Cyan
Write-Host "🧪 Test Suite 4: Cooldown Clearing & Password Reset" -ForegroundColor Cyan
Write-Host "="*60 -ForegroundColor Cyan
# Test cooldown clearing with password reset
if ($result2 -and $result2.success) {
$userEmail = $result2.data.user.email
# Send password reset code
$result5 = Test-ApiCall -TestName "Send password reset code" -Url "$BaseUrl/auth/forgot-password" -Body (@{
identifier = $userEmail
} | ConvertTo-Json)
if ($result5 -and $result5.data.verification_code) {
$resetCode = $result5.data.verification_code
# Reset password
$result6 = Test-ApiCall -TestName "Reset password (should clear cooldown)" -Url "$BaseUrl/auth/reset-password" -Body (@{
identifier = $userEmail
verification_code = $resetCode
new_password = "newpassword123"
} | ConvertTo-Json)
if ($result6 -and $result6.success) {
$testResults.PasswordReset = $true
Write-Host "✅ PASS: Password reset working" -ForegroundColor Green
# Test immediate code sending (should work if cooldown cleared)
Start-Sleep -Seconds 1
$result7 = Test-ApiCall -TestName "Send reset code immediately (test cooldown clearing)" -Url "$BaseUrl/auth/forgot-password" -Body (@{
identifier = $userEmail
} | ConvertTo-Json)
if ($result7 -and $result7.success) {
$testResults.CooldownClearing = $true
Write-Host "✅ PASS: Cooldown clearing working" -ForegroundColor Green
} else {
Write-Host "❌ FAIL: Cooldown not cleared properly" -ForegroundColor Red
}
} else {
Write-Host "❌ FAIL: Password reset failed" -ForegroundColor Red
}
}
}
}
if (-not $SkipThrottleTest) {
Write-Host "`n" + "="*60 -ForegroundColor Cyan
Write-Host "🧪 Test Suite 5: Throttle Protection" -ForegroundColor Cyan
Write-Host "="*60 -ForegroundColor Cyan
$successCount = 0
$throttleCount = 0
Write-Host "Testing throttle limits (making 12 registration requests)..." -ForegroundColor Yellow
for ($i = 1; $i -le 12; $i++) {
$result = Test-ApiCall -TestName "Registration attempt $i" -Url "$BaseUrl/auth/register" -Body (@{
username = "throttle_test_$i"
password = "password123"
nickname = "Throttle Test $i"
} | ConvertTo-Json) -Silent
if ($result -and $result.success) {
$successCount++
Write-Host " Request $i`: ✅ Success" -ForegroundColor Green
} else {
$throttleCount++
Write-Host " Request $i`: 🚦 Throttled" -ForegroundColor Yellow
}
Start-Sleep -Milliseconds 100
}
Write-Host "`nThrottle Results: $successCount success, $throttleCount throttled" -ForegroundColor Cyan
if ($successCount -ge 8 -and $throttleCount -ge 1) {
$testResults.ThrottleProtection = $true
Write-Host "✅ PASS: Throttle protection working" -ForegroundColor Green
} else {
Write-Host "❌ FAIL: Throttle protection not working properly" -ForegroundColor Red
}
}
Write-Host "`n🎯 Test Results Summary" -ForegroundColor Green
Write-Host "=======================" -ForegroundColor Green
$passCount = 0
$totalTests = 0
foreach ($test in $testResults.GetEnumerator()) {
$totalTests++
if ($test.Value) {
$passCount++
Write-Host "$($test.Key): PASS" -ForegroundColor Green
} else {
Write-Host "$($test.Key): FAIL" -ForegroundColor Red
}
}
Write-Host "`n📊 Overall Result: $passCount/$totalTests tests passed" -ForegroundColor $(if ($passCount -eq $totalTests) { "Green" } else { "Yellow" })
if ($passCount -eq $totalTests) {
Write-Host "🎉 All tests passed! API is working correctly." -ForegroundColor Green
} else {
Write-Host "⚠️ Some tests failed. Please check the implementation." -ForegroundColor Yellow
}
Write-Host "`n💡 Usage Tips:" -ForegroundColor Cyan
Write-Host " • Use -SkipThrottleTest to skip throttle testing" -ForegroundColor White
Write-Host " • Use -SkipCooldownTest to skip cooldown testing" -ForegroundColor White
Write-Host " • Check server logs for detailed error information" -ForegroundColor White
Write-Host " • For production testing: .\test-comprehensive.ps1 -BaseUrl 'https://your-server.com'" -ForegroundColor White
Write-Host "`n📋 Test Coverage:" -ForegroundColor Cyan
Write-Host " ✓ Application Status & Health Check" -ForegroundColor White
Write-Host " ✓ User Registration & Login Flow" -ForegroundColor White
Write-Host " ✓ Email Verification & Conflict Detection" -ForegroundColor White
Write-Host " ✓ Verification Code Login" -ForegroundColor White
Write-Host " ✓ Password Reset Flow" -ForegroundColor White
Write-Host " ✓ Cooldown Time Clearing" -ForegroundColor White
Write-Host " ✓ Rate Limiting & Throttle Protection" -ForegroundColor White