github.com/matrixorigin/matrixone@v1.2.0/pkg/common/moerr/error_test.go (about) 1 // Copyright 2021 - 2022 Matrix Origin 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package moerr 16 17 import ( 18 "context" 19 "fmt" 20 "testing" 21 22 "github.com/stretchr/testify/require" 23 ) 24 25 func pf1() { 26 panic("foo") 27 } 28 29 func pf2(a, b int) int { 30 return a / b 31 } 32 33 func pf3() { 34 panic(NewInternalError(context.TODO(), fmt.Sprintf("%s %s %s %d", "foo", "bar", "zoo", 2))) 35 } 36 37 func PanicF(i int) (err *Error) { 38 defer func() { 39 if e := recover(); e != nil { 40 err = ConvertPanicError(context.TODO(), e) 41 } 42 }() 43 switch i { 44 case 1: 45 pf1() 46 case 2: 47 foo := pf2(1, 0) 48 panic(foo) 49 case 3: 50 pf3() 51 default: 52 return nil 53 } 54 return 55 } 56 57 func TestPanicError(t *testing.T) { 58 for i := 0; i <= 3; i++ { 59 err := PanicF(i) 60 if i == 0 { 61 if err != nil { 62 t.Errorf("No panic should be OK") 63 } 64 } else { 65 if err == nil { 66 t.Errorf("Uncaught panic") 67 } 68 if err.Succeeded() { 69 t.Errorf("Caught OK panic") 70 } 71 } 72 } 73 } 74 75 func TestNew_panic(t *testing.T) { 76 defer func() { 77 var err any 78 if err = recover(); err != nil { 79 require.Equal(t, "foobarzoo is not yet implemented", err.(*Error).Error()) 80 t.Logf("err: %+v", err) 81 } 82 }() 83 panic(NewNYI(context.TODO(), "foobarzoo")) 84 } 85 86 func TestNew_MyErrorCode(t *testing.T) { 87 err := NewDivByZero(context.TODO()) 88 require.Equal(t, ER_DIVISION_BY_ZERO, err.MySQLCode()) 89 90 err = NewOutOfRange(context.TODO(), "int8", "1111") 91 require.Equal(t, ER_DATA_OUT_OF_RANGE, err.MySQLCode()) 92 } 93 94 func TestIsMoErrCode(t *testing.T) { 95 err := NewDivByZero(context.TODO()) 96 require.True(t, IsMoErrCode(err, ErrDivByZero)) 97 require.False(t, IsMoErrCode(err, ErrOOM)) 98 99 err2 := NewInternalError(context.TODO(), "what is this") 100 require.False(t, IsMoErrCode(err2, ErrDivByZero)) 101 require.False(t, IsMoErrCode(err2, ErrOOM)) 102 } 103 104 func TestEncoding(t *testing.T) { 105 e := NewDivByZero(context.TODO()) 106 data, err := e.MarshalBinary() 107 require.Nil(t, err) 108 e2 := new(Error) 109 err = e2.UnmarshalBinary(data) 110 require.Nil(t, err) 111 require.Equal(t, e, e2) 112 }