aboutsummaryrefslogtreecommitdiffstats
path: root/library/go/x/xreflect/assign_test.go
blob: 45fd7186a7f875320648916dfa38f7e95a0772a0 (plain) (blame)
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
package xreflect_test

import (
	"testing"

	"github.com/stretchr/testify/require"
	"github.com/ydb-platform/ydb/library/go/x/xreflect"
)

type Foo struct {
	S string
}

var _ InterfaceFoo = &Foo{}

func (f *Foo) FuncFoo() {}

type InterfaceFoo interface {
	FuncFoo()
}

type Bar struct {
	I int
}

var _ InterfaceBar = &Bar{}

func (f *Bar) FuncBar() {}

type InterfaceBar interface {
	FuncBar()
}

func TestAssign(t *testing.T) {
	t.Run("ValueToValue", func(t *testing.T) {
		src := Foo{S: "S"}
		var dst Foo
		require.True(t, xreflect.Assign(src, &dst))
		require.Equal(t, src, dst)
	})

	t.Run("ValueToValueInvalid", func(t *testing.T) {
		src := Foo{S: "S"}
		var dst Bar
		require.False(t, xreflect.Assign(src, &dst))
		require.Equal(t, Bar{}, dst)
	})

	t.Run("ValueToInterface", func(t *testing.T) {
		src := Foo{S: "S"}
		var dst InterfaceFoo
		require.True(t, xreflect.Assign(&src, &dst))
		require.NotNil(t, dst)
		v, ok := dst.(*Foo)
		require.True(t, ok)
		require.Equal(t, &src, v)
	})

	t.Run("ValueToInterfaceInvalid", func(t *testing.T) {
		src := Bar{I: 42}
		var dst InterfaceFoo
		require.False(t, xreflect.Assign(&src, &dst))
		require.Nil(t, dst)
	})

	t.Run("InterfaceToInterface", func(t *testing.T) {
		src := InterfaceFoo(&Foo{S: "S"})
		var dst InterfaceFoo
		require.True(t, xreflect.Assign(src, &dst))
		require.NotNil(t, dst)
		require.Equal(t, src, dst)
		v, ok := dst.(*Foo)
		require.True(t, ok)
		require.Equal(t, src, v)
	})

	t.Run("InterfaceToInterfaceInvalid", func(t *testing.T) {
		src := InterfaceFoo(&Foo{S: "S"})
		var dst InterfaceBar
		require.False(t, xreflect.Assign(src, &dst))
		require.Nil(t, dst)
	})
}