feat: expose transaction failure stages and conservative outcomes
This commit is contained in:
56
database/transactionResponse_test.go
Normal file
56
database/transactionResponse_test.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package database_test
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
omni "git.yuntuo.hk/k2safe/go-omni"
|
||||
apierrors "git.yuntuo.hk/k2safe/go-omni/errors"
|
||||
"git.yuntuo.hk/k2safe/go-omni/response"
|
||||
)
|
||||
|
||||
func TestInTxPublicErrorCompatibility(t *testing.T) {
|
||||
private := errors.New("private database details")
|
||||
for _, scenario := range []string{"business", "businessAndRollback", "commit"} {
|
||||
t.Run(scenario, func(t *testing.T) {
|
||||
f := &txFixture{}
|
||||
if scenario == "businessAndRollback" {
|
||||
f.rollbackErr = private
|
||||
} else if scenario == "commit" {
|
||||
f.commitErr = private
|
||||
}
|
||||
pool := txPool(t, f)
|
||||
app := omni.New(omni.WithResponse(response.Config{CodeType: "int32", SuccessCode: 0, ErrorCode: 9999, MessageField: "msg", DataMode: "always"}),
|
||||
omni.WithErrors(apierrors.Catalog{DefaultStatus: 200, Definitions: map[string]apierrors.Definition{
|
||||
"INVALID": {Code: 400002, Message: "{field} is invalid", Params: []apierrors.Parameter{{Name: "field", Type: "string"}}},
|
||||
}}))
|
||||
defer app.Close()
|
||||
app.POST("/record", func(c *omni.Context) error {
|
||||
return pool.InTx(c.Context(), nil, func(*sql.Tx) error {
|
||||
if scenario == "commit" {
|
||||
return nil
|
||||
}
|
||||
return apierrors.ByCode("INVALID").WithParams(map[string]any{"field": "name"}).WithCause(private)
|
||||
})
|
||||
})
|
||||
w := httptest.NewRecorder()
|
||||
app.ServeHTTP(w, httptest.NewRequest("POST", "/record", nil))
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wantStatus, wantCode, wantMessage := 200, float64(400002), "name is invalid"
|
||||
if scenario == "commit" {
|
||||
wantStatus, wantCode, wantMessage = 500, 9999, "internal server error"
|
||||
}
|
||||
data, hasData := body["data"]
|
||||
if w.Code != wantStatus || body["code"] != wantCode || body["msg"] != wantMessage || !hasData || data != nil || strings.Contains(w.Body.String(), "private") {
|
||||
t.Fatal("transaction wrapper changed public error response:", w.Code, w.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user