package httpapi import ( "strings" "testing" ) // TestFilter guards the sys_query grammar list pages depend on: conditions // joined by ^ all apply, = and != compare the whole value, LIKE matches part of // it, case is ignored, and a bad condition or an unknown field is refused with // the fields the list offers rather than silently returning nothing. func TestFilter(t *testing.T) { type row struct{ name, state string } rows := []row{{"reversibility", "running"}, {"precedent", "failed"}, {"freeze", "disabled"}} fields := Fields[row]{ "name": func(r row) string { return r.name }, "state": func(r row) string { return r.state }, } tests := []struct { name string query string want []string wantErr string }{ {name: "no filter keeps every row", query: "", want: []string{"reversibility", "precedent", "freeze"}}, {name: "equals keeps the matching row", query: "state=failed", want: []string{"precedent"}}, {name: "equals ignores case", query: "state=FAILED", want: []string{"precedent"}}, {name: "not equals drops the matching row", query: "state!=running", want: []string{"precedent", "freeze"}}, {name: "LIKE matches part of the value", query: "nameLIKEeced", want: []string{"precedent"}}, {name: "LIKE ignores case", query: "nameLIKEECE", want: []string{"precedent"}}, {name: "conditions joined by ^ all apply", query: "nameLIKEe^state=disabled", want: []string{"freeze"}}, {name: "spaces around a condition are ignored", query: " state = disabled ", want: []string{"freeze"}}, {name: "a value may contain an equals sign", query: "name=precedent=x", want: nil}, {name: "unknown field is refused with the fields on offer", query: "stat=running", wantErr: `"stat" is not a field here; filter on name, state`}, {name: "a field name outside ASCII keeps its offset", query: "ıxLIKEa", wantErr: `"ıx" is not a field here`}, {name: "no operator is refused", query: "running", wantErr: `"running" has no operator`}, {name: "an empty condition is refused", query: "state=running^", wantErr: "an empty condition"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := Filter(tt.query, fields, rows) if tt.wantErr != "" { if err == nil || !strings.Contains(err.Error(), tt.wantErr) { t.Fatalf("Filter(%q) error = %v, want %q", tt.query, err, tt.wantErr) } return } if err != nil { t.Fatalf("Filter(%q) error = %v", tt.query, err) } names := make([]string, 0, len(got)) for _, r := range got { names = append(names, r.name) } if strings.Join(names, ",") != strings.Join(tt.want, ",") { t.Fatalf("Filter(%q) = %v, want %v", tt.query, names, tt.want) } }) } }