109 lines
2.6 KiB
Go
109 lines
2.6 KiB
Go
package authlogic
|
||
|
||
import (
|
||
"crypto/sha256"
|
||
"encoding/hex"
|
||
"testing"
|
||
)
|
||
|
||
func TestHashPassword(t *testing.T) {
|
||
tests := []struct {
|
||
name string
|
||
password string
|
||
want string
|
||
}{
|
||
{
|
||
name: "空密码",
|
||
password: "",
|
||
want: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||
},
|
||
{
|
||
name: "简单密码",
|
||
password: "123456",
|
||
want: "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92",
|
||
},
|
||
{
|
||
name: "复杂密码",
|
||
password: "MyP@ssw0rd!",
|
||
want: "e493c394a28652900d73f0fc7e6713840b1af0ab1f3fd9c5878d82e5f753c6c1",
|
||
},
|
||
{
|
||
name: "中文字符",
|
||
password: "密码123",
|
||
want: "5a75e520515bf7695cd356454c4edb05ce925e230acf6c881701b7b8444dcbed",
|
||
},
|
||
{
|
||
name: "特殊字符",
|
||
password: "!@#$%^&*()",
|
||
want: "95ce789c5c9d18490972709838ca3a9719094bca3ac16332cfec0652b0236141",
|
||
},
|
||
}
|
||
|
||
for _, tt := range tests {
|
||
t.Run(tt.name, func(t *testing.T) {
|
||
got := hashPassword(tt.password)
|
||
if got != tt.want {
|
||
t.Errorf("hashPassword() = %v, want %v", got, tt.want)
|
||
}
|
||
})
|
||
}
|
||
}
|
||
|
||
// 测试hashPassword函数的确定性(相同输入总是产生相同输出)
|
||
func TestHashPasswordDeterministic(t *testing.T) {
|
||
password := "testPassword123"
|
||
|
||
// 多次调用应该产生相同的结果
|
||
result1 := hashPassword(password)
|
||
result2 := hashPassword(password)
|
||
result3 := hashPassword(password)
|
||
|
||
if result1 != result2 || result2 != result3 {
|
||
t.Errorf("hashPassword() 不是确定性的: %v, %v, %v", result1, result2, result3)
|
||
}
|
||
}
|
||
|
||
// 测试hashPassword函数的输出格式
|
||
func TestHashPasswordFormat(t *testing.T) {
|
||
password := "test"
|
||
result := hashPassword(password)
|
||
|
||
// 检查输出是否为64个字符的十六进制字符串
|
||
if len(result) != 64 {
|
||
t.Errorf("hashPassword() 输出长度不正确: got %d, want 64", len(result))
|
||
}
|
||
|
||
// 检查是否为有效的十六进制字符串
|
||
_, err := hex.DecodeString(result)
|
||
if err != nil {
|
||
t.Errorf("hashPassword() 输出不是有效的十六进制字符串: %v", err)
|
||
}
|
||
}
|
||
|
||
// 基准测试
|
||
func BenchmarkHashPassword(b *testing.B) {
|
||
password := "benchmarkPassword123"
|
||
|
||
b.ResetTimer()
|
||
for i := 0; i < b.N; i++ {
|
||
hashPassword(password)
|
||
}
|
||
}
|
||
|
||
// 验证我们的实现与标准库的一致性
|
||
func TestHashPasswordConsistency(t *testing.T) {
|
||
password := "consistencyTest"
|
||
|
||
// 使用我们的函数
|
||
ourResult := hashPassword(password)
|
||
|
||
// 手动计算SHA256
|
||
h := sha256.New()
|
||
h.Write([]byte(password))
|
||
expectedResult := hex.EncodeToString(h.Sum(nil))
|
||
|
||
if ourResult != expectedResult {
|
||
t.Errorf("hashPassword() 与标准库不一致: got %v, want %v", ourResult, expectedResult)
|
||
}
|
||
}
|