Files
unitech-golib/metrics/prometheus/prometheus_test.go

62 lines
1.5 KiB
Go
Raw Normal View History

2020-04-06 19:57:19 +08:00
package prometheus
import (
"fmt"
stdprometheus "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"globalfintech/golib/metrics"
"io/ioutil"
"math/rand"
"net/http"
"net/http/httptest"
"regexp"
"strconv"
"testing"
)
func TestCounter(t *testing.T) {
s := httptest.NewServer(promhttp.Handler())
defer s.Close()
scrape := func() string {
resp, _ := http.Get(s.URL)
buf, _ := ioutil.ReadAll(resp.Body)
return string(buf)
}
namespace, subsystem, name := "ns", "ss", "foo"
re := regexp.MustCompile(namespace + `_` + subsystem + `_` + name + `{alpha="alpha-value",beta="beta-value"} ([0-9\.]+)`)
counter := NewCounterFrom(stdprometheus.CounterOpts{
Namespace: namespace,
Subsystem: subsystem,
Name: name,
Help: "This is the help string.",
}, []string{"alpha", "beta"}).With("beta", "beta-value", "alpha", "alpha-value") // order shouldn't matter
value := func() float64 {
matches := re.FindStringSubmatch(scrape())
f, _ := strconv.ParseFloat(matches[1], 64)
return f
}
want := FillCounter(counter)
if have := value(); want != have {
t.Fatal(fmt.Errorf("want %f, have %f", want, have))
}
}
// FillCounter puts some deltas through the counter and returns the total value.
func FillCounter(counter metrics.Counter) float64 {
a := rand.Perm(100)
n := rand.Intn(len(a))
var want float64
for i := 0; i < n; i++ {
f := float64(a[i])
counter.Add(f)
want += f
}
return want
}