github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/infra/errcode/registry_test.go (about) 1 package errcode 2 3 import ( 4 "testing" 5 6 "github.com/stretchr/testify/assert" 7 ) 8 9 func TestRegistry(t *testing.T) { 10 reg := New() 11 got1 := reg.Register(-1024, "oops") 12 got2 := reg.Register(0, "success") 13 got3 := reg.Register(404, "not found") 14 15 assert.Equal(t, "[-1024] oops", got1.Error()) 16 assert.Equal(t, "[0] success", got2.Error()) 17 assert.Equal(t, "[404] not found", got3.Error()) 18 19 list := reg.Dump() 20 assert.Equal(t, int32(-1024), list[0].Code()) 21 assert.Equal(t, int32(0), list[1].Code()) 22 assert.Equal(t, int32(404), list[2].Code()) 23 24 reg.UpdateMessages(map[int32]string{ 25 400: "bad request", 26 401: "unauthorized", 27 403: "forbidden", 28 }) 29 assert.Equal(t, "bad request", reg.getMessage(400)) 30 assert.Equal(t, "unauthorized", reg.getMessage(401)) 31 assert.Equal(t, "forbidden", reg.getMessage(403)) 32 33 reg.UpdateMessages(map[int32]string{ 34 -1: "error", 35 0: "success", 36 }) 37 assert.Equal(t, "oops", got1.Message()) 38 assert.Equal(t, "success", got2.Message()) 39 assert.Equal(t, "not found", got3.Message()) 40 } 41 42 func TestRegistryWithReserved(t *testing.T) { 43 reg := New(WithReserved(func(code int32) bool { return code <= 99 })) 44 45 assert.Panics(t, func() { reg.Register(-1, "") }) 46 assert.Panics(t, func() { reg.Register(99, "") }) 47 assert.NotPanics(t, func() { reg.Register(100, "") }) 48 assert.NotPanics(t, func() { reg.RegisterReserved(-1, "") }) 49 assert.NotPanics(t, func() { reg.RegisterReserved(99, "") }) 50 }