| 1 | package internal |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "runtime" |
| 6 | "strings" |
| 7 | "testing" |
| 8 | |
| 9 | "github.com/go-quicktest/qt" |
| 10 | |
| 11 | "github.com/cilium/ebpf/internal/platform" |
| 12 | "github.com/cilium/ebpf/internal/testutils/testmain" |
| 13 | ) |
| 14 | |
| 15 | func TestMain(m *testing.M) { |
| 16 | testmain.Run(m) |
| 17 | } |
| 18 | |
| 19 | func TestFeatureTest(t *testing.T) { |
| 20 | var called bool |
| 21 | |
| 22 | fn := NewFeatureTest("foo", func() error { |
| 23 | called = true |
| 24 | return nil |
| 25 | }, "1.0") |
| 26 | |
| 27 | if called { |
| 28 | t.Error("Function was called too early") |
| 29 | } |
| 30 | |
| 31 | err := fn() |
| 32 | if errors.Is(err, ErrNotSupportedOnOS) { |
| 33 | qt.Assert(t, qt.IsFalse(called)) |
| 34 | return |
| 35 | } |
| 36 | |
| 37 | qt.Assert(t, qt.IsTrue(called), qt.Commentf("function should be invoked")) |
| 38 | |
| 39 | if err != nil { |
| 40 | t.Error("Unexpected negative result:", err) |
| 41 | } |
| 42 | |
| 43 | fn = NewFeatureTest("bar", func() error { |
| 44 | return ErrNotSupported |
| 45 | }, "2.1.1") |
| 46 | |
| 47 | err = fn() |
| 48 | if err == nil { |
| 49 | t.Fatal("Unexpected positive result") |
| 50 | } |
| 51 | |
| 52 | fte, ok := err.(*UnsupportedFeatureError) |
| 53 | if !ok { |
| 54 | t.Fatal("Result is not a *UnsupportedFeatureError") |
| 55 | } |
| 56 | |
| 57 | if !strings.Contains(fte.Error(), "2.1.1") { |
| 58 | t.Error("UnsupportedFeatureError.Error doesn't contain version") |
| 59 | } |
| 60 | |
| 61 | if !errors.Is(err, ErrNotSupported) { |
| 62 | t.Error("UnsupportedFeatureError is not ErrNotSupported") |
| 63 | } |
| 64 | |
| 65 | err2 := fn() |
| 66 | if err != err2 { |
| 67 | t.Error("Didn't cache an error wrapping ErrNotSupported") |
| 68 | } |
| 69 | |
| 70 | fn = NewFeatureTest("bar", func() error { |
| 71 | return errors.New("foo") |
| 72 | }, "2.1.1") |
| 73 | |
| 74 | err1, err2 := fn(), fn() |
| 75 | if err1 == err2 { |
| 76 | t.Error("Cached result of unsuccessful execution") |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | func TestFeatureTestNotSupportedOnOS(t *testing.T) { |
| 81 | sentinel := errors.New("quux") |
| 82 | fn := func() error { return sentinel } |
| 83 | |
| 84 | qt.Assert(t, qt.IsNotNil(NewFeatureTest("foo", fn)())) |
| 85 | qt.Assert(t, qt.ErrorIs(NewFeatureTest("foo", fn, "froz:1.0.0")(), ErrNotSupportedOnOS)) |
| 86 | qt.Assert(t, qt.ErrorIs(NewFeatureTest("foo", fn, runtime.GOOS+":1.0")(), sentinel)) |
| 87 | if platform.IsLinux { |
| 88 | qt.Assert(t, qt.ErrorIs(NewFeatureTest("foo", fn, "1.0")(), sentinel)) |
| 89 | } |
| 90 | } |