decred.org/dcrwallet/v3@v3.1.0/errors/errors_test.go (about) 1 // Copyright (c) 2018-2019 The Decred developers 2 // Use of this source code is governed by an ISC 3 // license that can be found in the LICENSE file. 4 5 package errors 6 7 import ( 8 std "errors" 9 "testing" 10 ) 11 12 func depth(err error) int { 13 if err == nil { 14 return 0 15 } 16 e, ok := err.(*Error) 17 if !ok { 18 return 1 19 } 20 return 1 + depth(e.Err) 21 } 22 23 func eq(e0, e1 *Error) bool { 24 if e0.Op != e1.Op { 25 return false 26 } 27 if e0.Kind != e1.Kind { 28 return false 29 } 30 if e0.Err != e1.Err { 31 return false 32 } 33 return true 34 } 35 36 func TestCollapse(t *testing.T) { 37 e0 := E(Op("abc")) 38 e0 = E(e0, Passphrase) 39 if depth(e0) != 1 { 40 t.Fatal("e0 was not collapsed") 41 } 42 43 e1 := E(Op("abc"), Passphrase) 44 if !eq(e0.(*Error), e1.(*Error)) { 45 t.Fatal("e0 was not collapsed to e1") 46 } 47 } 48 49 func TestIs(t *testing.T) { 50 base := std.New("base error") 51 e := E(base, Op("operation"), Permission) 52 if !Is(e, base) { 53 t.Fatal("no match on base errors") 54 } 55 if Is(e, E("different error")) { 56 t.Fatal("match on different error strings") 57 } 58 if !Is(e, E(Op("operation"))) { 59 t.Fatal("no match on operation") 60 } 61 if Is(e, E(Op("different operation"))) { 62 t.Fatal("match on different operation") 63 } 64 if !Is(e, E(Permission)) { 65 t.Fatal("no match on kind") 66 } 67 if Is(e, E(Invalid)) { 68 t.Fatal("match on different kind") 69 } 70 } 71 72 func TestCause(t *testing.T) { 73 inner := New("inner") 74 outer := E(inner) 75 if Cause(outer) != inner { 76 t.Fatal("Cause is not equal to inner error") 77 } 78 if Cause(nil) != nil { 79 t.Fatal("Cause(nil) must be nil") 80 } 81 bottom := std.New("bottom") 82 for _, e := range []error{ 83 E(bottom), 84 E(Passphrase, E(Invalid, bottom)), 85 } { 86 c := Cause(e) 87 if c != bottom { 88 t.Fatalf("wrong bottom error %v", c) 89 } 90 } 91 } 92 93 func TestDoubleWrappedErrorWithKind(t *testing.T) { 94 err := E(Invalid, "abc") 95 // Wrap the error again 96 err = E(err, "def") 97 // Now try to match against the kind 98 if !Is(err, Invalid) { 99 t.Errorf("Is returned false for error object: %T %+[1]v", err) 100 t.Errorf("Wrapped error: %T %+[1]v", err.(*Error).Unwrap()) 101 } 102 }