grafana/pkg/util/converter/prom_test.go

106 lines
2.6 KiB
Go

package converter
import (
"io/ioutil"
"os"
"path"
"strings"
"testing"
"time"
"github.com/grafana/grafana-plugin-sdk-go/experimental"
jsoniter "github.com/json-iterator/go"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestReadPromFrames(t *testing.T) {
files := []string{
"prom-labels",
"prom-matrix",
"prom-matrix-with-nans",
"prom-matrix-histogram-no-labels",
"prom-matrix-histogram-partitioned",
"prom-vector-histogram-no-labels",
"prom-vector",
"prom-string",
"prom-scalar",
"prom-series",
"prom-warnings",
"prom-error",
"prom-exemplars",
"loki-streams-a",
"loki-streams-b",
}
for _, name := range files {
t.Run(name, runScenario(name, Options{}))
t.Run(name, runScenario(name, Options{MatrixWideSeries: true, VectorWideSeries: true}))
}
}
func runScenario(name string, opts Options) func(t *testing.T) {
return func(t *testing.T) {
// nolint:gosec
// We can ignore the gosec G304 because this is a test with static defined paths
f, err := os.Open(path.Join("testdata", name+".json"))
require.NoError(t, err)
if opts.MatrixWideSeries || opts.VectorWideSeries {
name = name + "-wide"
}
iter := jsoniter.Parse(jsoniter.ConfigDefault, f, 1024)
rsp := ReadPrometheusStyleResult(iter, opts)
out, err := jsoniter.MarshalIndent(rsp, "", " ")
require.NoError(t, err)
save := true
fpath := path.Join("testdata", name+"-frame.json")
// nolint:gosec
// We can ignore the gosec G304 because this is a test with static defined paths
current, err := ioutil.ReadFile(fpath)
if err == nil {
same := assert.JSONEq(t, string(out), string(current))
if !same {
save = true
}
} else {
assert.Fail(t, "missing file: "+fpath)
save = true
}
if save {
err = os.WriteFile(fpath, out, 0600)
require.NoError(t, err)
}
// skip checking golden file for error response. it's not currently supported
if strings.Contains(name, "prom-error") {
return
}
fpath = path.Join("testdata", name+"-golden.txt")
err = experimental.CheckGoldenDataResponse(fpath, rsp, true)
assert.NoError(t, err)
}
}
func TestTimeConversions(t *testing.T) {
// include millisecond precision
assert.Equal(t,
time.Date(2020, time.September, 14, 15, 22, 25, 479000000, time.UTC),
timeFromFloat(1600096945.479))
// Loki date parsing
assert.Equal(t,
time.Date(2022, time.February, 16, 16, 50, 46, 277587968, time.UTC),
timeFromLokiString("1645030246277587968"))
assert.Equal(t,
time.Date(2033, time.May, 18, 3, 33, 20, 0, time.UTC),
timeFromLokiString("2000000000000000000"))
}