MCPcopy
hub / github.com/prometheus/client_golang / TestInstrumentMetricHandler

Function TestInstrumentMetricHandler

prometheus/promhttp/http_test.go:249–307  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

247}
248
249func TestInstrumentMetricHandler(t *testing.T) {
250 reg := prometheus.NewRegistry()
251 mReg := &mockTransactionGatherer{g: reg}
252 handler := InstrumentMetricHandler(reg, HandlerForTransactional(mReg, HandlerOpts{}))
253 // Do it again to test idempotency.
254 InstrumentMetricHandler(reg, HandlerForTransactional(mReg, HandlerOpts{}))
255 writer := httptest.NewRecorder()
256 request, _ := http.NewRequest(http.MethodGet, "/", nil)
257 request.Header.Add(acceptHeader, acceptTextPlain)
258
259 handler.ServeHTTP(writer, request)
260 if got := mReg.gatherInvoked; got != 1 {
261 t.Fatalf("unexpected number of gather invokes, want 1, got %d", got)
262 }
263 if got := mReg.doneInvoked; got != 1 {
264 t.Fatalf("unexpected number of done invokes, want 1, got %d", got)
265 }
266
267 if got, want := writer.Code, http.StatusOK; got != want {
268 t.Errorf("got HTTP status code %d, want %d", got, want)
269 }
270
271 if got, want := writer.Header().Get(contentEncodingHeader), ""; got != want {
272 t.Errorf("got HTTP content encoding header %s, want %s", got, want)
273 }
274
275 want := "promhttp_metric_handler_requests_in_flight 1\n"
276 if got := writer.Body.String(); !strings.Contains(got, want) {
277 t.Errorf("got body %q, does not contain %q", got, want)
278 }
279 want = "promhttp_metric_handler_requests_total{code=\"200\"} 0\n"
280 if got := writer.Body.String(); !strings.Contains(got, want) {
281 t.Errorf("got body %q, does not contain %q", got, want)
282 }
283
284 for i := 0; i < 100; i++ {
285 writer.Body.Reset()
286 handler.ServeHTTP(writer, request)
287
288 if got, want := mReg.gatherInvoked, i+2; got != want {
289 t.Fatalf("unexpected number of gather invokes, want %d, got %d", want, got)
290 }
291 if got, want := mReg.doneInvoked, i+2; got != want {
292 t.Fatalf("unexpected number of done invokes, want %d, got %d", want, got)
293 }
294 if got, want := writer.Code, http.StatusOK; got != want {
295 t.Errorf("got HTTP status code %d, want %d", got, want)
296 }
297
298 want := "promhttp_metric_handler_requests_in_flight 1\n"
299 if got := writer.Body.String(); !strings.Contains(got, want) {
300 t.Errorf("got body %q, does not contain %q", got, want)
301 }
302 want = fmt.Sprintf("promhttp_metric_handler_requests_total{code=\"200\"} %d\n", i+1)
303 if got := writer.Body.String(); !strings.Contains(got, want) {
304 t.Errorf("got body %q, does not contain %q", got, want)
305 }
306 }

Callers

nothing calls this directly

Calls 9

NewRegistryFunction · 0.92
InstrumentMetricHandlerFunction · 0.85
HandlerForTransactionalFunction · 0.85
ContainsMethod · 0.80
AddMethod · 0.65
ServeHTTPMethod · 0.45
HeaderMethod · 0.45
StringMethod · 0.45
ResetMethod · 0.45

Tested by

no test coverage detected