| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package selectorcore |
| 4 | |
| 5 | import ( |
| 6 | "testing" |
| 7 | |
| 8 | "github.com/stretchr/testify/assert" |
| 9 | "github.com/stretchr/testify/require" |
| 10 | ) |
| 11 | |
| 12 | func TestExprEmpty(t *testing.T) { |
| 13 | assert.True(t, Expr{}.Empty()) |
| 14 | assert.False(t, Expr{Allow: []string{"foo"}}.Empty()) |
| 15 | assert.False(t, Expr{Deny: []string{"foo"}}.Empty()) |
| 16 | } |
| 17 | |
| 18 | func TestExprParseScenarios(t *testing.T) { |
| 19 | tests := map[string]struct { |
| 20 | expr Expr |
| 21 | metric string |
| 22 | labels mapLabels |
| 23 | match bool |
| 24 | wantErr bool |
| 25 | }{ |
| 26 | "allow only": { |
| 27 | expr: Expr{Allow: []string{"go_*"}}, |
| 28 | metric: "go_gc_duration_seconds", |
| 29 | match: true, |
| 30 | }, |
| 31 | "deny only": { |
| 32 | expr: Expr{Deny: []string{"go_*"}}, |
| 33 | metric: "go_gc_duration_seconds", |
| 34 | match: false, |
| 35 | }, |
| 36 | "allow and deny": { |
| 37 | expr: Expr{Allow: []string{"go_*"}, Deny: []string{"go_gc_*"}}, |
| 38 | metric: "go_gc_duration_seconds", |
| 39 | match: false, |
| 40 | }, |
| 41 | "invalid selector": { |
| 42 | expr: Expr{Allow: []string{"metric{a=\"x\",}"}}, |
| 43 | wantErr: true, |
| 44 | }, |
| 45 | } |
| 46 | |
| 47 | for name, tc := range tests { |
| 48 | t.Run(name, func(t *testing.T) { |
| 49 | s, err := tc.expr.Parse() |
| 50 | if tc.wantErr { |
| 51 | require.Error(t, err) |
| 52 | return |
| 53 | } |
| 54 | require.NoError(t, err) |
| 55 | require.NotNil(t, s) |
| 56 | assert.Equal(t, tc.match, s.Matches(tc.metric, tc.labels)) |
| 57 | }) |
| 58 | } |
| 59 | } |