test(backend): add unit tests for HTTP result handlers and password hashing functionality

This commit is contained in:
keven1024
2025-08-14 14:40:03 +08:00
parent e41d7a6305
commit 4d0a6f0a49
2 changed files with 129 additions and 0 deletions

View File

@@ -0,0 +1,58 @@
package utils
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
)
func TestHTTPSuccessHandler(t *testing.T) {
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
data := map[string]interface{}{"result": "success"}
err := HTTPSuccessHandler(c, data)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, rec.Code)
var response map[string]interface{}
err = json.Unmarshal(rec.Body.Bytes(), &response)
assert.NoError(t, err)
expected := map[string]interface{}{
"code": float64(http.StatusOK),
"message": "success",
"data": data,
}
assert.Equal(t, expected, response)
}
func TestHTTPErrorHandler(t *testing.T) {
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
err := HTTPErrorHandler(c, assert.AnError)
assert.NoError(t, err)
assert.Equal(t, http.StatusBadRequest, rec.Code)
var response map[string]interface{}
err = json.Unmarshal(rec.Body.Bytes(), &response)
assert.NoError(t, err)
expected := map[string]interface{}{
"code": float64(http.StatusBadRequest),
"message": assert.AnError.Error(),
"data": map[string]interface{}{},
}
assert.Equal(t, expected, response)
}

View File

@@ -0,0 +1,71 @@
package utils
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
)
func TestGeneratePasswordHash(t *testing.T) {
// 保存原始环境变量
originalSalt := os.Getenv("PASSWORD_SALT")
defer os.Setenv("PASSWORD_SALT", originalSalt)
tests := []struct {
name string
password string
salt string
expectError bool
errorMsg string
}{
{
name: "PASSWORD_SALT未配置",
password: "testpassword",
salt: "",
expectError: true,
errorMsg: "请配置PASSWORD_SALT",
},
{
name: "正常生成哈希",
password: "testpassword123",
salt: "testsalt",
expectError: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// 设置环境变量
if tt.salt != "" {
os.Setenv("PASSWORD_SALT", tt.salt)
} else {
os.Unsetenv("PASSWORD_SALT")
}
hash, err := GeneratePasswordHash(tt.password)
if tt.expectError {
if err == nil {
t.Errorf("期望错误,但得到了 nil")
return
}
if err.Error() != tt.errorMsg {
t.Errorf("期望错误信息 '%s',但得到了 '%s'", tt.errorMsg, err.Error())
}
return
}
if err != nil {
t.Errorf("不期望错误,但得到了: %v", err)
return
}
// 验证哈希格式argon2 32字节 = 64个十六进制字符
if len(hash) != 64 {
t.Errorf("期望哈希长度为64但得到了 %d", len(hash))
}
assert.Equal(t, hash, "537275f995fdd46eb2e5455b8a29adccb60c5637689d29646676a5f1bffb63f3")
})
}
}