Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/grafana-agent
Path: blob/main/pkg/river/internal/reflectutil/walk_test.go
4096 views
1
package reflectutil_test
2
3
import (
4
"reflect"
5
"testing"
6
7
"github.com/grafana/agent/pkg/river/internal/reflectutil"
8
"github.com/grafana/agent/pkg/river/internal/rivertags"
9
"github.com/stretchr/testify/assert"
10
"github.com/stretchr/testify/require"
11
)
12
13
func TestDeeplyNested_Access(t *testing.T) {
14
type Struct struct {
15
Field1 struct {
16
Field2 struct {
17
Field3 struct {
18
Value string
19
}
20
}
21
}
22
}
23
24
var s Struct
25
s.Field1.Field2.Field3.Value = "Hello, world!"
26
27
rv := reflect.ValueOf(&s).Elem()
28
innerValue := reflectutil.GetOrAlloc(rv, rivertags.Field{Index: []int{0, 0, 0, 0}})
29
assert.True(t, innerValue.CanSet())
30
assert.Equal(t, reflect.String, innerValue.Kind())
31
}
32
33
func TestDeeplyNested_Allocate(t *testing.T) {
34
type Struct struct {
35
Field1 *struct {
36
Field2 *struct {
37
Field3 *struct {
38
Value string
39
}
40
}
41
}
42
}
43
44
var s Struct
45
46
rv := reflect.ValueOf(&s).Elem()
47
innerValue := reflectutil.GetOrAlloc(rv, rivertags.Field{Index: []int{0, 0, 0, 0}})
48
require.True(t, innerValue.CanSet())
49
require.Equal(t, reflect.String, innerValue.Kind())
50
51
innerValue.Set(reflect.ValueOf("Hello, world!"))
52
require.Equal(t, "Hello, world!", s.Field1.Field2.Field3.Value)
53
}
54
55
func TestDeeplyNested_NoAllocate(t *testing.T) {
56
type Struct struct {
57
Field1 *struct {
58
Field2 *struct {
59
Field3 *struct {
60
Value string
61
}
62
}
63
}
64
}
65
66
var s Struct
67
68
rv := reflect.ValueOf(&s).Elem()
69
innerValue := reflectutil.Get(rv, rivertags.Field{Index: []int{0, 0, 0, 0}})
70
assert.False(t, innerValue.CanSet())
71
assert.Equal(t, reflect.String, innerValue.Kind())
72
}
73
74