// `promassert` is the easiest way to test prometheus metrics in go unit tests. // It handles the hard parts so you can test metrics using one-line assert statements. // // `promassert` works by scraping the prometheus exposition format, in-memory, from promhttp.Handler(). // Each member of the ParsedMetrics slice represents one line in the exposition format. // Each line itself represents a unique collection label combinations, and their values. // For example, you might see the following lines for the metric "http_requests_total": // // # HELP http_requests_total The total number of HTTP requests. // # TYPE http_requests_total counter // http_requests_total{method="post",code="200"} 42 // http_requests_total{method="post",code="204"} 777 // http_requests_total{method="get",code="404"} 8 // // Parsing this metric would return a slice containing 3 members. // // pm := promassert.Counter("http_requests_total") // this scrapes and parses the metric // // That slice can be used as-is when testing across all the labels and values: // // pm.Exists(t) // true // pm.Equals(t, 42.0 + 777.0 + 8.0) // true // pm.LabelKeysExist(t, "method", "code") // true // // ParsedMetrics can be filtered based on labels: // // labels := map[string]string{"method":"post"} // pm.With(labels).Exists(t) // true // pm.With(labels).Equals(t, 42.0 + 777.0) // true // labels["code"] = "204" // pm.With(labels).Exists(t) // true // pm.With(labels).Equals(t, 777.0) // true // // Sometimes you need to exit immediately when an assertion fails. // Simply check the returned value and return: // // if !pm.Exists(t) { // return // } // // For more advanced testing, you can inspect the ParsedMetrics values directly. // A good strategy when using the `go test --count=N` flag, is to get the value at the beginning of the test. // Then do whatever increases the metric, and assert based on that value. // // value := pm.TryFold() // callSomeHTTPRequests() // // you must reparse the metric after it changes. // promassert.Counter("http_requests_total").GreaterThan(t, value) // // When `promassert.Verbose` is true, the assert library logs assertions. // // Every assert statement can take a nil `testing.T` as an argument. // This feature is used for sad path testing in the `promassert_test` package. // Providing a nil `testing.T` value turns off logging since logging uses `t.Logf(...)` // // For questions or comments, please reach out to Mathew Reny on slack. package promassert