-
Notifications
You must be signed in to change notification settings - Fork 0
/
optional_test.go
100 lines (76 loc) · 1.58 KB
/
optional_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
package optional
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestInitNil(t *testing.T) {
o1 := Value[string]{}
assert.Nil(t, o1.value)
o2 := OfNil[string]()
assert.Nil(t, o2.value)
}
func TestInitOfValue(t *testing.T) {
o := Of("foo")
if assert.NotNil(t, o.value) {
assert.Equal(t, "foo", *o.value)
}
}
func TestSetters(t *testing.T) {
o := Value[string]{}
o.Set("foo")
if assert.NotNil(t, o.value) {
assert.Equal(t, "foo", *o.value)
}
o.SetNil()
assert.Nil(t, o.value)
}
func TestGetters(t *testing.T) {
o := Of("foo")
assert.True(t, o.HasValue())
ok, v := o.Get()
assert.True(t, ok)
assert.Equal(t, "foo", v)
o.SetNil()
ok, v = o.Get()
assert.False(t, ok)
assert.Equal(t, "", v)
}
func TestGetterOfDefaultValue(t *testing.T) {
o := OfNil[string]()
assert.Equal(t, "bar", o.GetOr("bar"))
o.Set("foo")
assert.Equal(t, "foo", o.GetOr("bar"))
}
func TestTypeParameters(t *testing.T) {
s := Of("foo")
assert.Equal(t, "foo", *s.value)
i := Of(42)
assert.Equal(t, 42, *i.value)
x := Of(struct{}{})
assert.Equal(t, struct{}{}, *x.value)
}
func TestPointers(t *testing.T) {
s := "foo"
sPtr := &s
o := Of(sPtr)
assert.True(t, sPtr == *o.value)
}
func TestPanicsAsExpected(t *testing.T) {
o := OfNil[string]()
assert.Nil(t, o.value)
o.Set("foo")
if assert.NotNil(t, o.value) {
assert.Equal(t, "foo", *o.value)
}
ok, v := o.Get()
assert.Equal(t, true, ok)
assert.Equal(t, "foo", v)
assert.NotPanics(t, func() {
assert.Equal(t, "foo", o.MustGet())
})
o.SetNil()
assert.Nil(t, o.value)
assert.Panics(t, func() {
o.MustGet()
})
}