github.com/cilium/ebpf@v0.15.1-0.20240517100537-8079b37aa138/cmd/bpf2go/output_test.go (about)

     1  package main
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/go-quicktest/qt"
     7  	"github.com/google/go-cmp/cmp"
     8  
     9  	"github.com/cilium/ebpf"
    10  	"github.com/cilium/ebpf/btf"
    11  	"github.com/cilium/ebpf/internal/testutils"
    12  )
    13  
    14  func TestOrderTypes(t *testing.T) {
    15  	a := &btf.Int{}
    16  	b := &btf.Int{}
    17  	c := &btf.Int{}
    18  
    19  	for _, test := range []struct {
    20  		name string
    21  		in   map[btf.Type]string
    22  		out  []btf.Type
    23  	}{
    24  		{
    25  			"order",
    26  			map[btf.Type]string{
    27  				a: "foo",
    28  				b: "bar",
    29  				c: "baz",
    30  			},
    31  			[]btf.Type{b, c, a},
    32  		},
    33  	} {
    34  		t.Run(test.name, func(t *testing.T) {
    35  			result, err := sortTypes(test.in)
    36  			qt.Assert(t, qt.IsNil(err))
    37  			qt.Assert(t, qt.Equals(len(result), len(test.out)))
    38  			for i, o := range test.out {
    39  				if result[i] != o {
    40  					t.Fatalf("Index %d: expected %p got %p", i, o, result[i])
    41  				}
    42  			}
    43  		})
    44  	}
    45  
    46  	for _, test := range []struct {
    47  		name string
    48  		in   map[btf.Type]string
    49  	}{
    50  		{
    51  			"duplicate names",
    52  			map[btf.Type]string{
    53  				a: "foo",
    54  				b: "foo",
    55  			},
    56  		},
    57  	} {
    58  		t.Run(test.name, func(t *testing.T) {
    59  			result, err := sortTypes(test.in)
    60  			qt.Assert(t, qt.IsNotNil(err))
    61  			qt.Assert(t, qt.IsNil(result))
    62  		})
    63  	}
    64  }
    65  
    66  var typesEqualComparer = cmp.Comparer(func(a, b btf.Type) bool {
    67  	return a == b
    68  })
    69  
    70  func TestCollectFromSpec(t *testing.T) {
    71  	spec, err := ebpf.LoadCollectionSpec(testutils.NativeFile(t, "testdata/minimal-%s.elf"))
    72  	if err != nil {
    73  		t.Fatal(err)
    74  	}
    75  
    76  	map1 := spec.Maps["map1"]
    77  
    78  	maps, programs, types, err := collectFromSpec(spec, nil, false)
    79  	if err != nil {
    80  		t.Fatal(err)
    81  	}
    82  	qt.Assert(t, qt.ContentEquals(maps, []string{"map1"}))
    83  	qt.Assert(t, qt.ContentEquals(programs, []string{"filter"}))
    84  	qt.Assert(t, qt.CmpEquals(types, []btf.Type{map1.Key, map1.Value}, typesEqualComparer))
    85  
    86  	_, _, types, err = collectFromSpec(spec, nil, true)
    87  	if err != nil {
    88  		t.Fatal(err)
    89  	}
    90  	qt.Assert(t, qt.CmpEquals[[]btf.Type](types, nil, typesEqualComparer))
    91  
    92  	_, _, types, err = collectFromSpec(spec, []string{"barfoo"}, true)
    93  	if err != nil {
    94  		t.Fatal(err)
    95  	}
    96  	qt.Assert(t, qt.CmpEquals(types, []btf.Type{map1.Value}, typesEqualComparer))
    97  }