Files
backend/internal/handler/auth_handler_test.go
lan 4b4980820f
Some checks failed
SonarQube Analysis / sonarqube (push) Has been cancelled
Test / test (push) Has been cancelled
Test / lint (push) Has been cancelled
Test / build (push) Has been cancelled
chore: 初始化仓库,排除二进制文件和覆盖率文件
2025-11-28 23:30:49 +08:00

156 lines
3.0 KiB
Go

package handler
import (
"testing"
)
// TestAuthHandler_RequestValidation 测试认证请求验证逻辑
func TestAuthHandler_RequestValidation(t *testing.T) {
tests := []struct {
name string
username string
email string
password string
code string
wantValid bool
}{
{
name: "有效的注册请求",
username: "testuser",
email: "test@example.com",
password: "password123",
code: "123456",
wantValid: true,
},
{
name: "有效的登录请求",
username: "testuser",
email: "",
password: "password123",
code: "",
wantValid: true,
},
{
name: "用户名为空",
username: "",
email: "test@example.com",
password: "password123",
code: "123456",
wantValid: false,
},
{
name: "密码为空",
username: "testuser",
email: "test@example.com",
password: "",
code: "123456",
wantValid: false,
},
{
name: "注册时验证码为空",
username: "testuser",
email: "test@example.com",
password: "password123",
code: "",
wantValid: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// 验证请求参数逻辑
isValid := tt.username != "" && tt.password != ""
// 如果是注册请求,还需要验证码
if tt.email != "" && tt.code == "" {
isValid = false
}
if isValid != tt.wantValid {
t.Errorf("Request validation failed: got %v, want %v", isValid, tt.wantValid)
}
})
}
}
// TestAuthHandler_ErrorHandling 测试错误处理逻辑
func TestAuthHandler_ErrorHandling(t *testing.T) {
tests := []struct {
name string
errType string
wantCode int
wantError bool
}{
{
name: "参数错误",
errType: "binding",
wantCode: 400,
wantError: true,
},
{
name: "验证码错误",
errType: "verification",
wantCode: 400,
wantError: true,
},
{
name: "登录失败",
errType: "login",
wantCode: 401,
wantError: true,
},
{
name: "注册失败",
errType: "register",
wantCode: 400,
wantError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// 验证错误处理逻辑
if !tt.wantError {
t.Error("Error handling test should expect error")
}
})
}
}
// TestAuthHandler_ResponseFormat 测试响应格式逻辑
func TestAuthHandler_ResponseFormat(t *testing.T) {
tests := []struct {
name string
success bool
wantCode int
hasToken bool
}{
{
name: "注册成功",
success: true,
wantCode: 200,
hasToken: true,
},
{
name: "登录成功",
success: true,
wantCode: 200,
hasToken: true,
},
{
name: "发送验证码成功",
success: true,
wantCode: 200,
hasToken: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// 验证响应格式逻辑
if tt.success && tt.wantCode != 200 {
t.Errorf("Success response should have code 200, got %d", tt.wantCode)
}
})
}
}