diff --git a/api/client.go b/api/client.go index c91cf0c16..72a01309c 100644 --- a/api/client.go +++ b/api/client.go @@ -109,7 +109,7 @@ func (c *httpClient) URL(ep string, args map[string]string) *url.URL { for arg, val := range args { arg = ":" + arg - p = strings.Replace(p, arg, val, -1) + p = strings.ReplaceAll(p, arg, val) } u := *c.endpoint diff --git a/api/prometheus/v1/api.go b/api/prometheus/v1/api.go index c45e03dde..0ce84d6a1 100644 --- a/api/prometheus/v1/api.go +++ b/api/prometheus/v1/api.go @@ -858,7 +858,7 @@ func (h *httpAPI) Query(ctx context.Context, query string, ts time.Time, opts .. } var qres queryResult - return model.Value(qres.v), warnings, json.Unmarshal(body, &qres) + return qres.v, warnings, json.Unmarshal(body, &qres) } func (h *httpAPI) QueryRange(ctx context.Context, query string, r Range, opts ...Option) (model.Value, Warnings, error) { @@ -887,7 +887,7 @@ func (h *httpAPI) QueryRange(ctx context.Context, query string, r Range, opts .. var qres queryResult - return model.Value(qres.v), warnings, json.Unmarshal(body, &qres) + return qres.v, warnings, json.Unmarshal(body, &qres) } func (h *httpAPI) Series(ctx context.Context, matches []string, startTime time.Time, endTime time.Time) ([]model.LabelSet, Warnings, error) { diff --git a/api/prometheus/v1/api_test.go b/api/prometheus/v1/api_test.go index 82c234bbd..4dc777a73 100644 --- a/api/prometheus/v1/api_test.go +++ b/api/prometheus/v1/api_test.go @@ -40,10 +40,8 @@ type apiTest struct { inRes interface{} reqPath string - reqParam url.Values reqMethod string res interface{} - warnings Warnings err error } @@ -55,7 +53,7 @@ type apiTestClient struct { func (c *apiTestClient) URL(ep string, args map[string]string) *url.URL { path := ep for k, v := range args { - path = strings.Replace(path, ":"+k, v, -1) + path = strings.ReplaceAll(path, ":"+k, v) } u := &url.URL{ Host: "test:9090", @@ -257,11 +255,6 @@ func TestAPIs(t *testing.T) { reqMethod: "POST", reqPath: "/api/v1/query", - reqParam: url.Values{ - "query": []string{"2"}, - "time": []string{testTime.Format(time.RFC3339Nano)}, - "timeout": []string{(5 * time.Second).String()}, - }, res: &model.Scalar{ Value: 2, Timestamp: model.TimeFromUnix(testTime.Unix()), @@ -273,11 +266,7 @@ func TestAPIs(t *testing.T) { reqMethod: "POST", reqPath: "/api/v1/query", - reqParam: url.Values{ - "query": []string{"2"}, - "time": []string{testTime.Format(time.RFC3339Nano)}, - }, - err: fmt.Errorf("some error"), + err: fmt.Errorf("some error"), }, { do: doQuery("2", testTime), @@ -291,11 +280,7 @@ func TestAPIs(t *testing.T) { reqMethod: "POST", reqPath: "/api/v1/query", - reqParam: url.Values{ - "query": []string{"2"}, - "time": []string{testTime.Format(time.RFC3339Nano)}, - }, - err: errors.New("server_error: server error: 500"), + err: errors.New("server_error: server error: 500"), }, { do: doQuery("2", testTime), @@ -309,11 +294,7 @@ func TestAPIs(t *testing.T) { reqMethod: "POST", reqPath: "/api/v1/query", - reqParam: url.Values{ - "query": []string{"2"}, - "time": []string{testTime.Format(time.RFC3339Nano)}, - }, - err: errors.New("client_error: client error: 404"), + err: errors.New("client_error: client error: 404"), }, // Warning only. { @@ -329,15 +310,10 @@ func TestAPIs(t *testing.T) { reqMethod: "POST", reqPath: "/api/v1/query", - reqParam: url.Values{ - "query": []string{"2"}, - "time": []string{testTime.Format(time.RFC3339Nano)}, - }, res: &model.Scalar{ Value: 2, Timestamp: model.TimeFromUnix(testTime.Unix()), }, - warnings: []string{"warning"}, }, // Warning + error. { @@ -353,12 +329,7 @@ func TestAPIs(t *testing.T) { reqMethod: "POST", reqPath: "/api/v1/query", - reqParam: url.Values{ - "query": []string{"2"}, - "time": []string{testTime.Format(time.RFC3339Nano)}, - }, - err: errors.New("client_error: client error: 404"), - warnings: []string{"warning"}, + err: errors.New("client_error: client error: 404"), }, { @@ -371,14 +342,7 @@ func TestAPIs(t *testing.T) { reqMethod: "POST", reqPath: "/api/v1/query_range", - reqParam: url.Values{ - "query": []string{"2"}, - "start": []string{testTime.Add(-time.Minute).Format(time.RFC3339Nano)}, - "end": []string{testTime.Format(time.RFC3339Nano)}, - "step": []string{time.Minute.String()}, - "timeout": []string{(5 * time.Second).String()}, - }, - err: fmt.Errorf("some error"), + err: fmt.Errorf("some error"), }, { @@ -395,7 +359,6 @@ func TestAPIs(t *testing.T) { reqMethod: "GET", reqPath: "/api/v1/labels", res: []string{"val1", "val2"}, - warnings: []string{"a"}, }, { @@ -412,14 +375,12 @@ func TestAPIs(t *testing.T) { reqMethod: "GET", reqPath: "/api/v1/labels", err: fmt.Errorf("some error"), - warnings: []string{"a"}, }, { do: doLabelNames([]string{"up"}), inRes: []string{"val1", "val2"}, reqMethod: "GET", reqPath: "/api/v1/labels", - reqParam: url.Values{"match[]": {"up"}}, res: []string{"val1", "val2"}, }, @@ -437,7 +398,6 @@ func TestAPIs(t *testing.T) { reqMethod: "GET", reqPath: "/api/v1/label/mylabel/values", res: model.LabelValues{"val1", "val2"}, - warnings: []string{"a"}, }, { @@ -454,14 +414,12 @@ func TestAPIs(t *testing.T) { reqMethod: "GET", reqPath: "/api/v1/label/mylabel/values", err: fmt.Errorf("some error"), - warnings: []string{"a"}, }, { do: doLabelValues([]string{"up"}, "mylabel"), inRes: []string{"val1", "val2"}, reqMethod: "GET", reqPath: "/api/v1/label/mylabel/values", - reqParam: url.Values{"match[]": {"up"}}, res: model.LabelValues{"val1", "val2"}, }, @@ -475,11 +433,6 @@ func TestAPIs(t *testing.T) { }, reqMethod: "GET", reqPath: "/api/v1/series", - reqParam: url.Values{ - "match": []string{"up"}, - "start": []string{testTime.Add(-time.Minute).Format(time.RFC3339Nano)}, - "end": []string{testTime.Format(time.RFC3339Nano)}, - }, res: []model.LabelSet{ { "__name__": "up", @@ -500,11 +453,6 @@ func TestAPIs(t *testing.T) { inWarnings: []string{"a"}, reqMethod: "GET", reqPath: "/api/v1/series", - reqParam: url.Values{ - "match": []string{"up"}, - "start": []string{testTime.Add(-time.Minute).Format(time.RFC3339Nano)}, - "end": []string{testTime.Format(time.RFC3339Nano)}, - }, res: []model.LabelSet{ { "__name__": "up", @@ -512,7 +460,6 @@ func TestAPIs(t *testing.T) { "instance": "localhost:9090", }, }, - warnings: []string{"a"}, }, { @@ -520,12 +467,7 @@ func TestAPIs(t *testing.T) { inErr: fmt.Errorf("some error"), reqMethod: "GET", reqPath: "/api/v1/series", - reqParam: url.Values{ - "match": []string{"up"}, - "start": []string{testTime.Add(-time.Minute).Format(time.RFC3339Nano)}, - "end": []string{testTime.Format(time.RFC3339Nano)}, - }, - err: fmt.Errorf("some error"), + err: fmt.Errorf("some error"), }, // Series with error and warning. { @@ -534,13 +476,7 @@ func TestAPIs(t *testing.T) { inWarnings: []string{"a"}, reqMethod: "GET", reqPath: "/api/v1/series", - reqParam: url.Values{ - "match": []string{"up"}, - "start": []string{testTime.Add(-time.Minute).Format(time.RFC3339Nano)}, - "end": []string{testTime.Format(time.RFC3339Nano)}, - }, - err: fmt.Errorf("some error"), - warnings: []string{"a"}, + err: fmt.Errorf("some error"), }, { @@ -550,9 +486,6 @@ func TestAPIs(t *testing.T) { }, reqMethod: "POST", reqPath: "/api/v1/admin/tsdb/snapshot", - reqParam: url.Values{ - "skip_head": []string{"true"}, - }, res: SnapshotResult{ Name: "20171210T211224Z-2be650b6d019eb54", }, @@ -590,11 +523,6 @@ func TestAPIs(t *testing.T) { }, reqMethod: "POST", reqPath: "/api/v1/admin/tsdb/delete_series", - reqParam: url.Values{ - "match": []string{"up"}, - "start": []string{testTime.Add(-time.Minute).Format(time.RFC3339Nano)}, - "end": []string{testTime.Format(time.RFC3339Nano)}, - }, }, { @@ -602,12 +530,7 @@ func TestAPIs(t *testing.T) { inErr: fmt.Errorf("some error"), reqMethod: "POST", reqPath: "/api/v1/admin/tsdb/delete_series", - reqParam: url.Values{ - "match": []string{"up"}, - "start": []string{testTime.Add(-time.Minute).Format(time.RFC3339Nano)}, - "end": []string{testTime.Format(time.RFC3339Nano)}, - }, - err: fmt.Errorf("some error"), + err: fmt.Errorf("some error"), }, { @@ -1066,11 +989,6 @@ func TestAPIs(t *testing.T) { }, reqMethod: "GET", reqPath: "/api/v1/targets/metadata", - reqParam: url.Values{ - "match_target": []string{"{job=\"prometheus\"}"}, - "metric": []string{"go_goroutines"}, - "limit": []string{"1"}, - }, res: []MetricMetadata{ { Target: map[string]string{ @@ -1089,12 +1007,7 @@ func TestAPIs(t *testing.T) { inErr: fmt.Errorf("some error"), reqMethod: "GET", reqPath: "/api/v1/targets/metadata", - reqParam: url.Values{ - "match_target": []string{"{job=\"prometheus\"}"}, - "metric": []string{"go_goroutines"}, - "limit": []string{"1"}, - }, - err: fmt.Errorf("some error"), + err: fmt.Errorf("some error"), }, { @@ -1110,10 +1023,6 @@ func TestAPIs(t *testing.T) { }, reqMethod: "GET", reqPath: "/api/v1/metadata", - reqParam: url.Values{ - "metric": []string{"go_goroutines"}, - "limit": []string{"1"}, - }, res: map[string][]Metadata{ "go_goroutines": []Metadata{ { @@ -1130,11 +1039,7 @@ func TestAPIs(t *testing.T) { inErr: fmt.Errorf("some error"), reqMethod: "GET", reqPath: "/api/v1/metadata", - reqParam: url.Values{ - "metric": []string{""}, - "limit": []string{"1"}, - }, - err: fmt.Errorf("some error"), + err: fmt.Errorf("some error"), }, { @@ -1322,7 +1227,9 @@ func TestAPIs(t *testing.T) { if err.Error() != test.err.Error() { t.Errorf("unexpected error: want %s, got %s", test.err, err) } - if apiErr, ok := err.(*Error); ok { + + apiErr := &Error{} + if ok := errors.As(err, &apiErr); ok { if apiErr.Detail != test.inRes { t.Errorf("%q should be %q", apiErr.Detail, test.inRes) } diff --git a/prometheus/examples_test.go b/prometheus/examples_test.go index a7a8d0c14..a86826281 100644 --- a/prometheus/examples_test.go +++ b/prometheus/examples_test.go @@ -15,6 +15,7 @@ package prometheus_test import ( "bytes" + "errors" "fmt" "math" "net/http" @@ -713,7 +714,8 @@ func ExampleAlreadyRegisteredError() { Help: "The total number of requests served.", }) if err := prometheus.Register(reqCounter); err != nil { - if are, ok := err.(prometheus.AlreadyRegisteredError); ok { + are := &prometheus.AlreadyRegisteredError{} + if errors.As(err, are) { // A counter for that metric has been registered before. // Use the old counter from now on. reqCounter = are.ExistingCollector.(prometheus.Counter) diff --git a/prometheus/internal/difflib.go b/prometheus/internal/difflib.go index 178900619..7baf98a31 100644 --- a/prometheus/internal/difflib.go +++ b/prometheus/internal/difflib.go @@ -483,7 +483,7 @@ func (m *SequenceMatcher) QuickRatio() float64 { if m.fullBCount == nil { m.fullBCount = map[string]int{} for _, s := range m.b { - m.fullBCount[s] = m.fullBCount[s] + 1 + m.fullBCount[s]++ } } @@ -637,7 +637,7 @@ func WriteUnifiedDiff(writer io.Writer, diff UnifiedDiff) error { func GetUnifiedDiffString(diff UnifiedDiff) (string, error) { w := &bytes.Buffer{} err := WriteUnifiedDiff(w, diff) - return string(w.Bytes()), err + return w.String(), err } // Split a string on "\n" while preserving them. The output can be used diff --git a/prometheus/internal/difflib_test.go b/prometheus/internal/difflib_test.go index 1a2bb34d8..cc1a7ebad 100644 --- a/prometheus/internal/difflib_test.go +++ b/prometheus/internal/difflib_test.go @@ -58,7 +58,7 @@ func TestGetOptCodes(t *testing.T) { fmt.Fprintf(w, "%s a[%d:%d], (%s) b[%d:%d] (%s)\n", string(op.Tag), op.I1, op.I2, a[op.I1:op.I2], op.J1, op.J2, b[op.J1:op.J2]) } - result := string(w.Bytes()) + result := w.String() expected := `d a[0:1], (q) b[0:0] () e a[1:3], (ab) b[0:2] (ab) r a[3:4], (x) b[2:3] (y) @@ -93,7 +93,7 @@ func TestGroupedOpCodes(t *testing.T) { op.I1, op.I2, op.J1, op.J2) } } - result := string(w.Bytes()) + result := w.String() expected := `group e, 5, 8, 5, 8 i, 8, 8, 8, 9 @@ -134,7 +134,7 @@ four` Context: 3, } result, _ := GetUnifiedDiffString(diff) - fmt.Println(strings.Replace(result, "\t", " ", -1)) + fmt.Println(strings.ReplaceAll(result, "\t", " ")) // Output: // --- Original 2005-01-26 23:30:50 // +++ Current 2010-04-02 10:20:52 diff --git a/prometheus/internal/go_runtime_metrics.go b/prometheus/internal/go_runtime_metrics.go index fe0a52180..81f8c7796 100644 --- a/prometheus/internal/go_runtime_metrics.go +++ b/prometheus/internal/go_runtime_metrics.go @@ -61,9 +61,9 @@ func RuntimeMetricsToProm(d *metrics.Description) (string, string, string, bool) // name has - replaced with _ and is concatenated with the unit and // other data. name = strings.ReplaceAll(name, "-", "_") - name = name + "_" + unit + name += "_" + unit if d.Cumulative { - name = name + "_total" + name += "_total" } valid := model.IsValidMetricName(model.LabelValue(namespace + "_" + subsystem + "_" + name)) diff --git a/prometheus/labels.go b/prometheus/labels.go index 2744443ac..6eee198fe 100644 --- a/prometheus/labels.go +++ b/prometheus/labels.go @@ -39,7 +39,7 @@ var errInconsistentCardinality = errors.New("inconsistent label cardinality") func makeInconsistentCardinalityError(fqName string, labels, labelValues []string) error { return fmt.Errorf( - "%s: %q has %d variable labels named %q but %d values %q were provided", + "%w: %q has %d variable labels named %q but %d values %q were provided", errInconsistentCardinality, fqName, len(labels), labels, len(labelValues), labelValues, @@ -49,7 +49,7 @@ func makeInconsistentCardinalityError(fqName string, labels, labelValues []strin func validateValuesInLabels(labels Labels, expectedNumberOfValues int) error { if len(labels) != expectedNumberOfValues { return fmt.Errorf( - "%s: expected %d label values but got %d in %#v", + "%w: expected %d label values but got %d in %#v", errInconsistentCardinality, expectedNumberOfValues, len(labels), labels, ) @@ -67,7 +67,7 @@ func validateValuesInLabels(labels Labels, expectedNumberOfValues int) error { func validateLabelValues(vals []string, expectedNumberOfValues int) error { if len(vals) != expectedNumberOfValues { return fmt.Errorf( - "%s: expected %d label values but got %d in %#v", + "%w: expected %d label values but got %d in %#v", errInconsistentCardinality, expectedNumberOfValues, len(vals), vals, ) diff --git a/prometheus/promhttp/delegator.go b/prometheus/promhttp/delegator.go index e7c0d0546..3de60b873 100644 --- a/prometheus/promhttp/delegator.go +++ b/prometheus/promhttp/delegator.go @@ -261,7 +261,7 @@ func init() { http.Flusher }{d, pusherDelegator{d}, hijackerDelegator{d}, flusherDelegator{d}} } - pickDelegator[pusher+hijacker+flusher+closeNotifier] = func(d *responseWriterDelegator) delegator { //23 + pickDelegator[pusher+hijacker+flusher+closeNotifier] = func(d *responseWriterDelegator) delegator { // 23 return struct { *responseWriterDelegator http.Pusher diff --git a/prometheus/promhttp/http.go b/prometheus/promhttp/http.go index a6e4f850c..a4cc9810b 100644 --- a/prometheus/promhttp/http.go +++ b/prometheus/promhttp/http.go @@ -33,6 +33,7 @@ package promhttp import ( "compress/gzip" + "errors" "fmt" "io" "net/http" @@ -110,7 +111,8 @@ func HandlerForTransactional(reg prometheus.TransactionalGatherer, opts HandlerO errCnt.WithLabelValues("gathering") errCnt.WithLabelValues("encoding") if err := opts.Registry.Register(errCnt); err != nil { - if are, ok := err.(prometheus.AlreadyRegisteredError); ok { + are := &prometheus.AlreadyRegisteredError{} + if errors.As(err, are) { errCnt = are.ExistingCollector.(*prometheus.CounterVec) } else { panic(err) @@ -250,7 +252,8 @@ func InstrumentMetricHandler(reg prometheus.Registerer, handler http.Handler) ht cnt.WithLabelValues("500") cnt.WithLabelValues("503") if err := reg.Register(cnt); err != nil { - if are, ok := err.(prometheus.AlreadyRegisteredError); ok { + are := &prometheus.AlreadyRegisteredError{} + if errors.As(err, are) { cnt = are.ExistingCollector.(*prometheus.CounterVec) } else { panic(err) @@ -262,7 +265,8 @@ func InstrumentMetricHandler(reg prometheus.Registerer, handler http.Handler) ht Help: "Current number of scrapes being served.", }) if err := reg.Register(gge); err != nil { - if are, ok := err.(prometheus.AlreadyRegisteredError); ok { + are := &prometheus.AlreadyRegisteredError{} + if errors.As(err, are) { gge = are.ExistingCollector.(prometheus.Gauge) } else { panic(err) diff --git a/prometheus/promhttp/instrument_server.go b/prometheus/promhttp/instrument_server.go index a23f0edc6..8239b2814 100644 --- a/prometheus/promhttp/instrument_server.go +++ b/prometheus/promhttp/instrument_server.go @@ -48,7 +48,7 @@ func InstrumentHandlerInFlight(g prometheus.Gauge, next http.Handler) http.Handl // names are "code" and "method". The function panics otherwise. For the "method" // label a predefined default label value set is used to filter given values. // Values besides predefined values will count as `unknown` method. -//`WithExtraMethods` can be used to add more methods to the set. The Observe +// `WithExtraMethods` can be used to add more methods to the set. The Observe // method of the Observer in the ObserverVec is called with the request duration // in seconds. Partitioning happens by HTTP status code and/or HTTP method if // the respective instance label names are present in the ObserverVec. For diff --git a/prometheus/push/push.go b/prometheus/push/push.go index 3bb1466eb..ed6ad0feb 100644 --- a/prometheus/push/push.go +++ b/prometheus/push/push.go @@ -98,9 +98,7 @@ func New(url, job string) *Pusher { if !strings.Contains(url, "://") { url = "http://" + url } - if strings.HasSuffix(url, "/") { - url = url[:len(url)-1] - } + url = strings.TrimSuffix(url, "/") return &Pusher{ error: err, diff --git a/prometheus/push/push_test.go b/prometheus/push/push_test.go index e55e96672..0d478fb70 100644 --- a/prometheus/push/push_test.go +++ b/prometheus/push/push_test.go @@ -15,6 +15,7 @@ package push import ( "bytes" + "errors" "io/ioutil" "net/http" "net/http/httptest" @@ -201,8 +202,8 @@ func TestPush(t *testing.T) { Push(); err == nil { t.Error("push with empty job succeeded") } else { - if got, want := err, errJobEmpty; got != want { - t.Errorf("got error %q, want %q", got, want) + if want := errJobEmpty; !errors.Is(err, want) { + t.Errorf("got error %q, want %q", err, want) } } diff --git a/prometheus/registry.go b/prometheus/registry.go index 5046f7e2f..c00cb18d7 100644 --- a/prometheus/registry.go +++ b/prometheus/registry.go @@ -289,7 +289,7 @@ func (r *Registry) Register(c Collector) error { // Is the descriptor valid at all? if desc.err != nil { - return fmt.Errorf("descriptor %s is invalid: %s", desc, desc.err) + return fmt.Errorf("descriptor %s is invalid: %w", desc, desc.err) } // Is the descID unique? @@ -603,7 +603,7 @@ func processMetric( } dtoMetric := &dto.Metric{} if err := metric.Write(dtoMetric); err != nil { - return fmt.Errorf("error collecting metric %v: %s", desc, err) + return fmt.Errorf("error collecting metric %v: %w", desc, err) } metricFamily, ok := metricFamiliesByName[desc.fqName] if ok { // Existing name. @@ -727,10 +727,10 @@ func (gs Gatherers) Gather() ([]*dto.MetricFamily, error) { if err != nil { if multiErr, ok := err.(MultiError); ok { for _, err := range multiErr { - errs = append(errs, fmt.Errorf("[from Gatherer #%d] %s", i+1, err)) + errs = append(errs, fmt.Errorf("[from Gatherer #%d] %w", i+1, err)) } } else { - errs = append(errs, fmt.Errorf("[from Gatherer #%d] %s", i+1, err)) + errs = append(errs, fmt.Errorf("[from Gatherer #%d] %w", i+1, err)) } } for _, mf := range mfs { diff --git a/prometheus/registry_test.go b/prometheus/registry_test.go index 7a959da47..9d2aa94e2 100644 --- a/prometheus/registry_test.go +++ b/prometheus/registry_test.go @@ -121,8 +121,8 @@ metric: < > `) - externalMetricFamilyAsProtoCompactText := []byte(`name:"externalname" help:"externaldocstring" type:COUNTER metric: label: counter: > -`) + externalMetricFamilyAsProtoCompactText := []byte(`name:"externalname" help:"externaldocstring" type:COUNTER metric: label: counter: >`) + externalMetricFamilyAsProtoCompactText = append(externalMetricFamilyAsProtoCompactText, []byte(" \n")...) expectedMetricFamily := &dto.MetricFamily{ Name: proto.String("name"), @@ -203,8 +203,8 @@ metric: < > `) - expectedMetricFamilyAsProtoCompactText := []byte(`name:"name" help:"docstring" type:COUNTER metric: label: counter: > metric: label: counter: > -`) + expectedMetricFamilyAsProtoCompactText := []byte(`name:"name" help:"docstring" type:COUNTER metric: label: counter: > metric: label: counter: >`) + expectedMetricFamilyAsProtoCompactText = append(expectedMetricFamilyAsProtoCompactText, []byte(" \n")...) externalMetricFamilyWithSameName := &dto.MetricFamily{ Name: proto.String("name"), @@ -229,8 +229,8 @@ metric: < }, } - expectedMetricFamilyMergedWithExternalAsProtoCompactText := []byte(`name:"name" help:"docstring" type:COUNTER metric: label: counter: > metric: label: counter: > metric: label: counter: > -`) + expectedMetricFamilyMergedWithExternalAsProtoCompactText := []byte(`name:"name" help:"docstring" type:COUNTER metric: label: counter: > metric: label: counter: > metric: label: counter: >`) + expectedMetricFamilyMergedWithExternalAsProtoCompactText = append(expectedMetricFamilyMergedWithExternalAsProtoCompactText, []byte(" \n")...) externalMetricFamilyWithInvalidLabelValue := &dto.MetricFamily{ Name: proto.String("name"), @@ -851,7 +851,8 @@ func TestAlreadyRegistered(t *testing.T) { if err = s.reRegisterWith(reg).Register(s.newCollector); err == nil { t.Fatal("expected error when registering new collector") } - if are, ok := err.(prometheus.AlreadyRegisteredError); ok { + are := &prometheus.AlreadyRegisteredError{} + if errors.As(err, are) { if are.ExistingCollector != s.originalCollector { t.Error("expected original collector but got something else") } @@ -932,7 +933,7 @@ func TestHistogramVecRegisterGatherConcurrency(t *testing.T) { return default: if err := reg.Register(hv); err != nil { - if _, ok := err.(prometheus.AlreadyRegisteredError); !ok { + if !errors.As(err, &prometheus.AlreadyRegisteredError{}) { t.Error("Registering failed:", err) } } @@ -1164,15 +1165,15 @@ func TestAlreadyRegisteredCollision(t *testing.T) { // Register should not fail, since each collector has a unique // set of sub-collectors, determined by their names and const label values. if err := reg.Register(&collector); err != nil { - alreadyRegErr, ok := err.(prometheus.AlreadyRegisteredError) - if !ok { + are := &prometheus.AlreadyRegisteredError{} + if !errors.As(err, are) { t.Fatal(err) } - previous := alreadyRegErr.ExistingCollector.(*collidingCollector) - current := alreadyRegErr.NewCollector.(*collidingCollector) + previous := are.ExistingCollector.(*collidingCollector) + current := are.NewCollector.(*collidingCollector) - t.Errorf("Unexpected registration error: %q\nprevious collector: %s (i=%d)\ncurrent collector %s (i=%d)", alreadyRegErr, previous.name, previous.i, current.name, current.i) + t.Errorf("Unexpected registration error: %q\nprevious collector: %s (i=%d)\ncurrent collector %s (i=%d)", are, previous.name, previous.i, current.name, current.i) } } } diff --git a/prometheus/testutil/lint.go b/prometheus/testutil/lint.go index 7681877a8..8d2f05500 100644 --- a/prometheus/testutil/lint.go +++ b/prometheus/testutil/lint.go @@ -26,7 +26,7 @@ import ( func CollectAndLint(c prometheus.Collector, metricNames ...string) ([]promlint.Problem, error) { reg := prometheus.NewPedanticRegistry() if err := reg.Register(c); err != nil { - return nil, fmt.Errorf("registering collector failed: %s", err) + return nil, fmt.Errorf("registering collector failed: %w", err) } return GatherAndLint(reg, metricNames...) } @@ -37,7 +37,7 @@ func CollectAndLint(c prometheus.Collector, metricNames ...string) ([]promlint.P func GatherAndLint(g prometheus.Gatherer, metricNames ...string) ([]promlint.Problem, error) { got, err := g.Gather() if err != nil { - return nil, fmt.Errorf("gathering metrics failed: %s", err) + return nil, fmt.Errorf("gathering metrics failed: %w", err) } if metricNames != nil { got = filterMetrics(got, metricNames) diff --git a/prometheus/testutil/promlint/promlint.go b/prometheus/testutil/promlint/promlint.go index ec8061706..94fd0c0fc 100644 --- a/prometheus/testutil/promlint/promlint.go +++ b/prometheus/testutil/promlint/promlint.go @@ -15,6 +15,7 @@ package promlint import ( + "errors" "fmt" "io" "regexp" @@ -83,7 +84,7 @@ func (l *Linter) Lint() ([]Problem, error) { mf := &dto.MetricFamily{} for { if err := d.Decode(mf); err != nil { - if err == io.EOF { + if errors.Is(err, io.EOF) { break } diff --git a/prometheus/testutil/testutil.go b/prometheus/testutil/testutil.go index 115979dc1..5d7737a80 100644 --- a/prometheus/testutil/testutil.go +++ b/prometheus/testutil/testutil.go @@ -124,7 +124,7 @@ func ToFloat64(c prometheus.Collector) float64 { func CollectAndCount(c prometheus.Collector, metricNames ...string) int { reg := prometheus.NewPedanticRegistry() if err := reg.Register(c); err != nil { - panic(fmt.Errorf("registering collector failed: %s", err)) + panic(fmt.Errorf("registering collector failed: %w", err)) } result, err := GatherAndCount(reg, metricNames...) if err != nil { @@ -140,7 +140,7 @@ func CollectAndCount(c prometheus.Collector, metricNames ...string) int { func GatherAndCount(g prometheus.Gatherer, metricNames ...string) (int, error) { got, err := g.Gather() if err != nil { - return 0, fmt.Errorf("gathering metrics failed: %s", err) + return 0, fmt.Errorf("gathering metrics failed: %w", err) } if metricNames != nil { got = filterMetrics(got, metricNames) @@ -159,7 +159,7 @@ func GatherAndCount(g prometheus.Gatherer, metricNames ...string) (int, error) { func CollectAndCompare(c prometheus.Collector, expected io.Reader, metricNames ...string) error { reg := prometheus.NewPedanticRegistry() if err := reg.Register(c); err != nil { - return fmt.Errorf("registering collector failed: %s", err) + return fmt.Errorf("registering collector failed: %w", err) } return GatherAndCompare(reg, expected, metricNames...) } @@ -180,7 +180,7 @@ func TransactionalGatherAndCompare(g prometheus.TransactionalGatherer, expected got, done, err := g.Gather() defer done() if err != nil { - return fmt.Errorf("gathering metrics failed: %s", err) + return fmt.Errorf("gathering metrics failed: %w", err) } if metricNames != nil { got = filterMetrics(got, metricNames) @@ -188,7 +188,7 @@ func TransactionalGatherAndCompare(g prometheus.TransactionalGatherer, expected var tp expfmt.TextParser wantRaw, err := tp.TextToMetricFamilies(expected) if err != nil { - return fmt.Errorf("parsing expected metrics failed: %s", err) + return fmt.Errorf("parsing expected metrics failed: %w", err) } want := internal.NormalizeMetricFamilies(wantRaw) @@ -204,13 +204,13 @@ func compare(got, want []*dto.MetricFamily) error { enc := expfmt.NewEncoder(&gotBuf, expfmt.FmtText) for _, mf := range got { if err := enc.Encode(mf); err != nil { - return fmt.Errorf("encoding gathered metrics failed: %s", err) + return fmt.Errorf("encoding gathered metrics failed: %w", err) } } enc = expfmt.NewEncoder(&wantBuf, expfmt.FmtText) for _, mf := range want { if err := enc.Encode(mf); err != nil { - return fmt.Errorf("encoding expected metrics failed: %s", err) + return fmt.Errorf("encoding expected metrics failed: %w", err) } } if diffErr := diff(wantBuf, gotBuf); diffErr != "" { diff --git a/prometheus/vec_test.go b/prometheus/vec_test.go index fdb050fa7..3b557624d 100644 --- a/prometheus/vec_test.go +++ b/prometheus/vec_test.go @@ -49,7 +49,7 @@ func testDelete(t *testing.T, vec *GaugeVec) { t.Errorf("got %v, want %v", got, want) } - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Gauge).Set(42) + vec.With(Labels{"l1": "v1", "l2": "v2"}).Set(42) if got, want := vec.Delete(Labels{"l1": "v1", "l2": "v2"}), true; got != want { t.Errorf("got %v, want %v", got, want) } @@ -57,7 +57,7 @@ func testDelete(t *testing.T, vec *GaugeVec) { t.Errorf("got %v, want %v", got, want) } - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Gauge).Set(42) + vec.With(Labels{"l1": "v1", "l2": "v2"}).Set(42) if got, want := vec.Delete(Labels{"l2": "v2", "l1": "v1"}), true; got != want { t.Errorf("got %v, want %v", got, want) } @@ -65,7 +65,7 @@ func testDelete(t *testing.T, vec *GaugeVec) { t.Errorf("got %v, want %v", got, want) } - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Gauge).Set(42) + vec.With(Labels{"l1": "v1", "l2": "v2"}).Set(42) if got, want := vec.Delete(Labels{"l2": "v1", "l1": "v2"}), false; got != want { t.Errorf("got %v, want %v", got, want) } @@ -103,8 +103,8 @@ func testDeleteLabelValues(t *testing.T, vec *GaugeVec) { t.Errorf("got %v, want %v", got, want) } - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Gauge).Set(42) - vec.With(Labels{"l1": "v1", "l2": "v3"}).(Gauge).Set(42) // Add junk data for collision. + vec.With(Labels{"l1": "v1", "l2": "v2"}).Set(42) + vec.With(Labels{"l1": "v1", "l2": "v3"}).Set(42) // Add junk data for collision. if got, want := vec.DeleteLabelValues("v1", "v2"), true; got != want { t.Errorf("got %v, want %v", got, want) } @@ -115,7 +115,7 @@ func testDeleteLabelValues(t *testing.T, vec *GaugeVec) { t.Errorf("got %v, want %v", got, want) } - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Gauge).Set(42) + vec.With(Labels{"l1": "v1", "l2": "v2"}).Set(42) // Delete out of order. if got, want := vec.DeleteLabelValues("v2", "v1"), false; got != want { t.Errorf("got %v, want %v", got, want) @@ -146,9 +146,9 @@ func TestDeletePartialMatch(t *testing.T) { } baseVec.With(Labels{"l1": "baseValue1", "l2": "baseValue2", "l3": "baseValue3"}).Inc() - baseVec.With(Labels{"l1": "multiDeleteV1", "l2": "diff1BaseValue2", "l3": "v3"}).(Gauge).Set(42) - baseVec.With(Labels{"l1": "multiDeleteV1", "l2": "diff2BaseValue2", "l3": "v3"}).(Gauge).Set(84) - baseVec.With(Labels{"l1": "multiDeleteV1", "l2": "diff3BaseValue2", "l3": "v3"}).(Gauge).Set(168) + baseVec.With(Labels{"l1": "multiDeleteV1", "l2": "diff1BaseValue2", "l3": "v3"}).Set(42) + baseVec.With(Labels{"l1": "multiDeleteV1", "l2": "diff2BaseValue2", "l3": "v3"}).Set(84) + baseVec.With(Labels{"l1": "multiDeleteV1", "l2": "diff3BaseValue2", "l3": "v3"}).Set(168) curriedVec := baseVec.MustCurryWith(Labels{"l2": "curriedValue2"}) curriedVec.WithLabelValues("curriedValue1", "curriedValue3").Inc() @@ -249,7 +249,7 @@ func testMetricVec(t *testing.T, vec *GaugeVec) { vec.WithLabelValues(pair[0], pair[1]).Inc() expected[[2]string{"v1", "v2"}]++ - vec.WithLabelValues("v1", "v2").(Gauge).Inc() + vec.WithLabelValues("v1", "v2").Inc() } var total int