-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtry_test.go
115 lines (97 loc) · 2.2 KB
/
try_test.go
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 maybe_test
import (
"errors"
"fmt"
"testing"
"github.com/magicdrive/maybe"
)
type MyErr struct {
msg string
}
func (e MyErr) Error() string {
return e.msg
}
func TestFromValue(t *testing.T) {
val := maybe.FromValue(100, true)
if val.IsNone() || val.Unwrap() != 100 {
t.Errorf("expected Some(100)")
}
none := maybe.FromValue(0, false)
if none.IsSome() {
t.Errorf("expected None")
}
}
func TestTry(t *testing.T) {
okFn := func() (int, error) {
return 7, nil
}
failFn := func() (int, error) {
return 0, errors.New("fail")
}
res := maybe.Try(okFn)
if res.IsNone() || res.Unwrap() != 7 {
t.Errorf("expected Some(7)")
}
none := maybe.Try(failFn)
if none.IsSome() {
t.Errorf("expected None")
}
}
func TestFromValuePrimitive(t *testing.T) {
val := maybe.FromValuePrimitive(10, true)
if val.IsNone() || val.Unwrap() != 10 {
t.Errorf("expected SomePrimitive(10)")
}
none := maybe.FromValuePrimitive(0, false)
if none.IsSome() {
t.Errorf("expected NonePrimitive")
}
}
func TestTryPrimitive(t *testing.T) {
okFn := func() (int, error) {
return 5, nil
}
failFn := func() (int, error) {
return 0, errors.New("fail")
}
res := maybe.TryPrimitive(okFn)
if res.IsNone() || res.Unwrap() != 5 {
t.Errorf("expected SomePrimitive(5)")
}
none := maybe.TryPrimitive(failFn)
if none.IsSome() {
t.Errorf("expected NonePrimitive")
}
}
func TestFold(t *testing.T) {
m := maybe.Some(5)
result := maybe.Fold(m, func(x int) string {
return fmt.Sprintf("val=%d", x)
}, "none")
if result != "val=5" {
t.Errorf("expected val=5, got %s", result)
}
none := maybe.None[int]()
result2 := maybe.Fold(none, func(x int) string {
return "should not happen"
}, "none")
if result2 != "none" {
t.Errorf("expected 'none', got %s", result2)
}
}
func TestFoldPrimitive(t *testing.T) {
m := maybe.SomePrimitive(10)
result := maybe.FoldPrimitive(m, func(x int) string {
return fmt.Sprintf("prim=%d", x)
}, "none")
if result != "prim=10" {
t.Errorf("expected prim=10, got %s", result)
}
n := maybe.NonePrimitive[int]()
result2 := maybe.FoldPrimitive(n, func(x int) string {
return "should not happen"
}, "none")
if result2 != "none" {
t.Errorf("expected 'none', got %s", result2)
}
}