| 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 TestParseCompiledScenarios(t *testing.T) { |
| 13 | tests := map[string]struct { |
| 14 | expr string |
| 15 | wantErr bool |
| 16 | wantMetricNames []string |
| 17 | wantKeys []string |
| 18 | metric string |
| 19 | labels mapLabels |
| 20 | match bool |
| 21 | }{ |
| 22 | "extracts metric and keys": { |
| 23 | expr: `http_requests_total{job="api",instance="a"}`, |
| 24 | wantMetricNames: []string{"http_requests_total"}, |
| 25 | wantKeys: []string{"instance", "job"}, |
| 26 | metric: "http_requests_total", |
| 27 | labels: mapLabels{"job": "api", "instance": "a"}, |
| 28 | match: true, |
| 29 | }, |
| 30 | "wildcard metric no exact candidates": { |
| 31 | expr: `http_*{job="api"}`, |
| 32 | wantMetricNames: nil, |
| 33 | wantKeys: []string{"job"}, |
| 34 | metric: "http_requests_total", |
| 35 | labels: mapLabels{"job": "api"}, |
| 36 | match: true, |
| 37 | }, |
| 38 | "invalid": { |
| 39 | expr: `metric{job="api",}`, |
| 40 | wantErr: true, |
| 41 | }, |
| 42 | } |
| 43 | |
| 44 | for name, tc := range tests { |
| 45 | t.Run(name, func(t *testing.T) { |
| 46 | compiled, err := ParseCompiled(tc.expr) |
| 47 | if tc.wantErr { |
| 48 | require.Error(t, err) |
| 49 | return |
| 50 | } |
| 51 | require.NoError(t, err) |
| 52 | require.NotNil(t, compiled) |
| 53 | |
| 54 | meta := compiled.Meta() |
| 55 | assert.Equal(t, tc.wantMetricNames, meta.MetricNames) |
| 56 | assert.Equal(t, tc.wantKeys, meta.ConstrainedLabelKeys) |
| 57 | assert.Equal(t, tc.match, compiled.Matches(tc.metric, tc.labels)) |
| 58 | }) |
| 59 | } |
| 60 | } |