grafana/pkg/services/ngalert/state/template/funcs_test.go
George Robinson ed7d29f2b9
Alerting: Migrate old alerting templates to Go templates (#62911)
* Migrate old alerting templates to use $labels

* Fix imports

* Add test coverage and separate rewriting to Go templates

* Fix lint

* Check for additional closing braces

* Add logging of invalid message templates

* Fix tests

* Small fixes

* Update comments

* Panic on empty token

* Use logtest.Fake

* Fix lint

* Allow for spaces in variable names by not tokenizing spaces

* Add template function to deduplicate Labels in a Value map

* Fix behavior of mapLookupString

* Reference deduplicated labels in migrated message template

* Fix behavior of deduplicateLabelsFunc

* Don't create variable for parent logger

* Add more tests for deduplicateLabelsFunc

* Remove unused function

* Apply suggestions from code review

Co-authored by: Yuri Tseretyan <yuriy.tseretyan@grafana.com>

* Give label val merge function better name

* Extract template migration and escape literal tokens

* Consolidate + simplify template migration

---------

Co-authored-by: William Wernert <william.wernert@grafana.com>
2023-10-02 11:25:33 -04:00

52 lines
1.5 KiB
Go

package template
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestFilterLabelsFunc(t *testing.T) {
l := Labels{"foo": "bar", "bar": "baz"}
assert.Equal(t, Labels{"foo": "bar"}, filterLabelsFunc(l, "foo"))
}
func TestFilterLabelsReFunc(t *testing.T) {
l := Labels{"foo": "bar", "bar": "baz"}
assert.Equal(t, Labels{"foo": "bar"}, filterLabelsReFunc(l, "f.*"))
}
func TestRemoveLabelsFunc(t *testing.T) {
l := Labels{"foo": "bar", "bar": "baz"}
assert.Equal(t, Labels{"bar": "baz"}, removeLabelsFunc(l, "foo"))
}
func TestRemoveLabelsReFunc(t *testing.T) {
l := Labels{"foo": "bar", "bar": "baz"}
assert.Equal(t, Labels{"bar": "baz"}, removeLabelsReFunc(l, "f.*"))
}
func TestDeduplicateLabelsFunc(t *testing.T) {
v := map[string]Value{
"v1": {Labels: Labels{"foo": "bar", "bar": "foo"}, Value: 1},
"v2": {Labels: Labels{"foo": "bar", "bar": "baz", "baz": "bat"}, Value: 2},
}
assert.Equal(t, Labels{"foo": "bar", "bar": "baz, foo", "baz": "bat"}, mergeLabelValuesFunc(v))
}
func TestDeduplicateLabelsFuncAllSameVal(t *testing.T) {
v := map[string]Value{
"v1": {Labels: Labels{"foo": "bar", "bar": "baz"}, Value: 1},
"v2": {Labels: Labels{"foo": "bar", "bar": "baz"}, Value: 2},
}
assert.Equal(t, Labels{"foo": "bar", "bar": "baz"}, mergeLabelValuesFunc(v))
}
func TestDeduplicateLabelsFuncNoDuplicates(t *testing.T) {
v := map[string]Value{
"v1": {Labels: Labels{"foo": "bar"}, Value: 1},
"v2": {Labels: Labels{"bar": "baz"}, Value: 2},
}
assert.Equal(t, Labels{"foo": "bar", "bar": "baz"}, mergeLabelValuesFunc(v))
}