github.com/cilium/statedb@v0.3.2/script_test.go (about) 1 package statedb 2 3 import ( 4 "context" 5 "maps" 6 "slices" 7 "strings" 8 "testing" 9 10 "github.com/cilium/hive" 11 "github.com/cilium/hive/cell" 12 "github.com/cilium/hive/hivetest" 13 "github.com/cilium/hive/script" 14 "github.com/cilium/hive/script/scripttest" 15 "github.com/stretchr/testify/assert" 16 "github.com/stretchr/testify/require" 17 ) 18 19 func TestScript(t *testing.T) { 20 log := hivetest.Logger(t) 21 h := hive.New( 22 Cell, // DB 23 cell.Invoke(func(db *DB) { 24 t1 := newTestObjectTable(t, "test1", tagsIndex) 25 require.NoError(t, db.RegisterTable(t1), "RegisterTable") 26 t2 := newTestObjectTable(t, "test2", tagsIndex) 27 require.NoError(t, db.RegisterTable(t2), "RegisterTable") 28 }), 29 ) 30 t.Cleanup(func() { 31 assert.NoError(t, h.Stop(log, context.TODO())) 32 }) 33 cmds, err := h.ScriptCommands(log) 34 require.NoError(t, err, "ScriptCommands") 35 maps.Insert(cmds, maps.All(script.DefaultCmds())) 36 engine := &script.Engine{ 37 Cmds: cmds, 38 } 39 scripttest.Test(t, 40 context.Background(), func() *script.Engine { 41 return engine 42 }, []string{}, "testdata/*.txtar") 43 } 44 45 func TestHeaderLine(t *testing.T) { 46 type retrieval struct { 47 header string 48 idxs []int 49 } 50 testCases := []struct { 51 line string 52 names []string 53 pos []int 54 get []retrieval 55 }{ 56 { 57 "Foo Bar ", 58 []string{"Foo", "Bar"}, 59 []int{0, 6}, 60 []retrieval{ 61 {"Foo", []int{0}}, 62 {"Bar", []int{1}}, 63 {"Bar Foo Bar", []int{1, 0, 1}}, 64 }, 65 }, 66 { 67 "Foo Bar Quux", 68 []string{"Foo", "Bar", "Quux"}, 69 []int{0, 4, 10}, 70 []retrieval{ 71 {"Foo", []int{0}}, 72 {"Bar", []int{1}}, 73 {"Bar Foo", []int{1, 0}}, 74 {"Quux", []int{2}}, 75 {"Quux Foo", []int{2, 0}}, 76 }, 77 }, 78 } 79 80 for _, tc := range testCases { 81 // Parse header line into names and positions 82 names, pos := splitHeaderLine(tc.line) 83 require.Equal(t, tc.names, names) 84 require.Equal(t, tc.pos, pos) 85 86 // Split the header line with the parsed positions. 87 header := splitByPositions(tc.line, pos) 88 require.Equal(t, tc.names, header) 89 90 // Join the headers with the positions. 91 line := joinByPositions(header, pos) 92 require.Equal(t, strings.TrimRight(tc.line, " \t"), line) 93 94 // Test retrievals 95 for _, r := range tc.get { 96 names, pos = splitHeaderLine(r.header) 97 idxs, err := getColumnIndexes(names, header) 98 require.NoError(t, err) 99 require.Equal(t, r.idxs, idxs) 100 101 row := slices.Clone(header) 102 cols := takeColumns(row, idxs) 103 line := joinByPositions(cols, pos) 104 require.Equal(t, line, r.header) 105 } 106 } 107 }