| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package selector |
| 4 | |
| 5 | import ( |
| 6 | "testing" |
| 7 | |
| 8 | "github.com/prometheus/prometheus/model/labels" |
| 9 | "github.com/stretchr/testify/assert" |
| 10 | "github.com/stretchr/testify/require" |
| 11 | ) |
| 12 | |
| 13 | func TestParse(t *testing.T) { |
| 14 | tests := map[string]struct { |
| 15 | expr string |
| 16 | series labels.Labels |
| 17 | wantMatch bool |
| 18 | wantErr bool |
| 19 | }{ |
| 20 | "metric name only": { |
| 21 | expr: "go_memstats_alloc_bytes !go_memstats_* *", |
| 22 | series: labels.Labels{{Name: labels.MetricName, Value: "go_memstats_alloc_bytes"}}, |
| 23 | wantMatch: true, |
| 24 | }, |
| 25 | "string op with labels": { |
| 26 | expr: `go_memstats_*{label="value"}`, |
| 27 | series: labels.Labels{ |
| 28 | {Name: labels.MetricName, Value: "go_memstats_alloc_bytes"}, |
| 29 | {Name: "label", Value: "value"}, |
| 30 | }, |
| 31 | wantMatch: true, |
| 32 | }, |
| 33 | "neg string op with labels": { |
| 34 | expr: `go_memstats_*{label!="value"}`, |
| 35 | series: labels.Labels{ |
| 36 | {Name: labels.MetricName, Value: "go_memstats_alloc_bytes"}, |
| 37 | {Name: "label", Value: "value"}, |
| 38 | }, |
| 39 | wantMatch: false, |
| 40 | }, |
| 41 | "regexp op with labels": { |
| 42 | expr: `go_memstats_*{label=~"valu.+"}`, |
| 43 | series: labels.Labels{ |
| 44 | {Name: labels.MetricName, Value: "go_memstats_alloc_bytes"}, |
| 45 | {Name: "label", Value: "value"}, |
| 46 | }, |
| 47 | wantMatch: true, |
| 48 | }, |
| 49 | "only labels expression": { |
| 50 | expr: `{__name__=*"go_memstats_*",label1="value1",label2="value2"}`, |
| 51 | series: labels.Labels{ |
| 52 | {Name: labels.MetricName, Value: "go_memstats_alloc_bytes"}, |
| 53 | {Name: "label1", Value: "value1"}, |
| 54 | {Name: "label2", Value: "value2"}, |
| 55 | }, |
| 56 | wantMatch: true, |
| 57 | }, |
| 58 | "invalid syntax": { |
| 59 | expr: `metric{label="value",}`, |
| 60 | wantErr: true, |
| 61 | }, |
| 62 | } |
| 63 | |
| 64 | for name, tc := range tests { |
| 65 | t.Run(name, func(t *testing.T) { |
| 66 | sr, err := Parse(tc.expr) |
| 67 | if tc.wantErr { |
| 68 | require.Error(t, err) |
| 69 | return |
| 70 | } |
| 71 | require.NoError(t, err) |
| 72 | require.NotNil(t, sr) |
| 73 | assert.Equal(t, tc.wantMatch, sr.Matches(tc.series)) |
| 74 | }) |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | func TestParseEmptyExpressionReturnsNil(t *testing.T) { |
| 79 | tests := map[string]struct { |
| 80 | expr string |
| 81 | }{ |
| 82 | "empty": {expr: ""}, |
| 83 | "whitespace": {expr: " \n\t"}, |
| 84 | } |
| 85 | |
| 86 | for name, tc := range tests { |
| 87 | t.Run(name, func(t *testing.T) { |
| 88 | sr, err := Parse(tc.expr) |
| 89 | require.NoError(t, err) |
| 90 | assert.Nil(t, sr) |
| 91 | }) |
| 92 | } |
| 93 | } |