From 3b03264fbb9a90b74d0a7e2c3451403594fa7e10 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Fri, 8 Nov 2024 08:45:17 +0100 Subject: [PATCH] chore: use testify instead of t.Fatal Signed-off-by: Matthieu MOREL --- api/client_test.go | 22 +-- api/prometheus/v1/api.go | 1 - api/prometheus/v1/api_bench_test.go | 46 ++--- api/prometheus/v1/api_test.go | 162 +++++------------- examples/simple/main.go | 3 +- go.mod | 4 + .../collectors/dbstats_collector_test.go | 14 +- prometheus/collectors/gen_go_collector_set.go | 4 +- .../collectors/go_collector_latest_test.go | 22 +-- prometheus/counter_test.go | 14 +- prometheus/example_metricvec_test.go | 3 +- prometheus/gauge_test.go | 9 +- prometheus/gen_go_collector_metrics_set.go | 4 +- prometheus/go_collector_latest.go | 4 +- prometheus/go_collector_latest_test.go | 9 +- prometheus/graphite/bridge.go | 3 +- prometheus/graphite/bridge_test.go | 9 +- prometheus/histogram.go | 1 - prometheus/histogram_test.go | 45 ++--- prometheus/metric_test.go | 6 +- prometheus/process_collector_test.go | 23 +-- prometheus/process_collector_windows_test.go | 22 +-- prometheus/promhttp/instrument_client_test.go | 59 ++----- prometheus/promhttp/instrument_server_test.go | 6 +- prometheus/push/push_test.go | 13 +- prometheus/registry.go | 4 +- prometheus/registry_test.go | 41 ++--- prometheus/summary.go | 3 +- prometheus/summary_test.go | 9 +- prometheus/testutil/promlint/promlint_test.go | 38 ++-- prometheus/timer_test.go | 3 +- prometheus/value.go | 4 +- prometheus/vec_test.go | 65 ++----- prometheus/wrap.go | 4 +- prometheus/wrap_test.go | 13 +- tutorials/whatsup/internal/acceptance_test.go | 1 - tutorials/whatsup/main.go | 2 +- 37 files changed, 220 insertions(+), 475 deletions(-) diff --git a/api/client_test.go b/api/client_test.go index 874387868..5be652574 100644 --- a/api/client_test.go +++ b/api/client_test.go @@ -21,13 +21,13 @@ import ( "net/http/httptest" "net/url" "testing" + + "github.com/stretchr/testify/require" ) func TestConfig(t *testing.T) { c := Config{} - if c.roundTripper() != DefaultRoundTripper { - t.Fatalf("expected default roundtripper for nil RoundTripper field") - } + require.Equalf(t, c.roundTripper(), DefaultRoundTripper, "expected default roundtripper for nil RoundTripper field") } func TestClientURL(t *testing.T) { @@ -99,9 +99,7 @@ func TestClientURL(t *testing.T) { for _, test := range tests { ep, err := url.Parse(test.address) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) hclient := &httpClient{ endpoint: ep, @@ -140,22 +138,16 @@ func BenchmarkClient(b *testing.B) { client, err := NewClient(Config{ Address: testServer.URL, }) - if err != nil { - b.Fatalf("Failed to initialize client: %v", err) - } + require.NoErrorf(b, err, "Failed to initialize client: %v", err) url, err := url.Parse(testServer.URL + "/prometheus/api/v1/query?query=up") - if err != nil { - b.Fatalf("Failed to parse url: %v", err) - } + require.NoErrorf(b, err, "Failed to parse url: %v", err) req := &http.Request{ URL: url, } b.ResetTimer() for i := 0; i < b.N; i++ { _, _, err := client.Do(ctx, req) - if err != nil { - b.Fatalf("Query failed: %v", err) - } + require.NoErrorf(b, err, "Query failed: %v", err) } b.StopTimer() }) diff --git a/api/prometheus/v1/api.go b/api/prometheus/v1/api.go index cddf027fd..8fd795a97 100644 --- a/api/prometheus/v1/api.go +++ b/api/prometheus/v1/api.go @@ -28,7 +28,6 @@ import ( "unsafe" json "github.com/json-iterator/go" - "github.com/prometheus/common/model" "github.com/prometheus/client_golang/api" diff --git a/api/prometheus/v1/api_bench_test.go b/api/prometheus/v1/api_bench_test.go index f1f8000ef..e216dee22 100644 --- a/api/prometheus/v1/api_bench_test.go +++ b/api/prometheus/v1/api_bench_test.go @@ -19,8 +19,8 @@ import ( "time" jsoniter "github.com/json-iterator/go" - "github.com/prometheus/common/model" + "github.com/stretchr/testify/require" ) func generateData(timeseries, datapoints int) (floatMatrix, histogramMatrix model.Matrix) { @@ -111,45 +111,37 @@ func BenchmarkSamplesJsonSerialization(b *testing.B) { floats, histograms := generateData(timeseriesCount, datapointCount) floatBytes, err := json.Marshal(floats) - if err != nil { - b.Fatalf("Error marshaling: %v", err) - } + require.NoErrorf(b, err, "Error marshaling: %v", err) histogramBytes, err := json.Marshal(histograms) - if err != nil { - b.Fatalf("Error marshaling: %v", err) - } + require.NoErrorf(b, err, "Error marshaling: %v", err) b.Run("marshal", func(b *testing.B) { b.Run("encoding/json/floats", func(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { - if _, err := json.Marshal(floats); err != nil { - b.Fatal(err) - } + _, err := json.Marshal(floats) + require.NoError(b, err) } }) b.Run("jsoniter/floats", func(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { - if _, err := jsoniter.Marshal(floats); err != nil { - b.Fatal(err) - } + _, err := jsoniter.Marshal(floats) + require.NoError(b, err) } }) b.Run("encoding/json/histograms", func(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { - if _, err := json.Marshal(histograms); err != nil { - b.Fatal(err) - } + _, err := json.Marshal(histograms) + require.NoError(b, err) } }) b.Run("jsoniter/histograms", func(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { - if _, err := jsoniter.Marshal(histograms); err != nil { - b.Fatal(err) - } + _, err := jsoniter.Marshal(histograms) + require.NoError(b, err) } }) }) @@ -159,36 +151,28 @@ func BenchmarkSamplesJsonSerialization(b *testing.B) { b.ReportAllocs() var m model.Matrix for i := 0; i < b.N; i++ { - if err := json.Unmarshal(floatBytes, &m); err != nil { - b.Fatal(err) - } + require.NoError(b, json.Unmarshal(floatBytes, &m)) } }) b.Run("jsoniter/floats", func(b *testing.B) { b.ReportAllocs() var m model.Matrix for i := 0; i < b.N; i++ { - if err := jsoniter.Unmarshal(floatBytes, &m); err != nil { - b.Fatal(err) - } + require.NoError(b, jsoniter.Unmarshal(floatBytes, &m)) } }) b.Run("encoding/json/histograms", func(b *testing.B) { b.ReportAllocs() var m model.Matrix for i := 0; i < b.N; i++ { - if err := json.Unmarshal(histogramBytes, &m); err != nil { - b.Fatal(err) - } + require.NoError(b, json.Unmarshal(histogramBytes, &m)) } }) b.Run("jsoniter/histograms", func(b *testing.B) { b.ReportAllocs() var m model.Matrix for i := 0; i < b.N; i++ { - if err := jsoniter.Unmarshal(histogramBytes, &m); err != nil { - b.Fatal(err) - } + require.NoError(b, jsoniter.Unmarshal(histogramBytes, &m)) } }) }) diff --git a/api/prometheus/v1/api_test.go b/api/prometheus/v1/api_test.go index bacf6a096..8222726c9 100644 --- a/api/prometheus/v1/api_test.go +++ b/api/prometheus/v1/api_test.go @@ -28,8 +28,8 @@ import ( "time" json "github.com/json-iterator/go" - "github.com/prometheus/common/model" + "github.com/stretchr/testify/require" ) type apiTest struct { @@ -73,9 +73,7 @@ func (c *apiTestClient) Do(_ context.Context, req *http.Request) (*http.Response } b, err := json.Marshal(test.inRes) - if err != nil { - c.Fatal(err) - } + require.NoError(c, err) resp := &http.Response{} if test.inStatusCode != 0 { @@ -1222,9 +1220,7 @@ func TestAPIs(t *testing.T) { } if test.err != nil { - if err == nil { - t.Fatalf("expected error %q but got none", test.err) - } + require.Errorf(t, err, "expected error %q but got none", test.err) if err.Error() != test.err.Error() { t.Errorf("unexpected error: want %s, got %s", test.err, err) } @@ -1237,9 +1233,7 @@ func TestAPIs(t *testing.T) { } return } - if err != nil { - t.Fatalf("unexpected error: %s", err) - } + require.NoErrorf(t, err, "unexpected error: %s", err) if !reflect.DeepEqual(res, test.res) { t.Errorf("unexpected result: want %v, got %v", test.res, res) @@ -1268,12 +1262,8 @@ func (c *testClient) URL(ep string, args map[string]string) *url.URL { } func (c *testClient) Do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) { - if ctx == nil { - c.Fatalf("context was not passed down") - } - if req != c.req { - c.Fatalf("request was not passed down") - } + require.NotNilf(c, ctx, "context was not passed down") + require.Samef(c, req, c.req, "request was not passed down") test := <-c.ch @@ -1285,9 +1275,7 @@ func (c *testClient) Do(ctx context.Context, req *http.Request) (*http.Response, b = []byte(v) default: b, err = json.Marshal(v) - if err != nil { - c.Fatal(err) - } + require.NoError(c, err) } resp := &http.Response{ @@ -1436,30 +1424,20 @@ func TestAPIClientDo(t *testing.T) { _, body, warnings, err := client.Do(context.Background(), tc.req) if test.expectedWarnings != nil { - if !reflect.DeepEqual(test.expectedWarnings, warnings) { - t.Fatalf("mismatch in warnings expected=%v actual=%v", test.expectedWarnings, warnings) - } + require.Truef(t, reflect.DeepEqual(test.expectedWarnings, warnings), "mismatch in warnings expected=%v actual=%v", test.expectedWarnings, warnings) } else { - if warnings != nil { - t.Fatalf("unexpected warnings: %v", warnings) - } + require.Nilf(t, warnings, "unexpected warnings: %v", warnings) } if test.expectedErr != nil { - if err == nil { - t.Fatal("expected error, but got none") - } + require.Errorf(t, err, "expected error, but got none") - if test.expectedErr.Error() != err.Error() { - t.Fatalf("expected error:%v, but got:%v", test.expectedErr.Error(), err.Error()) - } + require.EqualErrorf(t, err, test.expectedErr.Error(), "expected error:%v, but got:%v", test.expectedErr.Error(), err.Error()) if test.expectedErr.Detail != "" { apiErr := &Error{} if errors.As(err, &apiErr) { - if apiErr.Detail != test.expectedErr.Detail { - t.Fatalf("expected error detail :%v, but got:%v", apiErr.Detail, test.expectedErr.Detail) - } + require.Equalf(t, apiErr.Detail, test.expectedErr.Detail, "expected error detail :%v, but got:%v", apiErr.Detail, test.expectedErr.Detail) } else { t.Fatalf("expected v1.Error instance, but got:%T", err) } @@ -1468,12 +1446,8 @@ func TestAPIClientDo(t *testing.T) { return } - if err != nil { - t.Fatalf("unexpected error:%v", err) - } - if test.expectedBody != string(body) { - t.Fatalf("expected body :%v, but got:%v", test.expectedBody, string(body)) - } + require.NoErrorf(t, err, "unexpected error:%v", err) + require.Equalf(t, test.expectedBody, string(body), "expected body :%v, but got:%v", test.expectedBody, string(body)) }) } } @@ -1548,28 +1522,18 @@ func TestSamplesJSONSerialization(t *testing.T) { for _, test := range tests { t.Run(test.expected, func(t *testing.T) { b, err := json.Marshal(test.point) - if err != nil { - t.Fatal(err) - } - if string(b) != test.expected { - t.Fatalf("Mismatch marshal expected=%s actual=%s", test.expected, string(b)) - } + require.NoError(t, err) + require.Equalf(t, test.expected, string(b), "Mismatch marshal expected=%s actual=%s", test.expected, string(b)) // To test Unmarshal we will Unmarshal then re-Marshal this way we // can do a string compare, otherwise Nan values don't show equivalence // properly. var sp model.SamplePair - if err = json.Unmarshal(b, &sp); err != nil { - t.Fatal(err) - } + require.NoError(t, json.Unmarshal(b, &sp)) b, err = json.Marshal(sp) - if err != nil { - t.Fatal(err) - } - if string(b) != test.expected { - t.Fatalf("Mismatch marshal expected=%s actual=%s", test.expected, string(b)) - } + require.NoError(t, err) + require.Equalf(t, test.expected, string(b), "Mismatch marshal expected=%s actual=%s", test.expected, string(b)) }) } } @@ -1653,28 +1617,18 @@ func TestHistogramJSONSerialization(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { b, err := json.Marshal(test.point) - if err != nil { - t.Fatal(err) - } - if string(b) != test.expected { - t.Fatalf("Mismatch marshal expected=%s actual=%s", test.expected, string(b)) - } + require.NoError(t, err) + require.Equalf(t, test.expected, string(b), "Mismatch marshal expected=%s actual=%s", test.expected, string(b)) // To test Unmarshal we will Unmarshal then re-Marshal. This way we // can do a string compare, otherwise NaN values don't show equivalence // properly. var sp model.SampleHistogramPair - if err = json.Unmarshal(b, &sp); err != nil { - t.Fatal(err) - } + require.NoError(t, json.Unmarshal(b, &sp)) b, err = json.Marshal(sp) - if err != nil { - t.Fatal(err) - } - if string(b) != test.expected { - t.Fatalf("Mismatch marshal expected=%s actual=%s", test.expected, string(b)) - } + require.NoError(t, err) + require.Equalf(t, test.expected, string(b), "Mismatch marshal expected=%s actual=%s", test.expected, string(b)) }) } } @@ -1711,21 +1665,13 @@ func TestSampleStreamJSONSerialization(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { b, err := json.Marshal(test.stream) - if err != nil { - t.Fatal(err) - } - if string(b) != test.expectedJSON { - t.Fatalf("Mismatch marshal expected=%s actual=%s", test.expectedJSON, string(b)) - } + require.NoError(t, err) + require.Equalf(t, test.expectedJSON, string(b), "Mismatch marshal expected=%s actual=%s", test.expectedJSON, string(b)) var stream model.SampleStream - if err = json.Unmarshal(b, &stream); err != nil { - t.Fatal(err) - } + require.NoError(t, json.Unmarshal(b, &stream)) - if !reflect.DeepEqual(test.stream, stream) { - t.Fatalf("Mismatch after unmarshal expected=%#v actual=%#v", test.stream, stream) - } + require.Truef(t, reflect.DeepEqual(test.stream, stream), "Mismatch after unmarshal expected=%#v actual=%#v", test.stream, stream) }) } } @@ -1806,9 +1752,7 @@ func TestDoGetFallback(t *testing.T) { defer server.Close() u, err := url.Parse(server.URL) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) client := &httpTestClient{client: *(server.Client())} api := &apiClientImpl{ client: client, @@ -1816,49 +1760,25 @@ func TestDoGetFallback(t *testing.T) { // Do a post, and ensure that the post succeeds. _, b, _, err := api.DoGetFallback(context.TODO(), u, v) - if err != nil { - t.Fatalf("Error doing local request: %v", err) - } + require.NoErrorf(t, err, "Error doing local request: %v", err) resp := &testResponse{} - if err := json.Unmarshal(b, resp); err != nil { - t.Fatal(err) - } - if resp.Method != http.MethodPost { - t.Fatalf("Mismatch method") - } - if resp.Values != v.Encode() { - t.Fatalf("Mismatch in values") - } + require.NoError(t, json.Unmarshal(b, resp)) + require.Equalf(t, http.MethodPost, resp.Method, "Mismatch method") + require.Equalf(t, resp.Values, v.Encode(), "Mismatch in values") // Do a fallback to a get on 405. u.Path = "/blockPost405" _, b, _, err = api.DoGetFallback(context.TODO(), u, v) - if err != nil { - t.Fatalf("Error doing local request: %v", err) - } - if err := json.Unmarshal(b, resp); err != nil { - t.Fatal(err) - } - if resp.Method != http.MethodGet { - t.Fatalf("Mismatch method") - } - if resp.Values != v.Encode() { - t.Fatalf("Mismatch in values") - } + require.NoErrorf(t, err, "Error doing local request: %v", err) + require.NoError(t, json.Unmarshal(b, resp)) + require.Equalf(t, http.MethodGet, resp.Method, "Mismatch method") + require.Equalf(t, resp.Values, v.Encode(), "Mismatch in values") // Do a fallback to a get on 501. u.Path = "/blockPost501" _, b, _, err = api.DoGetFallback(context.TODO(), u, v) - if err != nil { - t.Fatalf("Error doing local request: %v", err) - } - if err := json.Unmarshal(b, resp); err != nil { - t.Fatal(err) - } - if resp.Method != http.MethodGet { - t.Fatalf("Mismatch method") - } - if resp.Values != v.Encode() { - t.Fatalf("Mismatch in values") - } + require.NoErrorf(t, err, "Error doing local request: %v", err) + require.NoError(t, json.Unmarshal(b, resp)) + require.Equalf(t, http.MethodGet, resp.Method, "Mismatch method") + require.Equalf(t, resp.Values, v.Encode(), "Mismatch in values") } diff --git a/examples/simple/main.go b/examples/simple/main.go index 935f80577..00059924f 100644 --- a/examples/simple/main.go +++ b/examples/simple/main.go @@ -19,9 +19,8 @@ import ( "log" "net/http" - "github.com/prometheus/client_golang/prometheus/collectors" - "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/collectors" "github.com/prometheus/client_golang/prometheus/promhttp" ) diff --git a/go.mod b/go.mod index 1a0348a66..f89356a6e 100644 --- a/go.mod +++ b/go.mod @@ -12,21 +12,25 @@ require ( github.com/prometheus/client_model v0.6.1 github.com/prometheus/common v0.60.1 github.com/prometheus/procfs v0.15.1 + github.com/stretchr/testify v1.9.0 golang.org/x/sys v0.26.0 google.golang.org/protobuf v1.35.1 ) require ( + github.com/davecgh/go-spew v1.1.1 // indirect github.com/jpillora/backoff v1.0.0 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect golang.org/x/net v0.29.0 // indirect golang.org/x/oauth2 v0.23.0 // indirect golang.org/x/text v0.18.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect ) exclude github.com/prometheus/client_golang v1.12.1 diff --git a/prometheus/collectors/dbstats_collector_test.go b/prometheus/collectors/dbstats_collector_test.go index 057e24384..d45d42a41 100644 --- a/prometheus/collectors/dbstats_collector_test.go +++ b/prometheus/collectors/dbstats_collector_test.go @@ -17,6 +17,8 @@ import ( "database/sql" "testing" + "github.com/stretchr/testify/require" + "github.com/prometheus/client_golang/prometheus" ) @@ -24,21 +26,15 @@ func TestDBStatsCollector(t *testing.T) { reg := prometheus.NewPedanticRegistry() { db := new(sql.DB) - if err := reg.Register(NewDBStatsCollector(db, "db_A")); err != nil { - t.Fatal(err) - } + require.NoError(t, reg.Register(NewDBStatsCollector(db, "db_A"))) } { db := new(sql.DB) - if err := reg.Register(NewDBStatsCollector(db, "db_B")); err != nil { - t.Fatal(err) - } + require.NoError(t, reg.Register(NewDBStatsCollector(db, "db_B"))) } mfs, err := reg.Gather() - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) names := []string{ "go_sql_max_open_connections", diff --git a/prometheus/collectors/gen_go_collector_set.go b/prometheus/collectors/gen_go_collector_set.go index 7a5044fa7..434d6bf62 100644 --- a/prometheus/collectors/gen_go_collector_set.go +++ b/prometheus/collectors/gen_go_collector_set.go @@ -29,10 +29,10 @@ import ( "strings" "text/template" + version "github.com/hashicorp/go-version" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/internal" - - version "github.com/hashicorp/go-version" ) type metricGroup struct { diff --git a/prometheus/collectors/go_collector_latest_test.go b/prometheus/collectors/go_collector_latest_test.go index 974db6c13..1ee062d9a 100644 --- a/prometheus/collectors/go_collector_latest_test.go +++ b/prometheus/collectors/go_collector_latest_test.go @@ -25,6 +25,7 @@ import ( "testing" "github.com/google/go-cmp/cmp" + "github.com/stretchr/testify/require" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" @@ -87,9 +88,7 @@ func TestGoCollectorMarshalling(t *testing.T) { }), )) result, err := reg.Gather() - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if _, err := json.Marshal(result); err != nil { t.Errorf("json marshalling should not fail, %v", err) @@ -100,9 +99,7 @@ func TestWithGoCollectorDefault(t *testing.T) { reg := prometheus.NewPedanticRegistry() reg.MustRegister(NewGoCollector()) result, err := reg.Gather() - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) got := []string{} for _, r := range result { @@ -122,9 +119,7 @@ func TestWithGoCollectorMemStatsMetricsDisabled(t *testing.T) { WithGoCollectorMemStatsMetricsDisabled(), )) result, err := reg.Gather() - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) got := []string{} for _, r := range result { @@ -180,10 +175,7 @@ func TestGoCollectorAllowList(t *testing.T) { WithGoCollectorRuntimeMetrics(test.rules...), )) result, err := reg.Gather() - if err != nil { - t.Fatal(err) - } - + require.NoError(t, err) got := []string{} for _, r := range result { got = append(got, r.GetName()) @@ -242,9 +234,7 @@ func TestGoCollectorDenyList(t *testing.T) { WithoutGoCollectorRuntimeMetrics(test.matchers...), )) result, err := reg.Gather() - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) got := []string{} for _, r := range result { diff --git a/prometheus/counter_test.go b/prometheus/counter_test.go index 29d94bf0a..a341e94ed 100644 --- a/prometheus/counter_test.go +++ b/prometheus/counter_test.go @@ -20,6 +20,7 @@ import ( "time" dto "github.com/prometheus/client_model/go" + "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" ) @@ -268,9 +269,7 @@ func TestCounterExemplar(t *testing.T) { }).(*counter) ts := timestamppb.New(now) - if err := ts.CheckValid(); err != nil { - t.Fatal(err) - } + require.NoError(t, ts.CheckValid()) expectedExemplar := &dto.Exemplar{ Label: []*dto.LabelPair{ {Name: proto.String("foo"), Value: proto.String("bar")}, @@ -360,13 +359,10 @@ func expectCTsForMetricVecValues(t testing.TB, vec *MetricVec, typ dto.MetricTyp for val, ct := range ctsPerLabelValue { var metric dto.Metric m, err := vec.GetMetricWithLabelValues(val) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) - if err := m.Write(&metric); err != nil { - t.Fatal(err) - } + err = m.Write(&metric) + require.NoError(t, err) var gotTs time.Time switch typ { diff --git a/prometheus/example_metricvec_test.go b/prometheus/example_metricvec_test.go index 59e43f8f8..30ab00452 100644 --- a/prometheus/example_metricvec_test.go +++ b/prometheus/example_metricvec_test.go @@ -16,9 +16,8 @@ package prometheus_test import ( "fmt" - "google.golang.org/protobuf/proto" - dto "github.com/prometheus/client_model/go" + "google.golang.org/protobuf/proto" "github.com/prometheus/client_golang/prometheus" ) diff --git a/prometheus/gauge_test.go b/prometheus/gauge_test.go index 26759fbbc..e17f76f15 100644 --- a/prometheus/gauge_test.go +++ b/prometheus/gauge_test.go @@ -22,6 +22,7 @@ import ( "time" dto "github.com/prometheus/client_model/go" + "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" ) @@ -91,9 +92,7 @@ func TestGaugeConcurrency(t *testing.T) { return true } - if err := quick.Check(it, nil); err != nil { - t.Fatal(err) - } + require.NoError(t, quick.Check(it, nil)) } func TestGaugeVecConcurrency(t *testing.T) { @@ -156,9 +155,7 @@ func TestGaugeVecConcurrency(t *testing.T) { return true } - if err := quick.Check(it, nil); err != nil { - t.Fatal(err) - } + require.NoError(t, quick.Check(it, nil)) } func TestGaugeFunc(t *testing.T) { diff --git a/prometheus/gen_go_collector_metrics_set.go b/prometheus/gen_go_collector_metrics_set.go index f1db3d8d1..22b3ec9ed 100644 --- a/prometheus/gen_go_collector_metrics_set.go +++ b/prometheus/gen_go_collector_metrics_set.go @@ -28,10 +28,10 @@ import ( "strings" "text/template" + version "github.com/hashicorp/go-version" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/internal" - - version "github.com/hashicorp/go-version" ) func main() { diff --git a/prometheus/go_collector_latest.go b/prometheus/go_collector_latest.go index 6b8684731..363bd7309 100644 --- a/prometheus/go_collector_latest.go +++ b/prometheus/go_collector_latest.go @@ -24,10 +24,10 @@ import ( "strings" "sync" - "github.com/prometheus/client_golang/prometheus/internal" - dto "github.com/prometheus/client_model/go" "google.golang.org/protobuf/proto" + + "github.com/prometheus/client_golang/prometheus/internal" ) const ( diff --git a/prometheus/go_collector_latest_test.go b/prometheus/go_collector_latest_test.go index 2fbe01bae..9e800551a 100644 --- a/prometheus/go_collector_latest_test.go +++ b/prometheus/go_collector_latest_test.go @@ -26,6 +26,7 @@ import ( "testing" dto "github.com/prometheus/client_model/go" + "github.com/stretchr/testify/require" "github.com/prometheus/client_golang/prometheus/internal" ) @@ -162,13 +163,9 @@ func TestBatchHistogram(t *testing.T) { break } } - if mhist == nil { - t.Fatal("failed to find metric to test") - } + require.NotNilf(t, mhist, "failed to find metric to test") hist, ok := mhist.(*batchHistogram) - if !ok { - t.Fatal("found metric is not a runtime/metrics histogram") - } + require.Truef(t, ok, "found metric is not a runtime/metrics histogram") // Make a bunch of allocations then do another collection. // diff --git a/prometheus/graphite/bridge.go b/prometheus/graphite/bridge.go index 84eac0de9..821ef436e 100644 --- a/prometheus/graphite/bridge.go +++ b/prometheus/graphite/bridge.go @@ -25,11 +25,10 @@ import ( "sort" "time" + dto "github.com/prometheus/client_model/go" "github.com/prometheus/common/expfmt" "github.com/prometheus/common/model" - dto "github.com/prometheus/client_model/go" - "github.com/prometheus/client_golang/prometheus" ) diff --git a/prometheus/graphite/bridge_test.go b/prometheus/graphite/bridge_test.go index 8c596d5ac..67d2f6c5f 100644 --- a/prometheus/graphite/bridge_test.go +++ b/prometheus/graphite/bridge_test.go @@ -31,6 +31,7 @@ import ( "time" "github.com/prometheus/common/model" + "github.com/stretchr/testify/require" "github.com/prometheus/client_golang/prometheus" ) @@ -390,12 +391,8 @@ func TestPush(t *testing.T) { case got := <-nmg.readc: for _, want := range wants { matched, err := regexp.MatchString(want, got) - if err != nil { - t.Fatalf("error pushing: %v", err) - } - if !matched { - t.Fatalf("missing metric:\nno match for %s received by server:\n%s", want, got) - } + require.NoErrorf(t, err, "error pushing: %v", err) + require.Truef(t, matched, "missing metric:\nno match for %s received by server:\n%s", want, got) } return case err := <-nmg.errc: diff --git a/prometheus/histogram.go b/prometheus/histogram.go index c0b6ecd7b..08e50fb3a 100644 --- a/prometheus/histogram.go +++ b/prometheus/histogram.go @@ -23,7 +23,6 @@ import ( "time" dto "github.com/prometheus/client_model/go" - "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" ) diff --git a/prometheus/histogram_test.go b/prometheus/histogram_test.go index 9ed5971c6..cb3b084f6 100644 --- a/prometheus/histogram_test.go +++ b/prometheus/histogram_test.go @@ -25,11 +25,12 @@ import ( "testing/quick" "time" - "github.com/prometheus/client_golang/prometheus/internal" - dto "github.com/prometheus/client_model/go" + "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/prometheus/client_golang/prometheus/internal" ) func benchmarkHistogramObserve(w int, b *testing.B) { @@ -392,9 +393,7 @@ func TestHistogramAtomicObserve(t *testing.T) { for i := 0; i < 100; i++ { m := &dto.Metric{} - if err := his.Write(m); err != nil { - t.Fatal("unexpected error writing histogram:", err) - } + require.NoErrorf(t, his.Write(m), "unexpected error writing histogram") h := m.GetHistogram() if h.GetSampleCount() != uint64(h.GetSampleSum()) || h.GetSampleCount() != h.GetBucket()[1].GetCumulativeCount() || @@ -420,9 +419,7 @@ func TestHistogramExemplar(t *testing.T) { }).(*histogram) ts := timestamppb.New(now) - if err := ts.CheckValid(); err != nil { - t.Fatal(err) - } + require.NoError(t, ts.CheckValid()) expectedExemplars := []*dto.Exemplar{ nil, { @@ -994,13 +991,9 @@ func TestNativeHistogram(t *testing.T) { } } m := &dto.Metric{} - if err := his.Write(m); err != nil { - t.Fatal("unexpected error writing metric", err) - } + require.NoErrorf(t, his.Write(m), "unexpected error writing metric") got := m.Histogram - if !proto.Equal(s.want, got) { - t.Errorf("want histogram %q, got %q", s.want, got) - } + require.Truef(t, proto.Equal(s.want, got), "want histogram %q, got %q", s.want, got) }) } } @@ -1081,17 +1074,13 @@ func TestNativeHistogramConcurrency(t *testing.T) { current := 0 for _, delta := range m.Histogram.GetNegativeDelta() { current += int(delta) - if current < 0 { - t.Fatalf("negative bucket population negative: %d", current) - } + require.GreaterOrEqualf(t, current, 0, "negative bucket population negative: %d", current) sumBuckets += current } current = 0 for _, delta := range m.Histogram.GetPositiveDelta() { current += int(delta) - if current < 0 { - t.Fatalf("positive bucket population negative: %d", current) - } + require.GreaterOrEqualf(t, current, 0, "positive bucket population negative: %d", current) sumBuckets += current } if got, want := sumBuckets, int(*m.Histogram.SampleCount); got != want { @@ -1208,9 +1197,7 @@ func TestHistogramCreatedTimestamp(t *testing.T) { }) var metric dto.Metric - if err := histogram.Write(&metric); err != nil { - t.Fatal(err) - } + require.NoError(t, histogram.Write(&metric)) if metric.Histogram.CreatedTimestamp.AsTime().Unix() != now.Unix() { t.Errorf("expected created timestamp %d, got %d", now.Unix(), metric.Histogram.CreatedTimestamp.AsTime().Unix()) @@ -1229,9 +1216,7 @@ func TestHistogramVecCreatedTimestamp(t *testing.T) { histogram := histogramVec.WithLabelValues("value").(Histogram) var metric dto.Metric - if err := histogram.Write(&metric); err != nil { - t.Fatal(err) - } + require.NoError(t, histogram.Write(&metric)) if metric.Histogram.CreatedTimestamp.AsTime().Unix() != now.Unix() { t.Errorf("expected created timestamp %d, got %d", now.Unix(), metric.Histogram.CreatedTimestamp.AsTime().Unix()) @@ -1287,14 +1272,10 @@ func TestNewConstHistogramWithCreatedTimestamp(t *testing.T) { createdTs := time.Unix(1719670764, 123) h, err := NewConstHistogramWithCreatedTimestamp(metricDesc, 100, 200, buckets, createdTs) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) var metric dto.Metric - if err := h.Write(&metric); err != nil { - t.Fatal(err) - } + require.NoError(t, h.Write(&metric)) if metric.Histogram.CreatedTimestamp.AsTime().UnixMicro() != createdTs.UnixMicro() { t.Errorf("Expected created timestamp %v, got %v", createdTs, &metric.Histogram.CreatedTimestamp) diff --git a/prometheus/metric_test.go b/prometheus/metric_test.go index 629aa4f84..4c72253bc 100644 --- a/prometheus/metric_test.go +++ b/prometheus/metric_test.go @@ -18,7 +18,7 @@ import ( "testing" dto "github.com/prometheus/client_model/go" - + "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" ) @@ -62,9 +62,7 @@ func TestWithExemplarsMetric(t *testing.T) { {Value: proto.Float64(25.1)}, }} metric := dto.Metric{} - if err := m.Write(&metric); err != nil { - t.Fatal(err) - } + require.NoError(t, m.Write(&metric)) if want, got := 5, len(metric.GetHistogram().Bucket); want != got { t.Errorf("want %v, got %v", want, got) } diff --git a/prometheus/process_collector_test.go b/prometheus/process_collector_test.go index 9bead32a9..50543bdee 100644 --- a/prometheus/process_collector_test.go +++ b/prometheus/process_collector_test.go @@ -26,10 +26,10 @@ import ( "strings" "testing" + dto "github.com/prometheus/client_model/go" "github.com/prometheus/common/expfmt" "github.com/prometheus/procfs" - - dto "github.com/prometheus/client_model/go" + "github.com/stretchr/testify/require" ) func TestProcessCollector(t *testing.T) { @@ -38,27 +38,20 @@ func TestProcessCollector(t *testing.T) { } registry := NewPedanticRegistry() - if err := registry.Register(NewProcessCollector(ProcessCollectorOpts{})); err != nil { - t.Fatal(err) - } - if err := registry.Register(NewProcessCollector(ProcessCollectorOpts{ + require.NoError(t, registry.Register(NewProcessCollector(ProcessCollectorOpts{}))) + require.NoError(t, registry.Register(NewProcessCollector(ProcessCollectorOpts{ PidFn: func() (int, error) { return os.Getpid(), nil }, Namespace: "foobar", ReportErrors: true, // No errors expected, just to see if none are reported. - })); err != nil { - t.Fatal(err) - } + }))) mfs, err := registry.Gather() - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) var buf bytes.Buffer for _, mf := range mfs { - if _, err := expfmt.MetricFamilyToText(&buf, mf); err != nil { - t.Fatal(err) - } + _, err := expfmt.MetricFamilyToText(&buf, mf) + require.NoError(t, err) } for _, re := range []*regexp.Regexp{ diff --git a/prometheus/process_collector_windows_test.go b/prometheus/process_collector_windows_test.go index 670c0fc53..8d9b85446 100644 --- a/prometheus/process_collector_windows_test.go +++ b/prometheus/process_collector_windows_test.go @@ -20,31 +20,27 @@ import ( "testing" "github.com/prometheus/common/expfmt" + "github.com/stretchr/testify/require" ) func TestWindowsProcessCollector(t *testing.T) { registry := NewRegistry() - if err := registry.Register(NewProcessCollector(ProcessCollectorOpts{})); err != nil { - t.Fatal(err) - } - if err := registry.Register(NewProcessCollector(ProcessCollectorOpts{ + err := registry.Register(NewProcessCollector(ProcessCollectorOpts{})) + require.False(t, err != nil) + err = registry.Register(NewProcessCollector(ProcessCollectorOpts{ PidFn: func() (int, error) { return os.Getpid(), nil }, Namespace: "foobar", ReportErrors: true, // No errors expected, just to see if none are reported. - })); err != nil { - t.Fatal(err) - } + })) + require.False(t, err != nil) mfs, err := registry.Gather() - if err != nil { - t.Fatal(err) - } + require.False(t, err != nil) var buf bytes.Buffer for _, mf := range mfs { - if _, err := expfmt.MetricFamilyToText(&buf, mf); err != nil { - t.Fatal(err) - } + _, err := expfmt.MetricFamilyToText(&buf, mf) + require.False(t, err != nil) } for _, re := range []*regexp.Regexp{ diff --git a/prometheus/promhttp/instrument_client_test.go b/prometheus/promhttp/instrument_client_test.go index ce7c4da54..841138140 100644 --- a/prometheus/promhttp/instrument_client_test.go +++ b/prometheus/promhttp/instrument_client_test.go @@ -24,11 +24,12 @@ import ( "testing" "time" - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/testutil" - dto "github.com/prometheus/client_model/go" + "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/testutil" ) func makeInstrumentedClient(opts ...Option) (*http.Client, *prometheus.Registry) { @@ -124,12 +125,9 @@ func assetMetricAndExemplars( t.Helper() mfs, err := reg.Gather() - if err != nil { - t.Fatal(err) - } - if want, got := expectedNumMetrics, len(mfs); want != got { - t.Fatalf("unexpected number of metric families gathered, want %d, got %d", want, got) - } + require.NoError(t, err) + want, got := expectedNumMetrics, len(mfs) + require.Equalf(t, want, got, "unexpected number of metric families gathered, want %d, got %d", want, got) for _, mf := range mfs { if len(mf.Metric) == 0 { @@ -190,9 +188,7 @@ func TestClientMiddlewareAPI(t *testing.T) { defer backend.Close() resp, err := client.Get(backend.URL) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer resp.Body.Close() assetMetricAndExemplars(t, reg, 3, nil) @@ -208,9 +204,7 @@ func TestClientMiddlewareAPI_WithExemplars(t *testing.T) { defer backend.Close() resp, err := client.Get(backend.URL) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer resp.Body.Close() assetMetricAndExemplars(t, reg, 3, labelsToLabelPair(exemplar)) @@ -224,9 +218,7 @@ func TestClientMiddlewareAPI_WithRequestContext(t *testing.T) { defer backend.Close() req, err := http.NewRequest("GET", backend.URL, nil) - if err != nil { - t.Fatalf("%v", err) - } + require.NoError(t, err) // Set a context with a long timeout. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) @@ -234,18 +226,13 @@ func TestClientMiddlewareAPI_WithRequestContext(t *testing.T) { req = req.WithContext(ctx) resp, err := client.Do(req) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer resp.Body.Close() mfs, err := reg.Gather() - if err != nil { - t.Fatal(err) - } - if want, got := 3, len(mfs); want != got { - t.Fatalf("unexpected number of metric families gathered, want %d, got %d", want, got) - } + require.NoError(t, err) + want, got := 3, len(mfs) + require.Equalf(t, want, got, "unexpected number of metric families gathered, want %d, got %d", want, got) for _, mf := range mfs { if len(mf.Metric) == 0 { t.Errorf("metric family %s must not be empty", mf.GetName()) @@ -259,11 +246,9 @@ func TestClientMiddlewareAPI_WithRequestContext(t *testing.T) { client_api_requests_total{code="200",method="get"} 1 ` - if err := testutil.GatherAndCompare(reg, strings.NewReader(expected), + require.NoError(t, testutil.GatherAndCompare(reg, strings.NewReader(expected), "client_api_requests_total", - ); err != nil { - t.Fatal(err) - } + )) } func TestClientMiddlewareAPIWithRequestContextTimeout(t *testing.T) { @@ -277,9 +262,7 @@ func TestClientMiddlewareAPIWithRequestContextTimeout(t *testing.T) { defer backend.Close() req, err := http.NewRequest("GET", backend.URL, nil) - if err != nil { - t.Fatalf("%v", err) - } + require.NoErrorf(t, err, "%v", err) // Set a context with a short timeout. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) @@ -287,13 +270,9 @@ func TestClientMiddlewareAPIWithRequestContextTimeout(t *testing.T) { req = req.WithContext(ctx) _, err = client.Do(req) - if err == nil { - t.Fatal("did not get timeout error") - } + require.Errorf(t, err, "did not get timeout error") expectedMsg := "context deadline exceeded" - if !strings.Contains(err.Error(), expectedMsg) { - t.Fatalf("unexpected error: %q, expect error: %q", err.Error(), expectedMsg) - } + require.ErrorContainsf(t, err, expectedMsg, "unexpected error: %q, expect error: %q", err.Error(), expectedMsg) } func ExampleInstrumentRoundTripperDuration() { diff --git a/prometheus/promhttp/instrument_server_test.go b/prometheus/promhttp/instrument_server_test.go index 8aef09f70..68b5b7efe 100644 --- a/prometheus/promhttp/instrument_server_test.go +++ b/prometheus/promhttp/instrument_server_test.go @@ -21,6 +21,8 @@ import ( "net/http/httptest" "testing" + "github.com/stretchr/testify/require" + "github.com/prometheus/client_golang/prometheus" ) @@ -451,9 +453,7 @@ func TestInstrumentTimeToFirstWrite(t *testing.T) { d.WriteHeader(http.StatusOK) - if i != http.StatusOK { - t.Fatalf("failed to execute observeWriteHeader") - } + require.Equalf(t, http.StatusOK, i, "failed to execute observeWriteHeader") } // testResponseWriter is an http.ResponseWriter that also implements diff --git a/prometheus/push/push_test.go b/prometheus/push/push_test.go index d30d17550..4219d6b9b 100644 --- a/prometheus/push/push_test.go +++ b/prometheus/push/push_test.go @@ -22,6 +22,7 @@ import ( "testing" "github.com/prometheus/common/expfmt" + "github.com/stretchr/testify/require" "github.com/prometheus/client_golang/prometheus" ) @@ -42,9 +43,7 @@ func TestPush(t *testing.T) { lastHeader = r.Header var err error lastBody, err = io.ReadAll(r.Body) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) lastPath = r.URL.EscapedPath() w.Header().Set("Content-Type", `text/plain; charset=utf-8`) if r.Method == http.MethodDelete { @@ -79,17 +78,13 @@ func TestPush(t *testing.T) { reg.MustRegister(metric2) mfs, err := reg.Gather() - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) buf := &bytes.Buffer{} enc := expfmt.NewEncoder(buf, expfmt.NewFormat(expfmt.TypeProtoDelim)) for _, mf := range mfs { - if err := enc.Encode(mf); err != nil { - t.Fatal(err) - } + require.NoError(t, enc.Encode(mf)) } wantBody := buf.Bytes() diff --git a/prometheus/registry.go b/prometheus/registry.go index c6fd2f58b..e25d7b835 100644 --- a/prometheus/registry.go +++ b/prometheus/registry.go @@ -26,12 +26,12 @@ import ( "sync" "unicode/utf8" - "github.com/prometheus/client_golang/prometheus/internal" - "github.com/cespare/xxhash/v2" dto "github.com/prometheus/client_model/go" "github.com/prometheus/common/expfmt" "google.golang.org/protobuf/proto" + + "github.com/prometheus/client_golang/prometheus/internal" ) const ( diff --git a/prometheus/registry_test.go b/prometheus/registry_test.go index f6bca22b7..c9cd2f188 100644 --- a/prometheus/registry_test.go +++ b/prometheus/registry_test.go @@ -32,13 +32,14 @@ import ( "testing" "time" - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/promhttp" - dto "github.com/prometheus/client_model/go" "github.com/prometheus/common/expfmt" + "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" ) // uncheckedCollector wraps a Collector but its Describe method yields no Desc. @@ -94,9 +95,7 @@ func testHandler(t testing.TB) { } externalBuf := &bytes.Buffer{} enc := expfmt.NewEncoder(externalBuf, expfmt.NewFormat(expfmt.TypeProtoDelim)) - if err := enc.Encode(externalMetricFamily); err != nil { - t.Fatal(err) - } + require.NoError(t, enc.Encode(externalMetricFamily)) externalMetricFamilyAsBytes := externalBuf.Bytes() externalMetricFamilyAsText := []byte(`# HELP externalname externaldocstring # TYPE externalname counter @@ -164,9 +163,7 @@ metric: < } buf := &bytes.Buffer{} enc = expfmt.NewEncoder(buf, expfmt.NewFormat(expfmt.TypeProtoDelim)) - if err := enc.Encode(expectedMetricFamily); err != nil { - t.Fatal(err) - } + require.NoError(t, enc.Encode(expectedMetricFamily)) expectedMetricFamilyAsBytes := buf.Bytes() expectedMetricFamilyAsText := []byte(`# HELP name docstring # TYPE name counter @@ -848,14 +845,10 @@ func TestAlreadyRegistered(t *testing.T) { for _, s := range scenarios { t.Run(s.name, func(t *testing.T) { - var err error reg := prometheus.NewRegistry() - if err = s.registerWith(reg).Register(s.originalCollector); err != nil { - t.Fatal(err) - } - if err = s.reRegisterWith(reg).Register(s.newCollector); err == nil { - t.Fatal("expected error when registering new collector") - } + require.NoError(t, s.registerWith(reg).Register(s.originalCollector)) + err := s.reRegisterWith(reg).Register(s.newCollector) + require.Errorf(t, err, "expected error when registering new collector") are := &prometheus.AlreadyRegisteredError{} if errors.As(err, are) { if are.ExistingCollector != s.originalCollector { @@ -1073,19 +1066,13 @@ test_summary_count{name="foo"} 2 counter.With(prometheus.Labels{"name": "qux"}).Inc() tmpfile, err := os.CreateTemp("", "prom_registry_test") - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer os.Remove(tmpfile.Name()) - if err := prometheus.WriteToTextfile(tmpfile.Name(), registry); err != nil { - t.Fatal(err) - } + require.NoError(t, prometheus.WriteToTextfile(tmpfile.Name(), registry)) fileBytes, err := os.ReadFile(tmpfile.Name()) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) fileContents := string(fileBytes) if fileContents != expectedOut { @@ -1170,9 +1157,7 @@ func TestAlreadyRegisteredCollision(t *testing.T) { // set of sub-collectors, determined by their names and const label values. if err := reg.Register(&collector); err != nil { are := &prometheus.AlreadyRegisteredError{} - if !errors.As(err, are) { - t.Fatal(err) - } + require.ErrorAs(t, err, are) previous := are.ExistingCollector.(*collidingCollector) current := are.NewCollector.(*collidingCollector) diff --git a/prometheus/summary.go b/prometheus/summary.go index ac5203c6f..e90f116ca 100644 --- a/prometheus/summary.go +++ b/prometheus/summary.go @@ -22,9 +22,8 @@ import ( "sync/atomic" "time" - dto "github.com/prometheus/client_model/go" - "github.com/beorn7/perks/quantile" + dto "github.com/prometheus/client_model/go" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" ) diff --git a/prometheus/summary_test.go b/prometheus/summary_test.go index 440237206..3328e7fe4 100644 --- a/prometheus/summary_test.go +++ b/prometheus/summary_test.go @@ -23,6 +23,7 @@ import ( "time" dto "github.com/prometheus/client_model/go" + "github.com/stretchr/testify/require" ) func TestSummaryWithDefaultObjectives(t *testing.T) { @@ -483,14 +484,10 @@ func TestNewConstSummaryWithCreatedTimestamp(t *testing.T) { createdTs := time.Unix(1719670764, 123) s, err := NewConstSummaryWithCreatedTimestamp(metricDesc, 100, 200, quantiles, createdTs) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) var metric dto.Metric - if err := s.Write(&metric); err != nil { - t.Fatal(err) - } + require.NoError(t, s.Write(&metric)) if metric.Summary.CreatedTimestamp.AsTime().UnixMicro() != createdTs.UnixMicro() { t.Errorf("Expected created timestamp %v, got %v", createdTs, &metric.Summary.CreatedTimestamp) diff --git a/prometheus/testutil/promlint/promlint_test.go b/prometheus/testutil/promlint/promlint_test.go index c6a4e27a7..b844189fa 100644 --- a/prometheus/testutil/promlint/promlint_test.go +++ b/prometheus/testutil/promlint/promlint_test.go @@ -21,6 +21,7 @@ import ( "testing" dto "github.com/prometheus/client_model/go" + "github.com/stretchr/testify/require" "github.com/prometheus/client_golang/prometheus/testutil/promlint" ) @@ -425,14 +426,11 @@ x_ounces 10 l := promlint.New(strings.NewReader(tt.in)) problems, err := l.Lint() - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - if want, got := tt.problems, problems; !reflect.DeepEqual(want, got) { - t.Fatalf("unexpected problems:\n- want: %v\n- got: %v", - want, got) - } + require.NoErrorf(t, err, "unexpected error: %v", err) + + want, got := tt.problems, problems + require.Truef(t, reflect.DeepEqual(want, got), "unexpected problems:\n- want: %v\n- got: %v", + want, got) }) } } @@ -777,14 +775,11 @@ func runTests(t *testing.T, tests []test) { l := promlint.New(strings.NewReader(tt.in)) problems, err := l.Lint() - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - if want, got := tt.problems, problems; !reflect.DeepEqual(want, got) { - t.Fatalf("unexpected problems:\n- want: %v\n- got: %v", - want, got) - } + require.NoErrorf(t, err, "unexpected error: %v", err) + + want, got := tt.problems, problems + require.Truef(t, reflect.DeepEqual(want, got), "unexpected problems:\n- want: %v\n- got: %v", + want, got) }) } } @@ -792,14 +787,11 @@ func runTests(t *testing.T, tests []test) { func TestCustomValidations(t *testing.T) { lintAndVerify := func(l *promlint.Linter, cv test) { problems, err := l.Lint() - if err != nil { - t.Fatalf("unexpected error: %v", err) - } + require.NoErrorf(t, err, "unexpected error: %v", err) - if want, got := cv.problems, problems; !reflect.DeepEqual(want, got) { - t.Fatalf("unexpected problems:\n- want: %v\n- got: %v", - want, got) - } + want, got := cv.problems, problems + require.Truef(t, reflect.DeepEqual(want, got), "unexpected problems:\n- want: %v\n- got: %v", + want, got) } prob := []promlint.Problem{ diff --git a/prometheus/timer_test.go b/prometheus/timer_test.go index a27912dbe..101cb0c0e 100644 --- a/prometheus/timer_test.go +++ b/prometheus/timer_test.go @@ -17,9 +17,8 @@ import ( "reflect" "testing" - "google.golang.org/protobuf/proto" - dto "github.com/prometheus/client_model/go" + "google.golang.org/protobuf/proto" ) func TestTimerObserve(t *testing.T) { diff --git a/prometheus/value.go b/prometheus/value.go index cc23011fa..c5169d09b 100644 --- a/prometheus/value.go +++ b/prometheus/value.go @@ -20,11 +20,11 @@ import ( "time" "unicode/utf8" - "github.com/prometheus/client_golang/prometheus/internal" - dto "github.com/prometheus/client_model/go" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/prometheus/client_golang/prometheus/internal" ) // ValueType is an enumeration of metric types that represent a simple value. diff --git a/prometheus/vec_test.go b/prometheus/vec_test.go index fdd3abc36..fba1ab285 100644 --- a/prometheus/vec_test.go +++ b/prometheus/vec_test.go @@ -20,6 +20,7 @@ import ( "testing" dto "github.com/prometheus/client_model/go" + "github.com/stretchr/testify/require" ) func TestDelete(t *testing.T) { @@ -307,9 +308,7 @@ func testMetricVec(t *testing.T, vec *GaugeVec) { copy(pair[:], metric.values) var metricOut dto.Metric - if err := metric.metric.Write(&metricOut); err != nil { - t.Fatal(err) - } + require.NoError(t, metric.metric.Write(&metricOut)) actual := *metricOut.Gauge.Value var actualPair [2]string @@ -320,25 +319,17 @@ func testMetricVec(t *testing.T, vec *GaugeVec) { // Test output pair against metric.values to ensure we've selected // the right one. We check this to ensure the below check means // anything at all. - if actualPair != pair { - t.Fatalf("unexpected pair association in metric map: %v != %v", actualPair, pair) - } + require.Equalf(t, actualPair, pair, "unexpected pair association in metric map: %v != %v", actualPair, pair) - if actual != float64(expected[pair]) { - t.Fatalf("incorrect counter value for %v: %v != %v", pair, actual, expected[pair]) - } + require.False(t, actual != float64(expected[pair]), "incorrect counter value for %v: %v != %v", pair, actual, expected[pair]) } } - if total != len(expected) { - t.Fatalf("unexpected number of metrics: %v != %v", total, len(expected)) - } + require.Lenf(t, expected, total, "unexpected number of metrics: %v != %v", total, len(expected)) vec.Reset() - if len(vec.metricMap.metrics) > 0 { - t.Fatalf("reset failed") - } + require.Emptyf(t, vec.metricMap.metrics, "reset failed") } func TestMetricVecWithConstraints(t *testing.T) { @@ -379,9 +370,7 @@ func testConstrainedMetricVec(t *testing.T, vec *GaugeVec, constrain func(string copy(pair[:], metric.values) var metricOut dto.Metric - if err := metric.metric.Write(&metricOut); err != nil { - t.Fatal(err) - } + require.NoError(t, metric.metric.Write(&metricOut)) actual := *metricOut.Gauge.Value var actualPair [2]string @@ -392,25 +381,17 @@ func testConstrainedMetricVec(t *testing.T, vec *GaugeVec, constrain func(string // Test output pair against metric.values to ensure we've selected // the right one. We check this to ensure the below check means // anything at all. - if actualPair != pair { - t.Fatalf("unexpected pair association in metric map: %v != %v", actualPair, pair) - } + require.Equalf(t, actualPair, pair, "unexpected pair association in metric map: %v != %v", actualPair, pair) - if actual != float64(expected[pair]) { - t.Fatalf("incorrect counter value for %v: %v != %v", pair, actual, expected[pair]) - } + require.False(t, actual != float64(expected[pair]), "incorrect counter value for %v: %v != %v", pair, actual, expected[pair]) } } - if total != len(expected) { - t.Fatalf("unexpected number of metrics: %v != %v", total, len(expected)) - } + require.Lenf(t, expected, total, "unexpected number of metrics: %v != %v", total, len(expected)) vec.Reset() - if len(vec.metricMap.metrics) > 0 { - t.Fatalf("reset failed") - } + require.Emptyf(t, vec.metricMap.metrics, "reset failed") } func TestCounterVecEndToEndWithCollision(t *testing.T) { @@ -425,9 +406,7 @@ func TestCounterVecEndToEndWithCollision(t *testing.T) { vec.WithLabelValues("!0IC=VloaY").Add(2) m := &dto.Metric{} - if err := vec.WithLabelValues("77kepQFQ8Kl").Write(m); err != nil { - t.Fatal(err) - } + require.NoError(t, vec.WithLabelValues("77kepQFQ8Kl").Write(m)) if got, want := m.GetLabel()[0].GetValue(), "77kepQFQ8Kl"; got != want { t.Errorf("got label value %q, want %q", got, want) } @@ -435,9 +414,7 @@ func TestCounterVecEndToEndWithCollision(t *testing.T) { t.Errorf("got value %f, want %f", got, want) } m.Reset() - if err := vec.WithLabelValues("!0IC=VloaY").Write(m); err != nil { - t.Fatal(err) - } + require.NoError(t, vec.WithLabelValues("!0IC=VloaY").Write(m)) if got, want := m.GetLabel()[0].GetValue(), "!0IC=VloaY"; got != want { t.Errorf("got label value %q, want %q", got, want) } @@ -514,18 +491,14 @@ func testCurryVec(t *testing.T, vec *CounterVec) { } m := &dto.Metric{} c1, err := vec.GetMetricWithLabelValues("1", "2", "3") - if err != nil { - t.Fatal("unexpected error getting metric:", err) - } + require.NoErrorf(t, err, "unexpected error getting metric") c1.Write(m) if want, got := 1., m.GetCounter().GetValue(); want != got { t.Errorf("want %f as counter value, got %f", want, got) } m.Reset() c2, err := vec.GetMetricWithLabelValues("11", "22", "33") - if err != nil { - t.Fatal("unexpected error getting metric:", err) - } + require.NoErrorf(t, err, "unexpected error getting metric") c2.Write(m) if want, got := 1., m.GetCounter().GetValue(); want != got { t.Errorf("want %f as counter value, got %f", want, got) @@ -711,9 +684,7 @@ func testConstrainedCurryVec(t *testing.T, vec *CounterVec, constraint func(stri } m := &dto.Metric{} c1, err := vec.GetMetricWithLabelValues("1", "2", "3") - if err != nil { - t.Fatal("unexpected error getting metric:", err) - } + require.NoErrorf(t, err, "unexpected error getting metric") c1.Write(m) if want, got := 1., m.GetCounter().GetValue(); want != got { t.Errorf("want %f as counter value, got %f", want, got) @@ -727,9 +698,7 @@ func testConstrainedCurryVec(t *testing.T, vec *CounterVec, constraint func(stri } m.Reset() c2, err := vec.GetMetricWithLabelValues("11", "22", "33") - if err != nil { - t.Fatal("unexpected error getting metric:", err) - } + require.NoErrorf(t, err, "unexpected error getting metric") c2.Write(m) if want, got := 1., m.GetCounter().GetValue(); want != got { t.Errorf("want %f as counter value, got %f", want, got) diff --git a/prometheus/wrap.go b/prometheus/wrap.go index 25da157f1..efd8ec0b2 100644 --- a/prometheus/wrap.go +++ b/prometheus/wrap.go @@ -17,10 +17,10 @@ import ( "fmt" "sort" - "github.com/prometheus/client_golang/prometheus/internal" - dto "github.com/prometheus/client_model/go" "google.golang.org/protobuf/proto" + + "github.com/prometheus/client_golang/prometheus/internal" ) // WrapRegistererWith returns a Registerer wrapping the provided diff --git a/prometheus/wrap_test.go b/prometheus/wrap_test.go index d2b4e4c6d..007e9e53a 100644 --- a/prometheus/wrap_test.go +++ b/prometheus/wrap_test.go @@ -20,6 +20,7 @@ import ( "time" dto "github.com/prometheus/client_model/go" + "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" ) @@ -277,9 +278,7 @@ func TestWrap(t *testing.T) { t.Run(n, func(t *testing.T) { reg := NewPedanticRegistry() for _, c := range s.preRegister { - if err := reg.Register(c); err != nil { - t.Fatal("error registering with unwrapped registry:", err) - } + require.NoErrorf(t, reg.Register(c), "error registering with unwrapped registry") } preReg := WrapRegistererWithPrefix(s.prefix, reg) lReg := WrapRegistererWith(s.labels, preReg) @@ -306,9 +305,7 @@ func TestWrap(t *testing.T) { if !s.gatherFails && err != nil { t.Fatal("gathering failed:", err) } - if len(wantMF) != len(gotMF) { - t.Fatalf("Expected %d metricFamilies, got %d", len(wantMF), len(gotMF)) - } + require.Equalf(t, len(wantMF), len(gotMF), "Expected %d metricFamilies, got %d", len(wantMF), len(gotMF)) for i := range gotMF { if !proto.Equal(gotMF[i], wantMF[i]) { var want, got []string @@ -335,7 +332,5 @@ func TestNil(t *testing.T) { // A wrapped nil registerer should be treated as a no-op, and not panic. c := NewCounter(CounterOpts{Name: "test"}) err := WrapRegistererWith(Labels{"foo": "bar"}, nil).Register(c) - if err != nil { - t.Fatal("registering failed:", err) - } + require.NoErrorf(t, err, "registering failed") } diff --git a/tutorials/whatsup/internal/acceptance_test.go b/tutorials/whatsup/internal/acceptance_test.go index 38533c495..57848a9b9 100644 --- a/tutorials/whatsup/internal/acceptance_test.go +++ b/tutorials/whatsup/internal/acceptance_test.go @@ -78,5 +78,4 @@ func TestAcceptance(t *testing.T) { if gotErr { fmt.Println("Got this response from ", fmt.Sprintf("http://localhost:%v", WhatsupPort), ":", metrics) } - } diff --git a/tutorials/whatsup/main.go b/tutorials/whatsup/main.go index 5943eefb0..15ebd4e72 100644 --- a/tutorials/whatsup/main.go +++ b/tutorials/whatsup/main.go @@ -73,7 +73,7 @@ func runMain(opts internal.Config) (err error) { m := http.NewServeMux() // Create HTTP handler for Prometheus metrics. // TODO - //m.Handle("/metrics", ... + // m.Handle("/metrics", ... promClient, err := api.NewClient(api.Config{ Client: &http.Client{Transport: instrumentRoundTripper(nil, "prometheus", http.DefaultTransport)},