changePasswordHandler_test.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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.False(t, body.Success)
  26. assert.Equal(t, 400, body.ErrorCode,
  27. "handler 必须把 httpx.Parse 的错误包成 400; 旧实现有时会被吞成 500")
  28. assert.NotContains(t, body.ErrorMessage, "原密码", "400 的文案不应提到 logic 层的业务字段语义")
  29. }
  30. // TC-0799: handler 薄层契约 —— ChangePasswordHandler 在缺必填字段时也必须 400,
  31. // 这是 goctl 生成代码最容易退化的地方 (把 optional 错设成 required 或反之)。
  32. func TestChangePasswordHandler_MissingFieldsReturns400(t *testing.T) {
  33. svcCtx := svc.NewServiceContext(testutil.GetTestConfig())
  34. handler := ChangePasswordHandler(svcCtx)
  35. req := httptest.NewRequest(http.MethodPut, "/api/auth/password", strings.NewReader("{}"))
  36. req.Header.Set("Content-Type", "application/json")
  37. rr := httptest.NewRecorder()
  38. handler.ServeHTTP(rr, req)
  39. var body response.Body
  40. require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &body))
  41. assert.False(t, body.Success)
  42. assert.Equal(t, 400, body.ErrorCode)
  43. // 必填字段缺失应该精确到字段名, 便于客户端自动纠错
  44. assert.True(t,
  45. strings.Contains(body.ErrorMessage, "oldPassword") || strings.Contains(body.ErrorMessage, "newPassword"),
  46. "缺字段文案必须点名到 oldPassword / newPassword; 实际: %q", body.ErrorMessage)
  47. }