Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/grafana-agent
Path: blob/main/pkg/integrations/v2/metricsutils/metricshandler_integration_test.go
5340 views
1
package metricsutils
2
3
import (
4
"fmt"
5
"net/http"
6
"net/url"
7
"testing"
8
9
"github.com/go-kit/log"
10
"github.com/grafana/agent/pkg/integrations/v2"
11
"github.com/grafana/agent/pkg/integrations/v2/common"
12
"github.com/prometheus/common/model"
13
"github.com/prometheus/prometheus/discovery/targetgroup"
14
"github.com/prometheus/prometheus/model/labels"
15
"github.com/stretchr/testify/require"
16
)
17
18
func TestMetricsHandlerIntegration_Targets(t *testing.T) {
19
globals := integrations.Globals{
20
AgentIdentifier: "testagent",
21
AgentBaseURL: func() *url.URL {
22
u, err := url.Parse("http://testagent/")
23
require.NoError(t, err)
24
return u
25
}(),
26
SubsystemOpts: integrations.DefaultSubsystemOptions,
27
}
28
29
t.Run("Targets", func(t *testing.T) {
30
var cfg common.MetricsConfig
31
cfg.ApplyDefaults(globals.SubsystemOpts.Metrics.Autoscrape)
32
33
i, err := NewMetricsHandlerIntegration(nil, fakeConfig{}, cfg, globals, http.NotFoundHandler())
34
require.NoError(t, err)
35
36
actual := i.Targets(integrations.Endpoint{Host: "test", Prefix: "/test/"})
37
expect := []*targetgroup.Group{{
38
Source: "fake/testagent",
39
Labels: model.LabelSet{
40
"instance": "testagent",
41
"job": "integrations/fake",
42
"agent_hostname": "testagent",
43
44
"__meta_agent_integration_name": "fake",
45
"__meta_agent_integration_instance": "testagent",
46
"__meta_agent_integration_autoscrape": "1",
47
},
48
Targets: []model.LabelSet{{
49
"__address__": "test",
50
"__metrics_path__": "/test/metrics",
51
}},
52
}}
53
require.Equal(t, expect, actual)
54
55
t.Run("Extra labels", func(t *testing.T) {
56
cfg := common.MetricsConfig{
57
ExtraLabels: labels.FromMap(map[string]string{"foo": "bar", "fizz": "buzz"}),
58
}
59
cfg.ApplyDefaults(globals.SubsystemOpts.Metrics.Autoscrape)
60
61
i, err := NewMetricsHandlerIntegration(nil, fakeConfig{}, cfg, globals, http.NotFoundHandler())
62
require.NoError(t, err)
63
actual := i.Targets(integrations.Endpoint{Host: "test", Prefix: "/test/"})
64
require.Len(t, actual, 1)
65
66
for _, lbl := range cfg.ExtraLabels {
67
val, ok := actual[0].Labels[model.LabelName(lbl.Name)]
68
require.True(t, ok, "target does not have extra label %s", lbl.Name)
69
require.Equal(t, lbl.Value, string(val), "extra label %s does not match expectation", lbl.Name)
70
}
71
})
72
})
73
}
74
75
type fakeConfig struct{}
76
77
func (fakeConfig) Name() string { return "fake" }
78
func (fakeConfig) ApplyDefaults(_ integrations.Globals) error { return nil }
79
func (fakeConfig) Identifier(g integrations.Globals) (string, error) { return g.AgentIdentifier, nil }
80
func (fakeConfig) NewIntegration(_ log.Logger, _ integrations.Globals) (integrations.Integration, error) {
81
return nil, fmt.Errorf("not implemented")
82
}
83
84