captchaLogic_test.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package pub
  2. import (
  3. "context"
  4. "testing"
  5. "perms-system-server/internal/svc"
  6. "perms-system-server/internal/testutil"
  7. "perms-system-server/internal/types"
  8. "github.com/stretchr/testify/assert"
  9. "github.com/stretchr/testify/require"
  10. )
  11. // TC-1208: 正常获取(默认宽高)
  12. func TestCaptcha_DefaultSize(t *testing.T) {
  13. svcCtx := svc.NewServiceContext(testutil.GetTestConfig())
  14. logic := NewCaptchaLogic(context.Background(), svcCtx)
  15. resp, err := logic.Captcha(&types.CaptchaReq{})
  16. require.NoError(t, err)
  17. require.NotNil(t, resp)
  18. assert.NotEmpty(t, resp.Id)
  19. assert.NotEmpty(t, resp.Base64Image)
  20. }
  21. // TC-1209: 自定义宽高
  22. func TestCaptcha_CustomSize(t *testing.T) {
  23. svcCtx := svc.NewServiceContext(testutil.GetTestConfig())
  24. logic := NewCaptchaLogic(context.Background(), svcCtx)
  25. resp, err := logic.Captcha(&types.CaptchaReq{Width: 300, Height: 100})
  26. require.NoError(t, err)
  27. require.NotNil(t, resp)
  28. assert.NotEmpty(t, resp.Id)
  29. assert.NotEmpty(t, resp.Base64Image)
  30. }
  31. // TC-1210: 宽高为 0 或负数,退化为默认值
  32. func TestCaptcha_ZeroOrNegativeSize(t *testing.T) {
  33. svcCtx := svc.NewServiceContext(testutil.GetTestConfig())
  34. logic := NewCaptchaLogic(context.Background(), svcCtx)
  35. cases := []struct {
  36. name string
  37. width int
  38. height int
  39. }{
  40. {"zero_both", 0, 0},
  41. {"negative_width", -1, 80},
  42. {"negative_height", 240, -1},
  43. {"negative_both", -100, -100},
  44. }
  45. for _, tc := range cases {
  46. t.Run(tc.name, func(t *testing.T) {
  47. resp, err := logic.Captcha(&types.CaptchaReq{Width: tc.width, Height: tc.height})
  48. require.NoError(t, err)
  49. require.NotNil(t, resp)
  50. assert.NotEmpty(t, resp.Id)
  51. assert.NotEmpty(t, resp.Base64Image)
  52. })
  53. }
  54. }
  55. // TC-1252: VerifyCaptcha 验证:正确码消费后不可重用
  56. func TestVerifyCaptcha_CorrectCodeConsumes(t *testing.T) {
  57. id := "test_captcha_id_001"
  58. code := "1234"
  59. defaultCaptchaStore.Set(id, code)
  60. assert.True(t, VerifyCaptcha(id, code))
  61. assert.False(t, VerifyCaptcha(id, code), "should be consumed after first verification")
  62. }
  63. // TC-1253: VerifyCaptcha 验证:错误码不消费
  64. func TestVerifyCaptcha_WrongCode(t *testing.T) {
  65. id := "test_captcha_id_002"
  66. code := "5678"
  67. defaultCaptchaStore.Set(id, code)
  68. assert.False(t, VerifyCaptcha(id, "0000"))
  69. }
  70. // TC-1254: VerifyCaptcha 验证:不存在的 id
  71. func TestVerifyCaptcha_NonExistentId(t *testing.T) {
  72. assert.False(t, VerifyCaptcha("non_existent_id", "1234"))
  73. }