master
go 85 lines 1.68 KB
Raw
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 type mapLabels map[string]string
13
14 func (m mapLabels) Get(key string) (string, bool) {
15 v, ok := m[key]
16 return v, ok
17 }
18
19 func TestParseScenarios(t *testing.T) {
20 tests := map[string]struct {
21 expr string
22 metric string
23 labels mapLabels
24 match bool
25 wantErr bool
26 }{
27 "metric name only": {
28 expr: "go_memstats_alloc_bytes",
29 metric: "go_memstats_alloc_bytes",
30 match: true,
31 },
32 "metric and label exact": {
33 expr: `http_requests_total{job="api"}`,
34 metric: "http_requests_total",
35 labels: mapLabels{"job": "api"},
36 match: true,
37 },
38 "metric and label mismatch": {
39 expr: `http_requests_total{job="api"}`,
40 metric: "http_requests_total",
41 labels: mapLabels{"job": "db"},
42 match: false,
43 },
44 "only labels": {
45 expr: `{job="api"}`,
46 metric: "anything",
47 labels: mapLabels{"job": "api"},
48 match: true,
49 },
50 "invalid syntax": {
51 expr: `metric{job="api",}`,
52 wantErr: true,
53 },
54 }
55
56 for name, tc := range tests {
57 t.Run(name, func(t *testing.T) {
58 s, err := Parse(tc.expr)
59 if tc.wantErr {
60 require.Error(t, err)
61 return
62 }
63 require.NoError(t, err)
64 require.NotNil(t, s)
65 assert.Equal(t, tc.match, s.Matches(tc.metric, tc.labels))
66 })
67 }
68 }
69
70 func TestParseEmptyExpressionReturnsNil(t *testing.T) {
71 tests := map[string]struct {
72 expr string
73 }{
74 "empty": {expr: ""},
75 "whitespace": {expr: " \t\n"},
76 }
77
78 for name, tc := range tests {
79 t.Run(name, func(t *testing.T) {
80 s, err := Parse(tc.expr)
81 require.NoError(t, err)
82 assert.Nil(t, s)
83 })
84 }
85 }