Move away from testutil, refactor imports (#8087)

Signed-off-by: Julien Pivotto <roidelapluie@inuits.eu>
This commit is contained in:
Julien Pivotto 2020-10-22 11:00:08 +02:00 committed by GitHub
parent c5a832b394
commit 4e5b1722b3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
163 changed files with 7645 additions and 3610 deletions

View file

@ -44,6 +44,7 @@ import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/model"
"github.com/prometheus/common/promlog"
promlogflag "github.com/prometheus/common/promlog/flag"
"github.com/prometheus/common/version"
jcfg "github.com/uber/jaeger-client-go/config"
jprom "github.com/uber/jaeger-lib/metrics/prometheus"
@ -52,9 +53,9 @@ import (
klog "k8s.io/klog"
klogv2 "k8s.io/klog/v2"
promlogflag "github.com/prometheus/common/promlog/flag"
"github.com/prometheus/prometheus/config"
"github.com/prometheus/prometheus/discovery"
_ "github.com/prometheus/prometheus/discovery/install" // Register service discovery implementations.
"github.com/prometheus/prometheus/notifier"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/pkg/logging"
@ -68,8 +69,6 @@ import (
"github.com/prometheus/prometheus/tsdb"
"github.com/prometheus/prometheus/util/strutil"
"github.com/prometheus/prometheus/web"
_ "github.com/prometheus/prometheus/discovery/install" // Register service discovery implementations.
)
var (

View file

@ -28,10 +28,11 @@ import (
"github.com/go-kit/kit/log"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/assert"
"github.com/prometheus/prometheus/notifier"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/rules"
"github.com/prometheus/prometheus/util/testutil"
)
var promPath = os.Args[0]
@ -97,9 +98,9 @@ func TestComputeExternalURL(t *testing.T) {
for _, test := range tests {
_, err := computeExternalURL(test.input, "0.0.0.0:9090")
if test.valid {
testutil.Ok(t, err)
assert.NoError(t, err)
} else {
testutil.NotOk(t, err, "input=%q", test.input)
assert.Error(t, err, "input=%q", test.input)
}
}
}
@ -115,11 +116,11 @@ func TestFailedStartupExitCode(t *testing.T) {
prom := exec.Command(promPath, "-test.main", "--config.file="+fakeInputFile)
err := prom.Run()
testutil.NotOk(t, err)
assert.Error(t, err)
if exitError, ok := err.(*exec.ExitError); ok {
status := exitError.Sys().(syscall.WaitStatus)
testutil.Equals(t, expectedExitStatus, status.ExitStatus())
assert.Equal(t, expectedExitStatus, status.ExitStatus())
} else {
t.Errorf("unable to retrieve the exit status for prometheus: %v", err)
}
@ -188,7 +189,7 @@ func TestSendAlerts(t *testing.T) {
if len(tc.in) == 0 {
t.Fatalf("sender called with 0 alert")
}
testutil.Equals(t, tc.exp, alerts)
assert.Equal(t, tc.exp, alerts)
})
sendAlerts(senderFunc, "http://localhost:9090")(context.TODO(), "up", tc.in...)
})
@ -205,14 +206,14 @@ func TestWALSegmentSizeBounds(t *testing.T) {
// Log stderr in case of failure.
stderr, err := prom.StderrPipe()
testutil.Ok(t, err)
assert.NoError(t, err)
go func() {
slurp, _ := ioutil.ReadAll(stderr)
t.Log(string(slurp))
}()
err = prom.Start()
testutil.Ok(t, err)
assert.NoError(t, err)
if expectedExitStatus == 0 {
done := make(chan error, 1)
@ -227,10 +228,10 @@ func TestWALSegmentSizeBounds(t *testing.T) {
}
err = prom.Wait()
testutil.NotOk(t, err)
assert.Error(t, err)
if exitError, ok := err.(*exec.ExitError); ok {
status := exitError.Sys().(syscall.WaitStatus)
testutil.Equals(t, expectedExitStatus, status.ExitStatus())
assert.Equal(t, expectedExitStatus, status.ExitStatus())
} else {
t.Errorf("unable to retrieve the exit status for prometheus: %v", err)
}
@ -239,21 +240,21 @@ func TestWALSegmentSizeBounds(t *testing.T) {
func TestTimeMetrics(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "time_metrics_e2e")
testutil.Ok(t, err)
assert.NoError(t, err)
defer func() {
testutil.Ok(t, os.RemoveAll(tmpDir))
assert.NoError(t, os.RemoveAll(tmpDir))
}()
reg := prometheus.NewRegistry()
db, err := openDBWithMetrics(tmpDir, log.NewNopLogger(), reg, nil)
testutil.Ok(t, err)
assert.NoError(t, err)
defer func() {
testutil.Ok(t, db.Close())
assert.NoError(t, db.Close())
}()
// Check initial values.
testutil.Equals(t, map[string]float64{
assert.Equal(t, map[string]float64{
"prometheus_tsdb_lowest_timestamp_seconds": float64(math.MaxInt64) / 1000,
"prometheus_tsdb_head_min_time_seconds": float64(math.MaxInt64) / 1000,
"prometheus_tsdb_head_max_time_seconds": float64(math.MinInt64) / 1000,
@ -265,14 +266,14 @@ func TestTimeMetrics(t *testing.T) {
app := db.Appender(context.Background())
_, err = app.Add(labels.FromStrings(model.MetricNameLabel, "a"), 1000, 1)
testutil.Ok(t, err)
assert.NoError(t, err)
_, err = app.Add(labels.FromStrings(model.MetricNameLabel, "a"), 2000, 1)
testutil.Ok(t, err)
assert.NoError(t, err)
_, err = app.Add(labels.FromStrings(model.MetricNameLabel, "a"), 3000, 1)
testutil.Ok(t, err)
testutil.Ok(t, app.Commit())
assert.NoError(t, err)
assert.NoError(t, app.Commit())
testutil.Equals(t, map[string]float64{
assert.Equal(t, map[string]float64{
"prometheus_tsdb_lowest_timestamp_seconds": 1.0,
"prometheus_tsdb_head_min_time_seconds": 1.0,
"prometheus_tsdb_head_max_time_seconds": 3.0,
@ -285,7 +286,7 @@ func TestTimeMetrics(t *testing.T) {
func getCurrentGaugeValuesFor(t *testing.T, reg prometheus.Gatherer, metricNames ...string) map[string]float64 {
f, err := reg.Gather()
testutil.Ok(t, err)
assert.NoError(t, err)
res := make(map[string]float64, len(metricNames))
for _, g := range f {
@ -294,7 +295,7 @@ func getCurrentGaugeValuesFor(t *testing.T, reg prometheus.Gatherer, metricNames
continue
}
testutil.Equals(t, 1, len(g.GetMetric()))
assert.Equal(t, 1, len(g.GetMetric()))
if _, ok := res[m]; ok {
t.Error("expected only one metric family for", m)
t.FailNow()

View file

@ -30,7 +30,7 @@ import (
"testing"
"time"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
)
type origin int
@ -82,22 +82,22 @@ func (p *queryLogTest) waitForPrometheus() error {
// then reloads the configuration if needed.
func (p *queryLogTest) setQueryLog(t *testing.T, queryLogFile string) {
err := p.configFile.Truncate(0)
testutil.Ok(t, err)
assert.NoError(t, err)
_, err = p.configFile.Seek(0, 0)
testutil.Ok(t, err)
assert.NoError(t, err)
if queryLogFile != "" {
_, err = p.configFile.Write([]byte(fmt.Sprintf("global:\n query_log_file: %s\n", queryLogFile)))
testutil.Ok(t, err)
assert.NoError(t, err)
}
_, err = p.configFile.Write([]byte(p.configuration()))
testutil.Ok(t, err)
assert.NoError(t, err)
}
// reloadConfig reloads the configuration using POST.
func (p *queryLogTest) reloadConfig(t *testing.T) {
r, err := http.Post(fmt.Sprintf("http://%s:%d%s/-/reload", p.host, p.port, p.prefix), "text/plain", nil)
testutil.Ok(t, err)
testutil.Equals(t, 200, r.StatusCode)
assert.NoError(t, err)
assert.Equal(t, 200, r.StatusCode)
}
// query runs a query according to the test origin.
@ -111,8 +111,8 @@ func (p *queryLogTest) query(t *testing.T) {
p.prefix,
url.QueryEscape("query_with_api"),
))
testutil.Ok(t, err)
testutil.Equals(t, 200, r.StatusCode)
assert.NoError(t, err)
assert.Equal(t, 200, r.StatusCode)
case consoleOrigin:
r, err := http.Get(fmt.Sprintf(
"http://%s:%d%s/consoles/test.html",
@ -120,8 +120,8 @@ func (p *queryLogTest) query(t *testing.T) {
p.port,
p.prefix,
))
testutil.Ok(t, err)
testutil.Equals(t, 200, r.StatusCode)
assert.NoError(t, err)
assert.Equal(t, 200, r.StatusCode)
case ruleOrigin:
time.Sleep(2 * time.Second)
default:
@ -147,15 +147,15 @@ func (p *queryLogTest) queryString() string {
// test parameters.
func (p *queryLogTest) validateLastQuery(t *testing.T, ql []queryLogLine) {
q := ql[len(ql)-1]
testutil.Equals(t, p.queryString(), q.Params.Query)
assert.Equal(t, p.queryString(), q.Params.Query)
switch p.origin {
case apiOrigin:
testutil.Equals(t, 5, q.Params.Step)
testutil.Equals(t, "1970-01-01T00:00:00.000Z", q.Params.Start)
testutil.Equals(t, "1970-01-01T01:00:00.000Z", q.Params.End)
assert.Equal(t, 5, q.Params.Step)
assert.Equal(t, "1970-01-01T00:00:00.000Z", q.Params.Start)
assert.Equal(t, "1970-01-01T01:00:00.000Z", q.Params.End)
default:
testutil.Equals(t, 0, q.Params.Step)
assert.Equal(t, 0, q.Params.Step)
}
if p.origin != ruleOrigin {
@ -163,17 +163,17 @@ func (p *queryLogTest) validateLastQuery(t *testing.T, ql []queryLogLine) {
if host == "[::1]" {
host = "::1"
}
testutil.Equals(t, host, q.Request.ClientIP)
assert.Equal(t, host, q.Request.ClientIP)
}
switch p.origin {
case apiOrigin:
testutil.Equals(t, p.prefix+"/api/v1/query_range", q.Request.Path)
assert.Equal(t, p.prefix+"/api/v1/query_range", q.Request.Path)
case consoleOrigin:
testutil.Equals(t, p.prefix+"/consoles/test.html", q.Request.Path)
assert.Equal(t, p.prefix+"/consoles/test.html", q.Request.Path)
case ruleOrigin:
testutil.Equals(t, "querylogtest", q.RuleGroup.Name)
testutil.Equals(t, filepath.Join(p.cwd, "testdata", "rules", "test.yml"), q.RuleGroup.File)
assert.Equal(t, "querylogtest", q.RuleGroup.Name)
assert.Equal(t, filepath.Join(p.cwd, "testdata", "rules", "test.yml"), q.RuleGroup.File)
default:
panic("unknown origin")
}
@ -234,10 +234,10 @@ func (p *queryLogTest) run(t *testing.T) {
// Setup temporary files for this test.
queryLogFile, err := ioutil.TempFile("", "query")
testutil.Ok(t, err)
assert.NoError(t, err)
defer os.Remove(queryLogFile.Name())
p.configFile, err = ioutil.TempFile("", "config")
testutil.Ok(t, err)
assert.NoError(t, err)
defer os.Remove(p.configFile.Name())
if p.enabledAtStart {
@ -247,9 +247,9 @@ func (p *queryLogTest) run(t *testing.T) {
}
dir, err := ioutil.TempDir("", "query_log_test")
testutil.Ok(t, err)
assert.NoError(t, err)
defer func() {
testutil.Ok(t, os.RemoveAll(dir))
assert.NoError(t, os.RemoveAll(dir))
}()
params := append([]string{
@ -264,7 +264,7 @@ func (p *queryLogTest) run(t *testing.T) {
// Log stderr in case of failure.
stderr, err := prom.StderrPipe()
testutil.Ok(t, err)
assert.NoError(t, err)
// We use a WaitGroup to avoid calling t.Log after the test is done.
var wg sync.WaitGroup
@ -276,17 +276,17 @@ func (p *queryLogTest) run(t *testing.T) {
wg.Done()
}()
testutil.Ok(t, prom.Start())
assert.NoError(t, prom.Start())
defer func() {
prom.Process.Kill()
prom.Wait()
}()
testutil.Ok(t, p.waitForPrometheus())
assert.NoError(t, p.waitForPrometheus())
if !p.enabledAtStart {
p.query(t)
testutil.Equals(t, 0, len(readQueryLog(t, queryLogFile.Name())))
assert.Equal(t, 0, len(readQueryLog(t, queryLogFile.Name())))
p.setQueryLog(t, queryLogFile.Name())
p.reloadConfig(t)
}
@ -296,9 +296,9 @@ func (p *queryLogTest) run(t *testing.T) {
ql := readQueryLog(t, queryLogFile.Name())
qc := len(ql)
if p.exactQueryCount() {
testutil.Equals(t, 1, qc)
assert.Equal(t, 1, qc)
} else {
testutil.Assert(t, qc > 0, "no queries logged")
assert.True(t, qc > 0, "no queries logged")
}
p.validateLastQuery(t, ql)
@ -311,7 +311,7 @@ func (p *queryLogTest) run(t *testing.T) {
p.query(t)
ql = readQueryLog(t, queryLogFile.Name())
testutil.Equals(t, qc, len(ql))
assert.Equal(t, qc, len(ql))
qc = len(ql)
p.setQueryLog(t, queryLogFile.Name())
@ -322,9 +322,9 @@ func (p *queryLogTest) run(t *testing.T) {
ql = readQueryLog(t, queryLogFile.Name())
if p.exactQueryCount() {
testutil.Equals(t, qc, len(ql))
assert.Equal(t, qc, len(ql))
} else {
testutil.Assert(t, len(ql) > qc, "no queries logged")
assert.True(t, len(ql) > qc, "no queries logged")
}
p.validateLastQuery(t, ql)
qc = len(ql)
@ -336,13 +336,13 @@ func (p *queryLogTest) run(t *testing.T) {
}
// Move the file, Prometheus should still write to the old file.
newFile, err := ioutil.TempFile("", "newLoc")
testutil.Ok(t, err)
testutil.Ok(t, newFile.Close())
assert.NoError(t, err)
assert.NoError(t, newFile.Close())
defer os.Remove(newFile.Name())
testutil.Ok(t, os.Rename(queryLogFile.Name(), newFile.Name()))
assert.NoError(t, os.Rename(queryLogFile.Name(), newFile.Name()))
ql = readQueryLog(t, newFile.Name())
if p.exactQueryCount() {
testutil.Equals(t, qc, len(ql))
assert.Equal(t, qc, len(ql))
}
p.validateLastQuery(t, ql)
qc = len(ql)
@ -353,9 +353,9 @@ func (p *queryLogTest) run(t *testing.T) {
ql = readQueryLog(t, newFile.Name())
if p.exactQueryCount() {
testutil.Equals(t, qc, len(ql))
assert.Equal(t, qc, len(ql))
} else {
testutil.Assert(t, len(ql) > qc, "no queries logged")
assert.True(t, len(ql) > qc, "no queries logged")
}
p.validateLastQuery(t, ql)
@ -366,9 +366,9 @@ func (p *queryLogTest) run(t *testing.T) {
ql = readQueryLog(t, queryLogFile.Name())
qc = len(ql)
if p.exactQueryCount() {
testutil.Equals(t, 1, qc)
assert.Equal(t, 1, qc)
} else {
testutil.Assert(t, qc > 0, "no queries logged")
assert.True(t, qc > 0, "no queries logged")
}
}
@ -393,12 +393,12 @@ type queryLogLine struct {
func readQueryLog(t *testing.T, path string) []queryLogLine {
ql := []queryLogLine{}
file, err := os.Open(path)
testutil.Ok(t, err)
assert.NoError(t, err)
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
var q queryLogLine
testutil.Ok(t, json.Unmarshal(scanner.Bytes(), &q))
assert.NoError(t, json.Unmarshal(scanner.Bytes(), &q))
ql = append(ql, q)
}
return ql
@ -410,7 +410,7 @@ func TestQueryLog(t *testing.T) {
}
cwd, err := os.Getwd()
testutil.Ok(t, err)
assert.NoError(t, err)
port := 15000
for _, host := range []string{"127.0.0.1", "[::1]"} {

View file

@ -41,10 +41,9 @@ import (
"github.com/prometheus/prometheus/config"
"github.com/prometheus/prometheus/discovery/file"
_ "github.com/prometheus/prometheus/discovery/install" // Register service discovery implementations.
"github.com/prometheus/prometheus/discovery/kubernetes"
"github.com/prometheus/prometheus/pkg/rulefmt"
_ "github.com/prometheus/prometheus/discovery/install" // Register service discovery implementations.
)
func main() {

View file

@ -20,7 +20,7 @@ import (
"testing"
"time"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
)
func TestQueryRange(t *testing.T) {
@ -29,18 +29,18 @@ func TestQueryRange(t *testing.T) {
p := &promqlPrinter{}
exitCode := QueryRange(s.URL, map[string]string{}, "up", "0", "300", 0, p)
testutil.Equals(t, "/api/v1/query_range", getRequest().URL.Path)
assert.Equal(t, "/api/v1/query_range", getRequest().URL.Path)
form := getRequest().Form
testutil.Equals(t, "up", form.Get("query"))
testutil.Equals(t, "1", form.Get("step"))
testutil.Equals(t, 0, exitCode)
assert.Equal(t, "up", form.Get("query"))
assert.Equal(t, "1", form.Get("step"))
assert.Equal(t, 0, exitCode)
exitCode = QueryRange(s.URL, map[string]string{}, "up", "0", "300", 10*time.Millisecond, p)
testutil.Equals(t, "/api/v1/query_range", getRequest().URL.Path)
assert.Equal(t, "/api/v1/query_range", getRequest().URL.Path)
form = getRequest().Form
testutil.Equals(t, "up", form.Get("query"))
testutil.Equals(t, "0.01", form.Get("step"))
testutil.Equals(t, 0, exitCode)
assert.Equal(t, "up", form.Get("query"))
assert.Equal(t, "0.01", form.Get("step"))
assert.Equal(t, 0, exitCode)
}
func TestQueryInstant(t *testing.T) {
@ -49,11 +49,11 @@ func TestQueryInstant(t *testing.T) {
p := &promqlPrinter{}
exitCode := QueryInstant(s.URL, "up", "300", p)
testutil.Equals(t, "/api/v1/query", getRequest().URL.Path)
assert.Equal(t, "/api/v1/query", getRequest().URL.Path)
form := getRequest().Form
testutil.Equals(t, "up", form.Get("query"))
testutil.Equals(t, "300", form.Get("time"))
testutil.Equals(t, 0, exitCode)
assert.Equal(t, "up", form.Get("query"))
assert.Equal(t, "300", form.Get("time"))
assert.Equal(t, 0, exitCode)
}
func mockServer(code int, body string) (*httptest.Server, func() *http.Request) {

View file

@ -33,6 +33,7 @@ import (
"github.com/alecthomas/units"
"github.com/go-kit/kit/log"
"github.com/pkg/errors"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/storage"
"github.com/prometheus/prometheus/tsdb"

View file

@ -27,9 +27,9 @@ import (
"github.com/go-kit/kit/log"
"github.com/pkg/errors"
"github.com/prometheus/common/model"
yaml "gopkg.in/yaml.v2"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/promql"
"github.com/prometheus/prometheus/promql/parser"

View file

@ -25,6 +25,7 @@ import (
"github.com/prometheus/common/config"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/assert"
"gopkg.in/yaml.v2"
"github.com/prometheus/prometheus/discovery"
@ -45,7 +46,6 @@ import (
"github.com/prometheus/prometheus/discovery/zookeeper"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/pkg/relabel"
"github.com/prometheus/prometheus/util/testutil"
)
func mustParseURL(u string) *config.URL {
@ -720,77 +720,77 @@ var expectedConf = &Config{
func TestYAMLRoundtrip(t *testing.T) {
want, err := LoadFile("testdata/roundtrip.good.yml")
testutil.Ok(t, err)
assert.NoError(t, err)
out, err := yaml.Marshal(want)
testutil.Ok(t, err)
assert.NoError(t, err)
got := &Config{}
testutil.Ok(t, yaml.UnmarshalStrict(out, got))
assert.NoError(t, yaml.UnmarshalStrict(out, got))
testutil.Equals(t, want, got)
assert.Equal(t, want, got)
}
func TestLoadConfig(t *testing.T) {
// Parse a valid file that sets a global scrape timeout. This tests whether parsing
// an overwritten default field in the global config permanently changes the default.
_, err := LoadFile("testdata/global_timeout.good.yml")
testutil.Ok(t, err)
assert.NoError(t, err)
c, err := LoadFile("testdata/conf.good.yml")
testutil.Ok(t, err)
testutil.Equals(t, expectedConf, c)
assert.NoError(t, err)
assert.Equal(t, expectedConf, c)
}
func TestScrapeIntervalLarger(t *testing.T) {
c, err := LoadFile("testdata/scrape_interval_larger.good.yml")
testutil.Ok(t, err)
testutil.Equals(t, 1, len(c.ScrapeConfigs))
assert.NoError(t, err)
assert.Equal(t, 1, len(c.ScrapeConfigs))
for _, sc := range c.ScrapeConfigs {
testutil.Equals(t, true, sc.ScrapeInterval >= sc.ScrapeTimeout)
assert.Equal(t, true, sc.ScrapeInterval >= sc.ScrapeTimeout)
}
}
// YAML marshaling must not reveal authentication credentials.
func TestElideSecrets(t *testing.T) {
c, err := LoadFile("testdata/conf.good.yml")
testutil.Ok(t, err)
assert.NoError(t, err)
secretRe := regexp.MustCompile(`\\u003csecret\\u003e|<secret>`)
config, err := yaml.Marshal(c)
testutil.Ok(t, err)
assert.NoError(t, err)
yamlConfig := string(config)
matches := secretRe.FindAllStringIndex(yamlConfig, -1)
testutil.Assert(t, len(matches) == 10, "wrong number of secret matches found")
testutil.Assert(t, !strings.Contains(yamlConfig, "mysecret"),
assert.True(t, len(matches) == 10, "wrong number of secret matches found")
assert.True(t, !strings.Contains(yamlConfig, "mysecret"),
"yaml marshal reveals authentication credentials.")
}
func TestLoadConfigRuleFilesAbsolutePath(t *testing.T) {
// Parse a valid file that sets a rule files with an absolute path
c, err := LoadFile(ruleFilesConfigFile)
testutil.Ok(t, err)
testutil.Equals(t, ruleFilesExpectedConf, c)
assert.NoError(t, err)
assert.Equal(t, ruleFilesExpectedConf, c)
}
func TestKubernetesEmptyAPIServer(t *testing.T) {
_, err := LoadFile("testdata/kubernetes_empty_apiserver.good.yml")
testutil.Ok(t, err)
assert.NoError(t, err)
}
func TestKubernetesSelectors(t *testing.T) {
_, err := LoadFile("testdata/kubernetes_selectors_endpoints.good.yml")
testutil.Ok(t, err)
assert.NoError(t, err)
_, err = LoadFile("testdata/kubernetes_selectors_node.good.yml")
testutil.Ok(t, err)
assert.NoError(t, err)
_, err = LoadFile("testdata/kubernetes_selectors_ingress.good.yml")
testutil.Ok(t, err)
assert.NoError(t, err)
_, err = LoadFile("testdata/kubernetes_selectors_pod.good.yml")
testutil.Ok(t, err)
assert.NoError(t, err)
_, err = LoadFile("testdata/kubernetes_selectors_service.good.yml")
testutil.Ok(t, err)
assert.NoError(t, err)
}
var expectedErrors = []struct {
@ -1026,40 +1026,40 @@ var expectedErrors = []struct {
func TestBadConfigs(t *testing.T) {
for _, ee := range expectedErrors {
_, err := LoadFile("testdata/" + ee.filename)
testutil.NotOk(t, err, "%s", ee.filename)
testutil.Assert(t, strings.Contains(err.Error(), ee.errMsg),
assert.Error(t, err, "%s", ee.filename)
assert.True(t, strings.Contains(err.Error(), ee.errMsg),
"Expected error for %s to contain %q but got: %s", ee.filename, ee.errMsg, err)
}
}
func TestBadStaticConfigsJSON(t *testing.T) {
content, err := ioutil.ReadFile("testdata/static_config.bad.json")
testutil.Ok(t, err)
assert.NoError(t, err)
var tg targetgroup.Group
err = json.Unmarshal(content, &tg)
testutil.NotOk(t, err)
assert.Error(t, err)
}
func TestBadStaticConfigsYML(t *testing.T) {
content, err := ioutil.ReadFile("testdata/static_config.bad.yml")
testutil.Ok(t, err)
assert.NoError(t, err)
var tg targetgroup.Group
err = yaml.UnmarshalStrict(content, &tg)
testutil.NotOk(t, err)
assert.Error(t, err)
}
func TestEmptyConfig(t *testing.T) {
c, err := Load("")
testutil.Ok(t, err)
assert.NoError(t, err)
exp := DefaultConfig
testutil.Equals(t, exp, *c)
assert.Equal(t, exp, *c)
}
func TestEmptyGlobalBlock(t *testing.T) {
c, err := Load("global:\n")
testutil.Ok(t, err)
assert.NoError(t, err)
exp := DefaultConfig
testutil.Equals(t, exp, *c)
assert.Equal(t, exp, *c)
}
func kubernetesSDHostURL() config.URL {

View file

@ -14,10 +14,10 @@
package azure
import (
"reflect"
"testing"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute"
"github.com/stretchr/testify/assert"
"go.uber.org/goleak"
)
@ -63,9 +63,7 @@ func TestMapFromVMWithEmptyTags(t *testing.T) {
actualVM := mapFromVM(testVM)
if !reflect.DeepEqual(expectedVM, actualVM) {
t.Errorf("Expected %v got %v", expectedVM, actualVM)
}
assert.Equal(t, expectedVM, actualVM)
}
func TestMapFromVMWithTags(t *testing.T) {
@ -109,9 +107,7 @@ func TestMapFromVMWithTags(t *testing.T) {
actualVM := mapFromVM(testVM)
if !reflect.DeepEqual(expectedVM, actualVM) {
t.Errorf("Expected %v got %v", expectedVM, actualVM)
}
assert.Equal(t, expectedVM, actualVM)
}
func TestMapFromVMScaleSetVMWithEmptyTags(t *testing.T) {
@ -154,9 +150,7 @@ func TestMapFromVMScaleSetVMWithEmptyTags(t *testing.T) {
actualVM := mapFromVMScaleSetVM(testVM, scaleSet)
if !reflect.DeepEqual(expectedVM, actualVM) {
t.Errorf("Expected %v got %v", expectedVM, actualVM)
}
assert.Equal(t, expectedVM, actualVM)
}
func TestMapFromVMScaleSetVMWithTags(t *testing.T) {
@ -202,9 +196,7 @@ func TestMapFromVMScaleSetVMWithTags(t *testing.T) {
actualVM := mapFromVMScaleSetVM(testVM, scaleSet)
if !reflect.DeepEqual(expectedVM, actualVM) {
t.Errorf("Expected %v got %v", expectedVM, actualVM)
}
assert.Equal(t, expectedVM, actualVM)
}
func TestNewAzureResourceFromID(t *testing.T) {
@ -222,8 +214,6 @@ func TestNewAzureResourceFromID(t *testing.T) {
},
} {
actual, _ := newAzureResourceFromID(tc.id, nil)
if !reflect.DeepEqual(tc.expected, actual) {
t.Errorf("Expected %v got %v", tc.expected, actual)
}
assert.Equal(t, tc.expected, actual)
}
}

View file

@ -15,18 +15,18 @@ package consul
import (
"context"
"testing"
"time"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"
"github.com/go-kit/kit/log"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/discovery/targetgroup"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
"go.uber.org/goleak"
"github.com/prometheus/prometheus/discovery/targetgroup"
)
func TestMain(m *testing.M) {
@ -251,7 +251,7 @@ func newServer(t *testing.T) (*httptest.Server, *SDConfig) {
w.Write([]byte(response))
}))
stuburl, err := url.Parse(stub.URL)
testutil.Ok(t, err)
assert.NoError(t, err)
config := &SDConfig{
Server: stuburl.Host,
@ -264,18 +264,18 @@ func newServer(t *testing.T) (*httptest.Server, *SDConfig) {
func newDiscovery(t *testing.T, config *SDConfig) *Discovery {
logger := log.NewNopLogger()
d, err := NewDiscovery(config, logger)
testutil.Ok(t, err)
assert.NoError(t, err)
return d
}
func checkOneTarget(t *testing.T, tg []*targetgroup.Group) {
testutil.Equals(t, 1, len(tg))
assert.Equal(t, 1, len(tg))
target := tg[0]
testutil.Equals(t, "test-dc", string(target.Labels["__meta_consul_dc"]))
testutil.Equals(t, target.Source, string(target.Labels["__meta_consul_service"]))
assert.Equal(t, "test-dc", string(target.Labels["__meta_consul_dc"]))
assert.Equal(t, target.Source, string(target.Labels["__meta_consul_service"]))
if target.Source == "test" {
// test service should have one node.
testutil.Assert(t, len(target.Targets) > 0, "Test service should have one node")
assert.True(t, len(target.Targets) > 0, "Test service should have one node")
}
}
@ -359,7 +359,7 @@ func TestGetDatacenterShouldReturnError(t *testing.T) {
} {
stub := httptest.NewServer(http.HandlerFunc(tc.handler))
stuburl, err := url.Parse(stub.URL)
testutil.Ok(t, err)
assert.NoError(t, err)
config := &SDConfig{
Server: stuburl.Host,
@ -370,13 +370,13 @@ func TestGetDatacenterShouldReturnError(t *testing.T) {
d := newDiscovery(t, config)
// Should be empty if not initialized.
testutil.Equals(t, "", d.clientDatacenter)
assert.Equal(t, "", d.clientDatacenter)
err = d.getDatacenter()
// An error should be returned.
testutil.Equals(t, tc.errMessage, err.Error())
assert.Equal(t, tc.errMessage, err.Error())
// Should still be empty.
testutil.Equals(t, "", d.clientDatacenter)
assert.Equal(t, "", d.clientDatacenter)
}
}

View file

@ -21,7 +21,7 @@ import (
"github.com/go-kit/kit/log"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
)
type DigitalOceanSDTestSuite struct {
@ -47,21 +47,21 @@ func TestDigitalOceanSDRefresh(t *testing.T) {
cfg := DefaultSDConfig
cfg.HTTPClientConfig.BearerToken = tokenID
d, err := NewDiscovery(&cfg, log.NewNopLogger())
testutil.Ok(t, err)
assert.NoError(t, err)
endpoint, err := url.Parse(sdmock.Mock.Endpoint())
testutil.Ok(t, err)
assert.NoError(t, err)
d.client.BaseURL = endpoint
ctx := context.Background()
tgs, err := d.refresh(ctx)
testutil.Ok(t, err)
assert.NoError(t, err)
testutil.Equals(t, 1, len(tgs))
assert.Equal(t, 1, len(tgs))
tg := tgs[0]
testutil.Assert(t, tg != nil, "tg should not be nil")
testutil.Assert(t, tg.Targets != nil, "tg.targets should not be nil")
testutil.Equals(t, 4, len(tg.Targets))
assert.NotNil(t, tg)
assert.NotNil(t, tg.Targets)
assert.Equal(t, 4, len(tg.Targets))
for i, lbls := range []model.LabelSet{
{
@ -119,7 +119,7 @@ func TestDigitalOceanSDRefresh(t *testing.T) {
},
} {
t.Run(fmt.Sprintf("item %d", i), func(t *testing.T) {
testutil.Equals(t, lbls, tg.Targets[i])
assert.Equal(t, lbls, tg.Targets[i])
})
}
}

View file

@ -18,8 +18,8 @@ import (
"reflect"
"github.com/go-kit/kit/log"
"github.com/prometheus/common/config"
"github.com/prometheus/prometheus/discovery/targetgroup"
)

View file

@ -22,12 +22,12 @@ import (
"github.com/go-kit/kit/log"
"github.com/miekg/dns"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/assert"
"go.uber.org/goleak"
"gopkg.in/yaml.v2"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/discovery/targetgroup"
"github.com/prometheus/prometheus/util/testutil"
)
func TestMain(m *testing.M) {
@ -205,8 +205,8 @@ func TestDNS(t *testing.T) {
sd.lookupFn = tc.lookup
tgs, err := sd.refresh(context.Background())
testutil.Ok(t, err)
testutil.Equals(t, tc.expected, tgs)
assert.NoError(t, err)
assert.Equal(t, tc.expected, tgs)
})
}
}
@ -296,7 +296,7 @@ func TestSDConfigUnmarshalYAML(t *testing.T) {
var config SDConfig
d := marshal(c.input)
err := config.UnmarshalYAML(unmarshal(d))
testutil.Equals(t, c.expectErr, err != nil)
assert.Equal(t, c.expectErr, err != nil)
})
}
}

View file

@ -23,9 +23,10 @@ import (
"strings"
"testing"
"github.com/prometheus/prometheus/util/strutil"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
"gopkg.in/yaml.v2"
"github.com/prometheus/prometheus/util/strutil"
)
// SDMock is the interface for the DigitalOcean mock
@ -63,7 +64,7 @@ func (m *SDMock) Setup() {
func (m *SDMock) SetupHandlers() {
headers := make(map[string]string)
rawHeaders, err := ioutil.ReadFile(filepath.Join("testdata", m.directory, "headers.yml"))
testutil.Ok(m.t, err)
assert.NoError(m.t, err)
yaml.Unmarshal(rawHeaders, &headers)
prefix := "/"

View file

@ -18,6 +18,7 @@ import (
"fmt"
"github.com/docker/docker/api/types"
"github.com/prometheus/prometheus/util/strutil"
)

View file

@ -20,7 +20,7 @@ import (
"github.com/go-kit/kit/log"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
"gopkg.in/yaml.v2"
)
@ -36,21 +36,21 @@ role: nodes
host: %s
`, url)
var cfg SDConfig
testutil.Ok(t, yaml.Unmarshal([]byte(cfgString), &cfg))
assert.NoError(t, yaml.Unmarshal([]byte(cfgString), &cfg))
d, err := NewDiscovery(&cfg, log.NewNopLogger())
testutil.Ok(t, err)
assert.NoError(t, err)
ctx := context.Background()
tgs, err := d.refresh(ctx)
testutil.Ok(t, err)
assert.NoError(t, err)
testutil.Equals(t, 1, len(tgs))
assert.Equal(t, 1, len(tgs))
tg := tgs[0]
testutil.Assert(t, tg != nil, "tg should not be nil")
testutil.Assert(t, tg.Targets != nil, "tg.targets should not be nil")
testutil.Equals(t, 5, len(tg.Targets))
assert.NotNil(t, tg)
assert.NotNil(t, tg.Targets)
assert.Equal(t, 5, len(tg.Targets))
for i, lbls := range []model.LabelSet{
{
@ -124,7 +124,7 @@ host: %s
},
} {
t.Run(fmt.Sprintf("item %d", i), func(t *testing.T) {
testutil.Equals(t, lbls, tg.Targets[i])
assert.Equal(t, lbls, tg.Targets[i])
})
}
}

View file

@ -20,7 +20,7 @@ import (
"github.com/go-kit/kit/log"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
"gopkg.in/yaml.v2"
)
@ -36,21 +36,21 @@ role: services
host: %s
`, url)
var cfg SDConfig
testutil.Ok(t, yaml.Unmarshal([]byte(cfgString), &cfg))
assert.NoError(t, yaml.Unmarshal([]byte(cfgString), &cfg))
d, err := NewDiscovery(&cfg, log.NewNopLogger())
testutil.Ok(t, err)
assert.NoError(t, err)
ctx := context.Background()
tgs, err := d.refresh(ctx)
testutil.Ok(t, err)
assert.NoError(t, err)
testutil.Equals(t, 1, len(tgs))
assert.Equal(t, 1, len(tgs))
tg := tgs[0]
testutil.Assert(t, tg != nil, "tg should not be nil")
testutil.Assert(t, tg.Targets != nil, "tg.targets should not be nil")
testutil.Equals(t, 15, len(tg.Targets))
assert.NotNil(t, tg)
assert.NotNil(t, tg.Targets)
assert.Equal(t, 15, len(tg.Targets))
for i, lbls := range []model.LabelSet{
{
@ -310,7 +310,7 @@ host: %s
},
} {
t.Run(fmt.Sprintf("item %d", i), func(t *testing.T) {
testutil.Equals(t, lbls, tg.Targets[i])
assert.Equal(t, lbls, tg.Targets[i])
})
}
}

View file

@ -20,7 +20,7 @@ import (
"github.com/go-kit/kit/log"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
"gopkg.in/yaml.v2"
)
@ -36,21 +36,21 @@ role: tasks
host: %s
`, url)
var cfg SDConfig
testutil.Ok(t, yaml.Unmarshal([]byte(cfgString), &cfg))
assert.NoError(t, yaml.Unmarshal([]byte(cfgString), &cfg))
d, err := NewDiscovery(&cfg, log.NewNopLogger())
testutil.Ok(t, err)
assert.NoError(t, err)
ctx := context.Background()
tgs, err := d.refresh(ctx)
testutil.Ok(t, err)
assert.NoError(t, err)
testutil.Equals(t, 1, len(tgs))
assert.Equal(t, 1, len(tgs))
tg := tgs[0]
testutil.Assert(t, tg != nil, "tg should not be nil")
testutil.Assert(t, tg.Targets != nil, "tg.targets should not be nil")
testutil.Equals(t, 27, len(tg.Targets))
assert.NotNil(t, tg)
assert.NotNil(t, tg.Targets)
assert.Equal(t, 27, len(tg.Targets))
for i, lbls := range []model.LabelSet{
{
@ -787,7 +787,7 @@ host: %s
},
} {
t.Run(fmt.Sprintf("item %d", i), func(t *testing.T) {
testutil.Equals(t, lbls, tg.Targets[i])
assert.Equal(t, lbls, tg.Targets[i])
})
}
}

View file

@ -20,7 +20,7 @@ import (
"net/http/httptest"
"testing"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
)
func TestFetchApps(t *testing.T) {
@ -182,19 +182,19 @@ func TestFetchApps(t *testing.T) {
defer ts.Close()
apps, err := fetchApps(context.TODO(), ts.URL, &http.Client{})
testutil.Ok(t, err)
assert.NoError(t, err)
testutil.Equals(t, len(apps.Applications), 2)
testutil.Equals(t, apps.Applications[0].Name, "CONFIG-SERVICE")
testutil.Equals(t, apps.Applications[1].Name, "META-SERVICE")
assert.Equal(t, len(apps.Applications), 2)
assert.Equal(t, apps.Applications[0].Name, "CONFIG-SERVICE")
assert.Equal(t, apps.Applications[1].Name, "META-SERVICE")
testutil.Equals(t, len(apps.Applications[1].Instances), 2)
testutil.Equals(t, apps.Applications[1].Instances[0].InstanceID, "meta-service002.test.com:meta-service:8080")
testutil.Equals(t, apps.Applications[1].Instances[0].Metadata.Items[0].XMLName.Local, "project")
testutil.Equals(t, apps.Applications[1].Instances[0].Metadata.Items[0].Content, "meta-service")
testutil.Equals(t, apps.Applications[1].Instances[0].Metadata.Items[1].XMLName.Local, "management.port")
testutil.Equals(t, apps.Applications[1].Instances[0].Metadata.Items[1].Content, "8090")
testutil.Equals(t, apps.Applications[1].Instances[1].InstanceID, "meta-service001.test.com:meta-service:8080")
assert.Equal(t, len(apps.Applications[1].Instances), 2)
assert.Equal(t, apps.Applications[1].Instances[0].InstanceID, "meta-service002.test.com:meta-service:8080")
assert.Equal(t, apps.Applications[1].Instances[0].Metadata.Items[0].XMLName.Local, "project")
assert.Equal(t, apps.Applications[1].Instances[0].Metadata.Items[0].Content, "meta-service")
assert.Equal(t, apps.Applications[1].Instances[0].Metadata.Items[1].XMLName.Local, "management.port")
assert.Equal(t, apps.Applications[1].Instances[0].Metadata.Items[1].Content, "8090")
assert.Equal(t, apps.Applications[1].Instances[1].InstanceID, "meta-service001.test.com:meta-service:8080")
}
func Test500ErrorHttpResponse(t *testing.T) {
@ -209,5 +209,5 @@ func Test500ErrorHttpResponse(t *testing.T) {
defer ts.Close()
_, err := fetchApps(context.TODO(), ts.URL, &http.Client{})
testutil.NotOk(t, err, "5xx HTTP response")
assert.Error(t, err, "5xx HTTP response")
}

View file

@ -15,14 +15,14 @@ package eureka
import (
"context"
"github.com/prometheus/prometheus/util/testutil"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/pkg/errors"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/assert"
"github.com/prometheus/prometheus/discovery/targetgroup"
)
@ -45,7 +45,7 @@ func testUpdateServices(respHandler http.HandlerFunc) ([]*targetgroup.Group, err
func TestEurekaSDHandleError(t *testing.T) {
var (
errTesting = errors.Errorf("non 2xx status '%d' response during eureka service discovery", http.StatusInternalServerError)
errTesting = "non 2xx status '500' response during eureka service discovery"
respHandler = func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
w.Header().Set("Content-Type", "application/xml")
@ -54,8 +54,8 @@ func TestEurekaSDHandleError(t *testing.T) {
)
tgs, err := testUpdateServices(respHandler)
testutil.ErrorEqual(t, err, errTesting)
testutil.Equals(t, len(tgs), 0)
assert.EqualError(t, err, errTesting)
assert.Equal(t, len(tgs), 0)
}
func TestEurekaSDEmptyList(t *testing.T) {
@ -71,8 +71,8 @@ func TestEurekaSDEmptyList(t *testing.T) {
}
)
tgs, err := testUpdateServices(respHandler)
testutil.Ok(t, err)
testutil.Equals(t, len(tgs), 1)
assert.NoError(t, err)
assert.Equal(t, len(tgs), 1)
}
func TestEurekaSDSendGroup(t *testing.T) {
@ -231,16 +231,16 @@ func TestEurekaSDSendGroup(t *testing.T) {
)
tgs, err := testUpdateServices(respHandler)
testutil.Ok(t, err)
testutil.Equals(t, len(tgs), 1)
assert.NoError(t, err)
assert.Equal(t, len(tgs), 1)
tg := tgs[0]
testutil.Equals(t, tg.Source, "eureka")
testutil.Equals(t, len(tg.Targets), 4)
assert.Equal(t, tg.Source, "eureka")
assert.Equal(t, len(tg.Targets), 4)
tgt := tg.Targets[0]
testutil.Equals(t, tgt[model.AddressLabel], model.LabelValue("config-service001.test.com:8080"))
assert.Equal(t, tgt[model.AddressLabel], model.LabelValue("config-service001.test.com:8080"))
tgt = tg.Targets[2]
testutil.Equals(t, tgt[model.AddressLabel], model.LabelValue("meta-service002.test.com:8080"))
assert.Equal(t, tgt[model.AddressLabel], model.LabelValue("meta-service002.test.com:8080"))
}

View file

@ -26,10 +26,10 @@ import (
"time"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/assert"
"go.uber.org/goleak"
"github.com/prometheus/prometheus/discovery/targetgroup"
"github.com/prometheus/prometheus/util/testutil"
)
func TestMain(m *testing.M) {
@ -54,7 +54,7 @@ func newTestRunner(t *testing.T) *testRunner {
t.Helper()
tmpDir, err := ioutil.TempDir("", "prometheus-file-sd")
testutil.Ok(t, err)
assert.NoError(t, err)
return &testRunner{
T: t,
@ -77,19 +77,19 @@ func (t *testRunner) copyFileTo(src string, name string) string {
t.Helper()
newf, err := ioutil.TempFile(t.dir, "")
testutil.Ok(t, err)
assert.NoError(t, err)
f, err := os.Open(src)
testutil.Ok(t, err)
assert.NoError(t, err)
_, err = io.Copy(newf, f)
testutil.Ok(t, err)
testutil.Ok(t, f.Close())
testutil.Ok(t, newf.Close())
assert.NoError(t, err)
assert.NoError(t, f.Close())
assert.NoError(t, newf.Close())
dst := filepath.Join(t.dir, name)
err = os.Rename(newf.Name(), dst)
testutil.Ok(t, err)
assert.NoError(t, err)
return dst
}
@ -99,14 +99,14 @@ func (t *testRunner) writeString(file string, data string) {
t.Helper()
newf, err := ioutil.TempFile(t.dir, "")
testutil.Ok(t, err)
assert.NoError(t, err)
_, err = newf.WriteString(data)
testutil.Ok(t, err)
testutil.Ok(t, newf.Close())
assert.NoError(t, err)
assert.NoError(t, newf.Close())
err = os.Rename(newf.Name(), file)
testutil.Ok(t, err)
assert.NoError(t, err)
}
// appendString appends a string to a file.
@ -114,11 +114,11 @@ func (t *testRunner) appendString(file, data string) {
t.Helper()
f, err := os.OpenFile(file, os.O_WRONLY|os.O_APPEND, 0)
testutil.Ok(t, err)
assert.NoError(t, err)
defer f.Close()
_, err = f.WriteString(data)
testutil.Ok(t, err)
assert.NoError(t, err)
}
// run starts the file SD and the loop receiving target groups updates.
@ -230,7 +230,7 @@ func (t *testRunner) requireTargetGroups(expected, got []*targetgroup.Group) {
panic(err)
}
testutil.Equals(t, string(b1), string(b2))
assert.Equal(t, string(b1), string(b2))
}
// validTg() maps to fixtures/valid.{json,yml}.
@ -468,7 +468,7 @@ func TestRemoveFile(t *testing.T) {
// Verify that we receive the update about the target groups being removed.
ref := runner.lastReceive()
testutil.Ok(t, os.Remove(sdFile))
assert.NoError(t, os.Remove(sdFile))
runner.requireUpdate(
ref,
[]*targetgroup.Group{

View file

@ -26,6 +26,7 @@ import (
"github.com/prometheus/common/config"
"github.com/prometheus/common/model"
"github.com/prometheus/common/version"
"github.com/prometheus/prometheus/discovery/refresh"
"github.com/prometheus/prometheus/discovery/targetgroup"
"github.com/prometheus/prometheus/util/strutil"

View file

@ -16,10 +16,11 @@ package hetzner
import (
"context"
"fmt"
"testing"
"github.com/go-kit/kit/log"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/util/testutil"
"testing"
"github.com/stretchr/testify/assert"
)
type hcloudSDTestSuite struct {
@ -43,16 +44,16 @@ func TestHCloudSDRefresh(t *testing.T) {
cfg.hcloudEndpoint = suite.Mock.Endpoint()
d, err := newHcloudDiscovery(&cfg, log.NewNopLogger())
testutil.Ok(t, err)
assert.NoError(t, err)
targetGroups, err := d.refresh(context.Background())
testutil.Ok(t, err)
testutil.Equals(t, 1, len(targetGroups))
assert.NoError(t, err)
assert.Equal(t, 1, len(targetGroups))
targetGroup := targetGroups[0]
testutil.Assert(t, targetGroup != nil, "targetGroup should not be nil")
testutil.Assert(t, targetGroup.Targets != nil, "targetGroup.targets should not be nil")
testutil.Equals(t, 3, len(targetGroup.Targets))
assert.NotNil(t, targetGroup, "targetGroup should not be nil")
assert.NotNil(t, targetGroup.Targets, "targetGroup.targets should not be nil")
assert.Equal(t, 3, len(targetGroup.Targets))
for i, labelSet := range []model.LabelSet{
{
@ -118,7 +119,7 @@ func TestHCloudSDRefresh(t *testing.T) {
},
} {
t.Run(fmt.Sprintf("item %d", i), func(t *testing.T) {
testutil.Equals(t, labelSet, targetGroup.Targets[i])
assert.Equal(t, labelSet, targetGroup.Targets[i])
})
}
}

View file

@ -15,13 +15,14 @@ package hetzner
import (
"context"
"github.com/pkg/errors"
"time"
"github.com/go-kit/kit/log"
"github.com/hetznercloud/hcloud-go/hcloud"
"github.com/pkg/errors"
"github.com/prometheus/common/config"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/discovery"
"github.com/prometheus/prometheus/discovery/refresh"
"github.com/prometheus/prometheus/discovery/targetgroup"

View file

@ -30,6 +30,7 @@ import (
"github.com/prometheus/common/config"
"github.com/prometheus/common/model"
"github.com/prometheus/common/version"
"github.com/prometheus/prometheus/discovery/refresh"
"github.com/prometheus/prometheus/discovery/targetgroup"
)

View file

@ -16,11 +16,12 @@ package hetzner
import (
"context"
"fmt"
"testing"
"github.com/go-kit/kit/log"
"github.com/prometheus/common/config"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/util/testutil"
"testing"
"github.com/stretchr/testify/assert"
)
type robotSDTestSuite struct {
@ -42,16 +43,16 @@ func TestRobotSDRefresh(t *testing.T) {
cfg.robotEndpoint = suite.Mock.Endpoint()
d, err := newRobotDiscovery(&cfg, log.NewNopLogger())
testutil.Ok(t, err)
assert.NoError(t, err)
targetGroups, err := d.refresh(context.Background())
testutil.Ok(t, err)
testutil.Equals(t, 1, len(targetGroups))
assert.NoError(t, err)
assert.Equal(t, 1, len(targetGroups))
targetGroup := targetGroups[0]
testutil.Assert(t, targetGroup != nil, "targetGroup should not be nil")
testutil.Assert(t, targetGroup.Targets != nil, "targetGroup.targets should not be nil")
testutil.Equals(t, 2, len(targetGroup.Targets))
assert.NotNil(t, targetGroup, "targetGroup should not be nil")
assert.NotNil(t, targetGroup.Targets, "targetGroup.targets should not be nil")
assert.Equal(t, 2, len(targetGroup.Targets))
for i, labelSet := range []model.LabelSet{
{
@ -79,7 +80,7 @@ func TestRobotSDRefresh(t *testing.T) {
},
} {
t.Run(fmt.Sprintf("item %d", i), func(t *testing.T) {
testutil.Equals(t, labelSet, targetGroup.Targets[i])
assert.Equal(t, labelSet, targetGroup.Targets[i])
})
}
}
@ -91,11 +92,11 @@ func TestRobotSDRefreshHandleError(t *testing.T) {
cfg.robotEndpoint = suite.Mock.Endpoint()
d, err := newRobotDiscovery(&cfg, log.NewNopLogger())
testutil.Ok(t, err)
assert.NoError(t, err)
targetGroups, err := d.refresh(context.Background())
testutil.NotOk(t, err)
testutil.Equals(t, "non 2xx status '401' response during hetzner service discovery with role robot", err.Error())
assert.Error(t, err)
assert.Equal(t, "non 2xx status '401' response during hetzner service discovery with role robot", err.Error())
testutil.Equals(t, 0, len(targetGroups))
assert.Equal(t, 0, len(targetGroups))
}

View file

@ -18,12 +18,13 @@ import (
"testing"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/discovery/targetgroup"
v1 "k8s.io/api/core/v1"
disv1beta1 "k8s.io/api/discovery/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"github.com/prometheus/prometheus/discovery/targetgroup"
)
func strptr(str string) *string {

View file

@ -20,6 +20,7 @@ import (
"time"
"github.com/go-kit/kit/log"
"github.com/stretchr/testify/assert"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/fake"
@ -150,7 +151,7 @@ func requireTargetGroups(t *testing.T, expected, res map[string]*targetgroup.Gro
panic(err)
}
testutil.Equals(t, string(b1), string(b2))
assert.Equal(t, string(b1), string(b2))
}
type hasSynced interface {

View file

@ -16,7 +16,6 @@ package discovery
import (
"context"
"fmt"
"reflect"
"sort"
"strconv"
"testing"
@ -25,6 +24,8 @@ import (
"github.com/go-kit/kit/log"
client_testutil "github.com/prometheus/client_golang/prometheus/testutil"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/assert"
"github.com/prometheus/prometheus/discovery/targetgroup"
"github.com/prometheus/prometheus/util/testutil"
)
@ -696,25 +697,12 @@ func TestTargetUpdatesOrder(t *testing.T) {
func assertEqualGroups(t *testing.T, got, expected []*targetgroup.Group, msg func(got, expected string) string) {
t.Helper()
format := func(groups []*targetgroup.Group) string {
var s string
for i, group := range groups {
if i > 0 {
s += ","
}
s += group.Source + ":" + fmt.Sprint(group.Targets)
}
return s
}
// Need to sort by the groups's source as the received order is not guaranteed.
sort.Sort(byGroupSource(got))
sort.Sort(byGroupSource(expected))
if !reflect.DeepEqual(got, expected) {
t.Errorf(msg(format(got), format(expected)))
}
assert.Equal(t, expected, got)
}
func staticConfig(addrs ...string) StaticConfig {
@ -894,10 +882,7 @@ func TestApplyConfigDoesNotModifyStaticTargets(t *testing.T) {
<-discoveryManager.SyncCh()
for _, cfg := range cfgs {
if !reflect.DeepEqual(originalConfig, cfg) {
t.Fatalf("discovery manager modified static config \n expected: %v\n got: %v\n",
originalConfig, cfg)
}
assert.Equal(t, originalConfig, cfg)
}
}

View file

@ -22,6 +22,7 @@ import (
"testing"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/discovery/targetgroup"
)

View file

@ -19,7 +19,7 @@ import (
"testing"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
)
type OpenstackSDHypervisorTestSuite struct {
@ -55,12 +55,12 @@ func TestOpenstackSDHypervisorRefresh(t *testing.T) {
hypervisor, _ := mock.openstackAuthSuccess()
ctx := context.Background()
tgs, err := hypervisor.refresh(ctx)
testutil.Equals(t, 1, len(tgs))
assert.Equal(t, 1, len(tgs))
tg := tgs[0]
testutil.Ok(t, err)
testutil.Assert(t, tg != nil, "")
testutil.Assert(t, tg.Targets != nil, "")
testutil.Equals(t, 2, len(tg.Targets))
assert.NoError(t, err)
assert.NotNil(t, tg)
assert.NotNil(t, tg.Targets)
assert.Equal(t, 2, len(tg.Targets))
for l, v := range map[string]string{
"__address__": "172.16.70.14:0",
@ -71,7 +71,7 @@ func TestOpenstackSDHypervisorRefresh(t *testing.T) {
"__meta_openstack_hypervisor_status": "enabled",
"__meta_openstack_hypervisor_id": "1",
} {
testutil.Equals(t, model.LabelValue(v), tg.Targets[0][model.LabelName(l)])
assert.Equal(t, model.LabelValue(v), tg.Targets[0][model.LabelName(l)])
}
for l, v := range map[string]string{
@ -83,7 +83,7 @@ func TestOpenstackSDHypervisorRefresh(t *testing.T) {
"__meta_openstack_hypervisor_status": "enabled",
"__meta_openstack_hypervisor_id": "721",
} {
testutil.Equals(t, model.LabelValue(v), tg.Targets[1][model.LabelName(l)])
assert.Equal(t, model.LabelValue(v), tg.Targets[1][model.LabelName(l)])
}
}
@ -95,6 +95,6 @@ func TestOpenstackSDHypervisorRefreshWithDoneContext(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := hypervisor.refresh(ctx)
testutil.NotOk(t, err)
testutil.Assert(t, strings.Contains(err.Error(), context.Canceled.Error()), "%q doesn't contain %q", err, context.Canceled)
assert.Error(t, err)
assert.True(t, strings.Contains(err.Error(), context.Canceled.Error()), "%q doesn't contain %q", err, context.Canceled)
}

View file

@ -27,6 +27,7 @@ import (
"github.com/gophercloud/gophercloud/pagination"
"github.com/pkg/errors"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/discovery/targetgroup"
"github.com/prometheus/prometheus/util/strutil"
)

View file

@ -20,7 +20,7 @@ import (
"testing"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
)
type OpenstackSDInstanceTestSuite struct {
@ -57,18 +57,18 @@ func TestOpenstackSDInstanceRefresh(t *testing.T) {
mock.SetupTest(t)
instance, err := mock.openstackAuthSuccess()
testutil.Ok(t, err)
assert.NoError(t, err)
ctx := context.Background()
tgs, err := instance.refresh(ctx)
testutil.Ok(t, err)
testutil.Equals(t, 1, len(tgs))
assert.NoError(t, err)
assert.Equal(t, 1, len(tgs))
tg := tgs[0]
testutil.Assert(t, tg != nil, "")
testutil.Assert(t, tg.Targets != nil, "")
testutil.Equals(t, 4, len(tg.Targets))
assert.NotNil(t, tg)
assert.NotNil(t, tg.Targets)
assert.Equal(t, 4, len(tg.Targets))
for i, lbls := range []model.LabelSet{
{
@ -121,7 +121,7 @@ func TestOpenstackSDInstanceRefresh(t *testing.T) {
},
} {
t.Run(fmt.Sprintf("item %d", i), func(t *testing.T) {
testutil.Equals(t, lbls, tg.Targets[i])
assert.Equal(t, lbls, tg.Targets[i])
})
}
}
@ -134,6 +134,6 @@ func TestOpenstackSDInstanceRefreshWithDoneContext(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := hypervisor.refresh(ctx)
testutil.NotOk(t, err)
testutil.Assert(t, strings.Contains(err.Error(), context.Canceled.Error()), "%q doesn't contain %q", err, context.Canceled)
assert.Error(t, err)
assert.True(t, strings.Contains(err.Error(), context.Canceled.Error()), "%q doesn't contain %q", err, context.Canceled)
}

View file

@ -20,10 +20,10 @@ import (
"time"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/assert"
"go.uber.org/goleak"
"github.com/prometheus/prometheus/discovery/targetgroup"
"github.com/prometheus/prometheus/util/testutil"
)
func TestMain(m *testing.M) {
@ -73,10 +73,10 @@ func TestRefresh(t *testing.T) {
go d.Run(ctx, ch)
tg := <-ch
testutil.Equals(t, tg1, tg)
assert.Equal(t, tg1, tg)
tg = <-ch
testutil.Equals(t, tg2, tg)
assert.Equal(t, tg2, tg)
tick := time.NewTicker(2 * interval)
defer tick.Stop()

View file

@ -21,8 +21,9 @@ import (
"strings"
"sync"
"github.com/prometheus/prometheus/discovery/targetgroup"
"gopkg.in/yaml.v2"
"github.com/prometheus/prometheus/discovery/targetgroup"
)
const (

View file

@ -18,9 +18,8 @@ import (
"testing"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/assert"
"gopkg.in/yaml.v2"
"github.com/prometheus/prometheus/util/testutil"
)
func TestTargetGroupStrictJsonUnmarshal(t *testing.T) {
@ -54,8 +53,8 @@ func TestTargetGroupStrictJsonUnmarshal(t *testing.T) {
for _, test := range tests {
tg := Group{}
actual := tg.UnmarshalJSON([]byte(test.json))
testutil.Equals(t, test.expectedReply, actual)
testutil.Equals(t, test.expectedGroup, tg)
assert.Equal(t, test.expectedReply, actual)
assert.Equal(t, test.expectedGroup, tg)
}
}
@ -93,8 +92,8 @@ func TestTargetGroupYamlMarshal(t *testing.T) {
for _, test := range tests {
actual, err := test.group.MarshalYAML()
testutil.Equals(t, test.expectedErr, err)
testutil.Equals(t, test.expectedYaml, string(marshal(actual)))
assert.Equal(t, test.expectedErr, err)
assert.Equal(t, test.expectedYaml, string(marshal(actual)))
}
}
@ -133,8 +132,8 @@ func TestTargetGroupYamlUnmarshal(t *testing.T) {
for _, test := range tests {
tg := Group{}
actual := tg.UnmarshalYAML(unmarshal([]byte(test.yaml)))
testutil.Equals(t, test.expectedReply, actual)
testutil.Equals(t, test.expectedGroup, tg)
assert.Equal(t, test.expectedReply, actual)
assert.Equal(t, test.expectedGroup, tg)
}
}
@ -151,7 +150,7 @@ func TestString(t *testing.T) {
Group{Targets: []model.LabelSet{},
Source: "<source>",
Labels: model.LabelSet{}}
testutil.Equals(t, "<source>", group1.String())
testutil.Equals(t, "<source>", group2.String())
testutil.Equals(t, group1.String(), group2.String())
assert.Equal(t, "<source>", group1.String())
assert.Equal(t, "<source>", group2.String())
assert.Equal(t, group1.String(), group2.String())
}

View file

@ -26,8 +26,7 @@ import (
"github.com/prometheus/common/config"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
)
var (
@ -85,54 +84,54 @@ func newTritonDiscovery(c SDConfig) (*Discovery, error) {
func TestTritonSDNew(t *testing.T) {
td, err := newTritonDiscovery(conf)
testutil.Ok(t, err)
testutil.Assert(t, td != nil, "")
testutil.Assert(t, td.client != nil, "")
testutil.Assert(t, td.interval != 0, "")
testutil.Assert(t, td.sdConfig != nil, "")
testutil.Equals(t, conf.Account, td.sdConfig.Account)
testutil.Equals(t, conf.DNSSuffix, td.sdConfig.DNSSuffix)
testutil.Equals(t, conf.Endpoint, td.sdConfig.Endpoint)
testutil.Equals(t, conf.Port, td.sdConfig.Port)
assert.NoError(t, err)
assert.NotNil(t, td)
assert.NotNil(t, td.client)
assert.True(t, td.interval != 0, "")
assert.NotNil(t, td.sdConfig)
assert.Equal(t, conf.Account, td.sdConfig.Account)
assert.Equal(t, conf.DNSSuffix, td.sdConfig.DNSSuffix)
assert.Equal(t, conf.Endpoint, td.sdConfig.Endpoint)
assert.Equal(t, conf.Port, td.sdConfig.Port)
}
func TestTritonSDNewBadConfig(t *testing.T) {
td, err := newTritonDiscovery(badconf)
testutil.NotOk(t, err)
testutil.Assert(t, td == nil, "")
assert.Error(t, err)
assert.True(t, td == nil, "")
}
func TestTritonSDNewGroupsConfig(t *testing.T) {
td, err := newTritonDiscovery(groupsconf)
testutil.Ok(t, err)
testutil.Assert(t, td != nil, "")
testutil.Assert(t, td.client != nil, "")
testutil.Assert(t, td.interval != 0, "")
testutil.Assert(t, td.sdConfig != nil, "")
testutil.Equals(t, groupsconf.Account, td.sdConfig.Account)
testutil.Equals(t, groupsconf.DNSSuffix, td.sdConfig.DNSSuffix)
testutil.Equals(t, groupsconf.Endpoint, td.sdConfig.Endpoint)
testutil.Equals(t, groupsconf.Groups, td.sdConfig.Groups)
testutil.Equals(t, groupsconf.Port, td.sdConfig.Port)
assert.NoError(t, err)
assert.NotNil(t, td)
assert.NotNil(t, td.client)
assert.True(t, td.interval != 0, "")
assert.NotNil(t, td.sdConfig)
assert.Equal(t, groupsconf.Account, td.sdConfig.Account)
assert.Equal(t, groupsconf.DNSSuffix, td.sdConfig.DNSSuffix)
assert.Equal(t, groupsconf.Endpoint, td.sdConfig.Endpoint)
assert.Equal(t, groupsconf.Groups, td.sdConfig.Groups)
assert.Equal(t, groupsconf.Port, td.sdConfig.Port)
}
func TestTritonSDNewCNConfig(t *testing.T) {
td, err := newTritonDiscovery(cnconf)
testutil.Ok(t, err)
testutil.Assert(t, td != nil, "")
testutil.Assert(t, td.client != nil, "")
testutil.Assert(t, td.interval != 0, "")
testutil.Assert(t, td.sdConfig != nil, "")
testutil.Equals(t, cnconf.Role, td.sdConfig.Role)
testutil.Equals(t, cnconf.Account, td.sdConfig.Account)
testutil.Equals(t, cnconf.DNSSuffix, td.sdConfig.DNSSuffix)
testutil.Equals(t, cnconf.Endpoint, td.sdConfig.Endpoint)
testutil.Equals(t, cnconf.Port, td.sdConfig.Port)
assert.NoError(t, err)
assert.NotNil(t, td)
assert.NotNil(t, td.client)
assert.True(t, td.interval != 0, "")
assert.NotNil(t, td.sdConfig)
assert.Equal(t, cnconf.Role, td.sdConfig.Role)
assert.Equal(t, cnconf.Account, td.sdConfig.Account)
assert.Equal(t, cnconf.DNSSuffix, td.sdConfig.DNSSuffix)
assert.Equal(t, cnconf.Endpoint, td.sdConfig.Endpoint)
assert.Equal(t, cnconf.Port, td.sdConfig.Port)
}
func TestTritonSDRefreshNoTargets(t *testing.T) {
tgts := testTritonSDRefresh(t, conf, "{\"containers\":[]}")
testutil.Assert(t, tgts == nil, "")
assert.True(t, tgts == nil, "")
}
func TestTritonSDRefreshMultipleTargets(t *testing.T) {
@ -157,8 +156,8 @@ func TestTritonSDRefreshMultipleTargets(t *testing.T) {
)
tgts := testTritonSDRefresh(t, conf, dstr)
testutil.Assert(t, tgts != nil, "")
testutil.Equals(t, 2, len(tgts))
assert.NotNil(t, tgts)
assert.Equal(t, 2, len(tgts))
}
func TestTritonSDRefreshNoServer(t *testing.T) {
@ -167,8 +166,8 @@ func TestTritonSDRefreshNoServer(t *testing.T) {
)
_, err := td.refresh(context.Background())
testutil.NotOk(t, err)
testutil.Equals(t, strings.Contains(err.Error(), "an error occurred when requesting targets from the discovery endpoint"), true)
assert.Error(t, err)
assert.Equal(t, strings.Contains(err.Error(), "an error occurred when requesting targets from the discovery endpoint"), true)
}
func TestTritonSDRefreshCancelled(t *testing.T) {
@ -179,8 +178,8 @@ func TestTritonSDRefreshCancelled(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := td.refresh(ctx)
testutil.NotOk(t, err)
testutil.Equals(t, strings.Contains(err.Error(), context.Canceled.Error()), true)
assert.Error(t, err)
assert.Equal(t, strings.Contains(err.Error(), context.Canceled.Error()), true)
}
func TestTritonSDRefreshCNsUUIDOnly(t *testing.T) {
@ -196,8 +195,8 @@ func TestTritonSDRefreshCNsUUIDOnly(t *testing.T) {
)
tgts := testTritonSDRefresh(t, cnconf, dstr)
testutil.Assert(t, tgts != nil, "")
testutil.Equals(t, 2, len(tgts))
assert.NotNil(t, tgts)
assert.Equal(t, 2, len(tgts))
}
func TestTritonSDRefreshCNsWithHostname(t *testing.T) {
@ -215,8 +214,8 @@ func TestTritonSDRefreshCNsWithHostname(t *testing.T) {
)
tgts := testTritonSDRefresh(t, cnconf, dstr)
testutil.Assert(t, tgts != nil, "")
testutil.Equals(t, 2, len(tgts))
assert.NotNil(t, tgts)
assert.Equal(t, 2, len(tgts))
}
func testTritonSDRefresh(t *testing.T, c SDConfig, dstr string) []model.LabelSet {
@ -230,25 +229,25 @@ func testTritonSDRefresh(t *testing.T, c SDConfig, dstr string) []model.LabelSet
defer s.Close()
u, err := url.Parse(s.URL)
testutil.Ok(t, err)
testutil.Assert(t, u != nil, "")
assert.NoError(t, err)
assert.NotNil(t, u)
host, strport, err := net.SplitHostPort(u.Host)
testutil.Ok(t, err)
testutil.Assert(t, host != "", "")
testutil.Assert(t, strport != "", "")
assert.NoError(t, err)
assert.True(t, host != "", "")
assert.True(t, strport != "", "")
port, err := strconv.Atoi(strport)
testutil.Ok(t, err)
testutil.Assert(t, port != 0, "")
assert.NoError(t, err)
assert.True(t, port != 0, "")
td.sdConfig.Port = port
tgs, err := td.refresh(context.Background())
testutil.Ok(t, err)
testutil.Equals(t, 1, len(tgs))
assert.NoError(t, err)
assert.Equal(t, 1, len(tgs))
tg := tgs[0]
testutil.Assert(t, tg != nil, "")
assert.NotNil(t, tg)
return tg.Targets
}

View file

@ -29,10 +29,11 @@ import (
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/prometheus/common/model"
"gopkg.in/alecthomas/kingpin.v2"
"github.com/prometheus/prometheus/discovery/targetgroup"
"github.com/prometheus/prometheus/documentation/examples/custom-sd/adapter"
"github.com/prometheus/prometheus/util/strutil"
"gopkg.in/alecthomas/kingpin.v2"
)
var (

View file

@ -27,6 +27,7 @@ import (
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/discovery"
"github.com/prometheus/prometheus/discovery/targetgroup"
)

View file

@ -15,13 +15,14 @@ package adapter
import (
"context"
"github.com/prometheus/prometheus/util/testutil"
"io/ioutil"
"os"
"reflect"
"testing"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/assert"
"github.com/prometheus/prometheus/discovery/targetgroup"
)
@ -231,9 +232,9 @@ func TestGenerateTargetGroups(t *testing.T) {
func TestWriteOutput(t *testing.T) {
ctx := context.Background()
tmpfile, err := ioutil.TempFile("", "sd_adapter_test")
testutil.Ok(t, err)
assert.NoError(t, err)
defer os.Remove(tmpfile.Name())
tmpfile.Close()
adapter := NewAdapter(ctx, tmpfile.Name(), "test_sd", nil, nil)
testutil.Ok(t, adapter.writeOutput())
assert.NoError(t, adapter.writeOutput())
}

View file

@ -23,7 +23,6 @@ import (
"time"
influx "github.com/influxdata/influxdb/client/v2"
"github.com/prometheus/common/model"
)

View file

@ -29,16 +29,14 @@ import (
"github.com/go-kit/kit/log/level"
"github.com/gogo/protobuf/proto"
"github.com/golang/snappy"
influx "github.com/influxdata/influxdb/client/v2"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/model"
"gopkg.in/alecthomas/kingpin.v2"
influx "github.com/influxdata/influxdb/client/v2"
"github.com/prometheus/common/promlog"
"github.com/prometheus/common/promlog/flag"
"gopkg.in/alecthomas/kingpin.v2"
"github.com/prometheus/prometheus/documentation/examples/remote_storage/remote_storage_adapter/graphite"
"github.com/prometheus/prometheus/documentation/examples/remote_storage/remote_storage_adapter/influxdb"

5
go.mod
View file

@ -16,7 +16,6 @@ require (
github.com/aws/aws-sdk-go v1.35.5
github.com/cespare/xxhash/v2 v2.1.1
github.com/containerd/containerd v1.3.4 // indirect
github.com/davecgh/go-spew v1.1.1
github.com/dgryski/go-sip13 v0.0.0-20200911182023-62edffca9245
github.com/digitalocean/godo v1.46.0
github.com/docker/distribution v2.7.1+incompatible // indirect
@ -49,7 +48,6 @@ require (
github.com/opentracing-contrib/go-stdlib v1.0.0
github.com/opentracing/opentracing-go v1.2.0
github.com/pkg/errors v0.9.1
github.com/pmezard/go-difflib v1.0.0
github.com/prometheus/alertmanager v0.21.0
github.com/prometheus/client_golang v1.7.1
github.com/prometheus/client_model v0.2.0
@ -57,6 +55,7 @@ require (
github.com/samuel/go-zookeeper v0.0.0-20200724154423-2164a8ac840e
github.com/shurcooL/httpfs v0.0.0-20190707220628-8d4bc4ba7749
github.com/shurcooL/vfsgen v0.0.0-20200824052919-0d455de96546
github.com/stretchr/testify v1.6.1
github.com/uber/jaeger-client-go v2.25.0+incompatible
github.com/uber/jaeger-lib v2.4.0+incompatible
go.mongodb.org/mongo-driver v1.3.2 // indirect
@ -67,7 +66,7 @@ require (
golang.org/x/sync v0.0.0-20200930132711-30421366ff76
golang.org/x/sys v0.0.0-20201008064518-c1f3e3309c71
golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e
golang.org/x/tools v0.0.0-20201008025239-9df69603baec
golang.org/x/tools v0.0.0-20201020161133-226fd2f889ca
google.golang.org/api v0.32.0
gopkg.in/alecthomas/kingpin.v2 v2.2.6
gopkg.in/fsnotify/fsnotify.v1 v1.4.7

46
go.sum
View file

@ -11,7 +11,6 @@ cloud.google.com/go v0.51.0/go.mod h1:hWtGJ6gnXH+KgDv+V0zFGDvpi07n3z8ZNj3T1RW0Gc
cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4=
cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M=
cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc=
cloud.google.com/go v0.56.0 h1:WRz29PgAsVEyPSDHyk+0fpEkwEFyfhHn+JbksT6gIL4=
cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk=
cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs=
cloud.google.com/go v0.65.0 h1:Dg9iHVQfrhq82rUNu9ZxUDrJLaxFUe/HlCVaLyRruq8=
@ -63,11 +62,9 @@ github.com/Azure/go-autorest/autorest/to v0.3.0 h1:zebkZaadz7+wIQYgC7GXaz3Wb28yK
github.com/Azure/go-autorest/autorest/to v0.3.0/go.mod h1:MgwOyqaIuKdG4TL/2ywSsIWKAfJfgHDo8ObuUk3t5sA=
github.com/Azure/go-autorest/autorest/validation v0.2.0 h1:15vMO4y76dehZSq7pAaOLQxC6dZYsSrj2GQpflyM/L4=
github.com/Azure/go-autorest/autorest/validation v0.2.0/go.mod h1:3EEqHnBxQGHXRYq3HT1WyXAvT7LLY3tl70hw6tQIbjI=
github.com/Azure/go-autorest/logger v0.1.0 h1:ruG4BSDXONFRrZZJ2GUXDiUyVpayPmb1GnWeHDdaNKY=
github.com/Azure/go-autorest/logger v0.1.0/go.mod h1:oExouG+K6PryycPJfVSxi/koC6LSNgds39diKLz7Vrc=
github.com/Azure/go-autorest/logger v0.2.0 h1:e4RVHVZKC5p6UANLJHkM4OfR1UKZPj8Wt8Pcx+3oqrE=
github.com/Azure/go-autorest/logger v0.2.0/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8=
github.com/Azure/go-autorest/tracing v0.5.0 h1:TRn4WjSnkcSy5AEG3pnbtFSwNtwzjr4VYyQflFE619k=
github.com/Azure/go-autorest/tracing v0.5.0/go.mod h1:r/s2XiOKccPW3HrqB+W0TQzfbtp2fGCgRFtBroKn4Dk=
github.com/Azure/go-autorest/tracing v0.6.0 h1:TYi4+3m5t6K48TGI9AUdb+IzbnSxvnvUMfuitfgcfuo=
github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU=
@ -81,7 +78,6 @@ github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go
github.com/Microsoft/go-winio v0.4.14 h1:+hMXMk01us9KgxGb7ftKQt2Xpf5hH/yky+TDA+qxleU=
github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA=
github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46/go.mod h1:3wb06e3pkSAbeQ52E9H9iFoQsEEwGN64994WTCIhntQ=
github.com/OneOfOne/xxhash v1.2.2 h1:KMrpdQIwFcEqXDklaen+P1axHaj9BSKzvpUUfnHldSE=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
github.com/PuerkitoBio/purell v1.0.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
github.com/PuerkitoBio/purell v1.1.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
@ -141,7 +137,6 @@ github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghf
github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY=
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e h1:fY5BOSpyZCqRo5OhCuC+XN+r/bBCmeuuJtjz+bCNIf8=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
github.com/circonus-labs/circonus-gometrics v2.3.1+incompatible/go.mod h1:nmEj6Dob7S7YxXgwXpfOuvO54S+tGdZdw9fuRZt25Ag=
@ -163,7 +158,6 @@ github.com/dave/jennifer v1.2.0/go.mod h1:fIb+770HOpJ2fmN9EPPKOqm1vMGhB+TwXKMZhr
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/dgryski/go-bitstream v0.0.0-20180413035011-3522498ce2c8/go.mod h1:VMaSuZ+SZcx/wljOQKvp5srsbCiKDEb6K2wC4+PiBmQ=
github.com/dgryski/go-sip13 v0.0.0-20200911182023-62edffca9245 h1:9cOfvEwjQxdwKuNDTQSaMKNRvwKwgZG+U4HrjeRKHso=
@ -205,7 +199,6 @@ github.com/form3tech-oss/jwt-go v3.2.2+incompatible h1:TcekIExNqud5crz4xD2pavyTg
github.com/form3tech-oss/jwt-go v3.2.2+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k=
github.com/franela/goblin v0.0.0-20200105215937-c9ffbefa60db/go.mod h1:7dvUGVsVBjqR7JHJk0brhHOZYGmfBYOrK0ZhYMEtBr4=
github.com/franela/goreq v0.0.0-20171204163338-bcd34c9993f8/go.mod h1:ZhphrRTfi2rbfLwlschooIH4+wKKDR4Pdxhh+TRoA20=
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
@ -361,7 +354,6 @@ github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QD
github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0=
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4=
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/golang/snappy v0.0.2 h1:aeE13tS0IiQgFjYdoL8qN3K1N2bXXtI6Vi51/y7BpMw=
github.com/golang/snappy v0.0.2/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
@ -372,10 +364,8 @@ github.com/google/flatbuffers v1.11.0/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w=
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM=
@ -393,7 +383,6 @@ github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hf
github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99 h1:Ak8CrdlwwXwAZxzS66vgPt4U8yUZX7JwLvVR58FN5jM=
github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
github.com/google/pprof v0.0.0-20201007051231-1066cbb265c7 h1:qYWTuM6SUNWgtvkhV8oH6GFHCpU+rKQOxPcepM3xKi0=
github.com/google/pprof v0.0.0-20201007051231-1066cbb265c7/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
@ -414,7 +403,6 @@ github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2z
github.com/gorilla/mux v1.7.3 h1:gnP5JzjVOuiZD07fKKToCAOjS0yOpj/qPETTXCCS6hw=
github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7 h1:pdN6V1QBWetyv/0+wjACpqVH+eVULgEjkurDLq3goeM=
github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA=
github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk=
@ -440,7 +428,6 @@ github.com/hashicorp/go-immutable-radix v1.2.0 h1:l6UW37iCXwZkZoAbEYnptSHVE/cQ5b
github.com/hashicorp/go-immutable-radix v1.2.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60=
github.com/hashicorp/go-msgpack v0.5.3 h1:zKjpN5BK/P5lMYrLmBHdBULWbJ0XpYR+7NGzqkZzoD4=
github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM=
github.com/hashicorp/go-multierror v1.0.0 h1:iVjPR7a6H0tWELX5NxNe7bYopibicUzc7uPribsnS6o=
github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk=
github.com/hashicorp/go-multierror v1.1.0 h1:B9UzwGQJehnUY1yNrnwREHc3fGbC2xefo8g4TbElacI=
github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+vmowP0z+KUhOZdA=
@ -475,7 +462,6 @@ github.com/hetznercloud/hcloud-go v1.22.0/go.mod h1:xng8lbDUg+xM1dgc0yGHX5EeqbwI
github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg=
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6 h1:UDMh68UUwekSh5iP2OMhRRZJiiBccgV7axzUG8vi56c=
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/imdario/mergo v0.3.5/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
@ -525,13 +511,11 @@ github.com/klauspost/cpuid v0.0.0-20170728055534-ae7887de9fa5/go.mod h1:Pj4uuM52
github.com/klauspost/crc32 v0.0.0-20161016154125-cb6bfca970f6/go.mod h1:+ZoRqAPRLkC4NPOvfYeR5KNOrY6TD+/sAC3HXPZgDYg=
github.com/klauspost/pgzip v1.0.2-0.20170402124221-0bf5dcad4ada/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/konsorten/go-windows-terminal-sequences v1.0.2 h1:DB17ag19krx9CFsz4o3enTrPXyIXCl+2iCXH/aMAp9s=
github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8=
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.2.0 h1:s5hAObm+yFO5uHYt5dYjxi2rXrsnmRpJx4OYvIWUaQs=
github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
@ -638,7 +622,6 @@ github.com/opentracing-contrib/go-stdlib v1.0.0/go.mod h1:qtI1ogk+2JhVPIXVc6q+NH
github.com/opentracing/basictracer-go v1.0.0/go.mod h1:QfBfYuafItcjQuMwinw9GhYKwFXS9KnPs5lxoYwgW74=
github.com/opentracing/opentracing-go v1.0.2/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
github.com/opentracing/opentracing-go v1.0.3-0.20180606204148-bd9c31933947/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
github.com/opentracing/opentracing-go v1.1.0 h1:pWlfV3Bxv7k65HYwkikxat0+s3pV4bsqf19k25Ur8rU=
github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs=
github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc=
@ -654,7 +637,6 @@ github.com/paulbellamy/ratecounter v0.2.0/go.mod h1:Hfx1hDpSGoqxkVVpBi/IlYD7kChl
github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k=
github.com/pelletier/go-toml v1.4.0/go.mod h1:PN7xzY2wHTK0K9p34ErDQMlFxa51Fk0OUruD3k1mMwo=
github.com/performancecopilot/speed v3.0.0+incompatible/go.mod h1:/CLtqpZ5gBg1M9iaPbIdPPGyKcA8hKdoy6hAWba7Yac=
github.com/peterbourgon/diskv v2.0.1+incompatible h1:UBdAOUP5p4RWqPBg048CAvpKN+vxiaj6gdUUzhl4XmI=
github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU=
github.com/peterh/liner v1.0.1-0.20180619022028-8c1271fcf47f/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc=
github.com/philhofer/fwd v1.0.0/go.mod h1:gk3iGcWd9+svBvR0sR+KPcfE+RNWozjowpeBVG3ZVNU=
@ -692,7 +674,6 @@ github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y8
github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc=
github.com/prometheus/common v0.7.0/go.mod h1:DjGbpBbp5NYNiECxcL/VnbXCCaQpKd3tt26CguLLsqA=
github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8bs7vj7HSQ4=
github.com/prometheus/common v0.10.0 h1:RyRA7RzGXQZiW+tGMr7sxa85G1z0yOpM1qq5c8lNawc=
github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo=
github.com/prometheus/common v0.14.0 h1:RHRyE8UocrbjU+6UvRzwi6HjiDfxrrBU91TtbKzkGp4=
github.com/prometheus/common v0.14.0/go.mod h1:U+gB1OBLb1lF3O42bTCL+FK18tX9Oar16Clt/msog/s=
@ -714,7 +695,6 @@ github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da h1:p3Vo3i64TCLY7gIfzeQaUJ+kppEO5WQG3cL8iE8tGHU=
github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E=
github.com/samuel/go-zookeeper v0.0.0-20200724154423-2164a8ac840e h1:CGjiMQ0wMH4wtNWrlj6kiTbkPt2F3rbYnhGX6TWLfco=
github.com/samuel/go-zookeeper v0.0.0-20200724154423-2164a8ac840e/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E=
@ -727,7 +707,6 @@ github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAm
github.com/shurcooL/httpfs v0.0.0-20190707220628-8d4bc4ba7749 h1:bUGsEnyNbVPw06Bs80sCeARAlK8lhwqGyi6UT8ymuGk=
github.com/shurcooL/httpfs v0.0.0-20190707220628-8d4bc4ba7749/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/shurcooL/vfsgen v0.0.0-20181202132449-6a9ea43bcacd h1:ug7PpSOB5RBPK1Kg6qskGBoP3Vnj/aNYFTznWvlkGo0=
github.com/shurcooL/vfsgen v0.0.0-20181202132449-6a9ea43bcacd/go.mod h1:TrYk7fJVaAttu97ZZKrO9UbRa8izdowaMIZcxYMbVaw=
github.com/shurcooL/vfsgen v0.0.0-20200824052919-0d455de96546 h1:pXY9qYc/MP5zdvqWEUH6SjNiu7VhSjuVFTFiTcphaLU=
github.com/shurcooL/vfsgen v0.0.0-20200824052919-0d455de96546/go.mod h1:TrYk7fJVaAttu97ZZKrO9UbRa8izdowaMIZcxYMbVaw=
@ -738,16 +717,13 @@ github.com/simonpasquier/klog-gokit/v2 v2.0.1/go.mod h1:VgeTFrwzYYcMH8edEfh3/ai2
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q=
github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I=
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/soheilhy/cmux v0.1.4 h1:0HKaf1o97UwFjHH9o5XsHUOF+tqmdA7KEzXLpiyaw0E=
github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM=
github.com/sony/gobreaker v0.4.1/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY=
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72 h1:qLC7fQah7D6K1B0ujays3HV9gkFtllcxhzImRR7ArPQ=
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk=
github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
@ -768,8 +744,9 @@ github.com/stretchr/testify v1.2.0/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXf
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4=
github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
github.com/tinylib/msgp v1.0.2/go.mod h1:+d+yLhGm8mzTaHzB+wgMYrodPfmZrzkirds8fDWklFE=
@ -805,7 +782,6 @@ go.opencensus.io v0.20.2/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk=
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.opencensus.io v0.22.3 h1:8sGtKOrtQqkN1bp2AtX+misvLIlOmsEsNd+9NIcPEm8=
go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.opencensus.io v0.22.4 h1:LYy1Hy3MJdrCdMwwzxA/dRok4ejH+RwNGbuoD9fCjto=
go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
@ -836,7 +812,6 @@ golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392/go.mod h1:/lpIB1dKB+9EgE3
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191202143827-86a70503ff7e/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20191206172530-e9b2fee46413/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20201002170205-7f63de1d35b0 h1:hb9wdF1z5waM+dSIICn1l0DkLVDT3hqhhQsDNUmHPRE=
golang.org/x/crypto v0.0.0-20201002170205-7f63de1d35b0/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
@ -873,7 +848,6 @@ golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKG
golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY=
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/mod v0.2.0 h1:KU7oHjnv3XNWfa5COkzUifxZmxp1TyI7ImMXqFxLwvQ=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
@ -915,7 +889,6 @@ golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/
golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20200822124328-c89045814202 h1:VvcQYSHwXgi7W+TpUR6A9g6Up98WAHf3f/ulnJ62IyA=
golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20201006153459-a7d1128ccaa0 h1:wBouT66WTYFXdxfVdz9sVWARVd/2vfGcmI45D2gj45M=
golang.org/x/net v0.0.0-20201006153459-a7d1128ccaa0/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
@ -923,7 +896,6 @@ golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAG
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d h1:TzXSXBo42m9gQenoE3b9BGiEpg5IG2JkU5FkPIawgtw=
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43 h1:ld7aEMNHoBnnDAX15v1T6z31v8HwR2A9FYOuAhWqkwc=
golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
@ -934,9 +906,7 @@ golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.0.0-20190412183630-56d357773e84/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a h1:WXEvlFVvvGxCJLG6REjsT03iWnKLEWinaScsxF2Vm2o=
golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208 h1:qwRHBd0NqMbJxfbotnDhm2ByMI1Shq4Y6oRJo21SGJA=
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20200930132711-30421366ff76 h1:JnxiSYT3Nm0BT2a8CyvYyM6cnrWpidecD1UuSYbhKm0=
golang.org/x/sync v0.0.0-20200930132711-30421366ff76/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@ -991,7 +961,6 @@ golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1 h1:ogLJMz+qpzav7lGMh10LMvAkM/fAoGlaiiHYiFYdm80=
golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200622214017-ed371f2e16b4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@ -1003,7 +972,6 @@ golang.org/x/sys v0.0.0-20201008064518-c1f3e3309c71/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
@ -1069,18 +1037,16 @@ golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjs
golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8=
golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20200513201620-d5fe73897c97 h1:DAuln/hGp+aJiHpID1Y1hYzMEPP5WLwtZHPb50mN0OE=
golang.org/x/tools v0.0.0-20200513201620-d5fe73897c97/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/tools v0.0.0-20200828161849-5deb26317202/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE=
golang.org/x/tools v0.0.0-20201008025239-9df69603baec h1:RY2OghEV/7X1MLaecgm1mwFd3sGvUddm5pGVSxQvX0c=
golang.org/x/tools v0.0.0-20201008025239-9df69603baec/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU=
golang.org/x/tools v0.0.0-20201020161133-226fd2f889ca h1:pvScuB+UnCGDas2naNKUOXruM08MjwVcEdaweeynIqQ=
golang.org/x/tools v0.0.0-20201020161133-226fd2f889ca/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
@ -1142,7 +1108,6 @@ google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfG
google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884 h1:fiNLklpBwWK1mth30Hlwk+fcdBmIALlgF5iy77O37Ig=
google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U=
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
@ -1165,7 +1130,6 @@ google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8
google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60=
google.golang.org/grpc v1.29.1 h1:EC2SB8S04d2r73uptxphDSUG+kTKVgjRPF+N3xpxRB4=
google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk=
google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
google.golang.org/grpc v1.31.1/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
@ -1177,7 +1141,6 @@ google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQ
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.24.0 h1:UhZDfRO8JRQru4/+LlLE0BRKGF8L+PICnvYZmx/fEGA=
@ -1210,6 +1173,7 @@ gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776 h1:tQIYjPdBoyREyB9XMu+nnTclpTYkz2zFM+lzLJFO4gQ=
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo=

View file

@ -32,13 +32,13 @@ import (
"github.com/go-kit/kit/log/level"
"github.com/go-openapi/strfmt"
"github.com/pkg/errors"
"go.uber.org/atomic"
"github.com/prometheus/alertmanager/api/v2/models"
"github.com/prometheus/client_golang/prometheus"
config_util "github.com/prometheus/common/config"
"github.com/prometheus/common/model"
"github.com/prometheus/common/version"
"go.uber.org/atomic"
"github.com/prometheus/prometheus/config"
"github.com/prometheus/prometheus/discovery/targetgroup"
"github.com/prometheus/prometheus/pkg/labels"

View file

@ -29,6 +29,7 @@ import (
"github.com/prometheus/alertmanager/api/v2/models"
config_util "github.com/prometheus/common/config"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/assert"
"go.uber.org/atomic"
yaml "gopkg.in/yaml.v2"
@ -36,7 +37,6 @@ import (
"github.com/prometheus/prometheus/discovery/targetgroup"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/pkg/relabel"
"github.com/prometheus/prometheus/util/testutil"
)
func TestPostPath(t *testing.T) {
@ -65,7 +65,7 @@ func TestPostPath(t *testing.T) {
},
}
for _, c := range cases {
testutil.Equals(t, c.out, postPath(c.in, config.AlertmanagerAPIVersionV1))
assert.Equal(t, c.out, postPath(c.in, config.AlertmanagerAPIVersionV1))
}
}
@ -80,10 +80,10 @@ func TestHandlerNextBatch(t *testing.T) {
expected := append([]*Alert{}, h.queue...)
testutil.Ok(t, alertsEqual(expected[0:maxBatchSize], h.nextBatch()))
testutil.Ok(t, alertsEqual(expected[maxBatchSize:2*maxBatchSize], h.nextBatch()))
testutil.Ok(t, alertsEqual(expected[2*maxBatchSize:], h.nextBatch()))
testutil.Assert(t, len(h.queue) == 0, "Expected queue to be empty but got %d alerts", len(h.queue))
assert.NoError(t, alertsEqual(expected[0:maxBatchSize], h.nextBatch()))
assert.NoError(t, alertsEqual(expected[maxBatchSize:2*maxBatchSize], h.nextBatch()))
assert.NoError(t, alertsEqual(expected[2*maxBatchSize:], h.nextBatch()))
assert.True(t, len(h.queue) == 0, "Expected queue to be empty but got %d alerts", len(h.queue))
}
func alertsEqual(a, b []*Alert) error {
@ -188,20 +188,20 @@ func TestHandlerSendAll(t *testing.T) {
t.Helper()
select {
case err := <-errc:
testutil.Ok(t, err)
assert.NoError(t, err)
default:
}
}
testutil.Assert(t, h.sendAll(h.queue...), "all sends failed unexpectedly")
assert.True(t, h.sendAll(h.queue...), "all sends failed unexpectedly")
checkNoErr()
status1.Store(int32(http.StatusNotFound))
testutil.Assert(t, h.sendAll(h.queue...), "all sends failed unexpectedly")
assert.True(t, h.sendAll(h.queue...), "all sends failed unexpectedly")
checkNoErr()
status2.Store(int32(http.StatusInternalServerError))
testutil.Assert(t, !h.sendAll(h.queue...), "all sends succeeded unexpectedly")
assert.True(t, !h.sendAll(h.queue...), "all sends succeeded unexpectedly")
checkNoErr()
}
@ -215,11 +215,11 @@ func TestCustomDo(t *testing.T) {
received = true
body, err := ioutil.ReadAll(req.Body)
testutil.Ok(t, err)
assert.NoError(t, err)
testutil.Equals(t, testBody, string(body))
assert.Equal(t, testBody, string(body))
testutil.Equals(t, testURL, req.URL.String())
assert.Equal(t, testURL, req.URL.String())
return &http.Response{
Body: ioutil.NopCloser(bytes.NewBuffer(nil)),
@ -229,7 +229,7 @@ func TestCustomDo(t *testing.T) {
h.sendOne(context.Background(), nil, testURL, []byte(testBody))
testutil.Assert(t, received, "Expected to receive an alert, but didn't")
assert.True(t, received, "Expected to receive an alert, but didn't")
}
func TestExternalLabels(t *testing.T) {
@ -263,7 +263,7 @@ func TestExternalLabels(t *testing.T) {
{Labels: labels.FromStrings("alertname", "externalrelabelthis", "a", "c")},
}
testutil.Ok(t, alertsEqual(expected, h.queue))
assert.NoError(t, alertsEqual(expected, h.queue))
}
func TestHandlerRelabel(t *testing.T) {
@ -299,7 +299,7 @@ func TestHandlerRelabel(t *testing.T) {
{Labels: labels.FromStrings("alertname", "renamed")},
}
testutil.Ok(t, alertsEqual(expected, h.queue))
assert.NoError(t, alertsEqual(expected, h.queue))
}
func TestHandlerQueuing(t *testing.T) {
@ -375,7 +375,7 @@ func TestHandlerQueuing(t *testing.T) {
case <-called:
expectedc <- expected
case err := <-errc:
testutil.Ok(t, err)
assert.NoError(t, err)
return
case <-time.After(5 * time.Second):
t.Fatalf("Alerts were not pushed")
@ -408,7 +408,7 @@ func TestHandlerQueuing(t *testing.T) {
expectedc <- alerts[:maxBatchSize]
select {
case err := <-errc:
testutil.Ok(t, err)
assert.NoError(t, err)
case <-time.After(5 * time.Second):
t.Fatalf("Alerts were not pushed")
}
@ -435,10 +435,10 @@ func TestLabelSetNotReused(t *testing.T) {
tg := makeInputTargetGroup()
_, _, err := alertmanagerFromGroup(tg, &config.AlertmanagerConfig{})
testutil.Ok(t, err)
assert.NoError(t, err)
// Target modified during alertmanager extraction
testutil.Equals(t, tg, makeInputTargetGroup())
assert.Equal(t, tg, makeInputTargetGroup())
}
func TestReload(t *testing.T) {
@ -469,7 +469,7 @@ alerting:
if err := yaml.UnmarshalStrict([]byte(s), cfg); err != nil {
t.Fatalf("Unable to load YAML config: %s", err)
}
testutil.Equals(t, 1, len(cfg.AlertingConfig.AlertmanagerConfigs))
assert.Equal(t, 1, len(cfg.AlertingConfig.AlertmanagerConfigs))
if err := n.ApplyConfig(cfg); err != nil {
t.Fatalf("Error Applying the config:%v", err)
@ -486,7 +486,7 @@ alerting:
n.reload(tgs)
res := n.Alertmanagers()[0].String()
testutil.Equals(t, tt.out, res)
assert.Equal(t, tt.out, res)
}
}
@ -523,7 +523,7 @@ alerting:
if err := yaml.UnmarshalStrict([]byte(s), cfg); err != nil {
t.Fatalf("Unable to load YAML config: %s", err)
}
testutil.Equals(t, 1, len(cfg.AlertingConfig.AlertmanagerConfigs))
assert.Equal(t, 1, len(cfg.AlertingConfig.AlertmanagerConfigs))
if err := n.ApplyConfig(cfg); err != nil {
t.Fatalf("Error Applying the config:%v", err)
@ -541,7 +541,7 @@ alerting:
n.reload(tgs)
res := n.DroppedAlertmanagers()[0].String()
testutil.Equals(t, res, tt.out)
assert.Equal(t, res, tt.out)
}
}
@ -561,5 +561,5 @@ func makeInputTargetGroup() *targetgroup.Group {
}
func TestLabelsToOpenAPILabelSet(t *testing.T) {
testutil.Equals(t, models.LabelSet{"aaa": "111", "bbb": "222"}, labelsToOpenAPILabelSet(labels.Labels{{Name: "aaa", Value: "111"}, {Name: "bbb", Value: "222"}}))
assert.Equal(t, models.LabelSet{"aaa": "111", "bbb": "222"}, labelsToOpenAPILabelSet(labels.Labels{{Name: "aaa", Value: "111"}, {Name: "bbb", Value: "222"}}))
}

View file

@ -18,7 +18,7 @@ import (
"strings"
"testing"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
)
func TestLabels_String(t *testing.T) {
@ -50,7 +50,7 @@ func TestLabels_String(t *testing.T) {
}
for _, c := range cases {
str := c.lables.String()
testutil.Equals(t, c.expected, str)
assert.Equal(t, c.expected, str)
}
}
@ -181,7 +181,7 @@ func TestLabels_MatchLabels(t *testing.T) {
for i, test := range tests {
got := labels.MatchLabels(test.on, test.providedNames...)
testutil.Equals(t, test.expected, got, "unexpected labelset for test case %d", i)
assert.Equal(t, test.expected, got, "unexpected labelset for test case %d", i)
}
}
@ -206,8 +206,8 @@ func TestLabels_HasDuplicateLabelNames(t *testing.T) {
for i, c := range cases {
l, d := c.Input.HasDuplicateLabelNames()
testutil.Equals(t, c.Duplicate, d, "test %d: incorrect duplicate bool", i)
testutil.Equals(t, c.LabelName, l, "test %d: incorrect label name", i)
assert.Equal(t, c.Duplicate, d, "test %d: incorrect duplicate bool", i)
assert.Equal(t, c.LabelName, l, "test %d: incorrect label name", i)
}
}
@ -287,7 +287,7 @@ func TestLabels_WithoutEmpty(t *testing.T) {
},
} {
t.Run("", func(t *testing.T) {
testutil.Equals(t, test.expected, test.input.WithoutEmpty())
assert.Equal(t, test.expected, test.input.WithoutEmpty())
})
}
}
@ -368,7 +368,7 @@ func TestLabels_Equal(t *testing.T) {
for i, test := range tests {
got := Equal(labels, test.compared)
testutil.Equals(t, test.expected, got, "unexpected comparison result for test case %d", i)
assert.Equal(t, test.expected, got, "unexpected comparison result for test case %d", i)
}
}
@ -385,12 +385,12 @@ func TestLabels_FromStrings(t *testing.T) {
},
}
testutil.Equals(t, expected, labels, "unexpected labelset")
assert.Equal(t, expected, labels, "unexpected labelset")
defer func() { recover() }()
FromStrings("aaa", "111", "bbb")
testutil.Assert(t, false, "did not panic as expected")
assert.True(t, false, "did not panic as expected")
}
func TestLabels_Compare(t *testing.T) {
@ -508,7 +508,7 @@ func TestLabels_Compare(t *testing.T) {
for i, test := range tests {
got := Compare(labels, test.compared)
testutil.Equals(t, test.expected, got, "unexpected comparison result for test case %d", i)
assert.Equal(t, test.expected, got, "unexpected comparison result for test case %d", i)
}
}
@ -540,34 +540,34 @@ func TestLabels_Has(t *testing.T) {
for i, test := range tests {
got := labelsSet.Has(test.input)
testutil.Equals(t, test.expected, got, "unexpected comparison result for test case %d", i)
assert.Equal(t, test.expected, got, "unexpected comparison result for test case %d", i)
}
}
func TestLabels_Get(t *testing.T) {
testutil.Equals(t, "", Labels{{"aaa", "111"}, {"bbb", "222"}}.Get("foo"))
testutil.Equals(t, "111", Labels{{"aaa", "111"}, {"bbb", "222"}}.Get("aaa"))
assert.Equal(t, "", Labels{{"aaa", "111"}, {"bbb", "222"}}.Get("foo"))
assert.Equal(t, "111", Labels{{"aaa", "111"}, {"bbb", "222"}}.Get("aaa"))
}
func TestLabels_Copy(t *testing.T) {
testutil.Equals(t, Labels{{"aaa", "111"}, {"bbb", "222"}}, Labels{{"aaa", "111"}, {"bbb", "222"}}.Copy())
assert.Equal(t, Labels{{"aaa", "111"}, {"bbb", "222"}}, Labels{{"aaa", "111"}, {"bbb", "222"}}.Copy())
}
func TestLabels_Map(t *testing.T) {
testutil.Equals(t, map[string]string{"aaa": "111", "bbb": "222"}, Labels{{"aaa", "111"}, {"bbb", "222"}}.Map())
assert.Equal(t, map[string]string{"aaa": "111", "bbb": "222"}, Labels{{"aaa", "111"}, {"bbb", "222"}}.Map())
}
func TestLabels_WithLabels(t *testing.T) {
testutil.Equals(t, Labels{{"aaa", "111"}, {"bbb", "222"}}, Labels{{"aaa", "111"}, {"bbb", "222"}, {"ccc", "333"}}.WithLabels("aaa", "bbb"))
assert.Equal(t, Labels{{"aaa", "111"}, {"bbb", "222"}}, Labels{{"aaa", "111"}, {"bbb", "222"}, {"ccc", "333"}}.WithLabels("aaa", "bbb"))
}
func TestLabels_WithoutLabels(t *testing.T) {
testutil.Equals(t, Labels{{"aaa", "111"}}, Labels{{"aaa", "111"}, {"bbb", "222"}, {"ccc", "333"}}.WithoutLabels("bbb", "ccc"))
testutil.Equals(t, Labels{{"aaa", "111"}}, Labels{{"aaa", "111"}, {"bbb", "222"}, {MetricName, "333"}}.WithoutLabels("bbb"))
assert.Equal(t, Labels{{"aaa", "111"}}, Labels{{"aaa", "111"}, {"bbb", "222"}, {"ccc", "333"}}.WithoutLabels("bbb", "ccc"))
assert.Equal(t, Labels{{"aaa", "111"}}, Labels{{"aaa", "111"}, {"bbb", "222"}, {MetricName, "333"}}.WithoutLabels("bbb"))
}
func TestBulider_NewBulider(t *testing.T) {
testutil.Equals(
assert.Equal(
t,
&Builder{
base: Labels{{"aaa", "111"}},
@ -579,7 +579,7 @@ func TestBulider_NewBulider(t *testing.T) {
}
func TestBuilder_Del(t *testing.T) {
testutil.Equals(
assert.Equal(
t,
&Builder{
del: []string{"bbb"},
@ -593,7 +593,7 @@ func TestBuilder_Del(t *testing.T) {
}
func TestBuilder_Set(t *testing.T) {
testutil.Equals(
assert.Equal(
t,
&Builder{
base: Labels{{"aaa", "111"}},
@ -607,7 +607,7 @@ func TestBuilder_Set(t *testing.T) {
}).Set("bbb", "222"),
)
testutil.Equals(
assert.Equal(
t,
&Builder{
base: Labels{{"aaa", "111"}},
@ -623,7 +623,7 @@ func TestBuilder_Set(t *testing.T) {
}
func TestBuilder_Labels(t *testing.T) {
testutil.Equals(
assert.Equal(
t,
Labels{{"aaa", "111"}, {"ccc", "333"}, {"ddd", "444"}},
(&Builder{
@ -639,9 +639,9 @@ func TestLabels_Hash(t *testing.T) {
{Name: "foo", Value: "bar"},
{Name: "baz", Value: "qux"},
}
testutil.Equals(t, lbls.Hash(), lbls.Hash())
testutil.Assert(t, lbls.Hash() != Labels{lbls[1], lbls[0]}.Hash(), "unordered labels match.")
testutil.Assert(t, lbls.Hash() != Labels{lbls[0]}.Hash(), "different labels match.")
assert.Equal(t, lbls.Hash(), lbls.Hash())
assert.True(t, lbls.Hash() != Labels{lbls[1], lbls[0]}.Hash(), "unordered labels match.")
assert.True(t, lbls.Hash() != Labels{lbls[0]}.Hash(), "different labels match.")
}
var benchmarkLabelsResult uint64

View file

@ -16,12 +16,12 @@ package labels
import (
"testing"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
)
func mustNewMatcher(t *testing.T, mType MatchType, value string) *Matcher {
m, err := NewMatcher(mType, "", value)
testutil.Ok(t, err)
assert.NoError(t, err)
return m
}
@ -84,7 +84,7 @@ func TestMatcher(t *testing.T) {
}
for _, test := range tests {
testutil.Equals(t, test.matcher.Matches(test.value), test.match)
assert.Equal(t, test.matcher.Matches(test.value), test.match)
}
}
@ -113,7 +113,7 @@ func TestInverse(t *testing.T) {
for _, test := range tests {
result, err := test.matcher.Inverse()
testutil.Ok(t, err)
testutil.Equals(t, test.expected.Type, result.Type)
assert.NoError(t, err)
assert.Equal(t, test.expected.Type, result.Type)
}
}

View file

@ -17,7 +17,7 @@ import (
"regexp/syntax"
"testing"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
)
func TestNewFastRegexMatcher(t *testing.T) {
@ -54,8 +54,8 @@ func TestNewFastRegexMatcher(t *testing.T) {
for _, c := range cases {
m, err := NewFastRegexMatcher(c.regex)
testutil.Ok(t, err)
testutil.Equals(t, c.expected, m.MatchString(c.value))
assert.NoError(t, err)
assert.Equal(t, c.expected, m.MatchString(c.value))
}
}
@ -88,11 +88,11 @@ func TestOptimizeConcatRegex(t *testing.T) {
for _, c := range cases {
parsed, err := syntax.Parse(c.regex, syntax.Perl)
testutil.Ok(t, err)
assert.NoError(t, err)
prefix, suffix, contains := optimizeConcatRegex(parsed)
testutil.Equals(t, c.prefix, prefix)
testutil.Equals(t, c.suffix, suffix)
testutil.Equals(t, c.contains, contains)
assert.Equal(t, c.prefix, prefix)
assert.Equal(t, c.suffix, suffix)
assert.Equal(t, c.contains, contains)
}
}

View file

@ -17,7 +17,7 @@ import (
"testing"
"time"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
)
type counter int
@ -35,13 +35,13 @@ func TestDedupe(t *testing.T) {
// Log 10 times quickly, ensure they are deduped.
for i := 0; i < 10; i++ {
err := d.Log("msg", "hello")
testutil.Ok(t, err)
assert.NoError(t, err)
}
testutil.Equals(t, 1, int(c))
assert.Equal(t, 1, int(c))
// Wait, then log again, make sure it is logged.
time.Sleep(200 * time.Millisecond)
err := d.Log("msg", "hello")
testutil.Ok(t, err)
testutil.Equals(t, 2, int(c))
assert.NoError(t, err)
assert.Equal(t, 2, int(c))
}

View file

@ -20,71 +20,71 @@ import (
"strings"
"testing"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
)
func TestJSONFileLogger_basic(t *testing.T) {
f, err := ioutil.TempFile("", "logging")
testutil.Ok(t, err)
assert.NoError(t, err)
defer func() {
testutil.Ok(t, f.Close())
testutil.Ok(t, os.Remove(f.Name()))
assert.NoError(t, f.Close())
assert.NoError(t, os.Remove(f.Name()))
}()
l, err := NewJSONFileLogger(f.Name())
testutil.Ok(t, err)
testutil.Assert(t, l != nil, "logger can't be nil")
assert.NoError(t, err)
assert.NotNil(t, l, "logger can't be nil")
err = l.Log("test", "yes")
testutil.Ok(t, err)
assert.NoError(t, err)
r := make([]byte, 1024)
_, err = f.Read(r)
testutil.Ok(t, err)
assert.NoError(t, err)
result, err := regexp.Match(`^{"test":"yes","ts":"[^"]+"}\n`, r)
testutil.Ok(t, err)
testutil.Assert(t, result, "unexpected content: %s", r)
assert.NoError(t, err)
assert.True(t, result, "unexpected content: %s", r)
err = l.Close()
testutil.Ok(t, err)
assert.NoError(t, err)
err = l.file.Close()
testutil.NotOk(t, err)
testutil.Assert(t, strings.HasSuffix(err.Error(), os.ErrClosed.Error()), "file not closed")
assert.Error(t, err)
assert.True(t, strings.HasSuffix(err.Error(), os.ErrClosed.Error()), "file not closed")
}
func TestJSONFileLogger_parallel(t *testing.T) {
f, err := ioutil.TempFile("", "logging")
testutil.Ok(t, err)
assert.NoError(t, err)
defer func() {
testutil.Ok(t, f.Close())
testutil.Ok(t, os.Remove(f.Name()))
assert.NoError(t, f.Close())
assert.NoError(t, os.Remove(f.Name()))
}()
l, err := NewJSONFileLogger(f.Name())
testutil.Ok(t, err)
testutil.Assert(t, l != nil, "logger can't be nil")
assert.NoError(t, err)
assert.NotNil(t, l, "logger can't be nil")
err = l.Log("test", "yes")
testutil.Ok(t, err)
assert.NoError(t, err)
l2, err := NewJSONFileLogger(f.Name())
testutil.Ok(t, err)
testutil.Assert(t, l != nil, "logger can't be nil")
assert.NoError(t, err)
assert.NotNil(t, l, "logger can't be nil")
err = l2.Log("test", "yes")
testutil.Ok(t, err)
assert.NoError(t, err)
err = l.Close()
testutil.Ok(t, err)
assert.NoError(t, err)
err = l.file.Close()
testutil.NotOk(t, err)
testutil.Assert(t, strings.HasSuffix(err.Error(), os.ErrClosed.Error()), "file not closed")
assert.Error(t, err)
assert.True(t, strings.HasSuffix(err.Error(), os.ErrClosed.Error()), "file not closed")
err = l2.Close()
testutil.Ok(t, err)
assert.NoError(t, err)
err = l2.file.Close()
testutil.NotOk(t, err)
testutil.Assert(t, strings.HasSuffix(err.Error(), os.ErrClosed.Error()), "file not closed")
assert.Error(t, err)
assert.True(t, strings.HasSuffix(err.Error(), os.ErrClosed.Error()), "file not closed")
}

View file

@ -16,7 +16,7 @@ package pool
import (
"testing"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
)
func makeFunc(size int) interface{} {
@ -44,7 +44,7 @@ func TestPool(t *testing.T) {
}
for _, c := range cases {
ret := testPool.Get(c.size)
testutil.Equals(t, c.expectedCap, cap(ret.([]int)))
assert.Equal(t, c.expectedCap, cap(ret.([]int)))
testPool.Put(ret)
}
}

View file

@ -17,9 +17,9 @@ import (
"testing"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/assert"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/util/testutil"
)
func TestRelabel(t *testing.T) {
@ -414,7 +414,7 @@ func TestRelabel(t *testing.T) {
for _, test := range tests {
res := Process(test.input, test.relabel...)
testutil.Equals(t, test.output, res)
assert.Equal(t, test.output, res)
}
}
@ -440,7 +440,7 @@ func TestTargetLabelValidity(t *testing.T) {
{"foo${bar}foo", true},
}
for _, test := range tests {
testutil.Assert(t, relabelTarget.Match([]byte(test.str)) == test.valid,
assert.True(t, relabelTarget.Match([]byte(test.str)) == test.valid,
"Expected %q to be %v", test.str, test.valid)
}
}

View file

@ -18,7 +18,7 @@ import (
"strings"
"testing"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
)
func TestParseFileSuccess(t *testing.T) {
@ -163,9 +163,9 @@ groups:
for _, tst := range tests {
rgs, errs := Parse([]byte(tst.ruleString))
testutil.Assert(t, rgs != nil, "Rule parsing, rule=\n"+tst.ruleString)
assert.NotNil(t, rgs, "Rule parsing, rule=\n"+tst.ruleString)
passed := (tst.shouldPass && len(errs) == 0) || (!tst.shouldPass && len(errs) > 0)
testutil.Assert(t, passed, "Rule validation failed, rule=\n"+tst.ruleString)
assert.True(t, passed, "Rule validation failed, rule=\n"+tst.ruleString)
}
}

View file

@ -17,9 +17,10 @@ import (
"io"
"testing"
"github.com/stretchr/testify/assert"
"github.com/prometheus/prometheus/pkg/exemplar"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/util/testutil"
)
func TestOpenMetricsParse(t *testing.T) {
@ -220,7 +221,7 @@ foo_total 17.0 1520879607.789 # {xx="yy"} 5`
if err == io.EOF {
break
}
testutil.Ok(t, err)
assert.NoError(t, err)
switch et {
case EntrySeries:
@ -230,40 +231,40 @@ foo_total 17.0 1520879607.789 # {xx="yy"} 5`
p.Metric(&res)
found := p.Exemplar(&e)
testutil.Equals(t, exp[i].m, string(m))
testutil.Equals(t, exp[i].t, ts)
testutil.Equals(t, exp[i].v, v)
testutil.Equals(t, exp[i].lset, res)
assert.Equal(t, exp[i].m, string(m))
assert.Equal(t, exp[i].t, ts)
assert.Equal(t, exp[i].v, v)
assert.Equal(t, exp[i].lset, res)
if exp[i].e == nil {
testutil.Equals(t, false, found)
assert.Equal(t, false, found)
} else {
testutil.Equals(t, true, found)
testutil.Equals(t, *exp[i].e, e)
assert.Equal(t, true, found)
assert.Equal(t, *exp[i].e, e)
}
res = res[:0]
case EntryType:
m, typ := p.Type()
testutil.Equals(t, exp[i].m, string(m))
testutil.Equals(t, exp[i].typ, typ)
assert.Equal(t, exp[i].m, string(m))
assert.Equal(t, exp[i].typ, typ)
case EntryHelp:
m, h := p.Help()
testutil.Equals(t, exp[i].m, string(m))
testutil.Equals(t, exp[i].help, string(h))
assert.Equal(t, exp[i].m, string(m))
assert.Equal(t, exp[i].help, string(h))
case EntryUnit:
m, u := p.Unit()
testutil.Equals(t, exp[i].m, string(m))
testutil.Equals(t, exp[i].unit, string(u))
assert.Equal(t, exp[i].m, string(m))
assert.Equal(t, exp[i].unit, string(u))
case EntryComment:
testutil.Equals(t, exp[i].comment, string(p.Comment()))
assert.Equal(t, exp[i].comment, string(p.Comment()))
}
i++
}
testutil.Equals(t, len(exp), i)
assert.Equal(t, len(exp), i)
}
func TestOpenMetricsParseErrors(t *testing.T) {
@ -510,7 +511,7 @@ func TestOpenMetricsParseErrors(t *testing.T) {
for err == nil {
_, err = p.Next()
}
testutil.Equals(t, c.err, err.Error(), "test %d: %s", i, c.input)
assert.Equal(t, c.err, err.Error(), "test %d: %s", i, c.input)
}
}
@ -577,10 +578,10 @@ func TestOMNullByteHandling(t *testing.T) {
}
if c.err == "" {
testutil.Equals(t, io.EOF, err, "test %d", i)
assert.Equal(t, io.EOF, err, "test %d", i)
continue
}
testutil.Equals(t, c.err, err.Error(), "test %d", i)
assert.Equal(t, c.err, err.Error(), "test %d", i)
}
}

View file

@ -23,8 +23,9 @@ import (
"github.com/prometheus/common/expfmt"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/assert"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/util/testutil"
)
func TestPromParse(t *testing.T) {
@ -179,7 +180,7 @@ testmetric{label="\"bar\""} 1`
if err == io.EOF {
break
}
testutil.Ok(t, err)
assert.NoError(t, err)
switch et {
case EntrySeries:
@ -187,29 +188,29 @@ testmetric{label="\"bar\""} 1`
p.Metric(&res)
testutil.Equals(t, exp[i].m, string(m))
testutil.Equals(t, exp[i].t, ts)
testutil.Equals(t, exp[i].v, v)
testutil.Equals(t, exp[i].lset, res)
assert.Equal(t, exp[i].m, string(m))
assert.Equal(t, exp[i].t, ts)
assert.Equal(t, exp[i].v, v)
assert.Equal(t, exp[i].lset, res)
res = res[:0]
case EntryType:
m, typ := p.Type()
testutil.Equals(t, exp[i].m, string(m))
testutil.Equals(t, exp[i].typ, typ)
assert.Equal(t, exp[i].m, string(m))
assert.Equal(t, exp[i].typ, typ)
case EntryHelp:
m, h := p.Help()
testutil.Equals(t, exp[i].m, string(m))
testutil.Equals(t, exp[i].help, string(h))
assert.Equal(t, exp[i].m, string(m))
assert.Equal(t, exp[i].help, string(h))
case EntryComment:
testutil.Equals(t, exp[i].comment, string(p.Comment()))
assert.Equal(t, exp[i].comment, string(p.Comment()))
}
i++
}
testutil.Equals(t, len(exp), i)
assert.Equal(t, len(exp), i)
}
func TestPromParseErrors(t *testing.T) {
@ -277,8 +278,8 @@ func TestPromParseErrors(t *testing.T) {
for err == nil {
_, err = p.Next()
}
testutil.NotOk(t, err)
testutil.Equals(t, c.err, err.Error(), "test %d", i)
assert.Error(t, err)
assert.Equal(t, c.err, err.Error(), "test %d", i)
}
}
@ -329,12 +330,12 @@ func TestPromNullByteHandling(t *testing.T) {
}
if c.err == "" {
testutil.Equals(t, io.EOF, err, "test %d", i)
assert.Equal(t, io.EOF, err, "test %d", i)
continue
}
testutil.NotOk(t, err)
testutil.Equals(t, c.err, err.Error(), "test %d", i)
assert.Error(t, err)
assert.Equal(t, c.err, err.Error(), "test %d", i)
}
}
@ -349,11 +350,11 @@ func BenchmarkParse(b *testing.B) {
} {
for _, fn := range []string{"promtestdata.txt", "promtestdata.nometa.txt"} {
f, err := os.Open(fn)
testutil.Ok(b, err)
assert.NoError(b, err)
defer f.Close()
buf, err := ioutil.ReadAll(f)
testutil.Ok(b, err)
assert.NoError(b, err)
b.Run(parserName+"/no-decode-metric/"+fn, func(b *testing.B) {
total := 0
@ -483,18 +484,18 @@ func BenchmarkGzip(b *testing.B) {
for _, fn := range []string{"promtestdata.txt", "promtestdata.nometa.txt"} {
b.Run(fn, func(b *testing.B) {
f, err := os.Open(fn)
testutil.Ok(b, err)
assert.NoError(b, err)
defer f.Close()
var buf bytes.Buffer
gw := gzip.NewWriter(&buf)
n, err := io.Copy(gw, f)
testutil.Ok(b, err)
testutil.Ok(b, gw.Close())
assert.NoError(b, err)
assert.NoError(b, gw.Close())
gbuf, err := ioutil.ReadAll(&buf)
testutil.Ok(b, err)
assert.NoError(b, err)
k := b.N / promtestdataSampleCount
@ -506,11 +507,11 @@ func BenchmarkGzip(b *testing.B) {
for i := 0; i < k; i++ {
gr, err := gzip.NewReader(bytes.NewReader(gbuf))
testutil.Ok(b, err)
assert.NoError(b, err)
d, err := ioutil.ReadAll(gr)
testutil.Ok(b, err)
testutil.Ok(b, gr.Close())
assert.NoError(b, err)
assert.NoError(b, gr.Close())
total += len(d)
}

View file

@ -23,12 +23,13 @@ import (
"time"
"github.com/go-kit/kit/log"
"github.com/stretchr/testify/assert"
"go.uber.org/goleak"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/pkg/timestamp"
"github.com/prometheus/prometheus/promql/parser"
"github.com/prometheus/prometheus/storage"
"github.com/prometheus/prometheus/util/testutil"
"go.uber.org/goleak"
)
func TestMain(m *testing.M) {
@ -39,7 +40,7 @@ func TestQueryConcurrency(t *testing.T) {
maxConcurrency := 10
dir, err := ioutil.TempDir("", "test_concurrency")
testutil.Ok(t, err)
assert.NoError(t, err)
defer os.RemoveAll(dir)
queryTracker := NewActiveQueryTracker(dir, maxConcurrency, nil)
@ -118,10 +119,10 @@ func TestQueryTimeout(t *testing.T) {
})
res := query.Exec(ctx)
testutil.NotOk(t, res.Err, "expected timeout error but got none")
assert.Error(t, res.Err, "expected timeout error but got none")
var e ErrQueryTimeout
testutil.Assert(t, errors.As(res.Err, &e), "expected timeout error but got: %s", res.Err)
assert.True(t, errors.As(res.Err, &e), "expected timeout error but got: %s", res.Err)
}
const errQueryCanceled = ErrQueryCanceled("test statement execution")
@ -159,8 +160,8 @@ func TestQueryCancel(t *testing.T) {
block <- struct{}{}
<-processing
testutil.NotOk(t, res.Err, "expected cancellation error for query1 but got none")
testutil.Equals(t, errQueryCanceled, res.Err)
assert.Error(t, res.Err, "expected cancellation error for query1 but got none")
assert.Equal(t, errQueryCanceled, res.Err)
// Canceling a query before starting it must have no effect.
query2 := engine.newTestQuery(func(ctx context.Context) error {
@ -169,7 +170,7 @@ func TestQueryCancel(t *testing.T) {
query2.Cancel()
res = query2.Exec(ctx)
testutil.Ok(t, res.Err)
assert.NoError(t, res.Err)
}
// errQuerier implements storage.Querier which always returns error.
@ -210,18 +211,18 @@ func TestQueryError(t *testing.T) {
defer cancelCtx()
vectorQuery, err := engine.NewInstantQuery(queryable, "foo", time.Unix(1, 0))
testutil.Ok(t, err)
assert.NoError(t, err)
res := vectorQuery.Exec(ctx)
testutil.NotOk(t, res.Err, "expected error on failed select but got none")
testutil.Assert(t, errors.Is(res.Err, errStorage), "expected error doesn't match")
assert.Error(t, res.Err, "expected error on failed select but got none")
assert.True(t, errors.Is(res.Err, errStorage), "expected error doesn't match")
matrixQuery, err := engine.NewInstantQuery(queryable, "foo[1m]", time.Unix(1, 0))
testutil.Ok(t, err)
assert.NoError(t, err)
res = matrixQuery.Exec(ctx)
testutil.NotOk(t, res.Err, "expected error on failed select but got none")
testutil.Assert(t, errors.Is(res.Err, errStorage), "expected error doesn't match")
assert.Error(t, res.Err, "expected error on failed select but got none")
assert.True(t, errors.Is(res.Err, errStorage), "expected error doesn't match")
}
type noopHintRecordingQueryable struct {
@ -377,12 +378,12 @@ func TestSelectHintsSetCorrectly(t *testing.T) {
} else {
query, err = engine.NewRangeQuery(hintsRecorder, tc.query, timestamp.Time(tc.start), timestamp.Time(tc.end), time.Second)
}
testutil.Ok(t, err)
assert.NoError(t, err)
res := query.Exec(context.Background())
testutil.Ok(t, res.Err)
assert.NoError(t, res.Err)
testutil.Equals(t, tc.expected, hintsRecorder.hints)
assert.Equal(t, tc.expected, hintsRecorder.hints)
})
}
@ -425,8 +426,8 @@ func TestEngineShutdown(t *testing.T) {
block <- struct{}{}
<-processing
testutil.NotOk(t, res.Err, "expected error on shutdown during query but got none")
testutil.Equals(t, errQueryCanceled, res.Err)
assert.Error(t, res.Err, "expected error on shutdown during query but got none")
assert.Equal(t, errQueryCanceled, res.Err)
query2 := engine.newTestQuery(func(context.Context) error {
t.Fatalf("reached query execution unexpectedly")
@ -436,10 +437,10 @@ func TestEngineShutdown(t *testing.T) {
// The second query is started after the engine shut down. It must
// be canceled immediately.
res2 := query2.Exec(ctx)
testutil.NotOk(t, res2.Err, "expected error on querying with canceled context but got none")
assert.Error(t, res2.Err, "expected error on querying with canceled context but got none")
var e ErrQueryCanceled
testutil.Assert(t, errors.As(res2.Err, &e), "expected cancellation error but got: %s", res2.Err)
assert.True(t, errors.As(res2.Err, &e), "expected cancellation error but got: %s", res2.Err)
}
func TestEngineEvalStmtTimestamps(t *testing.T) {
@ -447,11 +448,11 @@ func TestEngineEvalStmtTimestamps(t *testing.T) {
load 10s
metric 1 2
`)
testutil.Ok(t, err)
assert.NoError(t, err)
defer test.Close()
err = test.Run()
testutil.Ok(t, err)
assert.NoError(t, err)
cases := []struct {
Query string
@ -528,16 +529,16 @@ load 10s
} else {
qry, err = test.QueryEngine().NewRangeQuery(test.Queryable(), c.Query, c.Start, c.End, c.Interval)
}
testutil.Ok(t, err)
assert.NoError(t, err)
res := qry.Exec(test.Context())
if c.ShouldError {
testutil.NotOk(t, res.Err, "expected error for the query %q", c.Query)
assert.Error(t, res.Err, "expected error for the query %q", c.Query)
continue
}
testutil.Ok(t, res.Err)
testutil.Equals(t, c.Result, res.Value, "query %q failed", c.Query)
assert.NoError(t, res.Err)
assert.Equal(t, c.Result, res.Value, "query %q failed", c.Query)
}
}
@ -548,11 +549,11 @@ load 10s
bigmetric{a="1"} 1 2
bigmetric{a="2"} 1 2
`)
testutil.Ok(t, err)
assert.NoError(t, err)
defer test.Close()
err = test.Run()
testutil.Ok(t, err)
assert.NoError(t, err)
cases := []struct {
Query string
@ -764,11 +765,11 @@ load 10s
} else {
qry, err = engine.NewRangeQuery(test.Queryable(), c.Query, c.Start, c.End, c.Interval)
}
testutil.Ok(t, err)
assert.NoError(t, err)
res := qry.Exec(test.Context())
testutil.Equals(t, c.Result.Err, res.Err)
testutil.Equals(t, c.Result.Value, res.Value, "query %q failed", c.Query)
assert.Equal(t, c.Result.Err, res.Err)
assert.Equal(t, c.Result.Value, res.Value, "query %q failed", c.Query)
}
}
@ -1051,21 +1052,21 @@ func TestSubquerySelector(t *testing.T) {
} {
t.Run("", func(t *testing.T) {
test, err := NewTest(t, tst.loadString)
testutil.Ok(t, err)
assert.NoError(t, err)
defer test.Close()
testutil.Ok(t, test.Run())
assert.NoError(t, test.Run())
engine := test.QueryEngine()
for _, c := range tst.cases {
t.Run(c.Query, func(t *testing.T) {
qry, err := engine.NewInstantQuery(test.Queryable(), c.Query, c.Start)
testutil.Ok(t, err)
assert.NoError(t, err)
res := qry.Exec(test.Context())
testutil.Equals(t, c.Result.Err, res.Err)
assert.Equal(t, c.Result.Err, res.Err)
mat := res.Value.(Matrix)
sort.Sort(mat)
testutil.Equals(t, c.Result.Value, mat)
assert.Equal(t, c.Result.Value, mat)
})
}
})
@ -1110,7 +1111,7 @@ func TestQueryLogger_basic(t *testing.T) {
return contextDone(ctx, "test statement execution")
})
res := query.Exec(ctx)
testutil.Ok(t, res.Err)
assert.NoError(t, res.Err)
}
// Query works without query log initialized.
@ -1120,28 +1121,28 @@ func TestQueryLogger_basic(t *testing.T) {
engine.SetQueryLogger(f1)
queryExec()
for i, field := range []interface{}{"params", map[string]interface{}{"query": "test statement"}} {
testutil.Equals(t, field, f1.logs[i])
assert.Equal(t, field, f1.logs[i])
}
l := len(f1.logs)
queryExec()
testutil.Equals(t, 2*l, len(f1.logs))
assert.Equal(t, 2*l, len(f1.logs))
// Test that we close the query logger when unsetting it.
testutil.Assert(t, !f1.closed, "expected f1 to be open, got closed")
assert.True(t, !f1.closed, "expected f1 to be open, got closed")
engine.SetQueryLogger(nil)
testutil.Assert(t, f1.closed, "expected f1 to be closed, got open")
assert.True(t, f1.closed, "expected f1 to be closed, got open")
queryExec()
// Test that we close the query logger when swapping.
f2 := NewFakeQueryLogger()
f3 := NewFakeQueryLogger()
engine.SetQueryLogger(f2)
testutil.Assert(t, !f2.closed, "expected f2 to be open, got closed")
assert.True(t, !f2.closed, "expected f2 to be open, got closed")
queryExec()
engine.SetQueryLogger(f3)
testutil.Assert(t, f2.closed, "expected f2 to be closed, got open")
testutil.Assert(t, !f3.closed, "expected f3 to be open, got closed")
assert.True(t, f2.closed, "expected f2 to be closed, got open")
assert.True(t, !f3.closed, "expected f3 to be open, got closed")
queryExec()
}
@ -1165,12 +1166,12 @@ func TestQueryLogger_fields(t *testing.T) {
})
res := query.Exec(ctx)
testutil.Ok(t, res.Err)
assert.NoError(t, res.Err)
expected := []string{"foo", "bar"}
for i, field := range expected {
v := f1.logs[len(f1.logs)-len(expected)+i].(string)
testutil.Equals(t, field, v)
assert.Equal(t, field, v)
}
}
@ -1195,9 +1196,9 @@ func TestQueryLogger_error(t *testing.T) {
})
res := query.Exec(ctx)
testutil.NotOk(t, res.Err, "query should have failed")
assert.Error(t, res.Err, "query should have failed")
for i, field := range []interface{}{"params", map[string]interface{}{"query": "test statement"}, "error", testErr} {
testutil.Equals(t, f1.logs[i], field)
assert.Equal(t, f1.logs[i], field)
}
}

View file

@ -19,11 +19,12 @@ import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/pkg/timestamp"
"github.com/prometheus/prometheus/promql/parser"
"github.com/prometheus/prometheus/util/teststorage"
"github.com/prometheus/prometheus/util/testutil"
)
func TestDeriv(t *testing.T) {
@ -46,28 +47,28 @@ func TestDeriv(t *testing.T) {
a.Add(metric, 1493712816939, 1.0)
a.Add(metric, 1493712846939, 1.0)
testutil.Ok(t, a.Commit())
assert.NoError(t, a.Commit())
query, err := engine.NewInstantQuery(storage, "deriv(foo[30m])", timestamp.Time(1493712846939))
testutil.Ok(t, err)
assert.NoError(t, err)
result := query.Exec(context.Background())
testutil.Ok(t, result.Err)
assert.NoError(t, result.Err)
vec, _ := result.Vector()
testutil.Assert(t, len(vec) == 1, "Expected 1 result, got %d", len(vec))
testutil.Assert(t, vec[0].V == 0.0, "Expected 0.0 as value, got %f", vec[0].V)
assert.True(t, len(vec) == 1, "Expected 1 result, got %d", len(vec))
assert.True(t, vec[0].V == 0.0, "Expected 0.0 as value, got %f", vec[0].V)
}
func TestFunctionList(t *testing.T) {
// Test that Functions and parser.Functions list the same functions.
for i := range FunctionCalls {
_, ok := parser.Functions[i]
testutil.Assert(t, ok, fmt.Sprintf("function %s exists in promql package, but not in parser package", i))
assert.True(t, ok, fmt.Sprintf("function %s exists in promql package, but not in parser package", i))
}
for i := range parser.Functions {
_, ok := FunctionCalls[i]
testutil.Assert(t, ok, (fmt.Sprintf("function %s exists in parser package, but not in promql package", i)))
assert.True(t, ok, (fmt.Sprintf("function %s exists in parser package, but not in promql package", i)))
}
}

View file

@ -3,11 +3,8 @@
//line generated_parser.y:15
package parser
import __yyfmt__ "fmt"
//line generated_parser.y:15
import (
__yyfmt__ "fmt"
"math"
"sort"
"strconv"
@ -15,7 +12,7 @@ import (
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/pkg/value"
)
) //line generated_parser.y:15
//line generated_parser.y:28
type yySymType struct {

View file

@ -16,7 +16,7 @@ package parser
import (
"testing"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
)
type testCase struct {
@ -731,10 +731,10 @@ func TestLexer(t *testing.T) {
}
eofItem := Item{EOF, Pos(len(test.input)), ""}
testutil.Equals(t, lastItem, eofItem, "%d: input %q", i, test.input)
assert.Equal(t, lastItem, eofItem, "%d: input %q", i, test.input)
out = out[:len(out)-1]
testutil.Equals(t, test.expected, out, "%d: input %q", i, test.input)
assert.Equal(t, test.expected, out, "%d: input %q", i, test.input)
}
})
}

View file

@ -21,9 +21,9 @@ import (
"github.com/pkg/errors"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/assert"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/util/testutil"
)
var testExpr = []struct {
@ -2659,23 +2659,23 @@ func TestParseExpressions(t *testing.T) {
expr, err := ParseExpr(test.input)
// Unexpected errors are always caused by a bug.
testutil.Assert(t, err != errUnexpected, "unexpected error occurred")
assert.True(t, err != errUnexpected, "unexpected error occurred")
if !test.fail {
testutil.Ok(t, err)
testutil.Equals(t, test.expected, expr, "error on input '%s'", test.input)
assert.NoError(t, err)
assert.Equal(t, test.expected, expr, "error on input '%s'", test.input)
} else {
testutil.NotOk(t, err)
testutil.Assert(t, strings.Contains(err.Error(), test.errMsg), "unexpected error on input '%s', expected '%s', got '%s'", test.input, test.errMsg, err.Error())
assert.Error(t, err)
assert.True(t, strings.Contains(err.Error(), test.errMsg), "unexpected error on input '%s', expected '%s', got '%s'", test.input, test.errMsg, err.Error())
errorList, ok := err.(ParseErrors)
testutil.Assert(t, ok, "unexpected error type")
assert.True(t, ok, "unexpected error type")
for _, e := range errorList {
testutil.Assert(t, 0 <= e.PositionRange.Start, "parse error has negative position\nExpression '%s'\nError: %v", test.input, e)
testutil.Assert(t, e.PositionRange.Start <= e.PositionRange.End, "parse error has negative length\nExpression '%s'\nError: %v", test.input, e)
testutil.Assert(t, e.PositionRange.End <= Pos(len(test.input)), "parse error is not contained in input\nExpression '%s'\nError: %v", test.input, e)
assert.True(t, 0 <= e.PositionRange.Start, "parse error has negative position\nExpression '%s'\nError: %v", test.input, e)
assert.True(t, e.PositionRange.Start <= e.PositionRange.End, "parse error has negative length\nExpression '%s'\nError: %v", test.input, e)
assert.True(t, e.PositionRange.End <= Pos(len(test.input)), "parse error is not contained in input\nExpression '%s'\nError: %v", test.input, e)
}
}
})
@ -2685,11 +2685,11 @@ func TestParseExpressions(t *testing.T) {
// NaN has no equality. Thus, we need a separate test for it.
func TestNaNExpression(t *testing.T) {
expr, err := ParseExpr("NaN")
testutil.Ok(t, err)
assert.NoError(t, err)
nl, ok := expr.(*NumberLiteral)
testutil.Assert(t, ok, "expected number literal but got %T", expr)
testutil.Assert(t, math.IsNaN(float64(nl.Val)), "expected 'NaN' in number literal but got %v", nl.Val)
assert.True(t, ok, "expected number literal but got %T", expr)
assert.True(t, math.IsNaN(float64(nl.Val)), "expected 'NaN' in number literal but got %v", nl.Val)
}
func mustLabelMatcher(mt labels.MatchType, name, val string) *labels.Matcher {
@ -2804,14 +2804,14 @@ func TestParseSeries(t *testing.T) {
metric, vals, err := ParseSeriesDesc(test.input)
// Unexpected errors are always caused by a bug.
testutil.Assert(t, err != errUnexpected, "unexpected error occurred")
assert.True(t, err != errUnexpected, "unexpected error occurred")
if !test.fail {
testutil.Ok(t, err)
testutil.Equals(t, test.expectedMetric, metric, "error on input '%s'", test.input)
testutil.Equals(t, test.expectedValues, vals, "error in input '%s'", test.input)
assert.NoError(t, err)
assert.Equal(t, test.expectedMetric, metric, "error on input '%s'", test.input)
assert.Equal(t, test.expectedValues, vals, "error in input '%s'", test.input)
} else {
testutil.NotOk(t, err)
assert.Error(t, err)
}
}
}
@ -2821,7 +2821,7 @@ func TestRecoverParserRuntime(t *testing.T) {
var err error
defer func() {
testutil.Equals(t, errUnexpected, err)
assert.Equal(t, errUnexpected, err)
}()
defer p.recover(&err)
// Cause a runtime panic.
@ -2837,7 +2837,7 @@ func TestRecoverParserError(t *testing.T) {
e := errors.New("custom error")
defer func() {
testutil.Equals(t, e.Error(), err.Error())
assert.Equal(t, e.Error(), err.Error())
}()
defer p.recover(&err)

View file

@ -20,6 +20,7 @@ import (
"time"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/pkg/labels"
)

View file

@ -16,7 +16,7 @@ package parser
import (
"testing"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
)
func TestExprString(t *testing.T) {
@ -102,13 +102,13 @@ func TestExprString(t *testing.T) {
for _, test := range inputs {
expr, err := ParseExpr(test.in)
testutil.Ok(t, err)
assert.NoError(t, err)
exp := test.in
if test.out != "" {
exp = test.out
}
testutil.Equals(t, exp, expr.String())
assert.Equal(t, exp, expr.String())
}
}

View file

@ -17,18 +17,18 @@ import (
"path/filepath"
"testing"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
)
func TestEvaluations(t *testing.T) {
files, err := filepath.Glob("testdata/*.test")
testutil.Ok(t, err)
assert.NoError(t, err)
for _, fn := range files {
t.Run(fn, func(t *testing.T) {
test, err := newTestFromFile(t, fn)
testutil.Ok(t, err)
testutil.Ok(t, test.Run())
assert.NoError(t, err)
assert.NoError(t, test.Run())
test.Close()
})

View file

@ -20,7 +20,7 @@ import (
"regexp"
"testing"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
)
func TestQueryLogging(t *testing.T) {
@ -109,18 +109,18 @@ func TestIndexReuse(t *testing.T) {
func TestMMapFile(t *testing.T) {
file, err := ioutil.TempFile("", "mmapedFile")
testutil.Ok(t, err)
assert.NoError(t, err)
filename := file.Name()
defer os.Remove(filename)
fileAsBytes, err := getMMapedFile(filename, 2, nil)
testutil.Ok(t, err)
assert.NoError(t, err)
copy(fileAsBytes, "ab")
f, err := os.Open(filename)
testutil.Ok(t, err)
assert.NoError(t, err)
bytes := make([]byte, 4)
n, err := f.Read(bytes)

View file

@ -25,6 +25,7 @@ import (
"github.com/pkg/errors"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/promql/parser"
"github.com/prometheus/prometheus/storage"

View file

@ -18,9 +18,9 @@ import (
"testing"
"time"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/stretchr/testify/assert"
"github.com/prometheus/prometheus/util/testutil"
"github.com/prometheus/prometheus/pkg/labels"
)
func TestLazyLoader_WithSamplesTill(t *testing.T) {
@ -110,12 +110,12 @@ func TestLazyLoader_WithSamplesTill(t *testing.T) {
for _, c := range cases {
suite, err := NewLazyLoader(t, c.loadString)
testutil.Ok(t, err)
assert.NoError(t, err)
defer suite.Close()
for _, tc := range c.testCases {
suite.WithSamplesTill(tc.ts, func(err error) {
testutil.Ok(t, err)
assert.NoError(t, err)
if tc.checkOnlyError {
return
}
@ -123,20 +123,20 @@ func TestLazyLoader_WithSamplesTill(t *testing.T) {
// Check the series.
queryable := suite.Queryable()
querier, err := queryable.Querier(suite.Context(), math.MinInt64, math.MaxInt64)
testutil.Ok(t, err)
assert.NoError(t, err)
for _, s := range tc.series {
var matchers []*labels.Matcher
for _, label := range s.Metric {
m, err := labels.NewMatcher(labels.MatchEqual, label.Name, label.Value)
testutil.Ok(t, err)
assert.NoError(t, err)
matchers = append(matchers, m)
}
// Get the series for the matcher.
ss := querier.Select(false, nil, matchers...)
testutil.Assert(t, ss.Next(), "")
assert.True(t, ss.Next(), "")
storageSeries := ss.At()
testutil.Assert(t, !ss.Next(), "Expecting only 1 series")
assert.True(t, !ss.Next(), "Expecting only 1 series")
// Convert `storage.Series` to `promql.Series`.
got := Series{
@ -147,9 +147,9 @@ func TestLazyLoader_WithSamplesTill(t *testing.T) {
t, v := it.At()
got.Points = append(got.Points, Point{T: t, V: v})
}
testutil.Ok(t, it.Err())
assert.NoError(t, it.Err())
testutil.Equals(t, s, got)
assert.Equal(t, s, got)
}
})
}

View file

@ -21,11 +21,10 @@ import (
"github.com/pkg/errors"
"github.com/prometheus/prometheus/tsdb/chunkenc"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/promql/parser"
"github.com/prometheus/prometheus/storage"
"github.com/prometheus/prometheus/tsdb/chunkenc"
)
func (Matrix) Type() parser.ValueType { return parser.ValueTypeMatrix }

View file

@ -16,19 +16,17 @@ package rules
import (
"context"
"fmt"
html_template "html/template"
"net/url"
"strings"
"sync"
"time"
html_template "html/template"
yaml "gopkg.in/yaml.v2"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/pkg/errors"
"github.com/prometheus/common/model"
yaml "gopkg.in/yaml.v2"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/pkg/rulefmt"

View file

@ -15,22 +15,22 @@ package rules
import (
"context"
"fmt"
"testing"
"time"
"github.com/go-kit/kit/log"
"github.com/stretchr/testify/assert"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/pkg/timestamp"
"github.com/prometheus/prometheus/promql"
"github.com/prometheus/prometheus/promql/parser"
"github.com/prometheus/prometheus/util/teststorage"
"github.com/prometheus/prometheus/util/testutil"
)
func TestAlertingRuleHTMLSnippet(t *testing.T) {
expr, err := parser.ParseExpr(`foo{html="<b>BOLD<b>"}`)
testutil.Ok(t, err)
assert.NoError(t, err)
rule := NewAlertingRule("testrule", expr, 0, labels.FromStrings("html", "<b>BOLD</b>"), labels.FromStrings("html", "<b>BOLD</b>"), nil, false, nil)
const want = `alert: <a href="/test/prefix/graph?g0.expr=ALERTS%7Balertname%3D%22testrule%22%7D&g0.tab=1">testrule</a>
@ -42,7 +42,7 @@ annotations:
`
got := rule.HTMLSnippet("/test/prefix")
testutil.Assert(t, want == got, "incorrect HTML snippet; want:\n\n|%v|\n\ngot:\n\n|%v|", want, got)
assert.True(t, want == got, "incorrect HTML snippet; want:\n\n|%v|\n\ngot:\n\n|%v|", want, got)
}
func TestAlertingRuleState(t *testing.T) {
@ -81,7 +81,7 @@ func TestAlertingRuleState(t *testing.T) {
rule := NewAlertingRule(test.name, nil, 0, nil, nil, nil, true, nil)
rule.active = test.active
got := rule.State()
testutil.Assert(t, test.want == got, "test case %d unexpected AlertState, want:%d got:%d", i, test.want, got)
assert.True(t, test.want == got, "test case %d unexpected AlertState, want:%d got:%d", i, test.want, got)
}
}
@ -90,13 +90,13 @@ func TestAlertingRuleLabelsUpdate(t *testing.T) {
load 1m
http_requests{job="app-server", instance="0"} 75 85 70 70
`)
testutil.Ok(t, err)
assert.NoError(t, err)
defer suite.Close()
testutil.Ok(t, suite.Run())
assert.NoError(t, suite.Run())
expr, err := parser.ParseExpr(`http_requests < 100`)
testutil.Ok(t, err)
assert.NoError(t, err)
rule := NewAlertingRule(
"HTTPRequestRateLow",
@ -170,7 +170,7 @@ func TestAlertingRuleLabelsUpdate(t *testing.T) {
evalTime := baseTime.Add(time.Duration(i) * time.Minute)
result[0].Point.T = timestamp.FromTime(evalTime)
res, err := rule.Eval(suite.Context(), evalTime, EngineQueryFunc(suite.QueryEngine(), suite.Storage()), nil)
testutil.Ok(t, err)
assert.NoError(t, err)
var filteredRes promql.Vector // After removing 'ALERTS_FOR_STATE' samples.
for _, smpl := range res {
@ -179,11 +179,11 @@ func TestAlertingRuleLabelsUpdate(t *testing.T) {
filteredRes = append(filteredRes, smpl)
} else {
// If not 'ALERTS', it has to be 'ALERTS_FOR_STATE'.
testutil.Equals(t, "ALERTS_FOR_STATE", smplName)
assert.Equal(t, "ALERTS_FOR_STATE", smplName)
}
}
testutil.Equals(t, result, filteredRes)
assert.Equal(t, result, filteredRes)
}
}
@ -192,13 +192,13 @@ func TestAlertingRuleExternalLabelsInTemplate(t *testing.T) {
load 1m
http_requests{job="app-server", instance="0"} 75 85 70 70
`)
testutil.Ok(t, err)
assert.NoError(t, err)
defer suite.Close()
testutil.Ok(t, suite.Run())
assert.NoError(t, suite.Run())
expr, err := parser.ParseExpr(`http_requests < 100`)
testutil.Ok(t, err)
assert.NoError(t, err)
ruleWithoutExternalLabels := NewAlertingRule(
"ExternalLabelDoesNotExist",
@ -251,32 +251,32 @@ func TestAlertingRuleExternalLabelsInTemplate(t *testing.T) {
res, err := ruleWithoutExternalLabels.Eval(
suite.Context(), evalTime, EngineQueryFunc(suite.QueryEngine(), suite.Storage()), nil,
)
testutil.Ok(t, err)
assert.NoError(t, err)
for _, smpl := range res {
smplName := smpl.Metric.Get("__name__")
if smplName == "ALERTS" {
filteredRes = append(filteredRes, smpl)
} else {
// If not 'ALERTS', it has to be 'ALERTS_FOR_STATE'.
testutil.Equals(t, "ALERTS_FOR_STATE", smplName)
assert.Equal(t, "ALERTS_FOR_STATE", smplName)
}
}
res, err = ruleWithExternalLabels.Eval(
suite.Context(), evalTime, EngineQueryFunc(suite.QueryEngine(), suite.Storage()), nil,
)
testutil.Ok(t, err)
assert.NoError(t, err)
for _, smpl := range res {
smplName := smpl.Metric.Get("__name__")
if smplName == "ALERTS" {
filteredRes = append(filteredRes, smpl)
} else {
// If not 'ALERTS', it has to be 'ALERTS_FOR_STATE'.
testutil.Equals(t, "ALERTS_FOR_STATE", smplName)
assert.Equal(t, "ALERTS_FOR_STATE", smplName)
}
}
testutil.Equals(t, result, filteredRes)
assert.Equal(t, result, filteredRes)
}
func TestAlertingRuleEmptyLabelFromTemplate(t *testing.T) {
@ -284,13 +284,13 @@ func TestAlertingRuleEmptyLabelFromTemplate(t *testing.T) {
load 1m
http_requests{job="app-server", instance="0"} 75 85 70 70
`)
testutil.Ok(t, err)
assert.NoError(t, err)
defer suite.Close()
testutil.Ok(t, suite.Run())
assert.NoError(t, suite.Run())
expr, err := parser.ParseExpr(`http_requests < 100`)
testutil.Ok(t, err)
assert.NoError(t, err)
rule := NewAlertingRule(
"EmptyLabel",
@ -321,17 +321,17 @@ func TestAlertingRuleEmptyLabelFromTemplate(t *testing.T) {
res, err := rule.Eval(
suite.Context(), evalTime, EngineQueryFunc(suite.QueryEngine(), suite.Storage()), nil,
)
testutil.Ok(t, err)
assert.NoError(t, err)
for _, smpl := range res {
smplName := smpl.Metric.Get("__name__")
if smplName == "ALERTS" {
filteredRes = append(filteredRes, smpl)
} else {
// If not 'ALERTS', it has to be 'ALERTS_FOR_STATE'.
testutil.Equals(t, "ALERTS_FOR_STATE", smplName)
assert.Equal(t, "ALERTS_FOR_STATE", smplName)
}
}
testutil.Equals(t, result, filteredRes)
assert.Equal(t, result, filteredRes)
}
func TestAlertingRuleDuplicate(t *testing.T) {
@ -362,7 +362,6 @@ func TestAlertingRuleDuplicate(t *testing.T) {
true, log.NewNopLogger(),
)
_, err := rule.Eval(ctx, now, EngineQueryFunc(engine, storage), nil)
testutil.NotOk(t, err)
e := fmt.Errorf("vector contains metrics with the same labelset after applying alert labels")
testutil.ErrorEqual(t, e, err)
assert.Error(t, err)
assert.EqualError(t, err, "vector contains metrics with the same labelset after applying alert labels")
}

View file

@ -26,6 +26,7 @@ import (
"github.com/go-kit/kit/log"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/assert"
"go.uber.org/goleak"
yaml "gopkg.in/yaml.v2"
@ -37,7 +38,6 @@ import (
"github.com/prometheus/prometheus/promql/parser"
"github.com/prometheus/prometheus/storage"
"github.com/prometheus/prometheus/util/teststorage"
"github.com/prometheus/prometheus/util/testutil"
)
func TestMain(m *testing.M) {
@ -50,14 +50,14 @@ func TestAlertingRule(t *testing.T) {
http_requests{job="app-server", instance="0", group="canary", severity="overwrite-me"} 75 85 95 105 105 95 85
http_requests{job="app-server", instance="1", group="canary", severity="overwrite-me"} 80 90 100 110 120 130 140
`)
testutil.Ok(t, err)
assert.NoError(t, err)
defer suite.Close()
err = suite.Run()
testutil.Ok(t, err)
assert.NoError(t, err)
expr, err := parser.ParseExpr(`http_requests{group="canary", job="app-server"} < 100`)
testutil.Ok(t, err)
assert.NoError(t, err)
rule := NewAlertingRule(
"HTTPRequestRateLow",
@ -157,7 +157,7 @@ func TestAlertingRule(t *testing.T) {
evalTime := baseTime.Add(test.time)
res, err := rule.Eval(suite.Context(), evalTime, EngineQueryFunc(suite.QueryEngine(), suite.Storage()), nil)
testutil.Ok(t, err)
assert.NoError(t, err)
var filteredRes promql.Vector // After removing 'ALERTS_FOR_STATE' samples.
for _, smpl := range res {
@ -166,21 +166,21 @@ func TestAlertingRule(t *testing.T) {
filteredRes = append(filteredRes, smpl)
} else {
// If not 'ALERTS', it has to be 'ALERTS_FOR_STATE'.
testutil.Equals(t, smplName, "ALERTS_FOR_STATE")
assert.Equal(t, smplName, "ALERTS_FOR_STATE")
}
}
for i := range test.result {
test.result[i].T = timestamp.FromTime(evalTime)
}
testutil.Assert(t, len(test.result) == len(filteredRes), "%d. Number of samples in expected and actual output don't match (%d vs. %d)", i, len(test.result), len(res))
assert.True(t, len(test.result) == len(filteredRes), "%d. Number of samples in expected and actual output don't match (%d vs. %d)", i, len(test.result), len(res))
sort.Slice(filteredRes, func(i, j int) bool {
return labels.Compare(filteredRes[i].Metric, filteredRes[j].Metric) < 0
})
testutil.Equals(t, test.result, filteredRes)
assert.Equal(t, test.result, filteredRes)
for _, aa := range rule.ActiveAlerts() {
testutil.Assert(t, aa.Labels.Get(model.MetricNameLabel) == "", "%s label set on active alert: %s", model.MetricNameLabel, aa.Labels)
assert.True(t, aa.Labels.Get(model.MetricNameLabel) == "", "%s label set on active alert: %s", model.MetricNameLabel, aa.Labels)
}
}
}
@ -191,14 +191,14 @@ func TestForStateAddSamples(t *testing.T) {
http_requests{job="app-server", instance="0", group="canary", severity="overwrite-me"} 75 85 95 105 105 95 85
http_requests{job="app-server", instance="1", group="canary", severity="overwrite-me"} 80 90 100 110 120 130 140
`)
testutil.Ok(t, err)
assert.NoError(t, err)
defer suite.Close()
err = suite.Run()
testutil.Ok(t, err)
assert.NoError(t, err)
expr, err := parser.ParseExpr(`http_requests{group="canary", job="app-server"} < 100`)
testutil.Ok(t, err)
assert.NoError(t, err)
rule := NewAlertingRule(
"HTTPRequestRateLow",
@ -306,7 +306,7 @@ func TestForStateAddSamples(t *testing.T) {
}
res, err := rule.Eval(suite.Context(), evalTime, EngineQueryFunc(suite.QueryEngine(), suite.Storage()), nil)
testutil.Ok(t, err)
assert.NoError(t, err)
var filteredRes promql.Vector // After removing 'ALERTS' samples.
for _, smpl := range res {
@ -315,7 +315,7 @@ func TestForStateAddSamples(t *testing.T) {
filteredRes = append(filteredRes, smpl)
} else {
// If not 'ALERTS_FOR_STATE', it has to be 'ALERTS'.
testutil.Equals(t, smplName, "ALERTS")
assert.Equal(t, smplName, "ALERTS")
}
}
for i := range test.result {
@ -325,15 +325,15 @@ func TestForStateAddSamples(t *testing.T) {
test.result[i].V = forState
}
}
testutil.Assert(t, len(test.result) == len(filteredRes), "%d. Number of samples in expected and actual output don't match (%d vs. %d)", i, len(test.result), len(res))
assert.True(t, len(test.result) == len(filteredRes), "%d. Number of samples in expected and actual output don't match (%d vs. %d)", i, len(test.result), len(res))
sort.Slice(filteredRes, func(i, j int) bool {
return labels.Compare(filteredRes[i].Metric, filteredRes[j].Metric) < 0
})
testutil.Equals(t, test.result, filteredRes)
assert.Equal(t, test.result, filteredRes)
for _, aa := range rule.ActiveAlerts() {
testutil.Assert(t, aa.Labels.Get(model.MetricNameLabel) == "", "%s label set on active alert: %s", model.MetricNameLabel, aa.Labels)
assert.True(t, aa.Labels.Get(model.MetricNameLabel) == "", "%s label set on active alert: %s", model.MetricNameLabel, aa.Labels)
}
}
@ -352,14 +352,14 @@ func TestForStateRestore(t *testing.T) {
http_requests{job="app-server", instance="0", group="canary", severity="overwrite-me"} 75 85 50 0 0 25 0 0 40 0 120
http_requests{job="app-server", instance="1", group="canary", severity="overwrite-me"} 125 90 60 0 0 25 0 0 40 0 130
`)
testutil.Ok(t, err)
assert.NoError(t, err)
defer suite.Close()
err = suite.Run()
testutil.Ok(t, err)
assert.NoError(t, err)
expr, err := parser.ParseExpr(`http_requests{group="canary", job="app-server"} < 100`)
testutil.Ok(t, err)
assert.NoError(t, err)
opts := &ManagerOptions{
QueryFunc: EngineQueryFunc(suite.QueryEngine(), suite.Storage()),
@ -402,7 +402,7 @@ func TestForStateRestore(t *testing.T) {
exp := rule.ActiveAlerts()
for _, aa := range exp {
testutil.Assert(t, aa.Labels.Get(model.MetricNameLabel) == "", "%s label set on active alert: %s", model.MetricNameLabel, aa.Labels)
assert.True(t, aa.Labels.Get(model.MetricNameLabel) == "", "%s label set on active alert: %s", model.MetricNameLabel, aa.Labels)
}
sort.Slice(exp, func(i, j int) bool {
return labels.Compare(exp[i].Labels, exp[j].Labels) < 0
@ -466,7 +466,7 @@ func TestForStateRestore(t *testing.T) {
got := newRule.ActiveAlerts()
for _, aa := range got {
testutil.Assert(t, aa.Labels.Get(model.MetricNameLabel) == "", "%s label set on active alert: %s", model.MetricNameLabel, aa.Labels)
assert.True(t, aa.Labels.Get(model.MetricNameLabel) == "", "%s label set on active alert: %s", model.MetricNameLabel, aa.Labels)
}
sort.Slice(got, func(i, j int) bool {
return labels.Compare(got[i].Labels, got[j].Labels) < 0
@ -474,27 +474,27 @@ func TestForStateRestore(t *testing.T) {
// Checking if we have restored it correctly.
if tst.noRestore {
testutil.Equals(t, tst.num, len(got))
assert.Equal(t, tst.num, len(got))
for _, e := range got {
testutil.Equals(t, e.ActiveAt, restoreTime)
assert.Equal(t, e.ActiveAt, restoreTime)
}
} else if tst.gracePeriod {
testutil.Equals(t, tst.num, len(got))
assert.Equal(t, tst.num, len(got))
for _, e := range got {
testutil.Equals(t, opts.ForGracePeriod, e.ActiveAt.Add(alertForDuration).Sub(restoreTime))
assert.Equal(t, opts.ForGracePeriod, e.ActiveAt.Add(alertForDuration).Sub(restoreTime))
}
} else {
exp := tst.alerts
testutil.Equals(t, len(exp), len(got))
assert.Equal(t, len(exp), len(got))
sortAlerts(exp)
sortAlerts(got)
for i, e := range exp {
testutil.Equals(t, e.Labels, got[i].Labels)
assert.Equal(t, e.Labels, got[i].Labels)
// Difference in time should be within 1e6 ns, i.e. 1ms
// (due to conversion between ns & ms, float64 & int64).
activeAtDiff := float64(e.ActiveAt.Unix() + int64(tst.downDuration/time.Second) - got[i].ActiveAt.Unix())
testutil.Assert(t, math.Abs(activeAtDiff) == 0, "'for' state restored time is wrong")
assert.True(t, math.Abs(activeAtDiff) == 0, "'for' state restored time is wrong")
}
}
}
@ -535,7 +535,7 @@ func TestStaleness(t *testing.T) {
}
expr, err := parser.ParseExpr("a + 1")
testutil.Ok(t, err)
assert.NoError(t, err)
rule := NewRecordingRule("a_plus_one", expr, labels.Labels{})
group := NewGroup(GroupOptions{
Name: "default",
@ -552,7 +552,7 @@ func TestStaleness(t *testing.T) {
app.Add(labels.FromStrings(model.MetricNameLabel, "a"), 2000, math.Float64frombits(value.StaleNaN))
err = app.Commit()
testutil.Ok(t, err)
assert.NoError(t, err)
ctx := context.Background()
@ -562,31 +562,31 @@ func TestStaleness(t *testing.T) {
group.Eval(ctx, time.Unix(2, 0))
querier, err := st.Querier(context.Background(), 0, 2000)
testutil.Ok(t, err)
assert.NoError(t, err)
defer querier.Close()
matcher, err := labels.NewMatcher(labels.MatchEqual, model.MetricNameLabel, "a_plus_one")
testutil.Ok(t, err)
assert.NoError(t, err)
set := querier.Select(false, nil, matcher)
samples, err := readSeriesSet(set)
testutil.Ok(t, err)
assert.NoError(t, err)
metric := labels.FromStrings(model.MetricNameLabel, "a_plus_one").String()
metricSample, ok := samples[metric]
testutil.Assert(t, ok, "Series %s not returned.", metric)
testutil.Assert(t, value.IsStaleNaN(metricSample[2].V), "Appended second sample not as expected. Wanted: stale NaN Got: %x", math.Float64bits(metricSample[2].V))
metricSample[2].V = 42 // reflect.DeepEqual cannot handle NaN.
assert.True(t, ok, "Series %s not returned.", metric)
assert.True(t, value.IsStaleNaN(metricSample[2].V), "Appended second sample not as expected. Wanted: stale NaN Got: %x", math.Float64bits(metricSample[2].V))
metricSample[2].V = 42 // assert.Equal cannot handle NaN.
want := map[string][]promql.Point{
metric: {{T: 0, V: 2}, {T: 1000, V: 3}, {T: 2000, V: 42}},
}
testutil.Equals(t, want, samples)
assert.Equal(t, want, samples)
}
// Convert a SeriesSet into a form usable with reflect.DeepEqual.
// Convert a SeriesSet into a form usable with assert.Equal.
func readSeriesSet(ss storage.SeriesSet) (map[string][]promql.Point, error) {
result := map[string][]promql.Point{}
@ -654,11 +654,11 @@ func TestCopyState(t *testing.T) {
{"a2": labels.Labels{{Name: "l2", Value: "v1"}}},
nil,
}
testutil.Equals(t, want, newGroup.seriesInPreviousEval)
testutil.Equals(t, oldGroup.rules[0], newGroup.rules[3])
testutil.Equals(t, oldGroup.evaluationTime, newGroup.evaluationTime)
testutil.Equals(t, oldGroup.lastEvaluation, newGroup.lastEvaluation)
testutil.Equals(t, []labels.Labels{{{Name: "l1", Value: "v3"}}}, newGroup.staleSeries)
assert.Equal(t, want, newGroup.seriesInPreviousEval)
assert.Equal(t, oldGroup.rules[0], newGroup.rules[3])
assert.Equal(t, oldGroup.evaluationTime, newGroup.evaluationTime)
assert.Equal(t, oldGroup.lastEvaluation, newGroup.lastEvaluation)
assert.Equal(t, []labels.Labels{{{Name: "l1", Value: "v3"}}}, newGroup.staleSeries)
}
func TestDeletedRuleMarkedStale(t *testing.T) {
@ -684,21 +684,21 @@ func TestDeletedRuleMarkedStale(t *testing.T) {
newGroup.Eval(context.Background(), time.Unix(0, 0))
querier, err := st.Querier(context.Background(), 0, 2000)
testutil.Ok(t, err)
assert.NoError(t, err)
defer querier.Close()
matcher, err := labels.NewMatcher(labels.MatchEqual, "l1", "v1")
testutil.Ok(t, err)
assert.NoError(t, err)
set := querier.Select(false, nil, matcher)
samples, err := readSeriesSet(set)
testutil.Ok(t, err)
assert.NoError(t, err)
metric := labels.FromStrings("l1", "v1").String()
metricSample, ok := samples[metric]
testutil.Assert(t, ok, "Series %s not returned.", metric)
testutil.Assert(t, value.IsStaleNaN(metricSample[0].V), "Appended sample not as expected. Wanted: stale NaN Got: %x", math.Float64bits(metricSample[0].V))
assert.True(t, ok, "Series %s not returned.", metric)
assert.True(t, value.IsStaleNaN(metricSample[0].V), "Appended sample not as expected. Wanted: stale NaN Got: %x", math.Float64bits(metricSample[0].V))
}
func TestUpdate(t *testing.T) {
@ -726,8 +726,8 @@ func TestUpdate(t *testing.T) {
defer ruleManager.Stop()
err := ruleManager.Update(10*time.Second, files, nil)
testutil.Ok(t, err)
testutil.Assert(t, len(ruleManager.groups) > 0, "expected non-empty rule groups")
assert.NoError(t, err)
assert.True(t, len(ruleManager.groups) > 0, "expected non-empty rule groups")
ogs := map[string]*Group{}
for h, g := range ruleManager.groups {
g.seriesInPreviousEval = []map[string]labels.Labels{
@ -737,26 +737,26 @@ func TestUpdate(t *testing.T) {
}
err = ruleManager.Update(10*time.Second, files, nil)
testutil.Ok(t, err)
assert.NoError(t, err)
for h, g := range ruleManager.groups {
for _, actual := range g.seriesInPreviousEval {
testutil.Equals(t, expected, actual)
assert.Equal(t, expected, actual)
}
// Groups are the same because of no updates.
testutil.Equals(t, ogs[h], g)
assert.Equal(t, ogs[h], g)
}
// Groups will be recreated if updated.
rgs, errs := rulefmt.ParseFile("fixtures/rules.yaml")
testutil.Assert(t, len(errs) == 0, "file parsing failures")
assert.True(t, len(errs) == 0, "file parsing failures")
tmpFile, err := ioutil.TempFile("", "rules.test.*.yaml")
testutil.Ok(t, err)
assert.NoError(t, err)
defer os.Remove(tmpFile.Name())
defer tmpFile.Close()
err = ruleManager.Update(10*time.Second, []string{tmpFile.Name()}, nil)
testutil.Ok(t, err)
assert.NoError(t, err)
for h, g := range ruleManager.groups {
ogs[h] = g
@ -822,12 +822,12 @@ func formatRules(r *rulefmt.RuleGroups) ruleGroupsTest {
func reloadAndValidate(rgs *rulefmt.RuleGroups, t *testing.T, tmpFile *os.File, ruleManager *Manager, expected map[string]labels.Labels, ogs map[string]*Group) {
bs, err := yaml.Marshal(formatRules(rgs))
testutil.Ok(t, err)
assert.NoError(t, err)
tmpFile.Seek(0, 0)
_, err = tmpFile.Write(bs)
testutil.Ok(t, err)
assert.NoError(t, err)
err = ruleManager.Update(10*time.Second, []string{tmpFile.Name()}, nil)
testutil.Ok(t, err)
assert.NoError(t, err)
for h, g := range ruleManager.groups {
if ogs[h] == g {
t.Fail()
@ -861,7 +861,7 @@ func TestNotify(t *testing.T) {
}
expr, err := parser.ParseExpr("a > 1")
testutil.Ok(t, err)
assert.NoError(t, err)
rule := NewAlertingRule("aTooHigh", expr, 0, labels.Labels{}, labels.Labels{}, nil, true, log.NewNopLogger())
group := NewGroup(GroupOptions{
Name: "alert",
@ -878,26 +878,26 @@ func TestNotify(t *testing.T) {
app.Add(labels.FromStrings(model.MetricNameLabel, "a"), 6000, 0)
err = app.Commit()
testutil.Ok(t, err)
assert.NoError(t, err)
ctx := context.Background()
// Alert sent right away
group.Eval(ctx, time.Unix(1, 0))
testutil.Equals(t, 1, len(lastNotified))
testutil.Assert(t, !lastNotified[0].ValidUntil.IsZero(), "ValidUntil should not be zero")
assert.Equal(t, 1, len(lastNotified))
assert.True(t, !lastNotified[0].ValidUntil.IsZero(), "ValidUntil should not be zero")
// Alert is not sent 1s later
group.Eval(ctx, time.Unix(2, 0))
testutil.Equals(t, 0, len(lastNotified))
assert.Equal(t, 0, len(lastNotified))
// Alert is resent at t=5s
group.Eval(ctx, time.Unix(5, 0))
testutil.Equals(t, 1, len(lastNotified))
assert.Equal(t, 1, len(lastNotified))
// Resolution alert sent right away
group.Eval(ctx, time.Unix(6, 0))
testutil.Equals(t, 1, len(lastNotified))
assert.Equal(t, 1, len(lastNotified))
}
func TestMetricsUpdate(t *testing.T) {
@ -934,7 +934,7 @@ func TestMetricsUpdate(t *testing.T) {
countMetrics := func() int {
ms, err := registry.Gather()
testutil.Ok(t, err)
assert.NoError(t, err)
var metrics int
for _, m := range ms {
s := m.GetName()
@ -972,9 +972,9 @@ func TestMetricsUpdate(t *testing.T) {
for i, c := range cases {
err := ruleManager.Update(time.Second, c.files, nil)
testutil.Ok(t, err)
assert.NoError(t, err)
time.Sleep(2 * time.Second)
testutil.Equals(t, c.metrics, countMetrics(), "test %d: invalid count of metrics", i)
assert.Equal(t, c.metrics, countMetrics(), "test %d: invalid count of metrics", i)
}
}
@ -1046,14 +1046,14 @@ func TestGroupStalenessOnRemoval(t *testing.T) {
var totalStaleNaN int
for i, c := range cases {
err := ruleManager.Update(time.Second, c.files, nil)
testutil.Ok(t, err)
assert.NoError(t, err)
time.Sleep(3 * time.Second)
totalStaleNaN += c.staleNaN
testutil.Equals(t, totalStaleNaN, countStaleNaN(t, storage), "test %d/%q: invalid count of staleness markers", i, c.files)
assert.Equal(t, totalStaleNaN, countStaleNaN(t, storage), "test %d/%q: invalid count of staleness markers", i, c.files)
}
ruleManager.Stop()
stopped = true
testutil.Equals(t, totalStaleNaN, countStaleNaN(t, storage), "invalid count of staleness markers after stopping the engine")
assert.Equal(t, totalStaleNaN, countStaleNaN(t, storage), "invalid count of staleness markers after stopping the engine")
}
func TestMetricsStalenessOnManagerShutdown(t *testing.T) {
@ -1089,34 +1089,34 @@ func TestMetricsStalenessOnManagerShutdown(t *testing.T) {
err := ruleManager.Update(2*time.Second, files, nil)
time.Sleep(4 * time.Second)
testutil.Ok(t, err)
assert.NoError(t, err)
start := time.Now()
err = ruleManager.Update(3*time.Second, files[:0], nil)
testutil.Ok(t, err)
assert.NoError(t, err)
ruleManager.Stop()
stopped = true
testutil.Assert(t, time.Since(start) < 1*time.Second, "rule manager does not stop early")
assert.True(t, time.Since(start) < 1*time.Second, "rule manager does not stop early")
time.Sleep(5 * time.Second)
testutil.Equals(t, 0, countStaleNaN(t, storage), "invalid count of staleness markers after stopping the engine")
assert.Equal(t, 0, countStaleNaN(t, storage), "invalid count of staleness markers after stopping the engine")
}
func countStaleNaN(t *testing.T, st storage.Storage) int {
var c int
querier, err := st.Querier(context.Background(), 0, time.Now().Unix()*1000)
testutil.Ok(t, err)
assert.NoError(t, err)
defer querier.Close()
matcher, err := labels.NewMatcher(labels.MatchEqual, model.MetricNameLabel, "test_2")
testutil.Ok(t, err)
assert.NoError(t, err)
set := querier.Select(false, nil, matcher)
samples, err := readSeriesSet(set)
testutil.Ok(t, err)
assert.NoError(t, err)
metric := labels.FromStrings(model.MetricNameLabel, "test_2").String()
metricSample, ok := samples[metric]
testutil.Assert(t, ok, "Series %s not returned.", metric)
assert.True(t, ok, "Series %s not returned.", metric)
for _, s := range metricSample {
if value.IsStaleNaN(s.V) {
c++
@ -1160,6 +1160,6 @@ func TestGroupHasAlertingRules(t *testing.T) {
for i, test := range tests {
got := test.group.HasAlertingRules()
testutil.Assert(t, test.want == got, "test case %d failed, expected:%t got:%t", i, test.want, got)
assert.True(t, test.want == got, "test case %d failed, expected:%t got:%t", i, test.want, got)
}
}

View file

@ -15,16 +15,16 @@ package rules
import (
"context"
"fmt"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/pkg/timestamp"
"github.com/prometheus/prometheus/promql"
"github.com/prometheus/prometheus/promql/parser"
"github.com/prometheus/prometheus/util/teststorage"
"github.com/prometheus/prometheus/util/testutil"
)
func TestRuleEval(t *testing.T) {
@ -73,14 +73,14 @@ func TestRuleEval(t *testing.T) {
for _, test := range suite {
rule := NewRecordingRule(test.name, test.expr, test.labels)
result, err := rule.Eval(ctx, now, EngineQueryFunc(engine, storage), nil)
testutil.Ok(t, err)
testutil.Equals(t, test.result, result)
assert.NoError(t, err)
assert.Equal(t, test.result, result)
}
}
func TestRecordingRuleHTMLSnippet(t *testing.T) {
expr, err := parser.ParseExpr(`foo{html="<b>BOLD<b>"}`)
testutil.Ok(t, err)
assert.NoError(t, err)
rule := NewRecordingRule("testrule", expr, labels.FromStrings("html", "<b>BOLD</b>"))
const want = `record: <a href="/test/prefix/graph?g0.expr=testrule&g0.tab=1">testrule</a>
@ -90,7 +90,7 @@ labels:
`
got := rule.HTMLSnippet("/test/prefix")
testutil.Assert(t, want == got, "incorrect HTML snippet; want:\n\n%s\n\ngot:\n\n%s", want, got)
assert.True(t, want == got, "incorrect HTML snippet; want:\n\n%s\n\ngot:\n\n%s", want, got)
}
// TestRuleEvalDuplicate tests for duplicate labels in recorded metrics, see #5529.
@ -114,7 +114,6 @@ func TestRuleEvalDuplicate(t *testing.T) {
expr, _ := parser.ParseExpr(`vector(0) or label_replace(vector(0),"test","x","","")`)
rule := NewRecordingRule("foo", expr, labels.FromStrings("test", "test"))
_, err := rule.Eval(ctx, now, EngineQueryFunc(engine, storage), nil)
testutil.NotOk(t, err)
e := fmt.Errorf("vector contains metrics with the same labelset after applying rule labels")
testutil.ErrorEqual(t, e, err)
assert.Error(t, err)
assert.EqualError(t, err, "vector contains metrics with the same labelset after applying rule labels")
}

View file

@ -15,6 +15,7 @@ package scrape
import (
"context"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/storage"
)

View file

@ -26,8 +26,8 @@ import (
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/prometheus/config"
"github.com/prometheus/prometheus/discovery/targetgroup"
"github.com/prometheus/prometheus/pkg/labels"

View file

@ -19,15 +19,14 @@ import (
"testing"
"time"
"github.com/pkg/errors"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/assert"
yaml "gopkg.in/yaml.v2"
"github.com/prometheus/prometheus/config"
"github.com/prometheus/prometheus/discovery/targetgroup"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/pkg/relabel"
"github.com/prometheus/prometheus/util/testutil"
)
func TestPopulateLabels(t *testing.T) {
@ -36,7 +35,7 @@ func TestPopulateLabels(t *testing.T) {
cfg *config.ScrapeConfig
res labels.Labels
resOrig labels.Labels
err error
err string
}{
// Regular population of scrape config options.
{
@ -129,7 +128,7 @@ func TestPopulateLabels(t *testing.T) {
},
res: nil,
resOrig: nil,
err: errors.New("no address"),
err: "no address",
},
// Address label missing, but added in relabelling.
{
@ -208,17 +207,21 @@ func TestPopulateLabels(t *testing.T) {
},
res: nil,
resOrig: nil,
err: errors.New("invalid label value for \"custom\": \"\\xbd\""),
err: "invalid label value for \"custom\": \"\\xbd\"",
},
}
for _, c := range cases {
in := c.in.Copy()
res, orig, err := populateLabels(c.in, c.cfg)
testutil.ErrorEqual(t, c.err, err)
testutil.Equals(t, c.in, in)
testutil.Equals(t, c.res, res)
testutil.Equals(t, c.resOrig, orig)
if c.err != "" {
assert.EqualError(t, err, c.err)
} else {
assert.NoError(t, err)
}
assert.Equal(t, c.in, in)
assert.Equal(t, c.res, res)
assert.Equal(t, c.resOrig, orig)
}
}
@ -362,7 +365,7 @@ func TestManagerTargetsUpdates(t *testing.T) {
m.mtxScrape.Unlock()
// Make sure all updates have been received.
testutil.Equals(t, tgSent, tsetActual)
assert.Equal(t, tgSent, tsetActual)
select {
case <-m.triggerReload:

View file

@ -33,6 +33,7 @@ import (
dto "github.com/prometheus/client_model/go"
config_util "github.com/prometheus/common/config"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/assert"
"github.com/prometheus/prometheus/config"
"github.com/prometheus/prometheus/discovery/targetgroup"
@ -134,7 +135,7 @@ func TestDiscoveredLabelsUpdate(t *testing.T) {
}
sp.sync([]*Target{t2})
testutil.Equals(t, t2.DiscoveredLabels(), sp.activeTargets[t1.hash()].DiscoveredLabels())
assert.Equal(t, t2.DiscoveredLabels(), sp.activeTargets[t1.hash()].DiscoveredLabels())
}
type testLoop struct {
@ -227,11 +228,11 @@ func TestScrapePoolStop(t *testing.T) {
}
mtx.Lock()
testutil.Equals(t, numTargets, len(stopped), "Unexpected number of stopped loops")
assert.Equal(t, numTargets, len(stopped), "Unexpected number of stopped loops")
mtx.Unlock()
testutil.Assert(t, len(sp.activeTargets) == 0, "Targets were not cleared on stopping: %d left", len(sp.activeTargets))
testutil.Assert(t, len(sp.loops) == 0, "Loops were not cleared on stopping: %d left", len(sp.loops))
assert.True(t, len(sp.activeTargets) == 0, "Targets were not cleared on stopping: %d left", len(sp.activeTargets))
assert.True(t, len(sp.loops) == 0, "Loops were not cleared on stopping: %d left", len(sp.loops))
}
func TestScrapePoolReload(t *testing.T) {
@ -249,12 +250,12 @@ func TestScrapePoolReload(t *testing.T) {
newLoop := func(opts scrapeLoopOptions) loop {
l := &testLoop{}
l.startFunc = func(interval, timeout time.Duration, errc chan<- error) {
testutil.Equals(t, 3*time.Second, interval, "Unexpected scrape interval")
testutil.Equals(t, 2*time.Second, timeout, "Unexpected scrape timeout")
assert.Equal(t, 3*time.Second, interval, "Unexpected scrape interval")
assert.Equal(t, 2*time.Second, timeout, "Unexpected scrape timeout")
mtx.Lock()
targetScraper := opts.scraper.(*targetScraper)
testutil.Assert(t, stopped[targetScraper.hash()], "Scrape loop for %v not stopped yet", targetScraper)
assert.True(t, stopped[targetScraper.hash()], "Scrape loop for %v not stopped yet", targetScraper)
mtx.Unlock()
}
return l
@ -313,11 +314,11 @@ func TestScrapePoolReload(t *testing.T) {
}
mtx.Lock()
testutil.Equals(t, numTargets, len(stopped), "Unexpected number of stopped loops")
assert.Equal(t, numTargets, len(stopped), "Unexpected number of stopped loops")
mtx.Unlock()
testutil.Equals(t, sp.activeTargets, beforeTargets, "Reloading affected target states unexpectedly")
testutil.Equals(t, numTargets, len(sp.loops), "Unexpected number of stopped loops after reload")
assert.Equal(t, sp.activeTargets, beforeTargets, "Reloading affected target states unexpectedly")
assert.Equal(t, numTargets, len(sp.loops), "Unexpected number of stopped loops after reload")
}
func TestScrapePoolTargetLimit(t *testing.T) {
@ -357,7 +358,7 @@ func TestScrapePoolTargetLimit(t *testing.T) {
var limit uint
reloadWithLimit := func(l uint) {
limit = l
testutil.Ok(t, sp.reload(&config.ScrapeConfig{
assert.NoError(t, sp.reload(&config.ScrapeConfig{
ScrapeInterval: model.Duration(3 * time.Second),
ScrapeTimeout: model.Duration(2 * time.Second),
TargetLimit: l,
@ -373,7 +374,7 @@ func TestScrapePoolTargetLimit(t *testing.T) {
validateIsRunning := func() {
wg.Wait()
for _, l := range sp.loops {
testutil.Assert(t, l.(*testLoop).runOnce, "loop should be running")
assert.True(t, l.(*testLoop).runOnce, "loop should be running")
}
}
@ -381,10 +382,10 @@ func TestScrapePoolTargetLimit(t *testing.T) {
for _, l := range sp.loops {
lerr := l.(*testLoop).getForcedError()
if shouldErr {
testutil.Assert(t, lerr != nil, "error was expected for %d targets with a limit of %d", targets, limit)
testutil.Equals(t, fmt.Sprintf("target_limit exceeded (number of targets: %d, limit: %d)", targets, limit), lerr.Error())
assert.NotNil(t, lerr, "error was expected for %d targets with a limit of %d", targets, limit)
assert.Equal(t, fmt.Sprintf("target_limit exceeded (number of targets: %d, limit: %d)", targets, limit), lerr.Error())
} else {
testutil.Equals(t, nil, lerr)
assert.Equal(t, nil, lerr)
}
}
}
@ -451,33 +452,33 @@ func TestScrapePoolAppender(t *testing.T) {
target: &Target{},
})
appl, ok := loop.(*scrapeLoop)
testutil.Assert(t, ok, "Expected scrapeLoop but got %T", loop)
assert.True(t, ok, "Expected scrapeLoop but got %T", loop)
wrapped := appl.appender(context.Background())
tl, ok := wrapped.(*timeLimitAppender)
testutil.Assert(t, ok, "Expected timeLimitAppender but got %T", wrapped)
assert.True(t, ok, "Expected timeLimitAppender but got %T", wrapped)
_, ok = tl.Appender.(nopAppender)
testutil.Assert(t, ok, "Expected base appender but got %T", tl.Appender)
assert.True(t, ok, "Expected base appender but got %T", tl.Appender)
loop = sp.newLoop(scrapeLoopOptions{
target: &Target{},
limit: 100,
})
appl, ok = loop.(*scrapeLoop)
testutil.Assert(t, ok, "Expected scrapeLoop but got %T", loop)
assert.True(t, ok, "Expected scrapeLoop but got %T", loop)
wrapped = appl.appender(context.Background())
sl, ok := wrapped.(*limitAppender)
testutil.Assert(t, ok, "Expected limitAppender but got %T", wrapped)
assert.True(t, ok, "Expected limitAppender but got %T", wrapped)
tl, ok = sl.Appender.(*timeLimitAppender)
testutil.Assert(t, ok, "Expected limitAppender but got %T", sl.Appender)
assert.True(t, ok, "Expected limitAppender but got %T", sl.Appender)
_, ok = tl.Appender.(nopAppender)
testutil.Assert(t, ok, "Expected base appender but got %T", tl.Appender)
assert.True(t, ok, "Expected base appender but got %T", tl.Appender)
}
func TestScrapePoolRaces(t *testing.T) {
@ -507,8 +508,8 @@ func TestScrapePoolRaces(t *testing.T) {
dropped := sp.DroppedTargets()
expectedActive, expectedDropped := len(tgts[0].Targets), 0
testutil.Equals(t, expectedActive, len(active), "Invalid number of active targets")
testutil.Equals(t, expectedDropped, len(dropped), "Invalid number of dropped targets")
assert.Equal(t, expectedActive, len(active), "Invalid number of active targets")
assert.Equal(t, expectedDropped, len(dropped), "Invalid number of dropped targets")
for i := 0; i < 20; i++ {
time.Sleep(time.Duration(10 * time.Millisecond))
@ -551,17 +552,17 @@ func TestScrapePoolScrapeLoopsStarted(t *testing.T) {
},
}
testutil.Ok(t, sp.reload(&config.ScrapeConfig{
assert.NoError(t, sp.reload(&config.ScrapeConfig{
ScrapeInterval: model.Duration(3 * time.Second),
ScrapeTimeout: model.Duration(2 * time.Second),
}))
sp.Sync(tgs)
testutil.Equals(t, 1, len(sp.loops))
assert.Equal(t, 1, len(sp.loops))
wg.Wait()
for _, l := range sp.loops {
testutil.Assert(t, l.(*testLoop).runOnce, "loop should be running")
assert.True(t, l.(*testLoop).runOnce, "loop should be running")
}
}
@ -865,27 +866,27 @@ test_metric 1
# TYPE test_metric_no_help gauge
# HELP test_metric_no_type other help text
# EOF`), "application/openmetrics-text", time.Now())
testutil.Ok(t, err)
testutil.Ok(t, slApp.Commit())
testutil.Equals(t, 1, total)
assert.NoError(t, err)
assert.NoError(t, slApp.Commit())
assert.Equal(t, 1, total)
md, ok := cache.GetMetadata("test_metric")
testutil.Assert(t, ok, "expected metadata to be present")
testutil.Assert(t, textparse.MetricTypeCounter == md.Type, "unexpected metric type")
testutil.Equals(t, "some help text", md.Help)
testutil.Equals(t, "metric", md.Unit)
assert.True(t, ok, "expected metadata to be present")
assert.True(t, textparse.MetricTypeCounter == md.Type, "unexpected metric type")
assert.Equal(t, "some help text", md.Help)
assert.Equal(t, "metric", md.Unit)
md, ok = cache.GetMetadata("test_metric_no_help")
testutil.Assert(t, ok, "expected metadata to be present")
testutil.Assert(t, textparse.MetricTypeGauge == md.Type, "unexpected metric type")
testutil.Equals(t, "", md.Help)
testutil.Equals(t, "", md.Unit)
assert.True(t, ok, "expected metadata to be present")
assert.True(t, textparse.MetricTypeGauge == md.Type, "unexpected metric type")
assert.Equal(t, "", md.Help)
assert.Equal(t, "", md.Unit)
md, ok = cache.GetMetadata("test_metric_no_type")
testutil.Assert(t, ok, "expected metadata to be present")
testutil.Assert(t, textparse.MetricTypeUnknown == md.Type, "unexpected metric type")
testutil.Equals(t, "other help text", md.Help)
testutil.Equals(t, "", md.Unit)
assert.True(t, ok, "expected metadata to be present")
assert.True(t, textparse.MetricTypeUnknown == md.Type, "unexpected metric type")
assert.Equal(t, "other help text", md.Help)
assert.Equal(t, "", md.Unit)
}
func TestScrapeLoopSeriesAdded(t *testing.T) {
@ -908,19 +909,19 @@ func TestScrapeLoopSeriesAdded(t *testing.T) {
slApp := sl.appender(ctx)
total, added, seriesAdded, err := sl.append(slApp, []byte("test_metric 1\n"), "", time.Time{})
testutil.Ok(t, err)
testutil.Ok(t, slApp.Commit())
testutil.Equals(t, 1, total)
testutil.Equals(t, 1, added)
testutil.Equals(t, 1, seriesAdded)
assert.NoError(t, err)
assert.NoError(t, slApp.Commit())
assert.Equal(t, 1, total)
assert.Equal(t, 1, added)
assert.Equal(t, 1, seriesAdded)
slApp = sl.appender(ctx)
total, added, seriesAdded, err = sl.append(slApp, []byte("test_metric 1\n"), "", time.Time{})
testutil.Ok(t, slApp.Commit())
testutil.Ok(t, err)
testutil.Equals(t, 1, total)
testutil.Equals(t, 1, added)
testutil.Equals(t, 0, seriesAdded)
assert.NoError(t, slApp.Commit())
assert.NoError(t, err)
assert.Equal(t, 1, total)
assert.Equal(t, 1, added)
assert.Equal(t, 0, seriesAdded)
}
func TestScrapeLoopRunCreatesStaleMarkersOnFailedScrape(t *testing.T) {
@ -970,9 +971,9 @@ func TestScrapeLoopRunCreatesStaleMarkersOnFailedScrape(t *testing.T) {
// 1 successfully scraped sample, 1 stale marker after first fail, 5 report samples for
// each scrape successful or not.
testutil.Equals(t, 27, len(appender.result), "Appended samples not as expected")
testutil.Equals(t, 42.0, appender.result[0].v, "Appended first sample not as expected")
testutil.Assert(t, value.IsStaleNaN(appender.result[6].v),
assert.Equal(t, 27, len(appender.result), "Appended samples not as expected")
assert.Equal(t, 42.0, appender.result[0].v, "Appended first sample not as expected")
assert.True(t, value.IsStaleNaN(appender.result[6].v),
"Appended second sample not as expected. Wanted: stale NaN Got: %x", math.Float64bits(appender.result[6].v))
}
@ -1026,9 +1027,9 @@ func TestScrapeLoopRunCreatesStaleMarkersOnParseFailure(t *testing.T) {
// 1 successfully scraped sample, 1 stale marker after first fail, 5 report samples for
// each scrape successful or not.
testutil.Equals(t, 17, len(appender.result), "Appended samples not as expected")
testutil.Equals(t, 42.0, appender.result[0].v, "Appended first sample not as expected")
testutil.Assert(t, value.IsStaleNaN(appender.result[6].v),
assert.Equal(t, 17, len(appender.result), "Appended samples not as expected")
assert.Equal(t, 42.0, appender.result[0].v, "Appended first sample not as expected")
assert.True(t, value.IsStaleNaN(appender.result[6].v),
"Appended second sample not as expected. Wanted: stale NaN Got: %x", math.Float64bits(appender.result[6].v))
}
@ -1101,7 +1102,7 @@ func TestScrapeLoopCache(t *testing.T) {
// 1 successfully scraped sample, 1 stale marker after first fail, 5 report samples for
// each scrape successful or not.
testutil.Equals(t, 26, len(appender.result), "Appended samples not as expected")
assert.Equal(t, 26, len(appender.result), "Appended samples not as expected")
}
func TestScrapeLoopCacheMemoryExhaustionProtection(t *testing.T) {
@ -1239,8 +1240,8 @@ func TestScrapeLoopAppend(t *testing.T) {
slApp := sl.appender(context.Background())
_, _, _, err := sl.append(slApp, []byte(test.scrapeLabels), "", now)
testutil.Ok(t, err)
testutil.Ok(t, slApp.Commit())
assert.NoError(t, err)
assert.NoError(t, slApp.Commit())
expected := []sample{
{
@ -1258,7 +1259,7 @@ func TestScrapeLoopAppend(t *testing.T) {
}
t.Logf("Test:%s", test.title)
testutil.Equals(t, expected, app.result)
assert.Equal(t, expected, app.result)
}
}
@ -1292,8 +1293,8 @@ func TestScrapeLoopAppendCacheEntryButErrNotFound(t *testing.T) {
slApp := sl.appender(context.Background())
_, _, _, err := sl.append(slApp, []byte(metric), "", now)
testutil.Ok(t, err)
testutil.Ok(t, slApp.Commit())
assert.NoError(t, err)
assert.NoError(t, slApp.Commit())
expected := []sample{
{
@ -1303,7 +1304,7 @@ func TestScrapeLoopAppendCacheEntryButErrNotFound(t *testing.T) {
},
}
testutil.Equals(t, expected, app.result)
assert.Equal(t, expected, app.result)
}
func TestScrapeLoopAppendSampleLimit(t *testing.T) {
@ -1328,7 +1329,7 @@ func TestScrapeLoopAppendSampleLimit(t *testing.T) {
// Get the value of the Counter before performing the append.
beforeMetric := dto.Metric{}
err := targetScrapeSampleLimit.Write(&beforeMetric)
testutil.Ok(t, err)
assert.NoError(t, err)
beforeMetricValue := beforeMetric.GetCounter().GetValue()
@ -1338,20 +1339,20 @@ func TestScrapeLoopAppendSampleLimit(t *testing.T) {
if err != errSampleLimit {
t.Fatalf("Did not see expected sample limit error: %s", err)
}
testutil.Ok(t, slApp.Rollback())
testutil.Equals(t, 3, total)
testutil.Equals(t, 3, added)
testutil.Equals(t, 1, seriesAdded)
assert.NoError(t, slApp.Rollback())
assert.Equal(t, 3, total)
assert.Equal(t, 3, added)
assert.Equal(t, 1, seriesAdded)
// Check that the Counter has been incremented a single time for the scrape,
// not multiple times for each sample.
metric := dto.Metric{}
err = targetScrapeSampleLimit.Write(&metric)
testutil.Ok(t, err)
assert.NoError(t, err)
value := metric.GetCounter().GetValue()
change := value - beforeMetricValue
testutil.Assert(t, change == 1, "Unexpected change of sample limit metric: %f", change)
assert.True(t, change == 1, "Unexpected change of sample limit metric: %f", change)
// And verify that we got the samples that fit under the limit.
want := []sample{
@ -1361,7 +1362,7 @@ func TestScrapeLoopAppendSampleLimit(t *testing.T) {
v: 1,
},
}
testutil.Equals(t, want, resApp.rolledbackResult, "Appended samples not as expected")
assert.Equal(t, want, resApp.rolledbackResult, "Appended samples not as expected")
now = time.Now()
slApp = sl.appender(context.Background())
@ -1369,10 +1370,10 @@ func TestScrapeLoopAppendSampleLimit(t *testing.T) {
if err != errSampleLimit {
t.Fatalf("Did not see expected sample limit error: %s", err)
}
testutil.Ok(t, slApp.Rollback())
testutil.Equals(t, 9, total)
testutil.Equals(t, 6, added)
testutil.Equals(t, 0, seriesAdded)
assert.NoError(t, slApp.Rollback())
assert.Equal(t, 9, total)
assert.Equal(t, 6, added)
assert.Equal(t, 0, seriesAdded)
}
func TestScrapeLoop_ChangingMetricString(t *testing.T) {
@ -1397,13 +1398,13 @@ func TestScrapeLoop_ChangingMetricString(t *testing.T) {
now := time.Now()
slApp := sl.appender(context.Background())
_, _, _, err := sl.append(slApp, []byte(`metric_a{a="1",b="1"} 1`), "", now)
testutil.Ok(t, err)
testutil.Ok(t, slApp.Commit())
assert.NoError(t, err)
assert.NoError(t, slApp.Commit())
slApp = sl.appender(context.Background())
_, _, _, err = sl.append(slApp, []byte(`metric_a{b="1",a="1"} 2`), "", now.Add(time.Minute))
testutil.Ok(t, err)
testutil.Ok(t, slApp.Commit())
assert.NoError(t, err)
assert.NoError(t, slApp.Commit())
// DeepEqual will report NaNs as being different, so replace with a different value.
want := []sample{
@ -1418,7 +1419,7 @@ func TestScrapeLoop_ChangingMetricString(t *testing.T) {
v: 2,
},
}
testutil.Equals(t, want, capp.result, "Appended samples not as expected")
assert.Equal(t, want, capp.result, "Appended samples not as expected")
}
func TestScrapeLoopAppendStaleness(t *testing.T) {
@ -1437,16 +1438,16 @@ func TestScrapeLoopAppendStaleness(t *testing.T) {
now := time.Now()
slApp := sl.appender(context.Background())
_, _, _, err := sl.append(slApp, []byte("metric_a 1\n"), "", now)
testutil.Ok(t, err)
testutil.Ok(t, slApp.Commit())
assert.NoError(t, err)
assert.NoError(t, slApp.Commit())
slApp = sl.appender(context.Background())
_, _, _, err = sl.append(slApp, []byte(""), "", now.Add(time.Second))
testutil.Ok(t, err)
testutil.Ok(t, slApp.Commit())
assert.NoError(t, err)
assert.NoError(t, slApp.Commit())
ingestedNaN := math.Float64bits(app.result[1].v)
testutil.Equals(t, value.StaleNaN, ingestedNaN, "Appended stale sample wasn't as expected")
assert.Equal(t, value.StaleNaN, ingestedNaN, "Appended stale sample wasn't as expected")
// DeepEqual will report NaNs as being different, so replace with a different value.
app.result[1].v = 42
@ -1462,7 +1463,7 @@ func TestScrapeLoopAppendStaleness(t *testing.T) {
v: 42,
},
}
testutil.Equals(t, want, app.result, "Appended samples not as expected")
assert.Equal(t, want, app.result, "Appended samples not as expected")
}
func TestScrapeLoopAppendNoStalenessIfTimestamp(t *testing.T) {
@ -1480,13 +1481,13 @@ func TestScrapeLoopAppendNoStalenessIfTimestamp(t *testing.T) {
now := time.Now()
slApp := sl.appender(context.Background())
_, _, _, err := sl.append(slApp, []byte("metric_a 1 1000\n"), "", now)
testutil.Ok(t, err)
testutil.Ok(t, slApp.Commit())
assert.NoError(t, err)
assert.NoError(t, slApp.Commit())
slApp = sl.appender(context.Background())
_, _, _, err = sl.append(slApp, []byte(""), "", now.Add(time.Second))
testutil.Ok(t, err)
testutil.Ok(t, slApp.Commit())
assert.NoError(t, err)
assert.NoError(t, slApp.Commit())
want := []sample{
{
@ -1495,7 +1496,7 @@ func TestScrapeLoopAppendNoStalenessIfTimestamp(t *testing.T) {
v: 1,
},
}
testutil.Equals(t, want, app.result, "Appended samples not as expected")
assert.Equal(t, want, app.result, "Appended samples not as expected")
}
func TestScrapeLoopRunReportsTargetDownOnScrapeError(t *testing.T) {
@ -1523,7 +1524,7 @@ func TestScrapeLoopRunReportsTargetDownOnScrapeError(t *testing.T) {
}
sl.run(10*time.Millisecond, time.Hour, nil)
testutil.Equals(t, 0.0, appender.result[0].v, "bad 'up' value")
assert.Equal(t, 0.0, appender.result[0].v, "bad 'up' value")
}
func TestScrapeLoopRunReportsTargetDownOnInvalidUTF8(t *testing.T) {
@ -1552,7 +1553,7 @@ func TestScrapeLoopRunReportsTargetDownOnInvalidUTF8(t *testing.T) {
}
sl.run(10*time.Millisecond, time.Hour, nil)
testutil.Equals(t, 0.0, appender.result[0].v, "bad 'up' value")
assert.Equal(t, 0.0, appender.result[0].v, "bad 'up' value")
}
type errorAppender struct {
@ -1593,8 +1594,8 @@ func TestScrapeLoopAppendGracefullyIfAmendOrOutOfOrderOrOutOfBounds(t *testing.T
now := time.Unix(1, 0)
slApp := sl.appender(context.Background())
total, added, seriesAdded, err := sl.append(slApp, []byte("out_of_order 1\namend 1\nnormal 1\nout_of_bounds 1\n"), "", now)
testutil.Ok(t, err)
testutil.Ok(t, slApp.Commit())
assert.NoError(t, err)
assert.NoError(t, slApp.Commit())
want := []sample{
{
@ -1603,10 +1604,10 @@ func TestScrapeLoopAppendGracefullyIfAmendOrOutOfOrderOrOutOfBounds(t *testing.T
v: 1,
},
}
testutil.Equals(t, want, app.result, "Appended samples not as expected")
testutil.Equals(t, 4, total)
testutil.Equals(t, 4, added)
testutil.Equals(t, 1, seriesAdded)
assert.Equal(t, want, app.result, "Appended samples not as expected")
assert.Equal(t, 4, total)
assert.Equal(t, 4, added)
assert.Equal(t, 1, seriesAdded)
}
func TestScrapeLoopOutOfBoundsTimeError(t *testing.T) {
@ -1630,11 +1631,11 @@ func TestScrapeLoopOutOfBoundsTimeError(t *testing.T) {
now := time.Now().Add(20 * time.Minute)
slApp := sl.appender(context.Background())
total, added, seriesAdded, err := sl.append(slApp, []byte("normal 1\n"), "", now)
testutil.Ok(t, err)
testutil.Ok(t, slApp.Commit())
testutil.Equals(t, 1, total)
testutil.Equals(t, 1, added)
testutil.Equals(t, 0, seriesAdded)
assert.NoError(t, err)
assert.NoError(t, slApp.Commit())
assert.Equal(t, 1, total)
assert.Equal(t, 1, added)
assert.Equal(t, 0, seriesAdded)
}
@ -1680,9 +1681,9 @@ func TestTargetScraperScrapeOK(t *testing.T) {
var buf bytes.Buffer
contentType, err := ts.scrape(context.Background(), &buf)
testutil.Ok(t, err)
testutil.Equals(t, "text/plain; version=0.0.4", contentType)
testutil.Equals(t, "metric_a 1\nmetric_b 2\n", buf.String())
assert.NoError(t, err)
assert.Equal(t, "text/plain; version=0.0.4", contentType)
assert.Equal(t, "metric_a 1\nmetric_b 2\n", buf.String())
}
func TestTargetScrapeScrapeCancel(t *testing.T) {
@ -1733,7 +1734,7 @@ func TestTargetScrapeScrapeCancel(t *testing.T) {
case <-time.After(5 * time.Second):
t.Fatalf("Scrape function did not return unexpectedly")
case err := <-errc:
testutil.Ok(t, err)
assert.NoError(t, err)
}
// If this is closed in a defer above the function the test server
// doesn't terminate and the test doesn't complete.
@ -1764,7 +1765,7 @@ func TestTargetScrapeScrapeNotFound(t *testing.T) {
}
_, err = ts.scrape(context.Background(), ioutil.Discard)
testutil.Assert(t, strings.Contains(err.Error(), "404"), "Expected \"404 NotFound\" error but got: %s", err)
assert.True(t, strings.Contains(err.Error(), "404"), "Expected \"404 NotFound\" error but got: %s", err)
}
// testScraper implements the scraper interface and allows setting values
@ -1817,8 +1818,8 @@ func TestScrapeLoop_RespectTimestamps(t *testing.T) {
now := time.Now()
slApp := sl.appender(context.Background())
_, _, _, err := sl.append(slApp, []byte(`metric_a{a="1",b="1"} 1 0`), "", now)
testutil.Ok(t, err)
testutil.Ok(t, slApp.Commit())
assert.NoError(t, err)
assert.NoError(t, slApp.Commit())
want := []sample{
{
@ -1827,7 +1828,7 @@ func TestScrapeLoop_RespectTimestamps(t *testing.T) {
v: 1,
},
}
testutil.Equals(t, want, capp.result, "Appended samples not as expected")
assert.Equal(t, want, capp.result, "Appended samples not as expected")
}
func TestScrapeLoop_DiscardTimestamps(t *testing.T) {
@ -1850,8 +1851,8 @@ func TestScrapeLoop_DiscardTimestamps(t *testing.T) {
now := time.Now()
slApp := sl.appender(context.Background())
_, _, _, err := sl.append(slApp, []byte(`metric_a{a="1",b="1"} 1 0`), "", now)
testutil.Ok(t, err)
testutil.Ok(t, slApp.Commit())
assert.NoError(t, err)
assert.NoError(t, slApp.Commit())
want := []sample{
{
@ -1860,7 +1861,7 @@ func TestScrapeLoop_DiscardTimestamps(t *testing.T) {
v: 1,
},
}
testutil.Equals(t, want, capp.result, "Appended samples not as expected")
assert.Equal(t, want, capp.result, "Appended samples not as expected")
}
func TestScrapeLoopDiscardDuplicateLabels(t *testing.T) {
@ -1883,27 +1884,27 @@ func TestScrapeLoopDiscardDuplicateLabels(t *testing.T) {
// We add a good and a bad metric to check that both are discarded.
slApp := sl.appender(ctx)
_, _, _, err := sl.append(slApp, []byte("test_metric{le=\"500\"} 1\ntest_metric{le=\"600\",le=\"700\"} 1\n"), "", time.Time{})
testutil.NotOk(t, err)
testutil.Ok(t, slApp.Rollback())
assert.Error(t, err)
assert.NoError(t, slApp.Rollback())
q, err := s.Querier(ctx, time.Time{}.UnixNano(), 0)
testutil.Ok(t, err)
assert.NoError(t, err)
series := q.Select(false, nil, labels.MustNewMatcher(labels.MatchRegexp, "__name__", ".*"))
testutil.Equals(t, false, series.Next(), "series found in tsdb")
testutil.Ok(t, series.Err())
assert.Equal(t, false, series.Next(), "series found in tsdb")
assert.NoError(t, series.Err())
// We add a good metric to check that it is recorded.
slApp = sl.appender(ctx)
_, _, _, err = sl.append(slApp, []byte("test_metric{le=\"500\"} 1\n"), "", time.Time{})
testutil.Ok(t, err)
testutil.Ok(t, slApp.Commit())
assert.NoError(t, err)
assert.NoError(t, slApp.Commit())
q, err = s.Querier(ctx, time.Time{}.UnixNano(), 0)
testutil.Ok(t, err)
assert.NoError(t, err)
series = q.Select(false, nil, labels.MustNewMatcher(labels.MatchEqual, "le", "500"))
testutil.Equals(t, true, series.Next(), "series not found in tsdb")
testutil.Ok(t, series.Err())
testutil.Equals(t, false, series.Next(), "more than one series found in tsdb")
assert.Equal(t, true, series.Next(), "series not found in tsdb")
assert.NoError(t, series.Err())
assert.Equal(t, false, series.Next(), "more than one series found in tsdb")
}
func TestScrapeLoopDiscardUnnamedMetrics(t *testing.T) {
@ -1932,15 +1933,15 @@ func TestScrapeLoopDiscardUnnamedMetrics(t *testing.T) {
slApp := sl.appender(context.Background())
_, _, _, err := sl.append(slApp, []byte("nok 1\nnok2{drop=\"drop\"} 1\n"), "", time.Time{})
testutil.NotOk(t, err)
testutil.Ok(t, slApp.Rollback())
testutil.Equals(t, errNameLabelMandatory, err)
assert.Error(t, err)
assert.NoError(t, slApp.Rollback())
assert.Equal(t, errNameLabelMandatory, err)
q, err := s.Querier(ctx, time.Time{}.UnixNano(), 0)
testutil.Ok(t, err)
assert.NoError(t, err)
series := q.Select(false, nil, labels.MustNewMatcher(labels.MatchRegexp, "__name__", ".*"))
testutil.Equals(t, false, series.Next(), "series found in tsdb")
testutil.Ok(t, series.Err())
assert.Equal(t, false, series.Next(), "series found in tsdb")
assert.NoError(t, series.Err())
}
func TestReusableConfig(t *testing.T) {
@ -1999,14 +2000,14 @@ func TestReusableConfig(t *testing.T) {
}
for i, m := range match {
testutil.Equals(t, true, reusableCache(variants[m[0]], variants[m[1]]), "match test %d", i)
testutil.Equals(t, true, reusableCache(variants[m[1]], variants[m[0]]), "match test %d", i)
testutil.Equals(t, true, reusableCache(variants[m[1]], variants[m[1]]), "match test %d", i)
testutil.Equals(t, true, reusableCache(variants[m[0]], variants[m[0]]), "match test %d", i)
assert.Equal(t, true, reusableCache(variants[m[0]], variants[m[1]]), "match test %d", i)
assert.Equal(t, true, reusableCache(variants[m[1]], variants[m[0]]), "match test %d", i)
assert.Equal(t, true, reusableCache(variants[m[1]], variants[m[1]]), "match test %d", i)
assert.Equal(t, true, reusableCache(variants[m[0]], variants[m[0]]), "match test %d", i)
}
for i, m := range noMatch {
testutil.Equals(t, false, reusableCache(variants[m[0]], variants[m[1]]), "not match test %d", i)
testutil.Equals(t, false, reusableCache(variants[m[1]], variants[m[0]]), "not match test %d", i)
assert.Equal(t, false, reusableCache(variants[m[0]], variants[m[1]]), "not match test %d", i)
assert.Equal(t, false, reusableCache(variants[m[1]], variants[m[0]]), "not match test %d", i)
}
}
@ -2117,15 +2118,15 @@ func TestReuseScrapeCache(t *testing.T) {
sp.reload(s.newConfig)
for fp, newCacheAddr := range cacheAddr(sp) {
if s.keep {
testutil.Assert(t, initCacheAddr[fp] == newCacheAddr, "step %d: old cache and new cache are not the same", i)
assert.True(t, initCacheAddr[fp] == newCacheAddr, "step %d: old cache and new cache are not the same", i)
} else {
testutil.Assert(t, initCacheAddr[fp] != newCacheAddr, "step %d: old cache and new cache are the same", i)
assert.True(t, initCacheAddr[fp] != newCacheAddr, "step %d: old cache and new cache are the same", i)
}
}
initCacheAddr = cacheAddr(sp)
sp.reload(s.newConfig)
for fp, newCacheAddr := range cacheAddr(sp) {
testutil.Assert(t, initCacheAddr[fp] == newCacheAddr, "step %d: reloading the exact config invalidates the cache", i)
assert.True(t, initCacheAddr[fp] == newCacheAddr, "step %d: reloading the exact config invalidates the cache", i)
}
}
}
@ -2149,8 +2150,8 @@ func TestScrapeAddFast(t *testing.T) {
slApp := sl.appender(ctx)
_, _, _, err := sl.append(slApp, []byte("up 1\n"), "", time.Time{})
testutil.Ok(t, err)
testutil.Ok(t, slApp.Commit())
assert.NoError(t, err)
assert.NoError(t, slApp.Commit())
// Poison the cache. There is just one entry, and one series in the
// storage. Changing the ref will create a 'not found' error.
@ -2160,8 +2161,8 @@ func TestScrapeAddFast(t *testing.T) {
slApp = sl.appender(ctx)
_, _, _, err = sl.append(slApp, []byte("up 1\n"), "", time.Time{}.Add(time.Second))
testutil.Ok(t, err)
testutil.Ok(t, slApp.Commit())
assert.NoError(t, err)
assert.NoError(t, slApp.Commit())
}
func TestReuseCacheRace(t *testing.T) {
@ -2205,7 +2206,7 @@ func TestCheckAddError(t *testing.T) {
var appErrs appendErrors
sl := scrapeLoop{l: log.NewNopLogger()}
sl.checkAddError(nil, nil, nil, storage.ErrOutOfOrderSample, nil, &appErrs)
testutil.Equals(t, 1, appErrs.numOutOfOrder)
assert.Equal(t, 1, appErrs.numOutOfOrder)
}
func TestScrapeReportSingleAppender(t *testing.T) {
@ -2248,7 +2249,7 @@ func TestScrapeReportSingleAppender(t *testing.T) {
start := time.Now()
for time.Since(start) < 3*time.Second {
q, err := s.Querier(ctx, time.Time{}.UnixNano(), time.Now().UnixNano())
testutil.Ok(t, err)
assert.NoError(t, err)
series := q.Select(false, nil, labels.MustNewMatcher(labels.MatchRegexp, "__name__", ".+"))
c := 0
@ -2259,7 +2260,7 @@ func TestScrapeReportSingleAppender(t *testing.T) {
}
}
testutil.Equals(t, 0, c%9, "Appended samples not as expected: %d", c)
assert.Equal(t, 0, c%9, "Appended samples not as expected: %d", c)
q.Close()
}
cancel()

View file

@ -21,14 +21,14 @@ import (
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"strings"
"testing"
"time"
"github.com/prometheus/common/model"
config_util "github.com/prometheus/common/config"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/assert"
"github.com/prometheus/prometheus/pkg/labels"
)
@ -40,9 +40,7 @@ func TestTargetLabels(t *testing.T) {
target := newTestTarget("example.com:80", 0, labels.FromStrings("job", "some_job", "foo", "bar"))
want := labels.FromStrings(model.JobLabel, "some_job", "foo", "bar")
got := target.Labels()
if !reflect.DeepEqual(want, got) {
t.Errorf("want base labels %v, got %v", want, got)
}
assert.Equal(t, want, got)
}
func TestTargetOffset(t *testing.T) {
@ -113,16 +111,14 @@ func TestTargetURL(t *testing.T) {
"cde": []string{"huu"},
"xyz": []string{"hoo"},
}
expectedURL := url.URL{
expectedURL := &url.URL{
Scheme: "https",
Host: "example.com:1234",
Path: "/metricz",
RawQuery: expectedParams.Encode(),
}
if u := target.URL(); !reflect.DeepEqual(u.String(), expectedURL.String()) {
t.Fatalf("Expected URL %q, but got %q", expectedURL.String(), u.String())
}
assert.Equal(t, expectedURL, target.URL())
}
func newTestTarget(targetURL string, deadline time.Duration, lbls labels.Labels) *Target {

View file

@ -17,7 +17,7 @@ import (
"math/rand"
"testing"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
)
func TestSampleRing(t *testing.T) {
@ -77,9 +77,9 @@ func TestSampleRing(t *testing.T) {
}
if found {
testutil.Assert(t, sold.t >= s.t-c.delta, "%d: unexpected sample %d in buffer; buffer %v", i, sold.t, buffered)
assert.True(t, sold.t >= s.t-c.delta, "%d: unexpected sample %d in buffer; buffer %v", i, sold.t, buffered)
} else {
testutil.Assert(t, sold.t < s.t-c.delta, "%d: expected sample %d to be in buffer but was not; buffer %v", i, sold.t, buffered)
assert.True(t, sold.t < s.t-c.delta, "%d: expected sample %d to be in buffer but was not; buffer %v", i, sold.t, buffered)
}
}
}
@ -96,12 +96,12 @@ func TestBufferedSeriesIterator(t *testing.T) {
t, v := bit.At()
b = append(b, sample{t: t, v: v})
}
testutil.Equals(t, exp, b, "buffer mismatch")
assert.Equal(t, exp, b, "buffer mismatch")
}
sampleEq := func(ets int64, ev float64) {
ts, v := it.Values()
testutil.Equals(t, ets, ts, "timestamp mismatch")
testutil.Equals(t, ev, v, "value mismatch")
assert.Equal(t, ets, ts, "timestamp mismatch")
assert.Equal(t, ev, v, "value mismatch")
}
it = NewBufferIterator(NewListSeriesIterator(samples{
@ -115,29 +115,29 @@ func TestBufferedSeriesIterator(t *testing.T) {
sample{t: 101, v: 10},
}), 2)
testutil.Assert(t, it.Seek(-123), "seek failed")
assert.True(t, it.Seek(-123), "seek failed")
sampleEq(1, 2)
bufferEq(nil)
testutil.Assert(t, it.Next(), "next failed")
assert.True(t, it.Next(), "next failed")
sampleEq(2, 3)
bufferEq([]sample{{t: 1, v: 2}})
testutil.Assert(t, it.Next(), "next failed")
testutil.Assert(t, it.Next(), "next failed")
testutil.Assert(t, it.Next(), "next failed")
assert.True(t, it.Next(), "next failed")
assert.True(t, it.Next(), "next failed")
assert.True(t, it.Next(), "next failed")
sampleEq(5, 6)
bufferEq([]sample{{t: 2, v: 3}, {t: 3, v: 4}, {t: 4, v: 5}})
testutil.Assert(t, it.Seek(5), "seek failed")
assert.True(t, it.Seek(5), "seek failed")
sampleEq(5, 6)
bufferEq([]sample{{t: 2, v: 3}, {t: 3, v: 4}, {t: 4, v: 5}})
testutil.Assert(t, it.Seek(101), "seek failed")
assert.True(t, it.Seek(101), "seek failed")
sampleEq(101, 10)
bufferEq([]sample{{t: 99, v: 8}, {t: 100, v: 9}})
testutil.Assert(t, !it.Next(), "next succeeded unexpectedly")
assert.True(t, !it.Next(), "next succeeded unexpectedly")
}
// At() should not be called once Next() returns false.
@ -147,7 +147,7 @@ func TestBufferedSeriesIteratorNoBadAt(t *testing.T) {
m := &mockSeriesIterator{
seek: func(int64) bool { return false },
at: func() (int64, float64) {
testutil.Assert(t, !done, "unexpectedly done")
assert.True(t, !done, "unexpectedly done")
done = true
return 0, 0
},
@ -171,7 +171,7 @@ func BenchmarkBufferedSeriesIterator(b *testing.B) {
for it.Next() {
// scan everything
}
testutil.Ok(b, it.Err())
assert.NoError(b, it.Err())
}
type mockSeriesIterator struct {

View file

@ -19,6 +19,7 @@ import (
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/pkg/labels"
tsdb_errors "github.com/prometheus/prometheus/tsdb/errors"
)

View file

@ -19,11 +19,11 @@ import (
"github.com/pkg/errors"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/assert"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/storage"
"github.com/prometheus/prometheus/util/teststorage"
"github.com/prometheus/prometheus/util/testutil"
)
func TestFanout_SelectSorted(t *testing.T) {
@ -43,7 +43,7 @@ func TestFanout_SelectSorted(t *testing.T) {
app1.Add(inputLabel, 2000, 2)
inputTotalSize++
err := app1.Commit()
testutil.Ok(t, err)
assert.NoError(t, err)
remoteStorage1 := teststorage.New(t)
defer remoteStorage1.Close()
@ -55,7 +55,7 @@ func TestFanout_SelectSorted(t *testing.T) {
app2.Add(inputLabel, 5000, 5)
inputTotalSize++
err = app2.Commit()
testutil.Ok(t, err)
assert.NoError(t, err)
remoteStorage2 := teststorage.New(t)
defer remoteStorage2.Close()
@ -69,17 +69,17 @@ func TestFanout_SelectSorted(t *testing.T) {
inputTotalSize++
err = app3.Commit()
testutil.Ok(t, err)
assert.NoError(t, err)
fanoutStorage := storage.NewFanout(nil, priStorage, remoteStorage1, remoteStorage2)
t.Run("querier", func(t *testing.T) {
querier, err := fanoutStorage.Querier(context.Background(), 0, 8000)
testutil.Ok(t, err)
assert.NoError(t, err)
defer querier.Close()
matcher, err := labels.NewMatcher(labels.MatchEqual, model.MetricNameLabel, "a")
testutil.Ok(t, err)
assert.NoError(t, err)
seriesSet := querier.Select(true, nil, matcher)
@ -96,16 +96,16 @@ func TestFanout_SelectSorted(t *testing.T) {
}
}
testutil.Equals(t, labelsResult, outputLabel)
testutil.Equals(t, inputTotalSize, len(result))
assert.Equal(t, labelsResult, outputLabel)
assert.Equal(t, inputTotalSize, len(result))
})
t.Run("chunk querier", func(t *testing.T) {
querier, err := fanoutStorage.ChunkQuerier(ctx, 0, 8000)
testutil.Ok(t, err)
assert.NoError(t, err)
defer querier.Close()
matcher, err := labels.NewMatcher(labels.MatchEqual, model.MetricNameLabel, "a")
testutil.Ok(t, err)
assert.NoError(t, err)
seriesSet := storage.NewSeriesSetFromChunkSeriesSet(querier.Select(true, nil, matcher))
@ -122,9 +122,9 @@ func TestFanout_SelectSorted(t *testing.T) {
}
}
testutil.Ok(t, seriesSet.Err())
testutil.Equals(t, labelsResult, outputLabel)
testutil.Equals(t, inputTotalSize, len(result))
assert.NoError(t, seriesSet.Err())
assert.Equal(t, labelsResult, outputLabel)
assert.Equal(t, inputTotalSize, len(result))
})
}
@ -157,7 +157,7 @@ func TestFanoutErrors(t *testing.T) {
t.Run("samples", func(t *testing.T) {
querier, err := fanoutStorage.Querier(context.Background(), 0, 8000)
testutil.Ok(t, err)
assert.NoError(t, err)
defer querier.Close()
matcher := labels.MustNewMatcher(labels.MatchEqual, "a", "b")
@ -169,20 +169,20 @@ func TestFanoutErrors(t *testing.T) {
}
if tc.err != nil {
testutil.NotOk(t, ss.Err())
testutil.Equals(t, tc.err.Error(), ss.Err().Error())
assert.Error(t, ss.Err())
assert.Equal(t, tc.err.Error(), ss.Err().Error())
}
if tc.warning != nil {
testutil.Assert(t, len(ss.Warnings()) > 0, "warnings expected")
testutil.NotOk(t, ss.Warnings()[0])
testutil.Equals(t, tc.warning.Error(), ss.Warnings()[0].Error())
assert.True(t, len(ss.Warnings()) > 0, "warnings expected")
assert.Error(t, ss.Warnings()[0])
assert.Equal(t, tc.warning.Error(), ss.Warnings()[0].Error())
}
})
t.Run("chunks", func(t *testing.T) {
t.Skip("enable once TestStorage and TSDB implements ChunkQuerier")
querier, err := fanoutStorage.ChunkQuerier(context.Background(), 0, 8000)
testutil.Ok(t, err)
assert.NoError(t, err)
defer querier.Close()
matcher := labels.MustNewMatcher(labels.MatchEqual, "a", "b")
@ -194,14 +194,14 @@ func TestFanoutErrors(t *testing.T) {
}
if tc.err != nil {
testutil.NotOk(t, ss.Err())
testutil.Equals(t, tc.err.Error(), ss.Err().Error())
assert.Error(t, ss.Err())
assert.Equal(t, tc.err.Error(), ss.Err().Error())
}
if tc.warning != nil {
testutil.Assert(t, len(ss.Warnings()) > 0, "warnings expected")
testutil.NotOk(t, ss.Warnings()[0])
testutil.Equals(t, tc.warning.Error(), ss.Warnings()[0].Error())
assert.True(t, len(ss.Warnings()) > 0, "warnings expected")
assert.Error(t, ss.Warnings()[0])
assert.Equal(t, tc.warning.Error(), ss.Warnings()[0].Error())
}
})
}

View file

@ -22,6 +22,7 @@ import (
"sync"
"github.com/pkg/errors"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/tsdb/chunkenc"
"github.com/prometheus/prometheus/tsdb/chunks"

View file

@ -21,11 +21,11 @@ import (
"testing"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/tsdb/chunkenc"
"github.com/prometheus/prometheus/tsdb/tsdbutil"
"github.com/prometheus/prometheus/util/testutil"
)
func TestMergeQuerierWithChainMerger(t *testing.T) {
@ -194,19 +194,19 @@ func TestMergeQuerierWithChainMerger(t *testing.T) {
for mergedQuerier.Next() {
mergedSeries = append(mergedSeries, mergedQuerier.At())
}
testutil.Ok(t, mergedQuerier.Err())
assert.NoError(t, mergedQuerier.Err())
for _, actualSeries := range mergedSeries {
testutil.Assert(t, tc.expected.Next(), "Expected Next() to be true")
assert.True(t, tc.expected.Next(), "Expected Next() to be true")
expectedSeries := tc.expected.At()
testutil.Equals(t, expectedSeries.Labels(), actualSeries.Labels())
assert.Equal(t, expectedSeries.Labels(), actualSeries.Labels())
expSmpl, expErr := ExpandSamples(expectedSeries.Iterator(), nil)
actSmpl, actErr := ExpandSamples(actualSeries.Iterator(), nil)
testutil.Equals(t, expErr, actErr)
testutil.Equals(t, expSmpl, actSmpl)
assert.Equal(t, expErr, actErr)
assert.Equal(t, expSmpl, actSmpl)
}
testutil.Assert(t, !tc.expected.Next(), "Expected Next() to be false")
assert.True(t, !tc.expected.Next(), "Expected Next() to be false")
})
}
}
@ -364,19 +364,19 @@ func TestMergeChunkQuerierWithNoVerticalChunkSeriesMerger(t *testing.T) {
merged := NewMergeChunkQuerier([]ChunkQuerier{p}, qs, NewCompactingChunkSeriesMerger(nil)).Select(false, nil)
for merged.Next() {
testutil.Assert(t, tc.expected.Next(), "Expected Next() to be true")
assert.True(t, tc.expected.Next(), "Expected Next() to be true")
actualSeries := merged.At()
expectedSeries := tc.expected.At()
testutil.Equals(t, expectedSeries.Labels(), actualSeries.Labels())
assert.Equal(t, expectedSeries.Labels(), actualSeries.Labels())
expChks, expErr := ExpandChunks(expectedSeries.Iterator())
actChks, actErr := ExpandChunks(actualSeries.Iterator())
testutil.Equals(t, expErr, actErr)
testutil.Equals(t, expChks, actChks)
assert.Equal(t, expErr, actErr)
assert.Equal(t, expChks, actChks)
}
testutil.Ok(t, merged.Err())
testutil.Assert(t, !tc.expected.Next(), "Expected Next() to be false")
assert.NoError(t, merged.Err())
assert.True(t, !tc.expected.Next(), "Expected Next() to be false")
})
}
}
@ -468,12 +468,12 @@ func TestCompactingChunkSeriesMerger(t *testing.T) {
} {
t.Run(tc.name, func(t *testing.T) {
merged := m(tc.input...)
testutil.Equals(t, tc.expected.Labels(), merged.Labels())
assert.Equal(t, tc.expected.Labels(), merged.Labels())
actChks, actErr := ExpandChunks(merged.Iterator())
expChks, expErr := ExpandChunks(tc.expected.Iterator())
testutil.Equals(t, expErr, actErr)
testutil.Equals(t, expChks, actChks)
assert.Equal(t, expErr, actErr)
assert.Equal(t, expChks, actChks)
})
}
}
@ -612,8 +612,8 @@ func TestChainSampleIterator(t *testing.T) {
} {
merged := newChainSampleIterator(tc.input)
actual, err := ExpandSamples(merged, nil)
testutil.Ok(t, err)
testutil.Equals(t, tc.expected, actual)
assert.NoError(t, err)
assert.Equal(t, tc.expected, actual)
}
}
@ -655,9 +655,9 @@ func TestChainSampleIteratorSeek(t *testing.T) {
actual = append(actual, sample{t, v})
}
s, err := ExpandSamples(merged, nil)
testutil.Ok(t, err)
assert.NoError(t, err)
actual = append(actual, s...)
testutil.Equals(t, tc.expected, actual)
assert.Equal(t, tc.expected, actual)
}
}
@ -689,7 +689,7 @@ func benchmarkDrain(seriesSet SeriesSet, b *testing.B) {
for n := 0; n < b.N; n++ {
for seriesSet.Next() {
result, err = ExpandSamples(seriesSet.At().Iterator(), nil)
testutil.Ok(b, err)
assert.NoError(b, err)
}
}
}
@ -789,9 +789,9 @@ func unwrapMockGenericQuerier(t *testing.T, qr genericQuerier) *mockGenericQueri
m, ok := qr.(*mockGenericQuerier)
if !ok {
s, ok := qr.(*secondaryQuerier)
testutil.Assert(t, ok, "expected secondaryQuerier got something else")
assert.True(t, ok, "expected secondaryQuerier got something else")
m, ok = s.genericQuerier.(*mockGenericQuerier)
testutil.Assert(t, ok, "expected mockGenericQuerier got something else")
assert.True(t, ok, "expected mockGenericQuerier got something else")
}
return m
}
@ -922,10 +922,10 @@ func TestMergeGenericQuerierWithSecondaries_ErrorHandling(t *testing.T) {
for res.Next() {
lbls = append(lbls, res.At().Labels())
}
testutil.Equals(t, tcase.expectedWarnings[0], res.Warnings())
testutil.Equals(t, tcase.expectedErrs[0], res.Err())
testutil.Assert(t, errors.Is(res.Err(), tcase.expectedErrs[0]), "expected error doesn't match")
testutil.Equals(t, tcase.expectedSelectsSeries, lbls)
assert.Equal(t, tcase.expectedWarnings[0], res.Warnings())
assert.Equal(t, tcase.expectedErrs[0], res.Err())
assert.True(t, errors.Is(res.Err(), tcase.expectedErrs[0]), "expected error doesn't match")
assert.Equal(t, tcase.expectedSelectsSeries, lbls)
for _, qr := range q.queriers {
m := unwrapMockGenericQuerier(t, qr)
@ -934,14 +934,14 @@ func TestMergeGenericQuerierWithSecondaries_ErrorHandling(t *testing.T) {
if len(q.queriers) == 1 {
exp[0] = false
}
testutil.Equals(t, exp, m.sortedSeriesRequested)
assert.Equal(t, exp, m.sortedSeriesRequested)
}
})
t.Run("LabelNames", func(t *testing.T) {
res, w, err := q.LabelNames()
testutil.Equals(t, tcase.expectedWarnings[1], w)
testutil.Assert(t, errors.Is(err, tcase.expectedErrs[1]), "expected error doesn't match")
testutil.Equals(t, tcase.expectedLabels, res)
assert.Equal(t, tcase.expectedWarnings[1], w)
assert.True(t, errors.Is(err, tcase.expectedErrs[1]), "expected error doesn't match")
assert.Equal(t, tcase.expectedLabels, res)
if err != nil {
return
@ -949,14 +949,14 @@ func TestMergeGenericQuerierWithSecondaries_ErrorHandling(t *testing.T) {
for _, qr := range q.queriers {
m := unwrapMockGenericQuerier(t, qr)
testutil.Equals(t, 1, m.labelNamesCalls)
assert.Equal(t, 1, m.labelNamesCalls)
}
})
t.Run("LabelValues", func(t *testing.T) {
res, w, err := q.LabelValues("test")
testutil.Equals(t, tcase.expectedWarnings[2], w)
testutil.Assert(t, errors.Is(err, tcase.expectedErrs[2]), "expected error doesn't match")
testutil.Equals(t, tcase.expectedLabels, res)
assert.Equal(t, tcase.expectedWarnings[2], w)
assert.True(t, errors.Is(err, tcase.expectedErrs[2]), "expected error doesn't match")
assert.Equal(t, tcase.expectedLabels, res)
if err != nil {
return
@ -964,7 +964,7 @@ func TestMergeGenericQuerierWithSecondaries_ErrorHandling(t *testing.T) {
for _, qr := range q.queriers {
m := unwrapMockGenericQuerier(t, qr)
testutil.Equals(t, []string{"test"}, m.labelNamesRequested)
assert.Equal(t, []string{"test"}, m.labelNamesRequested)
}
})
})

View file

@ -17,7 +17,7 @@ import (
"io"
"testing"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
)
type mockedFlusher struct {
@ -45,48 +45,48 @@ func TestChunkedReaderCanReadFromChunkedWriter(t *testing.T) {
for _, msg := range msgs {
n, err := w.Write(msg)
testutil.Ok(t, err)
testutil.Equals(t, len(msg), n)
assert.NoError(t, err)
assert.Equal(t, len(msg), n)
}
i := 0
for ; i < 4; i++ {
msg, err := r.Next()
testutil.Ok(t, err)
testutil.Assert(t, i < len(msgs), "more messages then expected")
testutil.Equals(t, msgs[i], msg)
assert.NoError(t, err)
assert.True(t, i < len(msgs), "more messages then expected")
assert.Equal(t, msgs[i], msg)
}
// Empty byte slice is skipped.
i++
msg, err := r.Next()
testutil.Ok(t, err)
testutil.Assert(t, i < len(msgs), "more messages then expected")
testutil.Equals(t, msgs[i], msg)
assert.NoError(t, err)
assert.True(t, i < len(msgs), "more messages then expected")
assert.Equal(t, msgs[i], msg)
_, err = r.Next()
testutil.NotOk(t, err, "expected io.EOF")
testutil.Equals(t, io.EOF, err)
assert.Error(t, err, "expected io.EOF")
assert.Equal(t, io.EOF, err)
testutil.Equals(t, 5, f.flushed)
assert.Equal(t, 5, f.flushed)
}
func TestChunkedReader_Overflow(t *testing.T) {
b := &bytes.Buffer{}
_, err := NewChunkedWriter(b, &mockedFlusher{}).Write([]byte("twelve bytes"))
testutil.Ok(t, err)
assert.NoError(t, err)
b2 := make([]byte, 12)
copy(b2, b.Bytes())
ret, err := NewChunkedReader(b, 12, nil).Next()
testutil.Ok(t, err)
testutil.Equals(t, "twelve bytes", string(ret))
assert.NoError(t, err)
assert.Equal(t, "twelve bytes", string(ret))
_, err = NewChunkedReader(bytes.NewReader(b2), 11, nil).Next()
testutil.NotOk(t, err, "expect exceed limit error")
testutil.Equals(t, "chunkedReader: message size exceeded the limit 11 bytes; got: 12 bytes", err.Error())
assert.Error(t, err, "expect exceed limit error")
assert.Equal(t, "chunkedReader: message size exceeded the limit 11 bytes; got: 12 bytes", err.Error())
}
func TestChunkedReader_CorruptedFrame(t *testing.T) {
@ -94,13 +94,13 @@ func TestChunkedReader_CorruptedFrame(t *testing.T) {
w := NewChunkedWriter(b, &mockedFlusher{})
n, err := w.Write([]byte("test1"))
testutil.Ok(t, err)
testutil.Equals(t, 5, n)
assert.NoError(t, err)
assert.Equal(t, 5, n)
bs := b.Bytes()
bs[9] = 1 // Malform the frame by changing one byte.
_, err = NewChunkedReader(bytes.NewReader(bs), 20, nil).Next()
testutil.NotOk(t, err, "expected malformed frame")
testutil.Equals(t, "chunkedReader: corrupted frame; checksum mismatch", err.Error())
assert.Error(t, err, "expected malformed frame")
assert.Equal(t, "chunkedReader: corrupted frame; checksum mismatch", err.Error())
}

View file

@ -27,6 +27,7 @@ import (
"github.com/gogo/protobuf/proto"
"github.com/golang/snappy"
"github.com/opentracing-contrib/go-stdlib/nethttp"
"github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
@ -34,7 +35,6 @@ import (
"github.com/prometheus/common/model"
"github.com/prometheus/common/version"
"github.com/opentracing-contrib/go-stdlib/nethttp"
"github.com/prometheus/prometheus/prompb"
)

View file

@ -25,7 +25,7 @@ import (
"github.com/pkg/errors"
config_util "github.com/prometheus/common/config"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
)
var longErrMessage = strings.Repeat("error message", maxErrMsgLen)
@ -53,7 +53,7 @@ func TestStoreHTTPErrorHandling(t *testing.T) {
},
}
for i, test := range tests {
for _, test := range tests {
server := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, longErrMessage, test.code)
@ -61,7 +61,7 @@ func TestStoreHTTPErrorHandling(t *testing.T) {
)
serverURL, err := url.Parse(server.URL)
testutil.Ok(t, err)
assert.NoError(t, err)
conf := &ClientConfig{
URL: &config_util.URL{URL: serverURL},
@ -69,12 +69,16 @@ func TestStoreHTTPErrorHandling(t *testing.T) {
}
hash, err := toHash(conf)
testutil.Ok(t, err)
assert.NoError(t, err)
c, err := NewWriteClient(hash, conf)
testutil.Ok(t, err)
assert.NoError(t, err)
err = c.Store(context.Background(), []byte{})
testutil.ErrorEqual(t, err, test.err, "unexpected error in test %d", i)
if test.err != nil {
assert.EqualError(t, err, test.err.Error())
} else {
assert.NoError(t, err)
}
server.Close()
}

View file

@ -24,6 +24,7 @@ import (
"github.com/golang/snappy"
"github.com/pkg/errors"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/prompb"
"github.com/prometheus/prometheus/storage"

View file

@ -17,10 +17,11 @@ import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/prompb"
"github.com/prometheus/prometheus/storage"
"github.com/prometheus/prometheus/util/testutil"
)
func TestValidateLabelsAndMetricName(t *testing.T) {
@ -114,10 +115,10 @@ func TestValidateLabelsAndMetricName(t *testing.T) {
t.Run(test.description, func(t *testing.T) {
err := validateLabelsAndMetricName(test.input)
if test.expectedErr != "" {
testutil.NotOk(t, err)
testutil.Equals(t, test.expectedErr, err.Error())
assert.Error(t, err)
assert.Equal(t, test.expectedErr, err.Error())
} else {
testutil.Ok(t, err)
assert.NoError(t, err)
}
})
}
@ -135,11 +136,11 @@ func TestConcreteSeriesSet(t *testing.T) {
c := &concreteSeriesSet{
series: []storage.Series{series1, series2},
}
testutil.Assert(t, c.Next(), "Expected Next() to be true.")
testutil.Equals(t, series1, c.At(), "Unexpected series returned.")
testutil.Assert(t, c.Next(), "Expected Next() to be true.")
testutil.Equals(t, series2, c.At(), "Unexpected series returned.")
testutil.Assert(t, !c.Next(), "Expected Next() to be false.")
assert.True(t, c.Next(), "Expected Next() to be true.")
assert.Equal(t, series1, c.At(), "Unexpected series returned.")
assert.True(t, c.Next(), "Expected Next() to be true.")
assert.Equal(t, series2, c.At(), "Unexpected series returned.")
assert.True(t, !c.Next(), "Expected Next() to be false.")
}
func TestConcreteSeriesClonesLabels(t *testing.T) {
@ -152,13 +153,13 @@ func TestConcreteSeriesClonesLabels(t *testing.T) {
}
gotLabels := cs.Labels()
testutil.Equals(t, lbls, gotLabels)
assert.Equal(t, lbls, gotLabels)
gotLabels[0].Value = "foo"
gotLabels[1].Value = "bar"
gotLabels = cs.Labels()
testutil.Equals(t, lbls, gotLabels)
assert.Equal(t, lbls, gotLabels)
}
func TestFromQueryResultWithDuplicates(t *testing.T) {
@ -182,9 +183,9 @@ func TestFromQueryResultWithDuplicates(t *testing.T) {
errSeries, isErrSeriesSet := series.(errSeriesSet)
testutil.Assert(t, isErrSeriesSet, "Expected resulting series to be an errSeriesSet")
assert.True(t, isErrSeriesSet, "Expected resulting series to be an errSeriesSet")
errMessage := errSeries.Err().Error()
testutil.Assert(t, errMessage == "duplicate label with name: foo", fmt.Sprintf("Expected error to be from duplicate label, but got: %s", errMessage))
assert.True(t, errMessage == "duplicate label with name: foo", fmt.Sprintf("Expected error to be from duplicate label, but got: %s", errMessage))
}
func TestNegotiateResponseType(t *testing.T) {
@ -192,23 +193,23 @@ func TestNegotiateResponseType(t *testing.T) {
prompb.ReadRequest_STREAMED_XOR_CHUNKS,
prompb.ReadRequest_SAMPLES,
})
testutil.Ok(t, err)
testutil.Equals(t, prompb.ReadRequest_STREAMED_XOR_CHUNKS, r)
assert.NoError(t, err)
assert.Equal(t, prompb.ReadRequest_STREAMED_XOR_CHUNKS, r)
r2, err := NegotiateResponseType([]prompb.ReadRequest_ResponseType{
prompb.ReadRequest_SAMPLES,
prompb.ReadRequest_STREAMED_XOR_CHUNKS,
})
testutil.Ok(t, err)
testutil.Equals(t, prompb.ReadRequest_SAMPLES, r2)
assert.NoError(t, err)
assert.Equal(t, prompb.ReadRequest_SAMPLES, r2)
r3, err := NegotiateResponseType([]prompb.ReadRequest_ResponseType{})
testutil.Ok(t, err)
testutil.Equals(t, prompb.ReadRequest_SAMPLES, r3)
assert.NoError(t, err)
assert.Equal(t, prompb.ReadRequest_SAMPLES, r3)
_, err = NegotiateResponseType([]prompb.ReadRequest_ResponseType{20})
testutil.NotOk(t, err, "expected error due to not supported requested response types")
testutil.Equals(t, "server does not support any of the requested response types: [20]; supported: map[SAMPLES:{} STREAMED_XOR_CHUNKS:{}]", err.Error())
assert.Error(t, err, "expected error due to not supported requested response types")
assert.Equal(t, "server does not support any of the requested response types: [20]; supported: map[SAMPLES:{} STREAMED_XOR_CHUNKS:{}]", err.Error())
}
func TestMergeLabels(t *testing.T) {
@ -226,6 +227,6 @@ func TestMergeLabels(t *testing.T) {
expected: []prompb.Label{{Name: "aaa", Value: "foo"}, {Name: "bbb", Value: "bar"}, {Name: "ccc", Value: "bar"}, {Name: "ddd", Value: "foo"}},
},
} {
testutil.Equals(t, tc.expected, MergeLabels(tc.primary, tc.secondary))
assert.Equal(t, tc.expected, MergeLabels(tc.primary, tc.secondary))
}
}

View file

@ -21,10 +21,9 @@ package remote
import (
"sync"
"go.uber.org/atomic"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"go.uber.org/atomic"
)
var noReferenceReleases = promauto.NewCounter(prometheus.CounterOpts{

View file

@ -23,7 +23,7 @@ import (
"testing"
"time"
"github.com/prometheus/prometheus/util/testutil"
"github.com/stretchr/testify/assert"
)
func TestIntern(t *testing.T) {
@ -32,8 +32,8 @@ func TestIntern(t *testing.T) {
interner.intern(testString)
interned, ok := interner.pool[testString]
testutil.Equals(t, true, ok)
testutil.Assert(t, interned.refs.Load() == 1, fmt.Sprintf("expected refs to be 1 but it was %d", interned.refs.Load()))
assert.Equal(t, true, ok)
assert.True(t, interned.refs.Load() == 1, fmt.Sprintf("expected refs to be 1 but it was %d", interned.refs.Load()))
}
func TestIntern_MultiRef(t *testing.T) {
@ -43,14 +43,14 @@ func TestIntern_MultiRef(t *testing.T) {
interner.intern(testString)
interned, ok := interner.pool[testString]
testutil.Equals(t, true, ok)
testutil.Assert(t, interned.refs.Load() == 1, fmt.Sprintf("expected refs to be 1 but it was %d", interned.refs.Load()))
assert.Equal(t, true, ok)
assert.True(t, interned.refs.Load() == 1, fmt.Sprintf("expected refs to be 1 but it was %d", interned.refs.Load()))
interner.intern(testString)
interned, ok = interner.pool[testString]
testutil.Equals(t, true, ok)
testutil.Assert(t, interned.refs.Load() == 2, fmt.Sprintf("expected refs to be 2 but it was %d", interned.refs.Load()))
assert.Equal(t, true, ok)
assert.True(t, interned.refs.Load() == 2, fmt.Sprintf("expected refs to be 2 but it was %d", interned.refs.Load()))
}
func TestIntern_DeleteRef(t *testing.T) {
@ -60,12 +60,12 @@ func TestIntern_DeleteRef(t *testing.T) {
interner.intern(testString)
interned, ok := interner.pool[testString]
testutil.Equals(t, true, ok)
testutil.Assert(t, interned.refs.Load() == 1, fmt.Sprintf("expected refs to be 1 but it was %d", interned.refs.Load()))
assert.Equal(t, true, ok)
assert.True(t, interned.refs.Load() == 1, fmt.Sprintf("expected refs to be 1 but it was %d", interned.refs.Load()))
interner.release(testString)
_, ok = interner.pool[testString]
testutil.Equals(t, false, ok)
assert.Equal(t, false, ok)
}
func TestIntern_MultiRef_Concurrent(t *testing.T) {
@ -74,8 +74,8 @@ func TestIntern_MultiRef_Concurrent(t *testing.T) {
interner.intern(testString)
interned, ok := interner.pool[testString]
testutil.Equals(t, true, ok)
testutil.Assert(t, interned.refs.Load() == 1, fmt.Sprintf("expected refs to be 1 but it was %d", interned.refs.Load()))
assert.Equal(t, true, ok)
assert.True(t, interned.refs.Load() == 1, fmt.Sprintf("expected refs to be 1 but it was %d", interned.refs.Load()))
go interner.release(testString)
@ -86,6 +86,6 @@ func TestIntern_MultiRef_Concurrent(t *testing.T) {
interner.mtx.RLock()
interned, ok = interner.pool[testString]
interner.mtx.RUnlock()
testutil.Equals(t, true, ok)
testutil.Assert(t, interned.refs.Load() == 1, fmt.Sprintf("expected refs to be 1 but it was %d", interned.refs.Load()))
assert.Equal(t, true, ok)
assert.True(t, interned.refs.Load() == 1, fmt.Sprintf("expected refs to be 1 but it was %d", interned.refs.Load()))
}

View file

@ -26,9 +26,9 @@ import (
"github.com/golang/snappy"
"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/atomic"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/prometheus/config"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/pkg/relabel"

View file

@ -18,8 +18,8 @@ import (
"fmt"
"io/ioutil"
"math"
"net/url"
"os"
"reflect"
"sort"
"strconv"
"strings"
@ -30,19 +30,18 @@ import (
"github.com/go-kit/kit/log"
"github.com/gogo/protobuf/proto"
"github.com/golang/snappy"
"go.uber.org/atomic"
"github.com/prometheus/client_golang/prometheus"
client_testutil "github.com/prometheus/client_golang/prometheus/testutil"
common_config "github.com/prometheus/common/config"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/assert"
"go.uber.org/atomic"
"github.com/prometheus/prometheus/config"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/pkg/timestamp"
"github.com/prometheus/prometheus/prompb"
"github.com/prometheus/prometheus/tsdb/record"
"github.com/prometheus/prometheus/util/testutil"
"net/url"
)
const defaultFlushDeadline = 1 * time.Minute
@ -74,9 +73,9 @@ func TestSampleDelivery(t *testing.T) {
queueConfig.MaxSamplesPerSend = len(samples) / 2
dir, err := ioutil.TempDir("", "TestSampleDeliver")
testutil.Ok(t, err)
assert.NoError(t, err)
defer func() {
testutil.Ok(t, os.RemoveAll(dir))
assert.NoError(t, os.RemoveAll(dir))
}()
s := NewStorage(nil, nil, nil, dir, defaultFlushDeadline)
@ -96,9 +95,9 @@ func TestSampleDelivery(t *testing.T) {
},
}
writeConfig.QueueConfig = queueConfig
testutil.Ok(t, s.ApplyConfig(conf))
assert.NoError(t, s.ApplyConfig(conf))
hash, err := toHash(writeConfig)
testutil.Ok(t, err)
assert.NoError(t, err)
qm := s.rws.queues[hash]
qm.SetClient(c)
@ -122,9 +121,9 @@ func TestSampleDeliveryTimeout(t *testing.T) {
cfg.BatchSendDeadline = model.Duration(100 * time.Millisecond)
dir, err := ioutil.TempDir("", "TestSampleDeliveryTimeout")
testutil.Ok(t, err)
assert.NoError(t, err)
defer func() {
testutil.Ok(t, os.RemoveAll(dir))
assert.NoError(t, os.RemoveAll(dir))
}()
metrics := newQueueManagerMetrics(nil, "", "")
@ -165,9 +164,9 @@ func TestSampleDeliveryOrder(t *testing.T) {
c.expectSamples(samples, series)
dir, err := ioutil.TempDir("", "TestSampleDeliveryOrder")
testutil.Ok(t, err)
assert.NoError(t, err)
defer func() {
testutil.Ok(t, os.RemoveAll(dir))
assert.NoError(t, os.RemoveAll(dir))
}()
metrics := newQueueManagerMetrics(nil, "", "")
@ -186,9 +185,9 @@ func TestShutdown(t *testing.T) {
c := NewTestBlockedWriteClient()
dir, err := ioutil.TempDir("", "TestShutdown")
testutil.Ok(t, err)
assert.NoError(t, err)
defer func() {
testutil.Ok(t, os.RemoveAll(dir))
assert.NoError(t, os.RemoveAll(dir))
}()
metrics := newQueueManagerMetrics(nil, "", "")
@ -227,9 +226,9 @@ func TestSeriesReset(t *testing.T) {
numSeries := 25
dir, err := ioutil.TempDir("", "TestSeriesReset")
testutil.Ok(t, err)
assert.NoError(t, err)
defer func() {
testutil.Ok(t, os.RemoveAll(dir))
assert.NoError(t, os.RemoveAll(dir))
}()
metrics := newQueueManagerMetrics(nil, "", "")
@ -241,9 +240,9 @@ func TestSeriesReset(t *testing.T) {
}
m.StoreSeries(series, i)
}
testutil.Equals(t, numSegments*numSeries, len(m.seriesLabels))
assert.Equal(t, numSegments*numSeries, len(m.seriesLabels))
m.SeriesReset(2)
testutil.Equals(t, numSegments*numSeries/2, len(m.seriesLabels))
assert.Equal(t, numSegments*numSeries/2, len(m.seriesLabels))
}
func TestReshard(t *testing.T) {
@ -259,9 +258,9 @@ func TestReshard(t *testing.T) {
cfg.MaxShards = 1
dir, err := ioutil.TempDir("", "TestReshard")
testutil.Ok(t, err)
assert.NoError(t, err)
defer func() {
testutil.Ok(t, os.RemoveAll(dir))
assert.NoError(t, os.RemoveAll(dir))
}()
metrics := newQueueManagerMetrics(nil, "", "")
@ -274,7 +273,7 @@ func TestReshard(t *testing.T) {
go func() {
for i := 0; i < len(samples); i += config.DefaultQueueConfig.Capacity {
sent := m.Append(samples[i : i+config.DefaultQueueConfig.Capacity])
testutil.Assert(t, sent, "samples not sent")
assert.True(t, sent, "samples not sent")
time.Sleep(100 * time.Millisecond)
}
}()
@ -335,7 +334,7 @@ func TestReleaseNoninternedString(t *testing.T) {
}
metric := client_testutil.ToFloat64(noReferenceReleases)
testutil.Assert(t, metric == 0, "expected there to be no calls to release for strings that were not already interned: %d", int(metric))
assert.True(t, metric == 0, "expected there to be no calls to release for strings that were not already interned: %d", int(metric))
}
func TestShouldReshard(t *testing.T) {
@ -377,7 +376,7 @@ func TestShouldReshard(t *testing.T) {
m.Stop()
testutil.Equals(t, c.expectedToReshard, shouldReshard)
assert.Equal(t, c.expectedToReshard, shouldReshard)
}
}
@ -456,9 +455,7 @@ func (c *TestWriteClient) waitForExpectedSamples(tb testing.TB) {
c.mtx.Lock()
defer c.mtx.Unlock()
for ts, expectedSamples := range c.expectedSamples {
if !reflect.DeepEqual(expectedSamples, c.receivedSamples[ts]) {
tb.Fatalf("%s: Expected %v, got %v", ts, expectedSamples, c.receivedSamples[ts])
}
assert.Equal(tb, expectedSamples, c.receivedSamples[ts], ts)
}
}
@ -567,7 +564,7 @@ func BenchmarkSampleDelivery(b *testing.B) {
cfg.MaxShards = 1
dir, err := ioutil.TempDir("", "BenchmarkSampleDelivery")
testutil.Ok(b, err)
assert.NoError(b, err)
defer os.RemoveAll(dir)
metrics := newQueueManagerMetrics(nil, "", "")
@ -597,7 +594,7 @@ func BenchmarkStartup(b *testing.B) {
// Find the second largest segment; we will replay up to this.
// (Second largest as WALWatcher will start tailing the largest).
dirents, err := ioutil.ReadDir(dir)
testutil.Ok(b, err)
assert.NoError(b, err)
var segments []int
for _, dirent := range dirents {
@ -619,7 +616,7 @@ func BenchmarkStartup(b *testing.B) {
m.watcher.SetStartTime(timestamp.Time(math.MaxInt64))
m.watcher.MaxSegment = segments[len(segments)-2]
err := m.watcher.Run()
testutil.Ok(b, err)
assert.NoError(b, err)
}
}
@ -650,7 +647,7 @@ func TestProcessExternalLabels(t *testing.T) {
expected: labels.Labels{{Name: "a", Value: "b"}},
},
} {
testutil.Equals(t, tc.expected, processExternalLabels(tc.labels, tc.externalLabels))
assert.Equal(t, tc.expected, processExternalLabels(tc.labels, tc.externalLabels))
}
}
@ -659,9 +656,9 @@ func TestCalculateDesiredShards(t *testing.T) {
cfg := config.DefaultQueueConfig
dir, err := ioutil.TempDir("", "TestCalculateDesiredShards")
testutil.Ok(t, err)
assert.NoError(t, err)
defer func() {
testutil.Ok(t, os.RemoveAll(dir))
assert.NoError(t, os.RemoveAll(dir))
}()
metrics := newQueueManagerMetrics(nil, "", "")
@ -706,7 +703,7 @@ func TestCalculateDesiredShards(t *testing.T) {
for ; ts < 120*time.Second; ts += shardUpdateDuration {
addSamples(inputRate*int64(shardUpdateDuration/time.Second), ts)
m.numShards = m.calculateDesiredShards()
testutil.Equals(t, 1, m.numShards)
assert.Equal(t, 1, m.numShards)
}
// Assume 100ms per request, or 10 requests per second per shard.
@ -728,10 +725,10 @@ func TestCalculateDesiredShards(t *testing.T) {
t.Log("desiredShards", m.numShards, "pendingSamples", pendingSamples)
m.numShards = m.calculateDesiredShards()
testutil.Assert(t, m.numShards >= minShards, "Shards are too low. desiredShards=%d, minShards=%d, t_seconds=%d", m.numShards, minShards, ts/time.Second)
testutil.Assert(t, m.numShards <= maxShards, "Shards are too high. desiredShards=%d, maxShards=%d, t_seconds=%d", m.numShards, maxShards, ts/time.Second)
assert.True(t, m.numShards >= minShards, "Shards are too low. desiredShards=%d, minShards=%d, t_seconds=%d", m.numShards, minShards, ts/time.Second)
assert.True(t, m.numShards <= maxShards, "Shards are too high. desiredShards=%d, maxShards=%d, t_seconds=%d", m.numShards, maxShards, ts/time.Second)
}
testutil.Assert(t, pendingSamples == 0, "Remote write never caught up, there are still %d pending samples.", pendingSamples)
assert.True(t, pendingSamples == 0, "Remote write never caught up, there are still %d pending samples.", pendingSamples)
}
func TestQueueManagerMetrics(t *testing.T) {
@ -740,12 +737,12 @@ func TestQueueManagerMetrics(t *testing.T) {
// Make sure metrics pass linting.
problems, err := client_testutil.GatherAndLint(reg)
testutil.Ok(t, err)
testutil.Equals(t, 0, len(problems), "Metric linting problems detected: %v", problems)
assert.NoError(t, err)
assert.Equal(t, 0, len(problems), "Metric linting problems detected: %v", problems)
// Make sure all metrics were unregistered. A failure here means you need
// unregister a metric in `queueManagerMetrics.unregister()`.
metrics.unregister()
err = client_testutil.GatherAndCompare(reg, strings.NewReader(""))
testutil.Ok(t, err)
assert.NoError(t, err)
}

View file

@ -17,6 +17,7 @@ import (
"context"
"github.com/pkg/errors"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/storage"
)

View file

@ -18,23 +18,23 @@ import (
"io/ioutil"
"net/url"
"os"
"reflect"
"sort"
"testing"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
config_util "github.com/prometheus/common/config"
"github.com/stretchr/testify/assert"
"github.com/prometheus/prometheus/config"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/prompb"
"github.com/prometheus/prometheus/storage"
"github.com/prometheus/prometheus/util/testutil"
)
func TestNoDuplicateReadConfigs(t *testing.T) {
dir, err := ioutil.TempDir("", "TestNoDuplicateReadConfigs")
testutil.Ok(t, err)
assert.NoError(t, err)
defer os.RemoveAll(dir)
cfg1 := config.RemoteReadConfig{
@ -103,8 +103,8 @@ func TestNoDuplicateReadConfigs(t *testing.T) {
err := s.ApplyConfig(conf)
prometheus.Unregister(s.rws.highestTimestamp)
gotError := err != nil
testutil.Equals(t, tc.err, gotError)
testutil.Ok(t, s.Close())
assert.Equal(t, tc.err, gotError)
assert.NoError(t, s.Close())
})
}
}
@ -170,12 +170,8 @@ func TestExternalLabelsQuerierAddExternalLabels(t *testing.T) {
sort.Slice(test.outMatchers, func(i, j int) bool { return test.outMatchers[i].Name < test.outMatchers[j].Name })
sort.Slice(matchers, func(i, j int) bool { return matchers[i].Name < matchers[j].Name })
if !reflect.DeepEqual(matchers, test.outMatchers) {
t.Fatalf("%d. unexpected matchers; want %v, got %v", i, test.outMatchers, matchers)
}
if !reflect.DeepEqual(added, test.added) {
t.Fatalf("%d. unexpected added labels; want %v, got %v", i, test.added, added)
}
assert.Equal(t, test.outMatchers, matchers, "%d", i)
assert.Equal(t, test.added, added, "%d", i)
}
}
@ -204,9 +200,9 @@ func TestSeriesSetFilter(t *testing.T) {
for _, tc := range tests {
filtered := newSeriesSetFilter(FromQueryResult(true, tc.in), tc.toRemove)
act, ws, err := ToQueryResult(filtered, 1e6)
testutil.Ok(t, err)
testutil.Equals(t, 0, len(ws))
testutil.Equals(t, tc.expected, act)
assert.NoError(t, err)
assert.Equal(t, 0, len(ws))
assert.Equal(t, tc.expected, act)
}
}
@ -495,21 +491,21 @@ func TestSampleAndChunkQueryableClient(t *testing.T) {
tc.callback,
)
q, err := c.Querier(context.TODO(), tc.mint, tc.maxt)
testutil.Ok(t, err)
defer testutil.Ok(t, q.Close())
assert.NoError(t, err)
defer assert.NoError(t, q.Close())
ss := q.Select(true, nil, tc.matchers...)
testutil.Ok(t, err)
testutil.Equals(t, storage.Warnings(nil), ss.Warnings())
assert.NoError(t, err)
assert.Equal(t, storage.Warnings(nil), ss.Warnings())
testutil.Equals(t, tc.expectedQuery, m.got)
assert.Equal(t, tc.expectedQuery, m.got)
var got []labels.Labels
for ss.Next() {
got = append(got, ss.At().Labels())
}
testutil.Ok(t, ss.Err())
testutil.Equals(t, tc.expectedSeries, got)
assert.NoError(t, ss.Err())
assert.Equal(t, tc.expectedSeries, got)
})
}

View file

@ -22,10 +22,10 @@ import (
"time"
"github.com/go-kit/kit/log"
"gopkg.in/yaml.v2"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/model"
"gopkg.in/yaml.v2"
"github.com/prometheus/prometheus/config"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/pkg/logging"

View file

@ -20,13 +20,14 @@ import (
"testing"
common_config "github.com/prometheus/common/config"
"github.com/stretchr/testify/assert"
"github.com/prometheus/prometheus/config"
"github.com/prometheus/prometheus/util/testutil"
)
func TestStorageLifecycle(t *testing.T) {
dir, err := ioutil.TempDir("", "TestStorageLifecycle")
testutil.Ok(t, err)
assert.NoError(t, err)
defer os.RemoveAll(dir)
s := NewStorage(nil, nil, nil, dir, defaultFlushDeadline)
@ -51,21 +52,21 @@ func TestStorageLifecycle(t *testing.T) {
},
}
testutil.Ok(t, s.ApplyConfig(conf))
assert.NoError(t, s.ApplyConfig(conf))
// make sure remote write has a queue.
testutil.Equals(t, 1, len(s.rws.queues))
assert.Equal(t, 1, len(s.rws.queues))
// make sure remote write has a queue.
testutil.Equals(t, 1, len(s.queryables))
assert.Equal(t, 1, len(s.queryables))
err = s.Close()
testutil.Ok(t, err)
assert.NoError(t, err)
}
func TestUpdateRemoteReadConfigs(t *testing.T) {
dir, err := ioutil.TempDir("", "TestUpdateRemoteReadConfigs")
testutil.Ok(t, err)
assert.NoError(t, err)
defer os.RemoveAll(dir)
s := NewStorage(nil, nil, nil, dir, defaultFlushDeadline)
@ -73,15 +74,15 @@ func TestUpdateRemoteReadConfigs(t *testing.T) {
conf := &config.Config{
GlobalConfig: config.GlobalConfig{},
}
testutil.Ok(t, s.ApplyConfig(conf))
testutil.Equals(t, 0, len(s.queryables))
assert.NoError(t, s.ApplyConfig(conf))
assert.Equal(t, 0, len(s.queryables))
conf.RemoteReadConfigs = []*config.RemoteReadConfig{
&config.DefaultRemoteReadConfig,
}
testutil.Ok(t, s.ApplyConfig(conf))
testutil.Equals(t, 1, len(s.queryables))
assert.NoError(t, s.ApplyConfig(conf))
assert.Equal(t, 1, len(s.queryables))
err = s.Close()
testutil.Ok(t, err)
assert.NoError(t, err)
}

View file

@ -22,6 +22,7 @@ import (
"github.com/go-kit/kit/log"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/prometheus/config"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/storage"

View file

@ -23,10 +23,11 @@ import (
"github.com/prometheus/client_golang/prometheus"
common_config "github.com/prometheus/common/config"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/assert"
"github.com/prometheus/prometheus/config"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/pkg/relabel"
"github.com/prometheus/prometheus/util/testutil"
)
var cfg = config.RemoteWriteConfig{
@ -42,9 +43,9 @@ var cfg = config.RemoteWriteConfig{
func TestNoDuplicateWriteConfigs(t *testing.T) {
dir, err := ioutil.TempDir("", "TestNoDuplicateWriteConfigs")
testutil.Ok(t, err)
assert.NoError(t, err)
defer func() {
testutil.Ok(t, os.RemoveAll(dir))
assert.NoError(t, os.RemoveAll(dir))
}()
cfg1 := config.RemoteWriteConfig{
@ -121,22 +122,22 @@ func TestNoDuplicateWriteConfigs(t *testing.T) {
}
err := s.ApplyConfig(conf)
gotError := err != nil
testutil.Equals(t, tc.err, gotError)
assert.Equal(t, tc.err, gotError)
err = s.Close()
testutil.Ok(t, err)
assert.NoError(t, err)
}
}
func TestRestartOnNameChange(t *testing.T) {
dir, err := ioutil.TempDir("", "TestRestartOnNameChange")
testutil.Ok(t, err)
assert.NoError(t, err)
defer func() {
testutil.Ok(t, os.RemoveAll(dir))
assert.NoError(t, os.RemoveAll(dir))
}()
hash, err := toHash(cfg)
testutil.Ok(t, err)
assert.NoError(t, err)
s := NewWriteStorage(nil, nil, dir, time.Millisecond)
conf := &config.Config{
@ -145,25 +146,25 @@ func TestRestartOnNameChange(t *testing.T) {
&cfg,
},
}
testutil.Ok(t, s.ApplyConfig(conf))
testutil.Equals(t, s.queues[hash].client().Name(), cfg.Name)
assert.NoError(t, s.ApplyConfig(conf))
assert.Equal(t, s.queues[hash].client().Name(), cfg.Name)
// Change the queues name, ensure the queue has been restarted.
conf.RemoteWriteConfigs[0].Name = "dev-2"
testutil.Ok(t, s.ApplyConfig(conf))
assert.NoError(t, s.ApplyConfig(conf))
hash, err = toHash(cfg)
testutil.Ok(t, err)
testutil.Equals(t, s.queues[hash].client().Name(), conf.RemoteWriteConfigs[0].Name)
assert.NoError(t, err)
assert.Equal(t, s.queues[hash].client().Name(), conf.RemoteWriteConfigs[0].Name)
err = s.Close()
testutil.Ok(t, err)
assert.NoError(t, err)
}
func TestUpdateWithRegisterer(t *testing.T) {
dir, err := ioutil.TempDir("", "TestRestartWithRegisterer")
testutil.Ok(t, err)
assert.NoError(t, err)
defer func() {
testutil.Ok(t, os.RemoveAll(dir))
assert.NoError(t, os.RemoveAll(dir))
}()
s := NewWriteStorage(nil, prometheus.NewRegistry(), dir, time.Millisecond)
@ -190,24 +191,24 @@ func TestUpdateWithRegisterer(t *testing.T) {
GlobalConfig: config.DefaultGlobalConfig,
RemoteWriteConfigs: []*config.RemoteWriteConfig{c1, c2},
}
testutil.Ok(t, s.ApplyConfig(conf))
assert.NoError(t, s.ApplyConfig(conf))
c1.QueueConfig.MaxShards = 10
c2.QueueConfig.MaxShards = 10
testutil.Ok(t, s.ApplyConfig(conf))
assert.NoError(t, s.ApplyConfig(conf))
for _, queue := range s.queues {
testutil.Equals(t, 10, queue.cfg.MaxShards)
assert.Equal(t, 10, queue.cfg.MaxShards)
}
err = s.Close()
testutil.Ok(t, err)
assert.NoError(t, err)
}
func TestWriteStorageLifecycle(t *testing.T) {
dir, err := ioutil.TempDir("", "TestWriteStorageLifecycle")
testutil.Ok(t, err)
assert.NoError(t, err)
defer func() {
testutil.Ok(t, os.RemoveAll(dir))
assert.NoError(t, os.RemoveAll(dir))
}()
s := NewWriteStorage(nil, nil, dir, defaultFlushDeadline)
@ -218,17 +219,17 @@ func TestWriteStorageLifecycle(t *testing.T) {
},
}
s.ApplyConfig(conf)
testutil.Equals(t, 1, len(s.queues))
assert.Equal(t, 1, len(s.queues))
err = s.Close()
testutil.Ok(t, err)
assert.NoError(t, err)
}
func TestUpdateExternalLabels(t *testing.T) {
dir, err := ioutil.TempDir("", "TestUpdateExternalLabels")
testutil.Ok(t, err)
assert.NoError(t, err)
defer func() {
testutil.Ok(t, os.RemoveAll(dir))
assert.NoError(t, os.RemoveAll(dir))
}()
s := NewWriteStorage(nil, prometheus.NewRegistry(), dir, time.Second)
@ -241,27 +242,27 @@ func TestUpdateExternalLabels(t *testing.T) {
},
}
hash, err := toHash(conf.RemoteWriteConfigs[0])
testutil.Ok(t, err)
assert.NoError(t, err)
s.ApplyConfig(conf)
testutil.Equals(t, 1, len(s.queues))
testutil.Equals(t, labels.Labels(nil), s.queues[hash].externalLabels)
assert.Equal(t, 1, len(s.queues))
assert.Equal(t, labels.Labels(nil), s.queues[hash].externalLabels)
conf.GlobalConfig.ExternalLabels = externalLabels
hash, err = toHash(conf.RemoteWriteConfigs[0])
testutil.Ok(t, err)
assert.NoError(t, err)
s.ApplyConfig(conf)
testutil.Equals(t, 1, len(s.queues))
testutil.Equals(t, externalLabels, s.queues[hash].externalLabels)
assert.Equal(t, 1, len(s.queues))
assert.Equal(t, externalLabels, s.queues[hash].externalLabels)
err = s.Close()
testutil.Ok(t, err)
assert.NoError(t, err)
}
func TestWriteStorageApplyConfigsIdempotent(t *testing.T) {
dir, err := ioutil.TempDir("", "TestWriteStorageApplyConfigsIdempotent")
testutil.Ok(t, err)
assert.NoError(t, err)
defer func() {
testutil.Ok(t, os.RemoveAll(dir))
assert.NoError(t, os.RemoveAll(dir))
}()
s := NewWriteStorage(nil, nil, dir, defaultFlushDeadline)
@ -279,25 +280,25 @@ func TestWriteStorageApplyConfigsIdempotent(t *testing.T) {
},
}
hash, err := toHash(conf.RemoteWriteConfigs[0])
testutil.Ok(t, err)
assert.NoError(t, err)
s.ApplyConfig(conf)
testutil.Equals(t, 1, len(s.queues))
assert.Equal(t, 1, len(s.queues))
s.ApplyConfig(conf)
testutil.Equals(t, 1, len(s.queues))
assert.Equal(t, 1, len(s.queues))
_, hashExists := s.queues[hash]
testutil.Assert(t, hashExists, "Queue pointer should have remained the same")
assert.True(t, hashExists, "Queue pointer should have remained the same")
err = s.Close()
testutil.Ok(t, err)
assert.NoError(t, err)
}
func TestWriteStorageApplyConfigsPartialUpdate(t *testing.T) {
dir, err := ioutil.TempDir("", "TestWriteStorageApplyConfigsPartialUpdate")
testutil.Ok(t, err)
assert.NoError(t, err)
defer func() {
testutil.Ok(t, os.RemoveAll(dir))
assert.NoError(t, os.RemoveAll(dir))
}()
s := NewWriteStorage(nil, nil, dir, defaultFlushDeadline)
@ -335,15 +336,15 @@ func TestWriteStorageApplyConfigsPartialUpdate(t *testing.T) {
},
}
}
testutil.Ok(t, s.ApplyConfig(conf))
testutil.Equals(t, 3, len(s.queues))
assert.NoError(t, s.ApplyConfig(conf))
assert.Equal(t, 3, len(s.queues))
hashes := make([]string, len(conf.RemoteWriteConfigs))
queues := make([]*QueueManager, len(conf.RemoteWriteConfigs))
storeHashes := func() {
for i := range conf.RemoteWriteConfigs {
hash, err := toHash(conf.RemoteWriteConfigs[i])
testutil.Ok(t, err)
assert.NoError(t, err)
hashes[i] = hash
queues[i] = s.queues[hash]
}
@ -357,32 +358,32 @@ func TestWriteStorageApplyConfigsPartialUpdate(t *testing.T) {
GlobalConfig: config.GlobalConfig{},
RemoteWriteConfigs: []*config.RemoteWriteConfig{c0, c1, c2},
}
testutil.Ok(t, s.ApplyConfig(conf))
testutil.Equals(t, 3, len(s.queues))
assert.NoError(t, s.ApplyConfig(conf))
assert.Equal(t, 3, len(s.queues))
_, hashExists := s.queues[hashes[0]]
testutil.Assert(t, !hashExists, "The queue for the first remote write configuration should have been restarted because the relabel configuration has changed.")
assert.True(t, !hashExists, "The queue for the first remote write configuration should have been restarted because the relabel configuration has changed.")
q, hashExists := s.queues[hashes[1]]
testutil.Assert(t, hashExists, "Hash of unchanged queue should have remained the same")
testutil.Assert(t, q == queues[1], "Pointer of unchanged queue should have remained the same")
assert.True(t, hashExists, "Hash of unchanged queue should have remained the same")
assert.True(t, q == queues[1], "Pointer of unchanged queue should have remained the same")
_, hashExists = s.queues[hashes[2]]
testutil.Assert(t, !hashExists, "The queue for the third remote write configuration should have been restarted because the timeout has changed.")
assert.True(t, !hashExists, "The queue for the third remote write configuration should have been restarted because the timeout has changed.")
storeHashes()
secondClient := s.queues[hashes[1]].client()
// Update c1.
c1.HTTPClientConfig.BearerToken = "bar"
err = s.ApplyConfig(conf)
testutil.Ok(t, err)
testutil.Equals(t, 3, len(s.queues))
assert.NoError(t, err)
assert.Equal(t, 3, len(s.queues))
_, hashExists = s.queues[hashes[0]]
testutil.Assert(t, hashExists, "Pointer of unchanged queue should have remained the same")
assert.True(t, hashExists, "Pointer of unchanged queue should have remained the same")
q, hashExists = s.queues[hashes[1]]
testutil.Assert(t, hashExists, "Hash of queue with secret change should have remained the same")
testutil.Assert(t, secondClient != q.client(), "Pointer of a client with a secret change should not be the same")
assert.True(t, hashExists, "Hash of queue with secret change should have remained the same")
assert.True(t, secondClient != q.client(), "Pointer of a client with a secret change should not be the same")
_, hashExists = s.queues[hashes[2]]
testutil.Assert(t, hashExists, "Pointer of unchanged queue should have remained the same")
assert.True(t, hashExists, "Pointer of unchanged queue should have remained the same")
storeHashes()
// Delete c0.
@ -391,15 +392,15 @@ func TestWriteStorageApplyConfigsPartialUpdate(t *testing.T) {
RemoteWriteConfigs: []*config.RemoteWriteConfig{c1, c2},
}
s.ApplyConfig(conf)
testutil.Equals(t, 2, len(s.queues))
assert.Equal(t, 2, len(s.queues))
_, hashExists = s.queues[hashes[0]]
testutil.Assert(t, !hashExists, "If a config is removed, the queue should be stopped and recreated.")
assert.True(t, !hashExists, "If a config is removed, the queue should be stopped and recreated.")
_, hashExists = s.queues[hashes[1]]
testutil.Assert(t, hashExists, "Pointer of unchanged queue should have remained the same")
assert.True(t, hashExists, "Pointer of unchanged queue should have remained the same")
_, hashExists = s.queues[hashes[2]]
testutil.Assert(t, hashExists, "Pointer of unchanged queue should have remained the same")
assert.True(t, hashExists, "Pointer of unchanged queue should have remained the same")
err = s.Close()
testutil.Ok(t, err)
assert.NoError(t, err)
}

View file

@ -17,20 +17,19 @@ import (
"bytes"
"context"
"fmt"
html_template "html/template"
"math"
"net/url"
"regexp"
"sort"
"strings"
text_template "text/template"
"time"
html_template "html/template"
text_template "text/template"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/promql"
"github.com/prometheus/prometheus/util/strutil"
)

View file

@ -20,9 +20,10 @@ import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/promql"
"github.com/prometheus/prometheus/util/testutil"
)
func TestTemplateExpansion(t *testing.T) {
@ -283,14 +284,14 @@ func TestTemplateExpansion(t *testing.T) {
result, err = expander.Expand()
}
if s.shouldFail {
testutil.NotOk(t, err, "%v", s.text)
assert.Error(t, err, "%v", s.text)
continue
}
testutil.Ok(t, err)
assert.NoError(t, err)
if err == nil {
testutil.Equals(t, result, s.output)
assert.Equal(t, result, s.output)
}
}
}

View file

@ -26,6 +26,7 @@ import (
"github.com/go-kit/kit/log/level"
"github.com/oklog/ulid"
"github.com/pkg/errors"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/tsdb/chunkenc"
"github.com/prometheus/prometheus/tsdb/chunks"

Some files were not shown because too many files have changed in this diff Show more