-
Notifications
You must be signed in to change notification settings - Fork 3
/
convert_test.go
107 lines (93 loc) · 2.51 KB
/
convert_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
package convert_test
import (
"testing"
"strconv"
"time"
"github.com/Eun/go-convert"
"github.com/stretchr/testify/require"
)
func TestEdgeCases(t *testing.T) {
t.Run("nil destination", func(t *testing.T) {
err := convert.Convert(0, nil)
require.EqualError(t, err, `destination type cannot be nil`)
})
t.Run("interface destination", func(t *testing.T) {
t.Run("string interface", func(t *testing.T) {
var dst interface{} = ""
err := convert.Convert("Hello World", &dst)
require.NoError(t, err)
require.Equal(t, "Hello World", dst)
})
t.Run("nil interface", func(t *testing.T) {
var dst interface{}
err := convert.Convert("Hello World", &dst)
require.NoError(t, err)
require.Equal(t, "Hello World", dst)
})
})
t.Run("to ptr", func(t *testing.T) {
t.Run("nil", func(t *testing.T) {
var dst *string
err := convert.Convert("Hello World", &dst)
require.NoError(t, err)
require.Equal(t, "Hello World", *dst)
})
t.Run("preset value", func(t *testing.T) {
d := "Good Bye"
dst := &d
err := convert.Convert("Hello World", &dst)
require.NoError(t, err)
require.Equal(t, "Hello World", *dst)
})
})
}
func TestSimpleString(t *testing.T) {
var s string
convert.MustConvert(123, &s)
require.Equal(t, "123", s)
}
func TestAddNewRecipe(t *testing.T) {
var s string
require.NoError(t, convert.Convert(10, &s, convert.Options{
SkipUnknownFields: false,
Recipes: []convert.Recipe{
convert.MustMakeRecipe(func(_ convert.Converter, in int, out *string) error {
*out = strconv.FormatInt(int64(in), 16)
return nil
}),
},
}))
require.Equal(t, "a", s)
}
func TestAddNewRecipeForGeneric(t *testing.T) {
var s string
require.NoError(t, convert.Convert(time.Time{}, &s, convert.Options{
SkipUnknownFields: false,
Recipes: []convert.Recipe{
convert.MustMakeRecipe(func(c convert.Converter, in convert.StructValue, out *string) error {
require.Fail(t, "Should not be called")
return nil
}),
},
}))
require.Equal(t, "0001-01-01 00:00:00 +0000 UTC", s)
require.NoError(t, convert.Convert(struct {
Name string
}{
Name: "Joe",
}, &s, convert.Options{
SkipUnknownFields: false,
Recipes: []convert.Recipe{
convert.MustMakeRecipe(func(c convert.Converter, in convert.StructValue, out *string) error {
*out = "I got you"
return nil
}),
},
}))
require.Equal(t, "I got you", s)
}
func TestConvertNilToNil(t *testing.T) {
var nilValue interface{} = nil
require.NoError(t, convert.Convert(nil, &nilValue))
require.Nil(t, nilValue)
}