mirror of
https://github.com/prometheus/prometheus.git
synced 2024-12-24 21:24:05 -08:00
tests: Move from t.Errorf and others. (Part 2) (#9309)
* Refactor util tests. Signed-off-by: Paweł Szulik <paul.szulik@gmail.com>
This commit is contained in:
parent
2042b91003
commit
f5563bfe95
|
@ -17,7 +17,6 @@ import (
|
||||||
"context"
|
"context"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"os"
|
"os"
|
||||||
"reflect"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/prometheus/common/model"
|
"github.com/prometheus/common/model"
|
||||||
|
@ -217,14 +216,7 @@ func TestGenerateTargetGroups(t *testing.T) {
|
||||||
|
|
||||||
for _, testCase := range testCases {
|
for _, testCase := range testCases {
|
||||||
result := generateTargetGroups(testCase.targetGroup)
|
result := generateTargetGroups(testCase.targetGroup)
|
||||||
|
require.Equal(t, testCase.expectedCustomSD, result)
|
||||||
if !reflect.DeepEqual(result, testCase.expectedCustomSD) {
|
|
||||||
t.Errorf("%q failed\ngot: %#v\nexpected: %v",
|
|
||||||
testCase.title,
|
|
||||||
result,
|
|
||||||
testCase.expectedCustomSD)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -17,6 +17,7 @@ import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/prometheus/common/model"
|
"github.com/prometheus/common/model"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
@ -32,17 +33,13 @@ func TestEscape(t *testing.T) {
|
||||||
value := "abzABZ019(){},'\"\\"
|
value := "abzABZ019(){},'\"\\"
|
||||||
expected := "abzABZ019\\(\\)\\{\\}\\,\\'\\\"\\\\"
|
expected := "abzABZ019\\(\\)\\{\\}\\,\\'\\\"\\\\"
|
||||||
actual := escape(model.LabelValue(value))
|
actual := escape(model.LabelValue(value))
|
||||||
if expected != actual {
|
require.Equal(t, expected, actual)
|
||||||
t.Errorf("Expected %s, got %s", expected, actual)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test percent-encoding.
|
// Test percent-encoding.
|
||||||
value = "é/|_;:%."
|
value = "é/|_;:%."
|
||||||
expected = "%C3%A9%2F|_;:%25%2E"
|
expected = "%C3%A9%2F|_;:%25%2E"
|
||||||
actual = escape(model.LabelValue(value))
|
actual = escape(model.LabelValue(value))
|
||||||
if expected != actual {
|
require.Equal(t, expected, actual)
|
||||||
t.Errorf("Expected %s, got %s", expected, actual)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestPathFromMetric(t *testing.T) {
|
func TestPathFromMetric(t *testing.T) {
|
||||||
|
@ -51,7 +48,5 @@ func TestPathFromMetric(t *testing.T) {
|
||||||
".many_chars.abc!ABC:012-3!45%C3%B667~89%2E%2F\\(\\)\\{\\}\\,%3D%2E\\\"\\\\" +
|
".many_chars.abc!ABC:012-3!45%C3%B667~89%2E%2F\\(\\)\\{\\}\\,%3D%2E\\\"\\\\" +
|
||||||
".testlabel.test:value")
|
".testlabel.test:value")
|
||||||
actual := pathFromMetric(metric, "prefix.")
|
actual := pathFromMetric(metric, "prefix.")
|
||||||
if expected != actual {
|
require.Equal(t, expected, actual)
|
||||||
t.Errorf("Expected %s, got %s", expected, actual)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -24,6 +24,7 @@ import (
|
||||||
|
|
||||||
influx "github.com/influxdata/influxdb/client/v2"
|
influx "github.com/influxdata/influxdb/client/v2"
|
||||||
"github.com/prometheus/common/model"
|
"github.com/prometheus/common/model"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestClient(t *testing.T) {
|
func TestClient(t *testing.T) {
|
||||||
|
@ -73,28 +74,17 @@ testmetric,test_label=test_label_value2 value=5.1234 123456789123
|
||||||
|
|
||||||
server := httptest.NewServer(http.HandlerFunc(
|
server := httptest.NewServer(http.HandlerFunc(
|
||||||
func(w http.ResponseWriter, r *http.Request) {
|
func(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.Method != "POST" {
|
require.Equal(t, "POST", r.Method, "Unexpected method.")
|
||||||
t.Fatalf("Unexpected method; expected POST, got %s", r.Method)
|
require.Equal(t, "/write", r.URL.Path, "Unexpected path.")
|
||||||
}
|
|
||||||
if r.URL.Path != "/write" {
|
|
||||||
t.Fatalf("Unexpected path; expected %s, got %s", "/write", r.URL.Path)
|
|
||||||
}
|
|
||||||
b, err := ioutil.ReadAll(r.Body)
|
b, err := ioutil.ReadAll(r.Body)
|
||||||
if err != nil {
|
require.NoError(t, err, "Error reading body.")
|
||||||
t.Fatalf("Error reading body: %s", err)
|
require.Equal(t, expectedBody, string(b), "Unexpected request body.")
|
||||||
}
|
|
||||||
|
|
||||||
if string(b) != expectedBody {
|
|
||||||
t.Fatalf("Unexpected request body; expected:\n\n%s\n\ngot:\n\n%s", expectedBody, string(b))
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
))
|
))
|
||||||
defer server.Close()
|
defer server.Close()
|
||||||
|
|
||||||
serverURL, err := url.Parse(server.URL)
|
serverURL, err := url.Parse(server.URL)
|
||||||
if err != nil {
|
require.NoError(t, err, "Unable to parse server URL.")
|
||||||
t.Fatalf("Unable to parse server URL %s: %s", server.URL, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
conf := influx.HTTPConfig{
|
conf := influx.HTTPConfig{
|
||||||
Addr: serverURL.String(),
|
Addr: serverURL.String(),
|
||||||
|
@ -103,8 +93,6 @@ testmetric,test_label=test_label_value2 value=5.1234 123456789123
|
||||||
Timeout: time.Minute,
|
Timeout: time.Minute,
|
||||||
}
|
}
|
||||||
c := NewClient(nil, conf, "test_db", "default")
|
c := NewClient(nil, conf, "test_db", "default")
|
||||||
|
err = c.Write(samples)
|
||||||
if err := c.Write(samples); err != nil {
|
require.NoError(t, err, "Error sending samples.")
|
||||||
t.Fatalf("Error sending samples: %s", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -14,12 +14,11 @@
|
||||||
package opentsdb
|
package opentsdb
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"reflect"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/prometheus/common/model"
|
"github.com/prometheus/common/model"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
@ -36,9 +35,7 @@ func TestTagsFromMetric(t *testing.T) {
|
||||||
"many_chars": TagValue("abc!ABC:012-3!45ö67~89./"),
|
"many_chars": TagValue("abc!ABC:012-3!45ö67~89./"),
|
||||||
}
|
}
|
||||||
actual := tagsFromMetric(metric)
|
actual := tagsFromMetric(metric)
|
||||||
if !reflect.DeepEqual(actual, expected) {
|
require.Equal(t, expected, actual)
|
||||||
t.Errorf("Expected %#v, got %#v", expected, actual)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestMarshalStoreSamplesRequest(t *testing.T) {
|
func TestMarshalStoreSamplesRequest(t *testing.T) {
|
||||||
|
@ -51,25 +48,11 @@ func TestMarshalStoreSamplesRequest(t *testing.T) {
|
||||||
expectedJSON := []byte(`{"metric":"test_.metric","timestamp":4711,"value":3.1415,"tags":{"many_chars":"abc_21ABC_.012-3_2145_C3_B667_7E89./","testlabel":"test_.value"}}`)
|
expectedJSON := []byte(`{"metric":"test_.metric","timestamp":4711,"value":3.1415,"tags":{"many_chars":"abc_21ABC_.012-3_2145_C3_B667_7E89./","testlabel":"test_.value"}}`)
|
||||||
|
|
||||||
resultingJSON, err := json.Marshal(request)
|
resultingJSON, err := json.Marshal(request)
|
||||||
if err != nil {
|
require.NoError(t, err, "Marshal(request) resulted in err.")
|
||||||
t.Fatalf("Marshal(request) resulted in err: %s", err)
|
require.Equal(t, expectedJSON, resultingJSON)
|
||||||
}
|
|
||||||
if !bytes.Equal(resultingJSON, expectedJSON) {
|
|
||||||
t.Errorf(
|
|
||||||
"Marshal(request) => %q, want %q",
|
|
||||||
resultingJSON, expectedJSON,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
var unmarshaledRequest StoreSamplesRequest
|
var unmarshaledRequest StoreSamplesRequest
|
||||||
err = json.Unmarshal(expectedJSON, &unmarshaledRequest)
|
err = json.Unmarshal(expectedJSON, &unmarshaledRequest)
|
||||||
if err != nil {
|
require.NoError(t, err, "Unmarshal(expectedJSON, &unmarshaledRequest) resulted in err.")
|
||||||
t.Fatalf("Unmarshal(expectedJSON, &unmarshaledRequest) resulted in err: %s", err)
|
require.Equal(t, request, unmarshaledRequest)
|
||||||
}
|
|
||||||
if !reflect.DeepEqual(unmarshaledRequest, request) {
|
|
||||||
t.Errorf(
|
|
||||||
"Unmarshal(expectedJSON, &unmarshaledRequest) => %#v, want %#v",
|
|
||||||
unmarshaledRequest, request,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -14,9 +14,10 @@
|
||||||
package opentsdb
|
package opentsdb
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
var stringtests = []struct {
|
var stringtests = []struct {
|
||||||
|
@ -32,17 +33,9 @@ var stringtests = []struct {
|
||||||
|
|
||||||
func TestTagValueMarshaling(t *testing.T) {
|
func TestTagValueMarshaling(t *testing.T) {
|
||||||
for i, tt := range stringtests {
|
for i, tt := range stringtests {
|
||||||
json, err := json.Marshal(tt.tv)
|
got, err := json.Marshal(tt.tv)
|
||||||
if err != nil {
|
require.NoError(t, err, "%d. Marshal(%q) returned error.", i, tt.tv)
|
||||||
t.Errorf("%d. Marshal(%q) returned err: %s", i, tt.tv, err)
|
require.Equal(t, tt.json, got, "%d. Marshal(%q) not equal.", i, tt.tv)
|
||||||
} else {
|
|
||||||
if !bytes.Equal(json, tt.json) {
|
|
||||||
t.Errorf(
|
|
||||||
"%d. Marshal(%q) => %q, want %q",
|
|
||||||
i, tt.tv, json, tt.json,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -50,15 +43,7 @@ func TestTagValueUnMarshaling(t *testing.T) {
|
||||||
for i, tt := range stringtests {
|
for i, tt := range stringtests {
|
||||||
var tv TagValue
|
var tv TagValue
|
||||||
err := json.Unmarshal(tt.json, &tv)
|
err := json.Unmarshal(tt.json, &tv)
|
||||||
if err != nil {
|
require.NoError(t, err, "%d. Unmarshal(%q, &str) returned error.", i, tt.json)
|
||||||
t.Errorf("%d. Unmarshal(%q, &str) returned err: %s", i, tt.json, err)
|
require.Equal(t, tt.tv, tv, "%d. Unmarshal(%q, &str) not equal.", i, tt.json)
|
||||||
} else {
|
|
||||||
if tv != tt.tv {
|
|
||||||
t.Errorf(
|
|
||||||
"%d. Unmarshal(%q, &str) => str==%q, want %q",
|
|
||||||
i, tt.json, tv, tt.tv,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -392,7 +392,7 @@ func TestHandlerQueuing(t *testing.T) {
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
return
|
return
|
||||||
case <-time.After(5 * time.Second):
|
case <-time.After(5 * time.Second):
|
||||||
t.Fatalf("Alerts were not pushed")
|
require.FailNow(t, "Alerts were not pushed.")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -424,7 +424,7 @@ func TestHandlerQueuing(t *testing.T) {
|
||||||
case err := <-errc:
|
case err := <-errc:
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
case <-time.After(5 * time.Second):
|
case <-time.After(5 * time.Second):
|
||||||
t.Fatalf("Alerts were not pushed")
|
require.FailNow(t, "Alerts were not pushed.")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify that we receive the last 3 batches.
|
// Verify that we receive the last 3 batches.
|
||||||
|
@ -480,14 +480,12 @@ alerting:
|
||||||
alertmanagers:
|
alertmanagers:
|
||||||
- static_configs:
|
- static_configs:
|
||||||
`
|
`
|
||||||
if err := yaml.UnmarshalStrict([]byte(s), cfg); err != nil {
|
err := yaml.UnmarshalStrict([]byte(s), cfg)
|
||||||
t.Fatalf("Unable to load YAML config: %s", err)
|
require.NoError(t, err, "Unable to load YAML config.")
|
||||||
}
|
|
||||||
require.Equal(t, 1, len(cfg.AlertingConfig.AlertmanagerConfigs))
|
require.Equal(t, 1, len(cfg.AlertingConfig.AlertmanagerConfigs))
|
||||||
|
|
||||||
if err := n.ApplyConfig(cfg); err != nil {
|
err = n.ApplyConfig(cfg)
|
||||||
t.Fatalf("Error Applying the config:%v", err)
|
require.NoError(t, err, "Error applying the config.")
|
||||||
}
|
|
||||||
|
|
||||||
tgs := make(map[string][]*targetgroup.Group)
|
tgs := make(map[string][]*targetgroup.Group)
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
|
@ -534,14 +532,12 @@ alerting:
|
||||||
regex: 'alertmanager:9093'
|
regex: 'alertmanager:9093'
|
||||||
action: drop
|
action: drop
|
||||||
`
|
`
|
||||||
if err := yaml.UnmarshalStrict([]byte(s), cfg); err != nil {
|
err := yaml.UnmarshalStrict([]byte(s), cfg)
|
||||||
t.Fatalf("Unable to load YAML config: %s", err)
|
require.NoError(t, err, "Unable to load YAML config.")
|
||||||
}
|
|
||||||
require.Equal(t, 1, len(cfg.AlertingConfig.AlertmanagerConfigs))
|
require.Equal(t, 1, len(cfg.AlertingConfig.AlertmanagerConfigs))
|
||||||
|
|
||||||
if err := n.ApplyConfig(cfg); err != nil {
|
err = n.ApplyConfig(cfg)
|
||||||
t.Fatalf("Error Applying the config:%v", err)
|
require.NoError(t, err, "Error applying the config.")
|
||||||
}
|
|
||||||
|
|
||||||
tgs := make(map[string][]*targetgroup.Group)
|
tgs := make(map[string][]*targetgroup.Group)
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
|
|
|
@ -15,19 +15,14 @@ package rulefmt
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestParseFileSuccess(t *testing.T) {
|
func TestParseFileSuccess(t *testing.T) {
|
||||||
if _, errs := ParseFile("testdata/test.yaml"); len(errs) > 0 {
|
_, errs := ParseFile("testdata/test.yaml")
|
||||||
t.Errorf("unexpected errors parsing file")
|
require.Empty(t, errs, "unexpected errors parsing file")
|
||||||
for _, err := range errs {
|
|
||||||
t.Error(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestParseFileFailure(t *testing.T) {
|
func TestParseFileFailure(t *testing.T) {
|
||||||
|
@ -79,15 +74,9 @@ func TestParseFileFailure(t *testing.T) {
|
||||||
|
|
||||||
for _, c := range table {
|
for _, c := range table {
|
||||||
_, errs := ParseFile(filepath.Join("testdata", c.filename))
|
_, errs := ParseFile(filepath.Join("testdata", c.filename))
|
||||||
if errs == nil {
|
require.NotNil(t, errs, "Expected error parsing %s but got none", c.filename)
|
||||||
t.Errorf("Expected error parsing %s but got none", c.filename)
|
require.Error(t, errs[0], c.errMsg, "Expected error for %s.", c.filename)
|
||||||
continue
|
|
||||||
}
|
|
||||||
if !strings.Contains(errs[0].Error(), c.errMsg) {
|
|
||||||
t.Errorf("Expected error for %s to contain %q but got: %s", c.filename, c.errMsg, errs)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestTemplateParsing(t *testing.T) {
|
func TestTemplateParsing(t *testing.T) {
|
||||||
|
|
|
@ -72,7 +72,7 @@ func TestQueryConcurrency(t *testing.T) {
|
||||||
case <-processing:
|
case <-processing:
|
||||||
// Expected.
|
// Expected.
|
||||||
case <-time.After(20 * time.Millisecond):
|
case <-time.After(20 * time.Millisecond):
|
||||||
t.Fatalf("Query within concurrency threshold not being executed")
|
require.Fail(t, "Query within concurrency threshold not being executed")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -81,7 +81,7 @@ func TestQueryConcurrency(t *testing.T) {
|
||||||
|
|
||||||
select {
|
select {
|
||||||
case <-processing:
|
case <-processing:
|
||||||
t.Fatalf("Query above concurrency threshold being executed")
|
require.Fail(t, "Query above concurrency threshold being executed")
|
||||||
case <-time.After(20 * time.Millisecond):
|
case <-time.After(20 * time.Millisecond):
|
||||||
// Expected.
|
// Expected.
|
||||||
}
|
}
|
||||||
|
@ -93,7 +93,7 @@ func TestQueryConcurrency(t *testing.T) {
|
||||||
case <-processing:
|
case <-processing:
|
||||||
// Expected.
|
// Expected.
|
||||||
case <-time.After(20 * time.Millisecond):
|
case <-time.After(20 * time.Millisecond):
|
||||||
t.Fatalf("Query within concurrency threshold not being executed")
|
require.Fail(t, "Query within concurrency threshold not being executed")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Terminate remaining queries.
|
// Terminate remaining queries.
|
||||||
|
@ -604,7 +604,7 @@ func TestEngineShutdown(t *testing.T) {
|
||||||
require.Equal(t, errQueryCanceled, res.Err)
|
require.Equal(t, errQueryCanceled, res.Err)
|
||||||
|
|
||||||
query2 := engine.newTestQuery(func(context.Context) error {
|
query2 := engine.newTestQuery(func(context.Context) error {
|
||||||
t.Fatalf("reached query execution unexpectedly")
|
require.FailNow(t, "reached query execution unexpectedly")
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
|
@ -1121,9 +1121,7 @@ func TestRecoverEvaluatorRuntime(t *testing.T) {
|
||||||
//nolint:govet
|
//nolint:govet
|
||||||
a[123] = 1
|
a[123] = 1
|
||||||
|
|
||||||
if err.Error() != "unexpected error" {
|
require.EqualError(t, err, "unexpected error")
|
||||||
t.Fatalf("wrong error message: %q, expected %q", err, "unexpected error")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestRecoverEvaluatorError(t *testing.T) {
|
func TestRecoverEvaluatorError(t *testing.T) {
|
||||||
|
@ -1133,9 +1131,7 @@ func TestRecoverEvaluatorError(t *testing.T) {
|
||||||
e := errors.New("custom error")
|
e := errors.New("custom error")
|
||||||
|
|
||||||
defer func() {
|
defer func() {
|
||||||
if err.Error() != e.Error() {
|
require.EqualError(t, err, e.Error())
|
||||||
t.Fatalf("wrong error message: %q, expected %q", err, e)
|
|
||||||
}
|
|
||||||
}()
|
}()
|
||||||
defer ev.recover(nil, &err)
|
defer ev.recover(nil, &err)
|
||||||
|
|
||||||
|
@ -1154,12 +1150,8 @@ func TestRecoverEvaluatorErrorWithWarnings(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() {
|
||||||
if err.Error() != e.Error() {
|
require.EqualError(t, err, e.Error())
|
||||||
t.Fatalf("wrong error message: %q, expected %q", err, e)
|
require.Equal(t, warnings, ws, "wrong warning message")
|
||||||
}
|
|
||||||
if len(ws) != len(warnings) && ws[0] != warnings[0] {
|
|
||||||
t.Fatalf("wrong warning message: %q, expected %q", ws[0], warnings[0])
|
|
||||||
}
|
|
||||||
}()
|
}()
|
||||||
defer ev.recover(&ws, &err)
|
defer ev.recover(&ws, &err)
|
||||||
|
|
||||||
|
|
|
@ -737,13 +737,13 @@ func TestLexer(t *testing.T) {
|
||||||
}
|
}
|
||||||
if !hasError {
|
if !hasError {
|
||||||
t.Logf("%d: input %q", i, test.input)
|
t.Logf("%d: input %q", i, test.input)
|
||||||
t.Fatalf("expected lexing error but did not fail")
|
require.Fail(t, "expected lexing error but did not fail")
|
||||||
}
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if lastItem.Typ == ERROR {
|
if lastItem.Typ == ERROR {
|
||||||
t.Logf("%d: input %q", i, test.input)
|
t.Logf("%d: input %q", i, test.input)
|
||||||
t.Fatalf("unexpected lexing error at position %d: %s", lastItem.Pos, lastItem)
|
require.Fail(t, "unexpected lexing error at position %d: %s", lastItem.Pos, lastItem)
|
||||||
}
|
}
|
||||||
|
|
||||||
eofItem := Item{EOF, Pos(len(test.input)), ""}
|
eofItem := Item{EOF, Pos(len(test.input)), ""}
|
||||||
|
|
|
@ -55,18 +55,16 @@ func TestQueryLogging(t *testing.T) {
|
||||||
queryLogger.Insert(context.Background(), queries[i])
|
queryLogger.Insert(context.Background(), queries[i])
|
||||||
|
|
||||||
have := string(fileAsBytes[start:end])
|
have := string(fileAsBytes[start:end])
|
||||||
if !regexp.MustCompile(want[i]).MatchString(have) {
|
require.True(t, regexp.MustCompile(want[i]).MatchString(have),
|
||||||
t.Fatalf("Query not written correctly: %s.\nHave %s\nWant %s", queries[i], have, want[i])
|
"Query not written correctly: %s", queries[i])
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if all queries have been deleted.
|
// Check if all queries have been deleted.
|
||||||
for i := 0; i < 4; i++ {
|
for i := 0; i < 4; i++ {
|
||||||
queryLogger.Delete(1 + i*entrySize)
|
queryLogger.Delete(1 + i*entrySize)
|
||||||
}
|
}
|
||||||
if !regexp.MustCompile(`^\x00+$`).Match(fileAsBytes[1 : 1+entrySize*4]) {
|
require.True(t, regexp.MustCompile(`^\x00+$`).Match(fileAsBytes[1:1+entrySize*4]),
|
||||||
t.Fatalf("All queries not deleted properly. Have %s\nWant only null bytes \\x00", string(fileAsBytes[1:1+entrySize*4]))
|
"All queries not deleted properly. Want only null bytes \\x00")
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestIndexReuse(t *testing.T) {
|
func TestIndexReuse(t *testing.T) {
|
||||||
|
@ -101,9 +99,8 @@ func TestIndexReuse(t *testing.T) {
|
||||||
end := start + entrySize
|
end := start + entrySize
|
||||||
|
|
||||||
have := queryBytes[start:end]
|
have := queryBytes[start:end]
|
||||||
if !regexp.MustCompile(want[i]).Match(have) {
|
require.True(t, regexp.MustCompile(want[i]).Match(have),
|
||||||
t.Fatalf("Index not reused properly:\nHave %s\nWant %s", string(queryBytes[start:end]), want[i])
|
"Index not reused properly.")
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -124,14 +121,10 @@ func TestMMapFile(t *testing.T) {
|
||||||
|
|
||||||
bytes := make([]byte, 4)
|
bytes := make([]byte, 4)
|
||||||
n, err := f.Read(bytes)
|
n, err := f.Read(bytes)
|
||||||
|
require.Equal(t, n, 2)
|
||||||
|
require.NoError(t, err, "Unexpected error while reading file.")
|
||||||
|
|
||||||
if n != 2 || err != nil {
|
require.Equal(t, fileAsBytes, bytes[:2], "Mmap failed")
|
||||||
t.Fatalf("Error reading file")
|
|
||||||
}
|
|
||||||
|
|
||||||
if string(bytes[:2]) != string(fileAsBytes) {
|
|
||||||
t.Fatalf("Mmap failed")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestParseBrokenJSON(t *testing.T) {
|
func TestParseBrokenJSON(t *testing.T) {
|
||||||
|
@ -163,12 +156,9 @@ func TestParseBrokenJSON(t *testing.T) {
|
||||||
} {
|
} {
|
||||||
t.Run("", func(t *testing.T) {
|
t.Run("", func(t *testing.T) {
|
||||||
out, ok := parseBrokenJSON(tc.b)
|
out, ok := parseBrokenJSON(tc.b)
|
||||||
if tc.ok != ok {
|
require.Equal(t, tc.ok, ok)
|
||||||
t.Fatalf("expected %t, got %t", tc.ok, ok)
|
if ok {
|
||||||
return
|
require.Equal(t, tc.out, out)
|
||||||
}
|
|
||||||
if ok && tc.out != out {
|
|
||||||
t.Fatalf("expected %s, got %s", tc.out, out)
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
|
@ -25,6 +25,7 @@ import (
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"github.com/prometheus/common/model"
|
"github.com/prometheus/common/model"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
|
||||||
"github.com/prometheus/prometheus/pkg/exemplar"
|
"github.com/prometheus/prometheus/pkg/exemplar"
|
||||||
"github.com/prometheus/prometheus/pkg/labels"
|
"github.com/prometheus/prometheus/pkg/labels"
|
||||||
|
@ -597,9 +598,8 @@ func (t *Test) exec(tc testCommand) error {
|
||||||
// clear the current test storage of all inserted samples.
|
// clear the current test storage of all inserted samples.
|
||||||
func (t *Test) clear() {
|
func (t *Test) clear() {
|
||||||
if t.storage != nil {
|
if t.storage != nil {
|
||||||
if err := t.storage.Close(); err != nil {
|
err := t.storage.Close()
|
||||||
t.T.Fatalf("closing test storage: %s", err)
|
require.NoError(t.T, err, "Unexpected error while closing test storage.")
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if t.cancelCtx != nil {
|
if t.cancelCtx != nil {
|
||||||
t.cancelCtx()
|
t.cancelCtx()
|
||||||
|
@ -623,9 +623,8 @@ func (t *Test) clear() {
|
||||||
func (t *Test) Close() {
|
func (t *Test) Close() {
|
||||||
t.cancelCtx()
|
t.cancelCtx()
|
||||||
|
|
||||||
if err := t.storage.Close(); err != nil {
|
err := t.storage.Close()
|
||||||
t.T.Fatalf("closing test storage: %s", err)
|
require.NoError(t.T, err, "Unexpected error while closing test storage.")
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// samplesAlmostEqual returns true if the two sample lines only differ by a
|
// samplesAlmostEqual returns true if the two sample lines only differ by a
|
||||||
|
@ -722,9 +721,8 @@ func (ll *LazyLoader) parse(input string) error {
|
||||||
// clear the current test storage of all inserted samples.
|
// clear the current test storage of all inserted samples.
|
||||||
func (ll *LazyLoader) clear() {
|
func (ll *LazyLoader) clear() {
|
||||||
if ll.storage != nil {
|
if ll.storage != nil {
|
||||||
if err := ll.storage.Close(); err != nil {
|
err := ll.storage.Close()
|
||||||
ll.T.Fatalf("closing test storage: %s", err)
|
require.NoError(ll.T, err, "Unexpected error while closing test storage.")
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if ll.cancelCtx != nil {
|
if ll.cancelCtx != nil {
|
||||||
ll.cancelCtx()
|
ll.cancelCtx()
|
||||||
|
@ -798,8 +796,6 @@ func (ll *LazyLoader) Storage() storage.Storage {
|
||||||
// Close closes resources associated with the LazyLoader.
|
// Close closes resources associated with the LazyLoader.
|
||||||
func (ll *LazyLoader) Close() {
|
func (ll *LazyLoader) Close() {
|
||||||
ll.cancelCtx()
|
ll.cancelCtx()
|
||||||
|
err := ll.storage.Close()
|
||||||
if err := ll.storage.Close(); err != nil {
|
require.NoError(ll.T, err, "Unexpected error while closing test storage.")
|
||||||
ll.T.Fatalf("closing test storage: %s", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -111,9 +111,8 @@ func TestClientRetryAfter(t *testing.T) {
|
||||||
|
|
||||||
c := getClient(conf)
|
c := getClient(conf)
|
||||||
err = c.Store(context.Background(), []byte{})
|
err = c.Store(context.Background(), []byte{})
|
||||||
if _, ok := err.(RecoverableError); ok {
|
_, ok := err.(RecoverableError)
|
||||||
t.Fatal("recoverable error not expected")
|
require.False(t, ok, "Recoverable error not expected.")
|
||||||
}
|
|
||||||
|
|
||||||
conf = &ClientConfig{
|
conf = &ClientConfig{
|
||||||
URL: &config_util.URL{URL: serverURL},
|
URL: &config_util.URL{URL: serverURL},
|
||||||
|
@ -123,9 +122,8 @@ func TestClientRetryAfter(t *testing.T) {
|
||||||
|
|
||||||
c = getClient(conf)
|
c = getClient(conf)
|
||||||
err = c.Store(context.Background(), []byte{})
|
err = c.Store(context.Background(), []byte{})
|
||||||
if _, ok := err.(RecoverableError); !ok {
|
_, ok = err.(RecoverableError)
|
||||||
t.Fatal("recoverable error was expected")
|
require.True(t, ok, "Recoverable error was expected.")
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestRetryAfterDuration(t *testing.T) {
|
func TestRetryAfterDuration(t *testing.T) {
|
||||||
|
|
|
@ -78,9 +78,7 @@ func TestSampledReadEndpoint(t *testing.T) {
|
||||||
recorder := httptest.NewRecorder()
|
recorder := httptest.NewRecorder()
|
||||||
h.ServeHTTP(recorder, request)
|
h.ServeHTTP(recorder, request)
|
||||||
|
|
||||||
if recorder.Code/100 != 2 {
|
require.Equal(t, 2, recorder.Code/100)
|
||||||
t.Fatal(recorder.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
require.Equal(t, "application/x-protobuf", recorder.Result().Header.Get("Content-Type"))
|
require.Equal(t, "application/x-protobuf", recorder.Result().Header.Get("Content-Type"))
|
||||||
require.Equal(t, "snappy", recorder.Result().Header.Get("Content-Encoding"))
|
require.Equal(t, "snappy", recorder.Result().Header.Get("Content-Encoding"))
|
||||||
|
@ -96,9 +94,7 @@ func TestSampledReadEndpoint(t *testing.T) {
|
||||||
err = proto.Unmarshal(uncompressed, &resp)
|
err = proto.Unmarshal(uncompressed, &resp)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
if len(resp.Results) != 1 {
|
require.Equal(t, 1, len(resp.Results), "Expected 1 result.")
|
||||||
t.Fatalf("Expected 1 result, got %d", len(resp.Results))
|
|
||||||
}
|
|
||||||
|
|
||||||
require.Equal(t, &prompb.QueryResult{
|
require.Equal(t, &prompb.QueryResult{
|
||||||
Timeseries: []*prompb.TimeSeries{
|
Timeseries: []*prompb.TimeSeries{
|
||||||
|
@ -189,9 +185,7 @@ func TestStreamReadEndpoint(t *testing.T) {
|
||||||
recorder := httptest.NewRecorder()
|
recorder := httptest.NewRecorder()
|
||||||
api.ServeHTTP(recorder, request)
|
api.ServeHTTP(recorder, request)
|
||||||
|
|
||||||
if recorder.Code/100 != 2 {
|
require.Equal(t, 2, recorder.Code/100)
|
||||||
t.Fatal(recorder.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
require.Equal(t, "application/x-streamed-protobuf; proto=prometheus.ChunkedReadResponse", recorder.Result().Header.Get("Content-Type"))
|
require.Equal(t, "application/x-streamed-protobuf; proto=prometheus.ChunkedReadResponse", recorder.Result().Header.Get("Content-Type"))
|
||||||
require.Equal(t, "", recorder.Result().Header.Get("Content-Encoding"))
|
require.Equal(t, "", recorder.Result().Header.Get("Content-Encoding"))
|
||||||
|
@ -208,9 +202,7 @@ func TestStreamReadEndpoint(t *testing.T) {
|
||||||
results = append(results, res)
|
results = append(results, res)
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(results) != 5 {
|
require.Equal(t, 5, len(results), "Expected 5 results.")
|
||||||
t.Fatalf("Expected 5 result, got %d", len(results))
|
|
||||||
}
|
|
||||||
|
|
||||||
require.Equal(t, []*prompb.ChunkedReadResponse{
|
require.Equal(t, []*prompb.ChunkedReadResponse{
|
||||||
{
|
{
|
||||||
|
|
|
@ -21,6 +21,8 @@ import (
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
@ -60,22 +62,14 @@ func TestCompressionHandler_PlainText(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
resp, err := client.Get(server.URL + "/foo_endpoint")
|
resp, err := client.Get(server.URL + "/foo_endpoint")
|
||||||
|
require.NoError(t, err, "client get failed with unexpected error")
|
||||||
if err != nil {
|
|
||||||
t.Error("client get failed with unexpected error")
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
contents, err := ioutil.ReadAll(resp.Body)
|
contents, err := ioutil.ReadAll(resp.Body)
|
||||||
|
require.NoError(t, err, "unexpected error while creating the response body reader")
|
||||||
if err != nil {
|
|
||||||
t.Errorf("unexpected error while reading the response body: %s", err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
expected := "Hello World!"
|
expected := "Hello World!"
|
||||||
actual := string(contents)
|
actual := string(contents)
|
||||||
if expected != actual {
|
require.Equal(t, expected, actual, "expected response with content")
|
||||||
t.Errorf("expected response with content %s, but got %s", expected, actual)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCompressionHandler_Gzip(t *testing.T) {
|
func TestCompressionHandler_Gzip(t *testing.T) {
|
||||||
|
@ -95,34 +89,22 @@ func TestCompressionHandler_Gzip(t *testing.T) {
|
||||||
req.Header.Set(acceptEncodingHeader, gzipEncoding)
|
req.Header.Set(acceptEncodingHeader, gzipEncoding)
|
||||||
|
|
||||||
resp, err := client.Do(req)
|
resp, err := client.Do(req)
|
||||||
if err != nil {
|
require.NoError(t, err, "client get failed with unexpected error")
|
||||||
t.Error("client get failed with unexpected error")
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
t.Errorf("unexpected error while reading the response body: %s", err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
actualHeader := resp.Header.Get(contentEncodingHeader)
|
actualHeader := resp.Header.Get(contentEncodingHeader)
|
||||||
|
require.Equal(t, gzipEncoding, actualHeader, "unexpected encoding header in response")
|
||||||
if actualHeader != gzipEncoding {
|
|
||||||
t.Errorf("expected response with encoding header %s, but got %s", gzipEncoding, actualHeader)
|
|
||||||
}
|
|
||||||
|
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
zr, _ := gzip.NewReader(resp.Body)
|
zr, err := gzip.NewReader(resp.Body)
|
||||||
|
require.NoError(t, err, "unexpected error while creating the response body reader")
|
||||||
|
|
||||||
_, err = buf.ReadFrom(zr)
|
_, err = buf.ReadFrom(zr)
|
||||||
if err != nil {
|
require.NoError(t, err, "unexpected error while reading the response body")
|
||||||
t.Error("unexpected error while reading from response body")
|
|
||||||
}
|
|
||||||
|
|
||||||
actual := buf.String()
|
actual := buf.String()
|
||||||
expected := "Hello World!"
|
expected := "Hello World!"
|
||||||
if expected != actual {
|
require.Equal(t, expected, actual, "unexpected response content")
|
||||||
t.Errorf("expected response with content %s, but got %s", expected, actual)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCompressionHandler_Deflate(t *testing.T) {
|
func TestCompressionHandler_Deflate(t *testing.T) {
|
||||||
|
@ -142,35 +124,20 @@ func TestCompressionHandler_Deflate(t *testing.T) {
|
||||||
req.Header.Set(acceptEncodingHeader, deflateEncoding)
|
req.Header.Set(acceptEncodingHeader, deflateEncoding)
|
||||||
|
|
||||||
resp, err := client.Do(req)
|
resp, err := client.Do(req)
|
||||||
if err != nil {
|
require.NoError(t, err, "client get failed with unexpected error")
|
||||||
t.Error("client get failed with unexpected error")
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
t.Errorf("unexpected error while reading the response body: %s", err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
actualHeader := resp.Header.Get(contentEncodingHeader)
|
actualHeader := resp.Header.Get(contentEncodingHeader)
|
||||||
|
require.Equal(t, deflateEncoding, actualHeader, "expected response with encoding header")
|
||||||
if actualHeader != deflateEncoding {
|
|
||||||
t.Errorf("expected response with encoding header %s, but got %s", deflateEncoding, actualHeader)
|
|
||||||
}
|
|
||||||
|
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
dr, err := zlib.NewReader(resp.Body)
|
dr, err := zlib.NewReader(resp.Body)
|
||||||
if err != nil {
|
require.NoError(t, err, "unexpected error while creating the response body reader")
|
||||||
t.Error("unexpected error while reading from response body")
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = buf.ReadFrom(dr)
|
_, err = buf.ReadFrom(dr)
|
||||||
if err != nil {
|
require.NoError(t, err, "unexpected error while reading the response body")
|
||||||
t.Error("unexpected error while reading from response body")
|
|
||||||
}
|
|
||||||
|
|
||||||
actual := buf.String()
|
actual := buf.String()
|
||||||
expected := "Hello World!"
|
expected := "Hello World!"
|
||||||
if expected != actual {
|
require.Equal(t, expected, actual, "expected response with content")
|
||||||
t.Errorf("expected response with content %s, but got %s", expected, actual)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -17,6 +17,8 @@ import (
|
||||||
"net/http"
|
"net/http"
|
||||||
"regexp"
|
"regexp"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
func getCORSHandlerFunc() http.Handler {
|
func getCORSHandlerFunc() http.Handler {
|
||||||
|
@ -40,41 +42,24 @@ func TestCORSHandler(t *testing.T) {
|
||||||
|
|
||||||
// OPTIONS with legit origin
|
// OPTIONS with legit origin
|
||||||
req, err := http.NewRequest("OPTIONS", server.URL+"/any_path", nil)
|
req, err := http.NewRequest("OPTIONS", server.URL+"/any_path", nil)
|
||||||
|
require.NoError(t, err, "could not create request")
|
||||||
if err != nil {
|
|
||||||
t.Error("could not create request")
|
|
||||||
}
|
|
||||||
|
|
||||||
req.Header.Set("Origin", dummyOrigin)
|
req.Header.Set("Origin", dummyOrigin)
|
||||||
resp, err := client.Do(req)
|
resp, err := client.Do(req)
|
||||||
|
require.NoError(t, err, "client get failed with unexpected error")
|
||||||
if err != nil {
|
|
||||||
t.Error("client get failed with unexpected error")
|
|
||||||
}
|
|
||||||
|
|
||||||
AccessControlAllowOrigin := resp.Header.Get("Access-Control-Allow-Origin")
|
AccessControlAllowOrigin := resp.Header.Get("Access-Control-Allow-Origin")
|
||||||
|
|
||||||
if AccessControlAllowOrigin != dummyOrigin {
|
require.Equal(t, dummyOrigin, AccessControlAllowOrigin, "expected Access-Control-Allow-Origin header")
|
||||||
t.Fatalf("%q does not match %q", dummyOrigin, AccessControlAllowOrigin)
|
|
||||||
}
|
|
||||||
|
|
||||||
// OPTIONS with bad origin
|
// OPTIONS with bad origin
|
||||||
req, err = http.NewRequest("OPTIONS", server.URL+"/any_path", nil)
|
req, err = http.NewRequest("OPTIONS", server.URL+"/any_path", nil)
|
||||||
|
require.NoError(t, err, "could not create request")
|
||||||
if err != nil {
|
|
||||||
t.Error("could not create request")
|
|
||||||
}
|
|
||||||
|
|
||||||
req.Header.Set("Origin", "https://not-foo.com")
|
req.Header.Set("Origin", "https://not-foo.com")
|
||||||
resp, err = client.Do(req)
|
resp, err = client.Do(req)
|
||||||
|
require.NoError(t, err, "client get failed with unexpected error")
|
||||||
if err != nil {
|
|
||||||
t.Error("client get failed with unexpected error")
|
|
||||||
}
|
|
||||||
|
|
||||||
AccessControlAllowOrigin = resp.Header.Get("Access-Control-Allow-Origin")
|
AccessControlAllowOrigin = resp.Header.Get("Access-Control-Allow-Origin")
|
||||||
|
require.Empty(t, AccessControlAllowOrigin, "Access-Control-Allow-Origin header should not exist but it was set")
|
||||||
if AccessControlAllowOrigin != "" {
|
|
||||||
t.Fatalf("Access-Control-Allow-Origin should not exist but it was set to: %q", AccessControlAllowOrigin)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -20,6 +20,7 @@ import (
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/prometheus/client_golang/prometheus"
|
"github.com/prometheus/client_golang/prometheus"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
|
||||||
"github.com/prometheus/prometheus/util/testutil"
|
"github.com/prometheus/prometheus/util/testutil"
|
||||||
)
|
)
|
||||||
|
@ -27,19 +28,17 @@ import (
|
||||||
func TestTimerGroupNewTimer(t *testing.T) {
|
func TestTimerGroupNewTimer(t *testing.T) {
|
||||||
tg := NewTimerGroup()
|
tg := NewTimerGroup()
|
||||||
timer := tg.GetTimer(ExecTotalTime)
|
timer := tg.GetTimer(ExecTotalTime)
|
||||||
if duration := timer.Duration(); duration != 0 {
|
duration := timer.Duration()
|
||||||
t.Fatalf("Expected duration of 0, but it was %f instead.", duration)
|
require.Equal(t, 0.0, duration, "Expected duration equal 0")
|
||||||
}
|
|
||||||
minimum := 2 * time.Millisecond
|
minimum := 2 * time.Millisecond
|
||||||
timer.Start()
|
timer.Start()
|
||||||
time.Sleep(minimum)
|
time.Sleep(minimum)
|
||||||
timer.Stop()
|
timer.Stop()
|
||||||
if duration := timer.Duration(); duration == 0 {
|
duration = timer.Duration()
|
||||||
t.Fatalf("Expected duration greater than 0, but it was %f instead.", duration)
|
require.Greater(t, duration, 0.0, "Expected duration greater than 0")
|
||||||
}
|
elapsed := timer.ElapsedTime()
|
||||||
if elapsed := timer.ElapsedTime(); elapsed < minimum {
|
require.GreaterOrEqual(t, elapsed, minimum,
|
||||||
t.Fatalf("Expected elapsed time to be greater than time slept, elapsed was %d, and time slept was %d.", elapsed.Nanoseconds(), minimum)
|
"Expected elapsed time to be greater than time slept.")
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestQueryStatsWithTimers(t *testing.T) {
|
func TestQueryStatsWithTimers(t *testing.T) {
|
||||||
|
@ -51,17 +50,11 @@ func TestQueryStatsWithTimers(t *testing.T) {
|
||||||
|
|
||||||
qs := NewQueryStats(qt)
|
qs := NewQueryStats(qt)
|
||||||
actual, err := json.Marshal(qs)
|
actual, err := json.Marshal(qs)
|
||||||
if err != nil {
|
require.NoError(t, err, "unexpected error during serialization")
|
||||||
t.Fatalf("Unexpected error during serialization: %v", err)
|
|
||||||
}
|
|
||||||
// Timing value is one of multiple fields, unit is seconds (float).
|
// Timing value is one of multiple fields, unit is seconds (float).
|
||||||
match, err := regexp.MatchString(`[,{]"execTotalTime":\d+\.\d+[,}]`, string(actual))
|
match, err := regexp.MatchString(`[,{]"execTotalTime":\d+\.\d+[,}]`, string(actual))
|
||||||
if err != nil {
|
require.NoError(t, err, "unexpected error while matching string")
|
||||||
t.Fatalf("Unexpected error while matching string: %v", err)
|
require.True(t, match, "Expected timings with one non-zero entry.")
|
||||||
}
|
|
||||||
if !match {
|
|
||||||
t.Fatalf("Expected timings with one non-zero entry, but got %s.", actual)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestQueryStatsWithSpanTimers(t *testing.T) {
|
func TestQueryStatsWithSpanTimers(t *testing.T) {
|
||||||
|
@ -72,51 +65,28 @@ func TestQueryStatsWithSpanTimers(t *testing.T) {
|
||||||
qst.Finish()
|
qst.Finish()
|
||||||
qs := NewQueryStats(qt)
|
qs := NewQueryStats(qt)
|
||||||
actual, err := json.Marshal(qs)
|
actual, err := json.Marshal(qs)
|
||||||
if err != nil {
|
require.NoError(t, err, "unexpected error during serialization")
|
||||||
t.Fatalf("Unexpected error during serialization: %v", err)
|
|
||||||
}
|
|
||||||
// Timing value is one of multiple fields, unit is seconds (float).
|
// Timing value is one of multiple fields, unit is seconds (float).
|
||||||
match, err := regexp.MatchString(`[,{]"execQueueTime":\d+\.\d+[,}]`, string(actual))
|
match, err := regexp.MatchString(`[,{]"execQueueTime":\d+\.\d+[,}]`, string(actual))
|
||||||
if err != nil {
|
require.NoError(t, err, "unexpected error while matching string")
|
||||||
t.Fatalf("Unexpected error while matching string: %v", err)
|
require.True(t, match, "Expected timings with one non-zero entry.")
|
||||||
}
|
|
||||||
if !match {
|
|
||||||
t.Fatalf("Expected timings with one non-zero entry, but got %s.", actual)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestTimerGroup(t *testing.T) {
|
func TestTimerGroup(t *testing.T) {
|
||||||
tg := NewTimerGroup()
|
tg := NewTimerGroup()
|
||||||
execTotalTimer := tg.GetTimer(ExecTotalTime)
|
require.Equal(t, "Exec total time: 0s", tg.GetTimer(ExecTotalTime).String())
|
||||||
if tg.GetTimer(ExecTotalTime).String() != "Exec total time: 0s" {
|
|
||||||
t.Fatalf("Expected string %s, but got %s", "", execTotalTimer.String())
|
require.Equal(t, "Exec queue wait time: 0s", tg.GetTimer(ExecQueueTime).String())
|
||||||
}
|
|
||||||
execQueueTimer := tg.GetTimer(ExecQueueTime)
|
require.Equal(t, "Inner eval time: 0s", tg.GetTimer(InnerEvalTime).String())
|
||||||
if tg.GetTimer(ExecQueueTime).String() != "Exec queue wait time: 0s" {
|
|
||||||
t.Fatalf("Expected string %s, but got %s", "", execQueueTimer.String())
|
require.Equal(t, "Query preparation time: 0s", tg.GetTimer(QueryPreparationTime).String())
|
||||||
}
|
|
||||||
innerEvalTimer := tg.GetTimer(InnerEvalTime)
|
require.Equal(t, "Result sorting time: 0s", tg.GetTimer(ResultSortTime).String())
|
||||||
if tg.GetTimer(InnerEvalTime).String() != "Inner eval time: 0s" {
|
|
||||||
t.Fatalf("Expected string %s, but got %s", "", innerEvalTimer.String())
|
require.Equal(t, "Eval total time: 0s", tg.GetTimer(EvalTotalTime).String())
|
||||||
}
|
|
||||||
queryPreparationTimer := tg.GetTimer(QueryPreparationTime)
|
|
||||||
if tg.GetTimer(QueryPreparationTime).String() != "Query preparation time: 0s" {
|
|
||||||
t.Fatalf("Expected string %s, but got %s", "", queryPreparationTimer.String())
|
|
||||||
}
|
|
||||||
resultSortTimer := tg.GetTimer(ResultSortTime)
|
|
||||||
if tg.GetTimer(ResultSortTime).String() != "Result sorting time: 0s" {
|
|
||||||
t.Fatalf("Expected string %s, but got %s", "", resultSortTimer.String())
|
|
||||||
}
|
|
||||||
evalTotalTimer := tg.GetTimer(EvalTotalTime)
|
|
||||||
if tg.GetTimer(EvalTotalTime).String() != "Eval total time: 0s" {
|
|
||||||
t.Fatalf("Expected string %s, but got %s", "", evalTotalTimer.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
actual := tg.String()
|
actual := tg.String()
|
||||||
expected := "Exec total time: 0s\nExec queue wait time: 0s\nInner eval time: 0s\nQuery preparation time: 0s\nResult sorting time: 0s\nEval total time: 0s\n"
|
expected := "Exec total time: 0s\nExec queue wait time: 0s\nInner eval time: 0s\nQuery preparation time: 0s\nResult sorting time: 0s\nEval total time: 0s\n"
|
||||||
|
require.Equal(t, expected, actual)
|
||||||
if actual != expected {
|
|
||||||
t.Fatalf("Expected timerGroup string %s, but got %s.", expected, actual)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -15,6 +15,8 @@ package strutil
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
var quotetests = []struct {
|
var quotetests = []struct {
|
||||||
|
@ -107,21 +109,22 @@ var misquoted = []string{
|
||||||
|
|
||||||
func TestUnquote(t *testing.T) {
|
func TestUnquote(t *testing.T) {
|
||||||
for _, tt := range unquotetests {
|
for _, tt := range unquotetests {
|
||||||
if out, err := Unquote(tt.in); err != nil && out != tt.out {
|
out, err := Unquote(tt.in)
|
||||||
t.Errorf("Unquote(%#q) = %q, %v want %q, nil", tt.in, out, err, tt.out)
|
if err != nil {
|
||||||
|
require.Equal(t, tt.out, out, "Unquote(%#q)", tt.in)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Run the quote tests too, backward.
|
// Run the quote tests too, backward.
|
||||||
for _, tt := range quotetests {
|
for _, tt := range quotetests {
|
||||||
if in, err := Unquote(tt.out); in != tt.in {
|
in, err := Unquote(tt.out)
|
||||||
t.Errorf("Unquote(%#q) = %q, %v, want %q, nil", tt.out, in, err, tt.in)
|
require.Equal(t, tt.in, in, "Unquote(%#q)", tt.out)
|
||||||
}
|
require.NoError(t, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, s := range misquoted {
|
for _, s := range misquoted {
|
||||||
if out, err := Unquote(s); out != "" || err != ErrSyntax {
|
out, err := Unquote(s)
|
||||||
t.Errorf("Unquote(%#q) = %q, %v want %q, %v", s, out, err, "", ErrSyntax)
|
require.Empty(t, out, "Unquote(%#q)", s)
|
||||||
}
|
require.EqualError(t, err, ErrSyntax.Error(), "Unquote(%#q)", s)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -15,6 +15,8 @@ package strutil
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
type linkTest struct {
|
type linkTest struct {
|
||||||
|
@ -38,28 +40,22 @@ var linkTests = []linkTest{
|
||||||
|
|
||||||
func TestLink(t *testing.T) {
|
func TestLink(t *testing.T) {
|
||||||
for _, tt := range linkTests {
|
for _, tt := range linkTests {
|
||||||
if graphLink := GraphLinkForExpression(tt.expression); graphLink != tt.expectedGraphLink {
|
graphLink := GraphLinkForExpression(tt.expression)
|
||||||
t.Errorf("GraphLinkForExpression failed for expression (%#q), want %q got %q", tt.expression, tt.expectedGraphLink, graphLink)
|
require.Equal(t, tt.expectedGraphLink, graphLink,
|
||||||
}
|
"GraphLinkForExpression failed for expression (%#q)", tt.expression)
|
||||||
|
|
||||||
if tableLink := TableLinkForExpression(tt.expression); tableLink != tt.expectedTableLink {
|
tableLink := TableLinkForExpression(tt.expression)
|
||||||
t.Errorf("TableLinkForExpression failed for expression (%#q), want %q got %q", tt.expression, tt.expectedTableLink, tableLink)
|
require.Equal(t, tt.expectedTableLink, tableLink,
|
||||||
}
|
"TableLinkForExpression failed for expression (%#q)", tt.expression)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSanitizeLabelName(t *testing.T) {
|
func TestSanitizeLabelName(t *testing.T) {
|
||||||
actual := SanitizeLabelName("fooClientLABEL")
|
actual := SanitizeLabelName("fooClientLABEL")
|
||||||
expected := "fooClientLABEL"
|
expected := "fooClientLABEL"
|
||||||
|
require.Equal(t, expected, actual, "SanitizeLabelName failed for label (%s)", expected)
|
||||||
if actual != expected {
|
|
||||||
t.Errorf("SanitizeLabelName failed for label (%s), want %s got %s", "fooClientLABEL", expected, actual)
|
|
||||||
}
|
|
||||||
|
|
||||||
actual = SanitizeLabelName("barClient.LABEL$$##")
|
actual = SanitizeLabelName("barClient.LABEL$$##")
|
||||||
expected = "barClient_LABEL____"
|
expected = "barClient_LABEL____"
|
||||||
|
require.Equal(t, expected, actual, "SanitizeLabelName failed for label (%s)", expected)
|
||||||
if actual != expected {
|
|
||||||
t.Errorf("SanitizeLabelName failed for label (%s), want %s got %s", "barClient.LABEL$$##", expected, actual)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -19,6 +19,8 @@ import (
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/prometheus/client_golang/prometheus"
|
"github.com/prometheus/client_golang/prometheus"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
|
||||||
"github.com/prometheus/prometheus/pkg/exemplar"
|
"github.com/prometheus/prometheus/pkg/exemplar"
|
||||||
"github.com/prometheus/prometheus/pkg/labels"
|
"github.com/prometheus/prometheus/pkg/labels"
|
||||||
"github.com/prometheus/prometheus/storage"
|
"github.com/prometheus/prometheus/storage"
|
||||||
|
@ -30,9 +32,7 @@ import (
|
||||||
// that removes all associated files on closing.
|
// that removes all associated files on closing.
|
||||||
func New(t testutil.T) *TestStorage {
|
func New(t testutil.T) *TestStorage {
|
||||||
dir, err := ioutil.TempDir("", "test_storage")
|
dir, err := ioutil.TempDir("", "test_storage")
|
||||||
if err != nil {
|
require.NoError(t, err, "unexpected error while opening test directory")
|
||||||
t.Fatalf("Opening test dir failed: %s", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Tests just load data for a series sequentially. Thus we
|
// Tests just load data for a series sequentially. Thus we
|
||||||
// need a long appendable window.
|
// need a long appendable window.
|
||||||
|
@ -40,16 +40,12 @@ func New(t testutil.T) *TestStorage {
|
||||||
opts.MinBlockDuration = int64(24 * time.Hour / time.Millisecond)
|
opts.MinBlockDuration = int64(24 * time.Hour / time.Millisecond)
|
||||||
opts.MaxBlockDuration = int64(24 * time.Hour / time.Millisecond)
|
opts.MaxBlockDuration = int64(24 * time.Hour / time.Millisecond)
|
||||||
db, err := tsdb.Open(dir, nil, nil, opts, tsdb.NewDBStats())
|
db, err := tsdb.Open(dir, nil, nil, opts, tsdb.NewDBStats())
|
||||||
if err != nil {
|
require.NoError(t, err, "unexpected error while opening test storage")
|
||||||
t.Fatalf("Opening test storage failed: %s", err)
|
|
||||||
}
|
|
||||||
reg := prometheus.NewRegistry()
|
reg := prometheus.NewRegistry()
|
||||||
eMetrics := tsdb.NewExemplarMetrics(reg)
|
eMetrics := tsdb.NewExemplarMetrics(reg)
|
||||||
|
|
||||||
es, err := tsdb.NewCircularExemplarStorage(10, eMetrics)
|
es, err := tsdb.NewCircularExemplarStorage(10, eMetrics)
|
||||||
if err != nil {
|
require.NoError(t, err, "unexpected error while opening test exemplar storage")
|
||||||
t.Fatalf("Opening test exemplar storage failed: %s", err)
|
|
||||||
}
|
|
||||||
return &TestStorage{DB: db, exemplarStorage: es, dir: dir}
|
return &TestStorage{DB: db, exemplarStorage: es, dir: dir}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -73,8 +73,8 @@ type (
|
||||||
// the test flags, which we do not want in non-test binaries even if
|
// the test flags, which we do not want in non-test binaries even if
|
||||||
// they make use of these utilities for some reason).
|
// they make use of these utilities for some reason).
|
||||||
T interface {
|
T interface {
|
||||||
Fatal(args ...interface{})
|
Errorf(format string, args ...interface{})
|
||||||
Fatalf(format string, args ...interface{})
|
FailNow()
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -105,9 +105,7 @@ func (t temporaryDirectory) Close() {
|
||||||
err = os.RemoveAll(t.path)
|
err = os.RemoveAll(t.path)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if err != nil {
|
require.NoError(t.tester, err)
|
||||||
t.tester.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t temporaryDirectory) Path() string {
|
func (t temporaryDirectory) Path() string {
|
||||||
|
@ -123,9 +121,7 @@ func NewTemporaryDirectory(name string, t T) (handler TemporaryDirectory) {
|
||||||
)
|
)
|
||||||
|
|
||||||
directory, err = ioutil.TempDir(defaultDirectory, name)
|
directory, err = ioutil.TempDir(defaultDirectory, name)
|
||||||
if err != nil {
|
require.NoError(t, err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
handler = temporaryDirectory{
|
handler = temporaryDirectory{
|
||||||
path: directory,
|
path: directory,
|
||||||
|
|
Loading…
Reference in a new issue