| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- package auth
- import (
- "encoding/json"
- "net/http"
- "net/http/httptest"
- "strings"
- "testing"
- "perms-system-server/internal/response"
- "perms-system-server/internal/svc"
- "perms-system-server/internal/testutil"
- "github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/require"
- )
- // TC-0798: handler 薄层契约 —— ChangePasswordHandler 在 body 非法 JSON 时必须 400,
- // 且错误文案定位到解析错误而不是"密码错误"之类的 logic 层语义。
- func TestChangePasswordHandler_MalformedBodyReturns400(t *testing.T) {
- svcCtx := svc.NewServiceContext(testutil.GetTestConfig())
- handler := ChangePasswordHandler(svcCtx)
- req := httptest.NewRequest(http.MethodPut, "/api/auth/password", strings.NewReader("{not-json"))
- req.Header.Set("Content-Type", "application/json")
- rr := httptest.NewRecorder()
- handler.ServeHTTP(rr, req)
- var body response.Body
- require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &body))
- assert.False(t, body.Success)
- assert.Equal(t, 400, body.ErrorCode,
- "handler 必须把 httpx.Parse 的错误包成 400; 旧实现有时会被吞成 500")
- assert.NotContains(t, body.ErrorMessage, "原密码", "400 的文案不应提到 logic 层的业务字段语义")
- }
- // TC-0799: handler 薄层契约 —— ChangePasswordHandler 在缺必填字段时也必须 400,
- // 这是 goctl 生成代码最容易退化的地方 (把 optional 错设成 required 或反之)。
- func TestChangePasswordHandler_MissingFieldsReturns400(t *testing.T) {
- svcCtx := svc.NewServiceContext(testutil.GetTestConfig())
- handler := ChangePasswordHandler(svcCtx)
- req := httptest.NewRequest(http.MethodPut, "/api/auth/password", strings.NewReader("{}"))
- req.Header.Set("Content-Type", "application/json")
- rr := httptest.NewRecorder()
- handler.ServeHTTP(rr, req)
- var body response.Body
- require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &body))
- assert.False(t, body.Success)
- assert.Equal(t, 400, body.ErrorCode)
- // 必填字段缺失应该精确到字段名, 便于客户端自动纠错
- assert.True(t,
- strings.Contains(body.ErrorMessage, "oldPassword") || strings.Contains(body.ErrorMessage, "newPassword"),
- "缺字段文案必须点名到 oldPassword / newPassword; 实际: %q", body.ErrorMessage)
- }
|