Skip to content

Instantly share code, notes, and snippets.

@pboothe
Last active February 14, 2025 13:49
Show Gist options
  • Save pboothe/349f0d165139447826f5e0cedbfdebfc to your computer and use it in GitHub Desktop.
Save pboothe/349f0d165139447826f5e0cedbfdebfc to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"context"
"io"
"net/http"
"testing"
"github.com/prometheus/client_golang/prometheus/testutil/promlint"
"github.com/stretchr/testify/require"
)
func TestMetrics(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Set up a metrics server running on `addr`.
//
// This function should be the same one main() uses. For my unit tests, I do a little extra
// work here and then invoke main() directly, meaning this test is also a smoke test of main().
// Putting that extra machinery here would be a distraction, so let's pretend this f'n exists.
addr, err := startMetricsServer(ctx, ":0") // `:0` means "use any available port"
require.NoError(t, err)
// Connect to the metrics server and get the metrics.
req, err := http.Get("http://"+addr+"/metrics")
require.NoError(t, err)
defer req.Body.Close()
metricBytes, err := io.ReadAll(req.Body)
require.NoError(t, err)
// Create a new linter and lint the metrics.
metricsLinter := promlint.New(bytes.NewBuffer(metricBytes))
problems, err := metricsLinter.Lint()
require.NoError(t, err)
// If there are any problems, print them out and fail the test.
for _, problem := range problems {
t.Error("Prometheus metric problem:", problem)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment