File: blackmagic_test.go

package info (click to toggle)
golang-github-lestrrat-go-blackmagic 1.0.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 92 kB
  • sloc: makefile: 2
file content (74 lines) | stat: -rw-r--r-- 1,590 bytes parent folder | download
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)
}