mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-09-29 22:06:38 +08:00
7c5c196ede
Lift the handler helpers that map a non-nil error to Abort* so plugins do not each reimplement record-not-found vs bad-request branching.
69 lines
1.9 KiB
Go
69 lines
1.9 KiB
Go
// Copyright 2026 Arctel.net
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
package response
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
func TestAbortNotFoundIfMissing(t *testing.T) {
|
|
t.Run("nil", func(t *testing.T) {
|
|
w := httptest.NewRecorder()
|
|
c, _ := gin.CreateTestContext(w)
|
|
assert.False(t, AbortNotFoundIfMissing(c, nil, "gone"))
|
|
assert.False(t, c.IsAborted())
|
|
assert.Empty(t, c.Errors)
|
|
})
|
|
|
|
t.Run("record not found", func(t *testing.T) {
|
|
w := httptest.NewRecorder()
|
|
c, _ := gin.CreateTestContext(w)
|
|
assert.True(t, AbortNotFoundIfMissing(c, gorm.ErrRecordNotFound, "记录不存在"))
|
|
assert.True(t, c.IsAborted())
|
|
var apiErr *APIError
|
|
require.True(t, errors.As(c.Errors.Last().Err, &apiErr))
|
|
assert.Equal(t, http.StatusNotFound, apiErr.Code)
|
|
assert.Equal(t, "记录不存在", apiErr.Msg)
|
|
})
|
|
|
|
t.Run("other error", func(t *testing.T) {
|
|
w := httptest.NewRecorder()
|
|
c, _ := gin.CreateTestContext(w)
|
|
assert.True(t, AbortNotFoundIfMissing(c, errors.New("boom"), "记录不存在"))
|
|
assert.True(t, c.IsAborted())
|
|
var apiErr *APIError
|
|
require.True(t, errors.As(c.Errors.Last().Err, &apiErr))
|
|
assert.Equal(t, http.StatusBadRequest, apiErr.Code)
|
|
assert.Equal(t, "boom", apiErr.Msg)
|
|
})
|
|
}
|
|
|
|
func TestAbortBadRequestOnError(t *testing.T) {
|
|
t.Run("nil", func(t *testing.T) {
|
|
w := httptest.NewRecorder()
|
|
c, _ := gin.CreateTestContext(w)
|
|
assert.False(t, AbortBadRequestOnError(c, nil))
|
|
assert.False(t, c.IsAborted())
|
|
})
|
|
|
|
t.Run("error", func(t *testing.T) {
|
|
w := httptest.NewRecorder()
|
|
c, _ := gin.CreateTestContext(w)
|
|
assert.True(t, AbortBadRequestOnError(c, errors.New("bad")))
|
|
assert.True(t, c.IsAborted())
|
|
var apiErr *APIError
|
|
require.True(t, errors.As(c.Errors.Last().Err, &apiErr))
|
|
assert.Equal(t, http.StatusBadRequest, apiErr.Code)
|
|
assert.Equal(t, "bad", apiErr.Msg)
|
|
})
|
|
}
|