collections/optional_test.go

129 lines
2.3 KiB
Go
Raw Permalink Normal View History

2023-07-26 22:13:21 +02:00
package collections
import (
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestIsPresent(t *testing.T) {
tests := map[string]struct {
optional Optional[string]
expectedResult bool
}{
"not present": {
optional: Optional[string]{},
expectedResult: false,
},
"present": {
optional: Optional[string]{
present: true,
},
expectedResult: true,
},
}
for name, tc := range tests {
name, tc := name, tc
t.Run(name, func(t *testing.T) {
require.Equal(t, tc.expectedResult, tc.optional.IsPresent())
})
}
}
func TestGet(t *testing.T) {
tests := map[string]struct {
optional Optional[string]
expectedResult string
}{
"not present": {
optional: Optional[string]{},
expectedResult: "",
},
"present": {
optional: Optional[string]{
e: "foo",
present: true,
},
expectedResult: "foo",
},
}
for name, tc := range tests {
name, tc := name, tc
t.Run(name, func(t *testing.T) {
require.Equal(t, tc.expectedResult, tc.optional.Get())
})
}
}
func TestOrElse(t *testing.T) {
tests := map[string]struct {
optional Optional[string]
expectedResult string
}{
"not present": {
optional: Optional[string]{},
expectedResult: "bar",
},
"present": {
optional: Optional[string]{
e: "foo",
present: true,
},
expectedResult: "foo",
},
}
for name, tc := range tests {
name, tc := name, tc
t.Run(name, func(t *testing.T) {
require.Equal(t, tc.expectedResult, tc.optional.OrElse("bar"))
})
}
}
func TestOrElseGet(t *testing.T) {
tests := map[string]struct {
optional Optional[string]
expectedResult string
}{
"not present": {
optional: Optional[string]{},
expectedResult: "bar",
},
"present": {
optional: Optional[string]{
e: "foo",
present: true,
},
expectedResult: "foo",
},
}
for name, tc := range tests {
name, tc := name, tc
t.Run(name, func(t *testing.T) {
require.Equal(t, tc.expectedResult, tc.optional.OrElseGet(func() string {
return "bar"
}))
})
}
}
func TestTransform(t *testing.T) {
given := &Optional[string]{
e: "foo",
present: true,
}
transformer := func(s string) string {
return strings.ToUpper(s)
}
result := MapOptional(given, transformer)
require.Equal(t, "FOO", result.Get())
}