github.com/go-playground/pkg/v5@v5.29.1/values/result/result_test.go (about) 1 //go:build go1.18 2 // +build go1.18 3 4 package resultext 5 6 import ( 7 "errors" 8 "io" 9 "testing" 10 11 . "github.com/go-playground/assert/v2" 12 ) 13 14 type myStruct struct{} 15 16 func TestAndXXX(t *testing.T) { 17 ok := Ok[int, error](1) 18 Equal(t, Ok[int, error](3), ok.And(func(int) int { return 3 })) 19 Equal(t, Ok[int, error](3), ok.AndThen(func(int) Result[int, error] { return Ok[int, error](3) })) 20 Equal(t, Err[int, error](io.EOF), ok.AndThen(func(int) Result[int, error] { return Err[int, error](io.EOF) })) 21 22 err := Err[int, error](io.EOF) 23 Equal(t, Err[int, error](io.EOF), err.And(func(int) int { return 3 })) 24 Equal(t, Err[int, error](io.EOF), err.AndThen(func(int) Result[int, error] { return Ok[int, error](3) })) 25 Equal(t, Err[int, error](io.EOF), err.AndThen(func(int) Result[int, error] { return Err[int, error](io.ErrUnexpectedEOF) })) 26 Equal(t, Err[int, error](io.ErrUnexpectedEOF), ok.AndThen(func(int) Result[int, error] { return Err[int, error](io.ErrUnexpectedEOF) })) 27 } 28 29 func TestUnwrap(t *testing.T) { 30 er := Err[int, error](io.EOF) 31 PanicMatches(t, func() { er.Unwrap() }, "Result.Unwrap(): result is Err") 32 33 v := er.UnwrapOr(3) 34 Equal(t, 3, v) 35 36 v = er.UnwrapOrElse(func() int { return 2 }) 37 Equal(t, 2, v) 38 39 v = er.UnwrapOrDefault() 40 Equal(t, 0, v) 41 } 42 43 func TestResult(t *testing.T) { 44 result := returnOk() 45 Equal(t, true, result.IsOk()) 46 Equal(t, false, result.IsErr()) 47 Equal(t, true, result.Err() == nil) 48 Equal(t, myStruct{}, result.Unwrap()) 49 50 result = returnErr() 51 Equal(t, false, result.IsOk()) 52 Equal(t, true, result.IsErr()) 53 Equal(t, false, result.Err() == nil) 54 PanicMatches(t, func() { 55 result.Unwrap() 56 }, "Result.Unwrap(): result is Err") 57 } 58 59 func returnOk() Result[myStruct, error] { 60 return Ok[myStruct, error](myStruct{}) 61 } 62 63 func returnErr() Result[myStruct, error] { 64 return Err[myStruct, error](errors.New("bad")) 65 } 66 67 func BenchmarkResultOk(b *testing.B) { 68 for i := 0; i < b.N; i++ { 69 res := returnOk() 70 if res.IsOk() { 71 _ = res.Unwrap() 72 } 73 } 74 } 75 76 func BenchmarkResultErr(b *testing.B) { 77 for i := 0; i < b.N; i++ { 78 res := returnErr() 79 if res.IsOk() { 80 _ = res.Unwrap() 81 } 82 } 83 } 84 85 func BenchmarkNoResultOk(b *testing.B) { 86 for i := 0; i < b.N; i++ { 87 res, err := returnOkNoResult() 88 if err != nil { 89 _ = res 90 } 91 } 92 } 93 94 func BenchmarkNoResultErr(b *testing.B) { 95 for i := 0; i < b.N; i++ { 96 res, err := returnErrNoResult() 97 if err != nil { 98 _ = res 99 } 100 } 101 } 102 103 func returnOkNoResult() (myStruct, error) { 104 return myStruct{}, nil 105 } 106 107 func returnErrNoResult() (myStruct, error) { 108 return myStruct{}, errors.New("bad") 109 }