-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathblackmagic_test.go
74 lines (68 loc) · 1.55 KB
/
blackmagic_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
package blackmagic_test
import (
"testing"
"github.com/lestrrat-go/blackmagic"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestAssignment(t *testing.T) {
testcases := []struct {
Name string
Error bool
Value interface{}
Destination func() interface{}
}{
{
Name: `empty struct`,
Error: false,
Value: struct{}{},
Destination: func() interface{} {
var v interface{}
return &v
},
},
{
Name: `non pointer destination`,
Error: true,
Value: &struct{}{},
},
{
Name: `assign empty struct to int`,
Error: true,
Value: &struct{}{},
Destination: func() interface{} {
var v int
return &v
},
},
}
for _, tc := range testcases {
tc := tc
t.Run(tc.Name, func(t *testing.T) {
var dst interface{}
if dstFunc := tc.Destination; dstFunc != nil {
dst = dstFunc()
}
err := blackmagic.AssignIfCompatible(dst, tc.Value)
if tc.Error {
if !assert.Error(t, err, `blackmagic.AssignIfCompatible should fail`) {
return
}
} else {
if !assert.NoError(t, err, `blackmagic.AssignIfCompatible should succeed`) {
return
}
}
})
}
}
func TestAssignOptionalField(t *testing.T) {
var f struct {
Foo *string
Bar *int
}
require.NoError(t, blackmagic.AssignOptionalField(&f.Foo, "Hello"), `blackmagic.AssignOptionalField should succeed`)
require.Equal(t, *(f.Foo), "Hello")
require.NoError(t, blackmagic.AssignOptionalField(&f.Bar, 1), `blackmagic.AssignOptionalField should succeed`)
require.Equal(t, *(f.Bar), 1)
}