Path: blob/main/pkg/river/internal/reflectutil/walk_test.go
4096 views
package reflectutil_test12import (3"reflect"4"testing"56"github.com/grafana/agent/pkg/river/internal/reflectutil"7"github.com/grafana/agent/pkg/river/internal/rivertags"8"github.com/stretchr/testify/assert"9"github.com/stretchr/testify/require"10)1112func TestDeeplyNested_Access(t *testing.T) {13type Struct struct {14Field1 struct {15Field2 struct {16Field3 struct {17Value string18}19}20}21}2223var s Struct24s.Field1.Field2.Field3.Value = "Hello, world!"2526rv := reflect.ValueOf(&s).Elem()27innerValue := reflectutil.GetOrAlloc(rv, rivertags.Field{Index: []int{0, 0, 0, 0}})28assert.True(t, innerValue.CanSet())29assert.Equal(t, reflect.String, innerValue.Kind())30}3132func TestDeeplyNested_Allocate(t *testing.T) {33type Struct struct {34Field1 *struct {35Field2 *struct {36Field3 *struct {37Value string38}39}40}41}4243var s Struct4445rv := reflect.ValueOf(&s).Elem()46innerValue := reflectutil.GetOrAlloc(rv, rivertags.Field{Index: []int{0, 0, 0, 0}})47require.True(t, innerValue.CanSet())48require.Equal(t, reflect.String, innerValue.Kind())4950innerValue.Set(reflect.ValueOf("Hello, world!"))51require.Equal(t, "Hello, world!", s.Field1.Field2.Field3.Value)52}5354func TestDeeplyNested_NoAllocate(t *testing.T) {55type Struct struct {56Field1 *struct {57Field2 *struct {58Field3 *struct {59Value string60}61}62}63}6465var s Struct6667rv := reflect.ValueOf(&s).Elem()68innerValue := reflectutil.Get(rv, rivertags.Field{Index: []int{0, 0, 0, 0}})69assert.False(t, innerValue.CanSet())70assert.Equal(t, reflect.String, innerValue.Kind())71}727374