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

     1  package tracefs
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"testing"
     7  
     8  	"github.com/go-quicktest/qt"
     9  )
    10  
    11  func TestEventID(t *testing.T) {
    12  
    13  	eid, err := EventID("syscalls", "sys_enter_mmap")
    14  	qt.Assert(t, qt.IsNil(err))
    15  	qt.Assert(t, qt.Not(qt.Equals(eid, 0)))
    16  }
    17  
    18  func TestSanitizePath(t *testing.T) {
    19  	_, err := sanitizeTracefsPath("../escaped")
    20  	if !errors.Is(err, ErrInvalidInput) {
    21  		t.Errorf("expected error %s, got: %s", ErrInvalidInput, err)
    22  	}
    23  
    24  	_, err = sanitizeTracefsPath("./not/escaped")
    25  	if err != nil {
    26  		t.Errorf("expected no error, got: %s", err)
    27  	}
    28  }
    29  
    30  func TestValidIdentifier(t *testing.T) {
    31  	tests := []struct {
    32  		name string
    33  		in   string
    34  		fail bool
    35  	}{
    36  		{"empty string", "", true},
    37  		{"leading number", "1test", true},
    38  		{"underscore first", "__x64_syscall", false},
    39  		{"contains number", "bpf_trace_run1", false},
    40  		{"underscore", "_", false},
    41  		{"contains dash", "-EINVAL", true},
    42  		{"contains number", "all0wed", false},
    43  	}
    44  
    45  	for _, tt := range tests {
    46  		t.Run(tt.name, func(t *testing.T) {
    47  			exp := "pass"
    48  			if tt.fail {
    49  				exp = "fail"
    50  			}
    51  
    52  			if validIdentifier(tt.in) == tt.fail {
    53  				t.Errorf("expected string '%s' to %s valid ID check", tt.in, exp)
    54  			}
    55  		})
    56  	}
    57  }
    58  
    59  func TestSanitizeIdentifier(t *testing.T) {
    60  	tests := []struct {
    61  		symbol   string
    62  		expected string
    63  	}{
    64  		{"readline", "readline"},
    65  		{"main.Func123", "main_Func123"},
    66  		{"a.....a", "a_a"},
    67  		{"./;'{}[]a", "_a"},
    68  		{"***xx**xx###", "_xx_xx_"},
    69  		{`@P#r$i%v^3*+t)i&k++--`, "_P_r_i_v_3_t_i_k_"},
    70  	}
    71  
    72  	for i, tt := range tests {
    73  		t.Run(fmt.Sprint(i), func(t *testing.T) {
    74  			sanitized := sanitizeIdentifier(tt.symbol)
    75  			if tt.expected != sanitized {
    76  				t.Errorf("Expected sanitized symbol to be '%s', got '%s'", tt.expected, sanitized)
    77  			}
    78  		})
    79  	}
    80  }
    81  
    82  func TestGetTracefsPath(t *testing.T) {
    83  	_, err := getTracefsPath()
    84  	qt.Assert(t, qt.IsNil(err))
    85  }