AuthPasswordTests.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using YZWater.Core.Services;
  2. namespace YZWater.Core.Tests.Services;
  3. /// <summary>
  4. /// AuthService 密码哈希相关测试(纯函数,无需数据库)
  5. /// </summary>
  6. public class AuthPasswordTests
  7. {
  8. [Fact]
  9. public void HashPassword_ReturnsPbkdf2Format()
  10. {
  11. var hash = AuthService.HashPassword("test123");
  12. Assert.StartsWith("pbkdf2$", hash);
  13. var parts = hash.Split('$');
  14. Assert.Equal(4, parts.Length);
  15. Assert.Equal("pbkdf2", parts[0]);
  16. Assert.Equal("100000", parts[1]);
  17. }
  18. [Fact]
  19. public void HashPassword_ProducesUniqueHashesEachCall()
  20. {
  21. var hash1 = AuthService.HashPassword("same_password");
  22. var hash2 = AuthService.HashPassword("same_password");
  23. // 由于盐值随机,每次哈希结果应不同
  24. Assert.NotEqual(hash1, hash2);
  25. }
  26. [Fact]
  27. public void VerifyPassword_CorrectPassword_ReturnsTrue()
  28. {
  29. var password = "my_secure_password";
  30. var hash = AuthService.HashPassword(password);
  31. Assert.True(AuthService.VerifyPassword(password, hash));
  32. }
  33. [Fact]
  34. public void VerifyPassword_WrongPassword_ReturnsFalse()
  35. {
  36. var hash = AuthService.HashPassword("correct_password");
  37. Assert.False(AuthService.VerifyPassword("wrong_password", hash));
  38. }
  39. [Fact]
  40. public void VerifyPassword_NullHash_ReturnsFalse()
  41. {
  42. Assert.False(AuthService.VerifyPassword("any_password", null));
  43. }
  44. [Fact]
  45. public void VerifyPassword_EmptyHash_ReturnsFalse()
  46. {
  47. Assert.False(AuthService.VerifyPassword("any_password", ""));
  48. Assert.False(AuthService.VerifyPassword("any_password", " "));
  49. }
  50. [Fact]
  51. public void VerifyPassword_InvalidFormat_ReturnsFalse()
  52. {
  53. Assert.False(AuthService.VerifyPassword("password", "not-a-valid-hash"));
  54. }
  55. [Fact]
  56. public void VerifyPassword_EmptyPassword_Works()
  57. {
  58. var hash = AuthService.HashPassword("");
  59. Assert.True(AuthService.VerifyPassword("", hash));
  60. Assert.False(AuthService.VerifyPassword("not_empty", hash));
  61. }
  62. [Fact]
  63. public void VerifyPassword_ChinesePassword_Works()
  64. {
  65. var password = "中文密码测试";
  66. var hash = AuthService.HashPassword(password);
  67. Assert.True(AuthService.VerifyPassword(password, hash));
  68. Assert.False(AuthService.VerifyPassword("其他密码", hash));
  69. }
  70. }