Skip to content

Commit

Permalink
Add tests for pkg/util/test.AssertGatherAndCompare
Browse files Browse the repository at this point in the history
Signed-off-by: Arve Knudsen <[email protected]>
  • Loading branch information
aknuds1 committed Oct 7, 2024
1 parent cd1294b commit cf10a30
Showing 1 changed file with 32 additions and 5 deletions.
37 changes: 32 additions & 5 deletions pkg/util/test/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (

"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/assert"
)

type ExpectedMetricsContext struct {
Expand Down Expand Up @@ -67,7 +67,20 @@ func (m *ExpectedMetrics) GetNames() []string {
return m.Names
}

// AssertGatherAndCompare asserts that metrics in expectedText are found among g's metrics.
// If, however, any metrics are provided, the following rules apply:
// * Provided metrics that also exist in expectedText are required to be found among g's metrics.
// * Provided metrics that don't exist in expectedText are required to be absent from g's metrics.
func AssertGatherAndCompare(t *testing.T, g prometheus.Gatherer, expectedText string, metrics ...string) {
t.Helper()
assert.NoError(t, gatherAndCompare(g, expectedText, metrics...))
}

func gatherAndCompare(g prometheus.Gatherer, expectedText string, metrics ...string) error {
if len(metrics) == 0 {
return testutil.GatherAndCompare(g, strings.NewReader(expectedText))
}

sc := bufio.NewScanner(strings.NewReader(expectedText))
absent := make([]string, len(metrics))
copy(absent, metrics)
Expand All @@ -85,17 +98,31 @@ func AssertGatherAndCompare(t *testing.T, g prometheus.Gatherer, expectedText st
}
}
}
require.Equal(t, len(metrics), len(required)+len(absent)) // Sanity check.
// Sanity check.
if len(required)+len(absent) != len(metrics) {
panic(fmt.Errorf("length of required+absent doesn't match up with metrics"))
}

if len(required) > 0 {
require.NoError(t, testutil.GatherAndCompare(g, strings.NewReader(expectedText), required...), "should be present: metrics=%s", strings.Join(required, ", "))
if err := testutil.GatherAndCompare(g, strings.NewReader(expectedText), required...); err != nil {
return err
}
}

notAbsent := []string{}
for _, metric := range absent {
count, err := testutil.GatherAndCount(g, metric)
require.NoError(t, err)
if err != nil {
return fmt.Errorf("GatherAndCount(g, %s): %w", metric, err)
}

if count > 0 {
notAbsent = append(notAbsent, metric)
}
}
require.Empty(t, notAbsent, "should be absent: metrics=%s", strings.Join(notAbsent, ", "))
if len(notAbsent) > 0 {
return fmt.Errorf("should be absent: metrics=%s", strings.Join(notAbsent, ", "))
}

return nil
}

0 comments on commit cf10a30

Please sign in to comment.