Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/grafana-agent
Path: blob/main/pkg/util/structwalk/structwalk_test.go
4094 views
1
package structwalk
2
3
import (
4
"testing"
5
6
"github.com/stretchr/testify/require"
7
)
8
9
type LevelA struct {
10
Field1 bool
11
Field2 string
12
Field3 int
13
Nested LevelB
14
}
15
16
type LevelB struct {
17
Level1 bool
18
Level2 string
19
Field3 int
20
Nested LevelC
21
}
22
23
type LevelC struct {
24
Level1 bool
25
Level2 string
26
Field3 int
27
}
28
29
func TestWalk(t *testing.T) {
30
var (
31
iteration int
32
fv FuncVisitor
33
)
34
fv = func(val interface{}) Visitor {
35
iteration++
36
37
// After visiting all 3 structs, should receive a w.Visit(nil) for each level
38
if iteration >= 4 {
39
require.Nil(t, val)
40
return nil
41
}
42
43
switch iteration {
44
case 1:
45
require.IsType(t, LevelA{}, val)
46
case 2:
47
require.IsType(t, LevelB{}, val)
48
case 3:
49
require.IsType(t, LevelC{}, val)
50
default:
51
require.FailNow(t, "unexpected iteration")
52
}
53
54
return fv
55
}
56
57
var val LevelA
58
Walk(fv, val)
59
}
60
61
type FuncVisitor func(v interface{}) Visitor
62
63
func (fv FuncVisitor) Visit(v interface{}) Visitor { return fv(v) }
64
65