-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcatch_test.go
More file actions
115 lines (94 loc) · 2.01 KB
/
catch_test.go
File metadata and controls
115 lines (94 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package mo_test
import (
"errors"
"fmt"
"testing"
"github.com/nordborn/mo"
"github.com/stretchr/testify/assert"
)
func TestCatch(t *testing.T) {
res := divideResultCatched(10, 0)
fmt.Printf("%+v\n", res)
assert.Equal(t, -1, res.TryOr(-1))
}
func divideResultCatched(a, b int) (ret mo.Result[int]) {
defer mo.Catch(&ret, "divideResultCatched ", a, b)
ret = mo.Ok(a / b)
return
}
func TestCatchTry(t *testing.T) {
res := process()
fmt.Println(res)
assert.Equal(t, false, res.IsOk())
}
func process() (ret mo.Result[int]) {
defer mo.Catch(&ret)
file := mo.ResultFrom(openFile()).Try("open file")
data := readFile(file).Try()
ret = parse(data)
return
}
// Mock functions to simulate operations
func openFile() (*File, error) {
return nil, errors.New("file not found")
}
func readFile(_ *File) mo.Result[[]byte] {
return mo.Ok([]byte("dummy data"))
}
func parse(_ []byte) mo.Result[int] {
return mo.Ok(42)
}
type File struct{}
func TestCatchErr(t *testing.T) {
ret := processErr()
fmt.Println(ret)
assert.Equal(t, false, ret.IsOk())
}
func processErr() (ret mo.Result[int]) {
defer mo.Catch(&ret, "processErr")
mo.TryErr(retErr())
return
}
func retErr() error {
return errors.New("a test error")
}
func BenchmarkPureDefer(b *testing.B) {
for i := 0; i < b.N; i++ {
defer func() {}()
}
}
func BenchmarkErr(b *testing.B) {
err0 := errors.New("some error")
for i := 0; i < b.N; i++ {
func() (err error) {
ctx := "some func"
err = fmt.Errorf("%s: %d: %w", ctx, i, err0)
return
}()
}
}
func BenchmarkCatch(b *testing.B) {
for i := 0; i < b.N; i++ {
func() (ret mo.Result[int]) {
defer mo.Catch(&ret, "some func")
panic(i)
}()
}
}
type Outer struct{}
func TestResultOutput(t *testing.T) {
ret := new(Outer).Outer()
if !ret.IsOk() {
t.Log(ret.Err())
t.Fail()
}
}
func (o *Outer) Outer() (ret mo.Result[int]) {
defer mo.Catch(&ret)
val := divide(1, 0).Try()
return ret.WithOk(val)
}
func divide(a, b int) (ret mo.Result[int]) {
defer mo.Catch(&ret, a, b)
return ret.WithOk(a / b)
}