changePasswordHandler_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package auth
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "net/http/httptest"
  6. "strings"
  7. "testing"
  8. "perms-system-server/internal/response"
  9. "perms-system-server/internal/svc"
  10. "perms-system-server/internal/testutil"
  11. "github.com/stretchr/testify/assert"
  12. "github.com/stretchr/testify/require"
  13. )
  14. // TC-0798: handler 薄层契约 —— ChangePasswordHandler 在 body 非法 JSON 时必须 400,
  15. // 且错误文案定位到解析错误而不是"密码错误"之类的 logic 层语义。
  16. func TestChangePasswordHandler_MalformedBodyReturns400(t *testing.T) {
  17. svcCtx := svc.NewServiceContext(testutil.GetTestConfig())
  18. handler := ChangePasswordHandler(svcCtx)
  19. req := httptest.NewRequest(http.MethodPut, "/api/auth/password", strings.NewReader("{not-json"))
  20. req.Header.Set("Content-Type", "application/json")
  21. rr := httptest.NewRecorder()
  22. handler.ServeHTTP(rr, req)
  23. var body response.Body
  24. require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &body))
  25. assert.Equal(t, 400, body.Code,
  26. "handler 必须把 httpx.Parse 的错误包成 400; 旧实现有时会被吞成 500")
  27. assert.NotContains(t, body.Msg, "原密码", "400 的文案不应提到 logic 层的业务字段语义")
  28. }
  29. // TC-0799: handler 薄层契约 —— ChangePasswordHandler 在缺必填字段时也必须 400,
  30. // 这是 goctl 生成代码最容易退化的地方 (把 optional 错设成 required 或反之)。
  31. func TestChangePasswordHandler_MissingFieldsReturns400(t *testing.T) {
  32. svcCtx := svc.NewServiceContext(testutil.GetTestConfig())
  33. handler := ChangePasswordHandler(svcCtx)
  34. req := httptest.NewRequest(http.MethodPut, "/api/auth/password", strings.NewReader("{}"))
  35. req.Header.Set("Content-Type", "application/json")
  36. rr := httptest.NewRecorder()
  37. handler.ServeHTTP(rr, req)
  38. var body response.Body
  39. require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &body))
  40. assert.Equal(t, 400, body.Code)
  41. // 必填字段缺失应该精确到字段名, 便于客户端自动纠错
  42. assert.True(t,
  43. strings.Contains(body.Msg, "oldPassword") || strings.Contains(body.Msg, "newPassword"),
  44. "缺字段文案必须点名到 oldPassword / newPassword; 实际: %q", body.Msg)
  45. }