github.com/cilium/ebpf@v0.15.1-0.20240517100537-8079b37aa138/internal/feature_test.go (about)

     1  package internal
     2  
     3  import (
     4  	"errors"
     5  	"strings"
     6  	"testing"
     7  
     8  	"github.com/cilium/ebpf/internal/testutils/fdtrace"
     9  )
    10  
    11  func TestMain(m *testing.M) {
    12  	fdtrace.TestMain(m)
    13  }
    14  
    15  func TestFeatureTest(t *testing.T) {
    16  	var called bool
    17  
    18  	fn := NewFeatureTest("foo", "1.0", func() error {
    19  		called = true
    20  		return nil
    21  	})
    22  
    23  	if called {
    24  		t.Error("Function was called too early")
    25  	}
    26  
    27  	err := fn()
    28  	if !called {
    29  		t.Error("Function wasn't called")
    30  	}
    31  
    32  	if err != nil {
    33  		t.Error("Unexpected negative result:", err)
    34  	}
    35  
    36  	fn = NewFeatureTest("bar", "2.1.1", func() error {
    37  		return ErrNotSupported
    38  	})
    39  
    40  	err = fn()
    41  	if err == nil {
    42  		t.Fatal("Unexpected positive result")
    43  	}
    44  
    45  	fte, ok := err.(*UnsupportedFeatureError)
    46  	if !ok {
    47  		t.Fatal("Result is not a *UnsupportedFeatureError")
    48  	}
    49  
    50  	if !strings.Contains(fte.Error(), "2.1.1") {
    51  		t.Error("UnsupportedFeatureError.Error doesn't contain version")
    52  	}
    53  
    54  	if !errors.Is(err, ErrNotSupported) {
    55  		t.Error("UnsupportedFeatureError is not ErrNotSupported")
    56  	}
    57  
    58  	err2 := fn()
    59  	if err != err2 {
    60  		t.Error("Didn't cache an error wrapping ErrNotSupported")
    61  	}
    62  
    63  	fn = NewFeatureTest("bar", "2.1.1", func() error {
    64  		return errors.New("foo")
    65  	})
    66  
    67  	err1, err2 := fn(), fn()
    68  	if err1 == err2 {
    69  		t.Error("Cached result of unsuccessful execution")
    70  	}
    71  }