|
| 1 | +// Copyright The OpenTelemetry Authors |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +package prometheusreceiver |
| 5 | + |
| 6 | +import ( |
| 7 | + "fmt" |
| 8 | + "os" |
| 9 | + "testing" |
| 10 | + |
| 11 | + "github.com/prometheus/prometheus/config" |
| 12 | + "github.com/stretchr/testify/assert" |
| 13 | + "github.com/stretchr/testify/require" |
| 14 | + "go.opentelemetry.io/collector/pdata/pmetric" |
| 15 | + semconv "go.opentelemetry.io/collector/semconv/v1.27.0" |
| 16 | + "gopkg.in/yaml.v2" |
| 17 | +) |
| 18 | + |
| 19 | +var scrapeFileTargetPage = ` |
| 20 | +# A simple counter |
| 21 | +# TYPE foo counter |
| 22 | +foo1 1 |
| 23 | +` |
| 24 | + |
| 25 | +// TestScrapeConfigFiles validates that scrape configs provided via scrape_config_files are |
| 26 | +// also considered and added to the applied configuration |
| 27 | + |
| 28 | +func TestScrapeConfigFiles(t *testing.T) { |
| 29 | + setMetricsTimestamp() |
| 30 | + targets := []*testData{ |
| 31 | + { |
| 32 | + name: "target1", |
| 33 | + pages: []mockPrometheusResponse{ |
| 34 | + {code: 200, data: scrapeFileTargetPage}, |
| 35 | + }, |
| 36 | + validateFunc: verifyScrapeConfigFiles, |
| 37 | + }, |
| 38 | + } |
| 39 | + |
| 40 | + testComponent(t, targets, func(cfg *Config) { |
| 41 | + // take the generated scrape config and move it into a file instead |
| 42 | + marshalledScrapeConfigs, err := yaml.Marshal(cfg.PrometheusConfig.ScrapeConfigs) |
| 43 | + require.NoError(t, err) |
| 44 | + tmpDir := t.TempDir() |
| 45 | + cfgFileName := fmt.Sprintf("%s/test-scrape-config.yaml", tmpDir) |
| 46 | + scrapeConfigFileContent := fmt.Sprintf("scrape_configs:\n%s", string(marshalledScrapeConfigs)) |
| 47 | + err = os.WriteFile(cfgFileName, []byte(scrapeConfigFileContent), 0400) |
| 48 | + require.NoError(t, err) |
| 49 | + cfg.PrometheusConfig.ScrapeConfigs = []*config.ScrapeConfig{} |
| 50 | + cfg.PrometheusConfig.ScrapeConfigFiles = []string{cfgFileName} |
| 51 | + }) |
| 52 | +} |
| 53 | + |
| 54 | +func verifyScrapeConfigFiles(t *testing.T, _ *testData, result []pmetric.ResourceMetrics) { |
| 55 | + require.Len(t, result, 1) |
| 56 | + serviceName, ok := result[0].Resource().Attributes().Get(semconv.AttributeServiceName) |
| 57 | + assert.True(t, ok) |
| 58 | + assert.Equal(t, "target1", serviceName.Str()) |
| 59 | + assert.Equal(t, 6, result[0].ScopeMetrics().At(0).Metrics().Len()) |
| 60 | + metricFound := false |
| 61 | + |
| 62 | + for i := 0; i < result[0].ScopeMetrics().At(0).Metrics().Len(); i++ { |
| 63 | + if result[0].ScopeMetrics().At(0).Metrics().At(i).Name() == "foo1" { |
| 64 | + metricFound = true |
| 65 | + break |
| 66 | + } |
| 67 | + } |
| 68 | + assert.True(t, metricFound) |
| 69 | +} |
0 commit comments