Debian Codegraph @

btf/traversal_test.go

raw symbols SCIP
1 package btf
2
3 import (
4 "fmt"
5 "testing"
6
7 "github.com/go-quicktest/qt"
8 )
9
10 func TestPostorderTraversal(t *testing.T) {
11 ptr := newCyclicalType(2).(*Pointer)
12 cst := ptr.Target.(*Const)
13 str := cst.Type.(*Struct)
14
15 t.Logf("%3v", ptr)
16 pending := []Type{str, cst, ptr}
17 for typ := range postorder(ptr, nil) {
18 qt.Assert(t, qt.Equals(typ, pending[0]))
19 pending = pending[1:]
20 }
21 qt.Assert(t, qt.HasLen(pending, 0))
22
23 i := &Int{Name: "foo"}
24 // i appears twice at the same nesting depth.
25 arr := &Array{Index: i, Type: i}
26 seen := make(map[Type]bool)
27 for typ := range postorder(arr, nil) {
28 qt.Assert(t, qt.IsFalse(seen[typ]))
29 seen[typ] = true
30 }
31 qt.Assert(t, qt.IsTrue(seen[arr]))
32 qt.Assert(t, qt.IsTrue(seen[i]))
33 }
34
35 func TestPostorderTraversalVmlinux(t *testing.T) {
36 spec := vmlinuxTestdataSpec(t)
37
38 typ, err := spec.AnyTypeByName("gov_update_cpu_data")
39 if err != nil {
40 t.Fatal(err)
41 }
42
43 for _, typ := range []Type{typ} {
44 t.Run(fmt.Sprintf("%s", typ), func(t *testing.T) {
45 seen := make(map[Type]bool)
46 var last Type
47 for typ := range postorder(typ, nil) {
48 if seen[typ] {
49 t.Fatalf("%s visited twice", typ)
50 }
51 seen[typ] = true
52 last = typ
53 }
54 if last != typ {
55 t.Fatalf("Expected %s got %s as last type", typ, last)
56 }
57
58 for child := range children(typ) {
59 qt.Check(t, qt.IsTrue(seen[*child]), qt.Commentf("missing child %s", *child))
60 }
61 })
62 }
63 }
64
65 func TestChildren(t *testing.T) {
66 for _, test := range []struct {
67 typ Type
68 count int
69 }{
70 {&Int{}, 0},
71 {&Const{&Int{}}, 1},
72 {&Array{Index: &Int{}, Type: &Int{}}, 2},
73 } {
74 t.Run(fmt.Sprint(test.typ), func(t *testing.T) {
75 var count int
76 allocs := testing.AllocsPerRun(1, func() {
77 count = 0
78 for range children(test.typ) {
79 count++
80 }
81 })
82 qt.Assert(t, qt.Equals(count, test.count))
83 qt.Assert(t, qt.Equals(allocs, 0))
84 })
85 }
86 }
87
88 func BenchmarkPostorderTraversal(b *testing.B) {
89 spec := vmlinuxTestdataSpec(b)
90
91 var fn *Func
92 err := spec.TypeByName("gov_update_cpu_data", &fn)
93 if err != nil {
94 b.Fatal(err)
95 }
96
97 for _, test := range []struct {
98 name string
99 typ Type
100 }{
101 {"single type", &Int{}},
102 {"cycle(1)", newCyclicalType(1)},
103 {"cycle(10)", newCyclicalType(10)},
104 {"gov_update_cpu_data", fn},
105 } {
106 b.Run(test.name, func(b *testing.B) {
107 b.ReportAllocs()
108 for b.Loop() {
109 for range postorder(test.typ, nil) {
110 }
111 }
112 })
113 }
114 }