| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- using YZWater.Core.Services;
- namespace YZWater.Core.Tests.Services;
- /// <summary>
- /// AuthService 密码哈希相关测试(纯函数,无需数据库)
- /// </summary>
- public class AuthPasswordTests
- {
- [Fact]
- public void HashPassword_ReturnsPbkdf2Format()
- {
- var hash = AuthService.HashPassword("test123");
- Assert.StartsWith("pbkdf2$", hash);
- var parts = hash.Split('$');
- Assert.Equal(4, parts.Length);
- Assert.Equal("pbkdf2", parts[0]);
- Assert.Equal("100000", parts[1]);
- }
- [Fact]
- public void HashPassword_ProducesUniqueHashesEachCall()
- {
- var hash1 = AuthService.HashPassword("same_password");
- var hash2 = AuthService.HashPassword("same_password");
- // 由于盐值随机,每次哈希结果应不同
- Assert.NotEqual(hash1, hash2);
- }
- [Fact]
- public void VerifyPassword_CorrectPassword_ReturnsTrue()
- {
- var password = "my_secure_password";
- var hash = AuthService.HashPassword(password);
- Assert.True(AuthService.VerifyPassword(password, hash));
- }
- [Fact]
- public void VerifyPassword_WrongPassword_ReturnsFalse()
- {
- var hash = AuthService.HashPassword("correct_password");
- Assert.False(AuthService.VerifyPassword("wrong_password", hash));
- }
- [Fact]
- public void VerifyPassword_NullHash_ReturnsFalse()
- {
- Assert.False(AuthService.VerifyPassword("any_password", null));
- }
- [Fact]
- public void VerifyPassword_EmptyHash_ReturnsFalse()
- {
- Assert.False(AuthService.VerifyPassword("any_password", ""));
- Assert.False(AuthService.VerifyPassword("any_password", " "));
- }
- [Fact]
- public void VerifyPassword_InvalidFormat_ReturnsFalse()
- {
- Assert.False(AuthService.VerifyPassword("password", "not-a-valid-hash"));
- }
- [Fact]
- public void VerifyPassword_EmptyPassword_Works()
- {
- var hash = AuthService.HashPassword("");
- Assert.True(AuthService.VerifyPassword("", hash));
- Assert.False(AuthService.VerifyPassword("not_empty", hash));
- }
- [Fact]
- public void VerifyPassword_ChinesePassword_Works()
- {
- var password = "中文密码测试";
- var hash = AuthService.HashPassword(password);
- Assert.True(AuthService.VerifyPassword(password, hash));
- Assert.False(AuthService.VerifyPassword("其他密码", hash));
- }
- }
|