github.com/containerd/containerd@v22.0.0-20200918172823-438c87b8e050+incompatible/errdefs/grpc_test.go (about) 1 /* 2 Copyright The containerd Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package errdefs 18 19 import ( 20 "context" 21 "testing" 22 23 "google.golang.org/grpc/codes" 24 "google.golang.org/grpc/status" 25 26 "github.com/pkg/errors" 27 ) 28 29 func TestGRPCRoundTrip(t *testing.T) { 30 errShouldLeaveAlone := errors.New("unknown to package") 31 32 for _, testcase := range []struct { 33 input error 34 cause error 35 str string 36 }{ 37 { 38 input: ErrAlreadyExists, 39 cause: ErrAlreadyExists, 40 }, 41 { 42 input: ErrNotFound, 43 cause: ErrNotFound, 44 }, 45 { 46 input: errors.Wrapf(ErrFailedPrecondition, "test test test"), 47 cause: ErrFailedPrecondition, 48 str: "test test test: failed precondition", 49 }, 50 { 51 input: status.Errorf(codes.Unavailable, "should be not available"), 52 cause: ErrUnavailable, 53 str: "should be not available: unavailable", 54 }, 55 { 56 input: errShouldLeaveAlone, 57 cause: ErrUnknown, 58 str: errShouldLeaveAlone.Error() + ": " + ErrUnknown.Error(), 59 }, 60 { 61 input: context.Canceled, 62 cause: context.Canceled, 63 str: "context canceled", 64 }, 65 { 66 input: errors.Wrapf(context.Canceled, "this is a test cancel"), 67 cause: context.Canceled, 68 str: "this is a test cancel: context canceled", 69 }, 70 { 71 input: context.DeadlineExceeded, 72 cause: context.DeadlineExceeded, 73 str: "context deadline exceeded", 74 }, 75 { 76 input: errors.Wrapf(context.DeadlineExceeded, "this is a test deadline exceeded"), 77 cause: context.DeadlineExceeded, 78 str: "this is a test deadline exceeded: context deadline exceeded", 79 }, 80 } { 81 t.Run(testcase.input.Error(), func(t *testing.T) { 82 t.Logf("input: %v", testcase.input) 83 gerr := ToGRPC(testcase.input) 84 t.Logf("grpc: %v", gerr) 85 ferr := FromGRPC(gerr) 86 t.Logf("recovered: %v", ferr) 87 88 if errors.Cause(ferr) != testcase.cause { 89 t.Fatalf("unexpected cause: %v != %v", errors.Cause(ferr), testcase.cause) 90 } 91 if !errors.Is(ferr, testcase.cause) { 92 t.Fatalf("unexpected cause: !errors.Is(%v, %v)", ferr, testcase.cause) 93 } 94 95 expected := testcase.str 96 if expected == "" { 97 expected = testcase.cause.Error() 98 } 99 if ferr.Error() != expected { 100 t.Fatalf("unexpected string: %q != %q", ferr.Error(), expected) 101 } 102 }) 103 } 104 105 }