diff --git a/cmd/mdatagen/validate_test.go b/cmd/mdatagen/validate_test.go index 888e910ccaf4..12871a4ab8c5 100644 --- a/cmd/mdatagen/validate_test.go +++ b/cmd/mdatagen/validate_test.go @@ -4,8 +4,12 @@ package main import ( + "fmt" + "io/fs" + "path/filepath" "testing" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -101,3 +105,49 @@ func TestValidate(t *testing.T) { }) } } + +func TestValidateMetricDuplicates(t *testing.T) { + allowedMetrics := map[string][]string{ + "container.cpu.utilization": {"docker_stats", "kubeletstats"}, + "container.memory.rss": {"docker_stats", "kubeletstats"}, + "container.uptime": {"docker_stats", "kubeletstats"}, + } + allMetrics := map[string][]string{} + err := filepath.Walk("../../receiver", func(path string, info fs.FileInfo, err error) error { + if info.Name() == "metadata.yaml" { + md, err := loadMetadata(path) + require.NoError(t, err) + if len(md.Metrics) > 0 { + for metricName := range md.Metrics { + allMetrics[md.Type] = append(allMetrics[md.Type], string(metricName)) + } + } + } + return nil + }) + require.NoError(t, err) + + seen := make(map[string]string) + for receiver, metrics := range allMetrics { + for _, metricName := range metrics { + if val, exists := seen[metricName]; exists { + receivers, allowed := allowedMetrics[metricName] + assert.True( + t, + allowed && contains(receiver, receivers) && contains(val, receivers), + fmt.Sprintf("Duplicate metric %v in receivers %v and %v. Please validate that this is intentional by adding the metric name and receiver types in the allowedMetrics map in this test\n", metricName, receiver, val), + ) + } + seen[metricName] = receiver + } + } +} + +func contains(r string, rs []string) bool { + for _, s := range rs { + if s == r { + return true + } + } + return false +}