github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/sql/pgwire/pgerror/pgcode_test.go (about) 1 // Copyright 2019 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 package pgerror_test 12 13 import ( 14 "context" 15 "fmt" 16 "strings" 17 "testing" 18 19 "github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode" 20 "github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror" 21 "github.com/cockroachdb/errors" 22 "github.com/cockroachdb/errors/testutils" 23 ) 24 25 func TestPGCode(t *testing.T) { 26 tt := testutils.T{T: t} 27 28 testData := []struct { 29 outerCode string 30 innerCode string 31 innerErr error 32 expectedCode string 33 }{ 34 {"foo", "bar", errors.New("world"), "bar"}, 35 {"foo", pgcode.Uncategorized, errors.New("world"), "foo"}, 36 {pgcode.Uncategorized, "foo", errors.New("world"), "foo"}, 37 {"foo", "bar", errors.WithAssertionFailure(errors.New("world")), pgcode.Internal}, 38 {"foo", "bar", errors.UnimplementedError(errors.IssueLink{}, "world"), pgcode.FeatureNotSupported}, 39 {"foo", pgcode.Internal, errors.New("world"), pgcode.Internal}, 40 {pgcode.Internal, "foo", errors.New("world"), pgcode.Internal}, 41 } 42 43 for _, t := range testData { 44 tt.Run(fmt.Sprintf("%s/%s/%s", t.outerCode, t.innerCode, t.innerErr), 45 func(tt testutils.T) { 46 origErr := t.innerErr 47 origErr = pgerror.WithCandidateCode(origErr, t.innerCode) 48 origErr = pgerror.WithCandidateCode(origErr, t.outerCode) 49 50 theTest := func(tt testutils.T, err error) { 51 tt.Check(errors.Is(err, t.innerErr)) 52 tt.CheckEqual(err.Error(), t.innerErr.Error()) 53 54 tt.Check(pgerror.HasCandidateCode(err)) 55 56 code := pgerror.GetPGCodeInternal(err, pgerror.ComputeDefaultCode) 57 tt.CheckEqual(code, t.expectedCode) 58 59 errV := fmt.Sprintf("%+v", err) 60 tt.Check(strings.Contains(errV, "code: "+t.innerCode)) 61 tt.Check(strings.Contains(errV, "code: "+t.outerCode)) 62 } 63 64 tt.Run("local", func(tt testutils.T) { theTest(tt, origErr) }) 65 66 enc := errors.EncodeError(context.Background(), origErr) 67 newErr := errors.DecodeError(context.Background(), enc) 68 69 tt.Run("remote", func(tt testutils.T) { theTest(tt, newErr) }) 70 71 }) 72 } 73 74 }