| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package selector |
| 4 | |
| 5 | import ( |
| 6 | "testing" |
| 7 | |
| 8 | "github.com/stretchr/testify/assert" |
| 9 | "github.com/stretchr/testify/require" |
| 10 | ) |
| 11 | |
| 12 | func TestSelectorLogicalCombinators_TruthTable(t *testing.T) { |
| 13 | type selectorBuilder func(t *testing.T) Selector |
| 14 | |
| 15 | tests := map[string]struct { |
| 16 | build selectorBuilder |
| 17 | metric string |
| 18 | labels mapLabelView |
| 19 | want bool |
| 20 | }{ |
| 21 | "true always matches": { |
| 22 | build: func(_ *testing.T) Selector { return True() }, |
| 23 | want: true, |
| 24 | }, |
| 25 | "not true is false": { |
| 26 | build: func(_ *testing.T) Selector { return Not(True()) }, |
| 27 | want: false, |
| 28 | }, |
| 29 | "and true true false is false": { |
| 30 | build: func(_ *testing.T) Selector { |
| 31 | return And(True(), True(), Not(True())) |
| 32 | }, |
| 33 | want: false, |
| 34 | }, |
| 35 | "or false false true is true": { |
| 36 | build: func(_ *testing.T) Selector { |
| 37 | return Or(Not(True()), Not(True()), True()) |
| 38 | }, |
| 39 | want: true, |
| 40 | }, |
| 41 | "and with metric selector matches only when base selector matches": { |
| 42 | build: func(t *testing.T) Selector { |
| 43 | sel, err := Parse(`http_requests_total{job="api"}`) |
| 44 | require.NoError(t, err) |
| 45 | require.NotNil(t, sel) |
| 46 | return And(True(), sel) |
| 47 | }, |
| 48 | metric: "http_requests_total", |
| 49 | labels: mapLabelView{"job": "api"}, |
| 50 | want: true, |
| 51 | }, |
| 52 | "or with negated selector keeps mismatch path true": { |
| 53 | build: func(t *testing.T) Selector { |
| 54 | sel, err := Parse(`http_requests_total{job="api"}`) |
| 55 | require.NoError(t, err) |
| 56 | require.NotNil(t, sel) |
| 57 | return Or(sel, Not(sel)) |
| 58 | }, |
| 59 | metric: "http_requests_total", |
| 60 | labels: mapLabelView{"job": "db"}, |
| 61 | want: true, |
| 62 | }, |
| 63 | } |
| 64 | |
| 65 | for name, tc := range tests { |
| 66 | t.Run(name, func(t *testing.T) { |
| 67 | sel := tc.build(t) |
| 68 | require.NotNil(t, sel) |
| 69 | assert.Equal(t, tc.want, sel.Matches(tc.metric, tc.labels)) |
| 70 | }) |
| 71 | } |
| 72 | } |