go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/errors/stdlib_test.go (about) 1 // Copyright 2022 The LUCI Authors. 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 errors 16 17 import ( 18 "errors" 19 "testing" 20 21 . "github.com/smartystreets/goconvey/convey" 22 ) 23 24 // TestErrorIs makes a new fake value implementing the Error interface and wraps it using Annotate(). 25 // Along the way, we test whether Is returns what's expected. 26 func TestErrorIs(t *testing.T) { 27 t.Parallel() 28 Convey("test is", t, func() { 29 newFakeError := &fakeError{} 30 wrappedError := Annotate(newFakeError, "8ed2d02c-a8c0-4b8e-b734-bf30cb88d0c6").Err() 31 So(newFakeError.Error(), ShouldEqual, "f9bd822e-6568-46ab-ba7d-419ef5f64b3b") 32 So(errors.Is(newFakeError, &fakeError{}), ShouldBeTrue) 33 So(Is(newFakeError, &fakeError{}), ShouldBeTrue) 34 So(errors.Is(wrappedError, &fakeError{}), ShouldBeTrue) 35 So(Is(wrappedError, &fakeError{}), ShouldBeTrue) 36 }) 37 } 38 39 // TestErrorAs makes a new fake value implementing the Error interface and wraps it using Annotate(). 40 // Along the way, we test whether As succeeds for the raw error and the annotated error. 41 func TestErrorAs(t *testing.T) { 42 t.Parallel() 43 Convey("test as", t, func() { 44 Convey("raw error", func() { 45 var dst *fakeError 46 newFakeError := &fakeError{} 47 So(As(newFakeError, &dst), ShouldBeTrue) 48 So(newFakeError == dst, ShouldBeTrue) 49 }) 50 Convey("wrapped error", func() { 51 var dst *fakeError 52 newFakeError := &fakeError{} 53 wrappedError := Annotate(newFakeError, "8ed2d02c-a8c0-4b8e-b734-bf30cb88d0c6").Err() 54 So(As(wrappedError, &dst), ShouldBeTrue) 55 So(newFakeError == dst, ShouldBeTrue) 56 }) 57 }) 58 } 59 60 // TestErrorJoin tests using the builtin error.Join. 61 func TestErrorJoin(t *testing.T) { 62 t.Parallel() 63 Convey("test join", t, func() { 64 errorA := errors.New("a") 65 errorB := errors.New("b") 66 combined := Join(errorA, errorB) 67 So(combined.Error(), ShouldEqual, `a 68 b`) 69 }) 70 } 71 72 type fakeError struct{} 73 74 func (w *fakeError) Error() string { 75 return "f9bd822e-6568-46ab-ba7d-419ef5f64b3b" 76 } 77 78 // Check that fakeError is an error. 79 var _ error = &fakeError{}