From c3e6a70ab8537e8d1330361c847ce914d228f64b Mon Sep 17 00:00:00 2001 From: Antoine Toulme Date: Wed, 15 Jan 2025 11:30:43 -0800 Subject: [PATCH] remove resource_metrics --- .../collector_process_integration_test.go | 22 +- tests/testutils/otlp_receiver_sink.go | 55 -- tests/testutils/otlp_receiver_sink_test.go | 48 -- tests/testutils/telemetry/common.go | 201 ------- tests/testutils/telemetry/common_test.go | 139 ----- tests/testutils/telemetry/helpers_test.go | 28 - tests/testutils/telemetry/metrics.go | 480 ----------------- tests/testutils/telemetry/metrics_test.go | 500 ------------------ tests/testutils/telemetry/pdata_common.go | 36 -- .../testutils/telemetry/pdata_common_test.go | 41 -- tests/testutils/telemetry/pdata_metrics.go | 453 ---------------- .../testutils/telemetry/pdata_metrics_test.go | 304 ----------- .../telemetry/testdata/common/attributes.yaml | 8 - .../attribute-value-resource-metrics.yaml | 9 - .../metrics/empty-attributes-required.yaml | 7 - .../testdata/metrics/expected-metrics.yaml | 17 - .../testdata/metrics/invalid-metric-type.yaml | 5 - .../metrics/invalid-resource-metrics.yaml | 3 - .../never-received-instrumentation-scope.yaml | 12 - .../metrics/never-received-metrics.yaml | 11 - .../metrics/never-received-resource.yaml | 12 - .../testdata/metrics/resource-metrics.yaml | 37 -- .../unspecified-attributes-allowed.yaml | 6 - tests/testutils/testcase.go | 35 +- .../testdata/collector_process_config.yaml | 17 - .../testdata/expected_host_metrics.yaml | 10 - 26 files changed, 7 insertions(+), 2489 deletions(-) delete mode 100644 tests/testutils/telemetry/common.go delete mode 100644 tests/testutils/telemetry/common_test.go delete mode 100644 tests/testutils/telemetry/helpers_test.go delete mode 100644 tests/testutils/telemetry/metrics.go delete mode 100644 tests/testutils/telemetry/metrics_test.go delete mode 100644 tests/testutils/telemetry/pdata_common.go delete mode 100644 tests/testutils/telemetry/pdata_common_test.go delete mode 100644 tests/testutils/telemetry/pdata_metrics.go delete mode 100644 tests/testutils/telemetry/pdata_metrics_test.go delete mode 100644 tests/testutils/telemetry/testdata/common/attributes.yaml delete mode 100644 tests/testutils/telemetry/testdata/metrics/attribute-value-resource-metrics.yaml delete mode 100644 tests/testutils/telemetry/testdata/metrics/empty-attributes-required.yaml delete mode 100644 tests/testutils/telemetry/testdata/metrics/expected-metrics.yaml delete mode 100644 tests/testutils/telemetry/testdata/metrics/invalid-metric-type.yaml delete mode 100644 tests/testutils/telemetry/testdata/metrics/invalid-resource-metrics.yaml delete mode 100644 tests/testutils/telemetry/testdata/metrics/never-received-instrumentation-scope.yaml delete mode 100644 tests/testutils/telemetry/testdata/metrics/never-received-metrics.yaml delete mode 100644 tests/testutils/telemetry/testdata/metrics/never-received-resource.yaml delete mode 100644 tests/testutils/telemetry/testdata/metrics/resource-metrics.yaml delete mode 100644 tests/testutils/telemetry/testdata/metrics/unspecified-attributes-allowed.yaml delete mode 100644 tests/testutils/testdata/collector_process_config.yaml delete mode 100644 tests/testutils/testdata/expected_host_metrics.yaml diff --git a/tests/testutils/collector_process_integration_test.go b/tests/testutils/collector_process_integration_test.go index 48dc188fc2..767d0033b6 100644 --- a/tests/testutils/collector_process_integration_test.go +++ b/tests/testutils/collector_process_integration_test.go @@ -16,15 +16,10 @@ package testutils import ( - "path/filepath" - "strings" - "testing" - "time" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - "github.com/signalfx/splunk-otel-collector/tests/testutils/telemetry" + "strings" + "testing" ) func TestCollectorPath(t *testing.T) { @@ -41,16 +36,3 @@ func TestConfigPathNotRequiredUponBuildWithArgs(t *testing.T) { require.NoError(t, err) require.NotNil(t, collector) } - -func TestCollectorProcessConfigSourced(t *testing.T) { - tc := NewTestcase(t) - defer tc.PrintLogsOnFailure() - defer tc.ShutdownOTLPReceiverSink() - - _, shutdown := tc.SplunkOtelCollectorProcess("collector_process_config.yaml") - defer shutdown() - - expectedMetrics, err := telemetry.LoadResourceMetrics(filepath.Join(".", "testdata", "expected_host_metrics.yaml")) - require.NoError(t, err) - require.NoError(t, tc.OTLPReceiverSink.AssertAllMetricsReceived(t, *expectedMetrics, 10*time.Second)) -} diff --git a/tests/testutils/otlp_receiver_sink.go b/tests/testutils/otlp_receiver_sink.go index e2d9d1fedd..0d46c8f214 100644 --- a/tests/testutils/otlp_receiver_sink.go +++ b/tests/testutils/otlp_receiver_sink.go @@ -17,11 +17,6 @@ package testutils import ( "context" "fmt" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/component/componenttest" "go.opentelemetry.io/collector/config/confignet" @@ -34,8 +29,6 @@ import ( mnoop "go.opentelemetry.io/otel/metric/noop" tnoop "go.opentelemetry.io/otel/trace/noop" "go.uber.org/zap" - - "github.com/signalfx/splunk-otel-collector/tests/testutils/telemetry" ) // To be used as a builder whose Build() method provides the actual instance capable of starting the OTLP receiver @@ -174,51 +167,3 @@ func (otlp *OTLPReceiverSink) SpanCount() int { } return otlp.tracesSink.SpanCount() } - -func (otlp *OTLPReceiverSink) Reset() { - if err := otlp.assertBuilt("Reset"); err == nil { - otlp.metricsSink.Reset() - otlp.logsSink.Reset() - otlp.tracesSink.Reset() - } -} - -func (otlp *OTLPReceiverSink) AssertAllMetricsReceived(t testing.TB, expectedResourceMetrics telemetry.ResourceMetrics, waitTime time.Duration) error { - if err := otlp.assertBuilt("AssertAllMetricsReceived"); err != nil { - return err - } - - if len(expectedResourceMetrics.ResourceMetrics) == 0 { - return fmt.Errorf("empty ResourceMetrics provided") - } - - receivedMetrics := telemetry.ResourceMetrics{} - - var err error - assert.Eventually(t, func() bool { - if otlp.DataPointCount() == 0 { - if err == nil { - err = fmt.Errorf("no metrics received") - } - return false - } - receivedOTLPMetrics := otlp.AllMetrics() - otlp.Reset() - - receivedResourceMetrics, e := telemetry.PDataToResourceMetrics(receivedOTLPMetrics...) - require.NoError(t, e) - require.NotNil(t, receivedResourceMetrics) - receivedMetrics = telemetry.FlattenResourceMetrics(receivedMetrics, receivedResourceMetrics) - - var containsOnly bool - containsOnly, err = receivedMetrics.ContainsOnly(expectedResourceMetrics) - return containsOnly - }, waitTime, 10*time.Millisecond, "Failed to receive expected metrics") - - // testify won't render exceptionally long errors, so leaving this here for easy debugging - if err != nil { - fmt.Printf("err: %v\n", err) - } - - return err -} diff --git a/tests/testutils/otlp_receiver_sink_test.go b/tests/testutils/otlp_receiver_sink_test.go index d3a448481a..9168e42cb4 100644 --- a/tests/testutils/otlp_receiver_sink_test.go +++ b/tests/testutils/otlp_receiver_sink_test.go @@ -78,31 +78,6 @@ func TestBuildDefaults(t *testing.T) { assert.NotNil(t, otlp.tracesSink) } -func TestReceiverMethodsWithoutBuildingDisallowed(t *testing.T) { - otlp := NewOTLPReceiverSink() - - err := otlp.Start() - require.Error(t, err) - require.EqualError(t, err, "cannot invoke Start() on an OTLPReceiverSink that hasn't been built") - - err = otlp.Shutdown() - require.Error(t, err) - require.EqualError(t, err, "cannot invoke Shutdown() on an OTLPReceiverSink that hasn't been built") - - metrics := otlp.AllMetrics() - require.Nil(t, metrics) - - dataPointCount := otlp.DataPointCount() - require.Zero(t, dataPointCount) - - // doesn't panic - otlp.Reset() - - err = otlp.AssertAllMetricsReceived(t, telemetry.ResourceMetrics{}, 0) - require.Error(t, err) - require.EqualError(t, err, "cannot invoke AssertAllMetricsReceived() on an OTLPReceiverSink that hasn't been built") -} - func createOTLPFactoryParameters() (otlpexporter.Config, otelcolexporter.Settings) { exporterCfg := otlpexporter.Config{ ClientConfig: configgrpc.ClientConfig{ @@ -159,26 +134,3 @@ func TestOTLPReceiverMetricsAvailableToSink(t *testing.T) { return otlp.DataPointCount() == expectedCount }, 5*time.Second, 1*time.Millisecond) } - -func TestAssertAllMetricsReceivedHappyPath(t *testing.T) { - otlp, err := NewOTLPReceiverSink().WithEndpoint("localhost:4317").Build() - require.NoError(t, err) - - err = otlp.Start() - defer func() { - require.NoError(t, otlp.Shutdown()) - }() - require.NoError(t, err) - - exporter := otlpMetricsExporter(t) - defer func() { require.NoError(t, exporter.Shutdown(context.Background())) }() - - metrics := telemetry.PDataMetrics() - err = exporter.ConsumeMetrics(context.Background(), metrics) - require.NoError(t, err) - - resourceMetrics, err := telemetry.PDataToResourceMetrics(metrics) - resourceMetrics = telemetry.FlattenResourceMetrics(resourceMetrics) - require.NoError(t, err) - require.NoError(t, otlp.AssertAllMetricsReceived(t, resourceMetrics, 100*time.Millisecond)) -} diff --git a/tests/testutils/telemetry/common.go b/tests/testutils/telemetry/common.go deleted file mode 100644 index 2c8b799c26..0000000000 --- a/tests/testutils/telemetry/common.go +++ /dev/null @@ -1,201 +0,0 @@ -// Copyright Splunk, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package telemetry - -import ( - "bytes" - "crypto/md5" // #nosec this is not for cryptographic purposes - "fmt" - "reflect" - "regexp" - - "gopkg.in/yaml.v3" - - "github.com/signalfx/splunk-otel-collector/tests/internal/version" -) - -const ( - anyValue = "" - buildVersionPlaceholder = "" - regexValue = "^.*)\\)>$" -) - -var reValueRegexp = regexp.MustCompile(regexValue) - -type Resource struct { - Attributes *map[string]any `yaml:"attributes,omitempty"` -} - -func (resource Resource) String() string { - return marshal(resource) -} - -// Hash provides an md5 hash determined by Resource content. -func (resource Resource) Hash() string { - return fmt.Sprintf("%x", md5.Sum([]byte(resource.String()))) // #nosec -} - -// Equals determines the equivalence of two Resource items by their Attributes. -func (resource Resource) Equals(toCompare Resource) bool { - return attributesAreEqual(resource.Attributes, toCompare.Attributes) -} - -func (resource Resource) FillDefaultValues() { - populateDirectives(resource.Attributes) -} - -func populateDirectives(attrs *map[string]any) { - if attrs == nil { - return - } - attributes := *attrs - for k, v := range attributes { - if subMap, ok := v.(map[string]any); ok { - populateDirectives(&subMap) - continue - } - - if v == buildVersionPlaceholder { - attributes[k] = version.Version - continue - } - - if subs := reValueRegexp.FindStringSubmatch(toString(v)); len(subs) == 2 { - pattern := subs[1] - rec, err := regexp.Compile(pattern) - if err != nil { - panic(fmt.Errorf("failed compiling resource attributes RE2 (%s): %w", k, err)) - } - attributes[k] = rec - } - } -} - -type InstrumentationScope struct { - Attributes *map[string]any `yaml:"attributes,omitempty"` - Name string `yaml:"name,omitempty"` - Version string `yaml:"version,omitempty"` -} - -func (is InstrumentationScope) String() string { - return marshal(is) -} - -// Hash provides an md5 hash determined by InstrumentationScope fields. -func (is InstrumentationScope) Hash() string { - return fmt.Sprintf("%x", md5.Sum([]byte(is.String()))) // #nosec -} - -// Equals determines the equivalence of two InstrumentationScope items. -func (is InstrumentationScope) Equals(toCompare InstrumentationScope) bool { - if is.Name != anyValue { - if is.Name != toCompare.Name { - return false - } - } - if is.Version != anyValue { - if is.Version != toCompare.Version { - return false - } - } - return attributesAreEqual(is.Attributes, toCompare.Attributes) -} - -// attributesAreEqual determines if the provided `attrs` are the same as -// `toCompare`, accounting for values in `attrs`. -func attributesAreEqual(attrs, toCompare *map[string]any) bool { - if attrs == nil { - return true - } - if toCompare == nil { - return false - } - if len(*attrs) != len(*toCompare) { - return false - } - - rAttrs := map[string]any{} - tcAttrs := map[string]any{} - - for k, v := range *attrs { - tcV, ok := (*toCompare)[k] - if !ok { - return false - } - if vMap, isMap := v.(map[string]any); isMap { - tcVMap, tcIsMap := tcV.(map[string]any) - if !tcIsMap { - return false - } - if !attributesAreEqual(&vMap, &tcVMap) { - return false - } - continue - } - if isDirective, equal := directiveEquality(v, tcV); isDirective { - if !equal { - return false - } - continue - } - rAttrs[k] = v - tcAttrs[k] = tcV - } - - return reflect.DeepEqual(rAttrs, tcAttrs) -} - -func directiveEquality(expected, actual any) (isDirective, equal bool) { - switch t := expected.(type) { - case string: - if t == anyValue { - return true, true - } - case *regexp.Regexp: - if t == nil { - return true, false - } - return true, t.MatchString(toString(actual)) - } - return false, false -} - -func marshal(y any) string { - b := &bytes.Buffer{} - enc := yaml.NewEncoder(b) - enc.SetIndent(2) - if err := enc.Encode(y); err != nil { - panic(err) - } - return b.String() -} - -func directiveMapToMarshal(m map[string]any) map[string]any { - cp := map[string]any{} - for k, v := range m { - if vMap, ok := v.(map[string]any); ok { - v = directiveMapToMarshal(vMap) - } - if t, ok := v.(*regexp.Regexp); ok { - v = fmt.Sprintf("", t.String()) - } - cp[k] = v - } - return cp -} - -func toString(v any) string { - return fmt.Sprintf("%v", v) -} diff --git a/tests/testutils/telemetry/common_test.go b/tests/testutils/telemetry/common_test.go deleted file mode 100644 index ff04612c0e..0000000000 --- a/tests/testutils/telemetry/common_test.go +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright Splunk, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build testutils - -package telemetry - -import ( - "regexp" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/signalfx/splunk-otel-collector/tests/internal/version" -) - -func TestResourceHashFunctionConsistency(t *testing.T) { - resource := Resource{Attributes: &map[string]any{ - "one": "1", "two": 2, "three": 3.000, "four": false, "five": nil, - }} - for i := 0; i < 100; i++ { - require.Equal(t, "8c2edf4b5b71836ef95c2d64c200f30c", resource.Hash()) - } - - il := InstrumentationScope{Name: "some instrumentation library", Version: "some instrumentation version"} - for i := 0; i < 100; i++ { - require.Equal(t, "aa00805240d9717e6db7a0d88cf5e2ba", il.Hash()) - } -} - -func TestEmptyResourcesAreEqual(t *testing.T) { - rOne := Resource{Attributes: &map[string]any{}} - rTwo := Resource{Attributes: &map[string]any{}} - rThree := Resource{} - - require.True(t, rOne.Equals(rTwo)) - require.True(t, rTwo.Equals(rOne)) - require.True(t, rThree.Equals(rOne)) - // nil attrs aren't equal to empty map - require.False(t, rTwo.Equals(rThree)) - - for i := 0; i < 100; i++ { - require.Equal(t, rOne.Hash(), rTwo.Hash()) - } -} - -func TestResourceEquivalence(t *testing.T) { - resource := func() Resource { - return Resource{Attributes: &map[string]any{ - "one": 1, "two": "two", "three": nil, - "four": []int{1, 2, 3, 4}, - "five": map[string]any{ - "true": true, "false": false, "nil": nil, - }, - }} - } - rOne := resource() - rOneSelf := rOne - assert.True(t, rOne.Equals(rOneSelf)) - - rTwo := resource() - assert.True(t, rOne.Equals(rTwo)) - assert.True(t, rTwo.Equals(rOne)) - - (*rTwo.Attributes)["five"].(map[string]any)["another"] = "item" - assert.False(t, rOne.Equals(rTwo)) - assert.False(t, rTwo.Equals(rOne)) - (*rOne.Attributes)["five"].(map[string]any)["another"] = "item" - assert.True(t, rOne.Equals(rTwo)) - assert.True(t, rTwo.Equals(rOne)) -} - -func TestResourceFillDefaultValues(t *testing.T) { - r := Resource{Attributes: &map[string]any{ - "version": "", - "any": "", - "re2": "", - }} - r.FillDefaultValues() - require.NotNil(t, r.Attributes) - regex := regexp.MustCompile(".*") - require.Equal(t, map[string]any{ - "version": version.Version, - "any": "", - "re2": regex, - }, *r.Attributes) -} - -func TestResourceFillDefaultValuesInvalidRE2(t *testing.T) { - r := Resource{Attributes: &map[string]any{ - "key": "", - }} - require.PanicsWithError( - t, "failed compiling resource attributes RE2 (key): error parsing regexp: missing argument to repetition operator: `*`", - r.FillDefaultValues, - ) -} - -func TestInstrumentationScopeEquivalence(t *testing.T) { - il := func() InstrumentationScope { - return InstrumentationScope{ - Name: "an_instrumentation_scope", Version: "an_instrumentation_scope_version", - } - } - - ilOne := il() - ilOneSelf := ilOne - assert.True(t, ilOne.Equals(ilOneSelf)) - - ilTwo := il() - assert.True(t, ilOne.Equals(ilTwo)) - assert.True(t, ilTwo.Equals(ilOne)) - - ilTwo.Version = "" - assert.False(t, ilOne.Equals(ilTwo)) - assert.False(t, ilTwo.Equals(ilOne)) - ilOne.Version = "" - assert.True(t, ilOne.Equals(ilTwo)) - assert.True(t, ilTwo.Equals(ilOne)) - - ilTwo.Name = "" - assert.False(t, ilOne.Equals(ilTwo)) - assert.False(t, ilTwo.Equals(ilOne)) - ilOne.Name = "" - assert.True(t, ilOne.Equals(ilTwo)) - assert.True(t, ilTwo.Equals(ilOne)) -} diff --git a/tests/testutils/telemetry/helpers_test.go b/tests/testutils/telemetry/helpers_test.go deleted file mode 100644 index 63d3aa6862..0000000000 --- a/tests/testutils/telemetry/helpers_test.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright Splunk, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build testutils - -package telemetry - -import ( - "runtime" -) - -func invalidPathErrorMsg() string { - if runtime.GOOS == "windows" { - return "open notafile: The system cannot find the file specified." - } - return "no such file or directory" -} diff --git a/tests/testutils/telemetry/metrics.go b/tests/testutils/telemetry/metrics.go deleted file mode 100644 index 7f8b495d36..0000000000 --- a/tests/testutils/telemetry/metrics.go +++ /dev/null @@ -1,480 +0,0 @@ -// Copyright Splunk, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package telemetry - -import ( - "bytes" - "crypto/md5" // #nosec this is not for cryptographic purposes - "fmt" - "os" - "sort" - "strings" - - "github.com/knadh/koanf/maps" - "github.com/stretchr/testify/assert" - "gopkg.in/yaml.v2" - - "github.com/signalfx/splunk-otel-collector/tests/internal/version" -) - -type MetricType string - -const ( - DoubleGauge MetricType = "DoubleGauge" - DoubleMonotonicCumulativeSum MetricType = "DoubleMonotonicCumulativeSum" - DoubleMonotonicDeltaSum MetricType = "DoubleMonotonicDeltaSum" - DoubleMonotonicUnspecifiedSum MetricType = "DoubleMonotonicUnspecifiedSum" - DoubleNonmonotonicCumulativeSum MetricType = "DoubleNonmonotonicCumulativeSum" - DoubleNonmonotonicDeltaSum MetricType = "DoubleNonmonotonicDeltaSum" - DoubleNonmonotonicUnspecifiedSum MetricType = "DoubleNonmonotonicUnspecifiedSum" - IntGauge MetricType = "IntGauge" - IntMonotonicCumulativeSum MetricType = "IntMonotonicCumulativeSum" - IntMonotonicDeltaSum MetricType = "IntMonotonicDeltaSum" - IntMonotonicUnspecifiedSum MetricType = "IntMonotonicUnspecifiedSum" - IntNonmonotonicCumulativeSum MetricType = "IntNonmonotonicCumulativeSum" - IntNonmonotonicDeltaSum MetricType = "IntNonmonotonicDeltaSum" - IntNonmonotonicUnspecifiedSum MetricType = "IntNonmonotonicUnspecifiedSum" - Summary MetricType = "Summary" - Histogram MetricType = "Histogram" - ExponentialHistogram MetricType = "ExponentialHistogram" -) - -var supportedMetricTypeOptions = fmt.Sprintf( - "%s, %s, %s, %s, %s, %s,%s, %s, %s, %s, %s, %s, %s, %s", - DoubleGauge, DoubleMonotonicCumulativeSum, - DoubleMonotonicDeltaSum, DoubleMonotonicUnspecifiedSum, - DoubleNonmonotonicCumulativeSum, DoubleNonmonotonicDeltaSum, - DoubleNonmonotonicUnspecifiedSum, IntGauge, - IntMonotonicCumulativeSum, IntMonotonicDeltaSum, - IntMonotonicUnspecifiedSum, IntNonmonotonicCumulativeSum, - IntNonmonotonicDeltaSum, IntNonmonotonicUnspecifiedSum, -) - -var supportedMetricTypes = map[MetricType]bool{ - DoubleGauge: true, DoubleMonotonicCumulativeSum: true, - DoubleMonotonicDeltaSum: true, DoubleMonotonicUnspecifiedSum: true, - DoubleNonmonotonicCumulativeSum: true, DoubleNonmonotonicDeltaSum: true, - DoubleNonmonotonicUnspecifiedSum: true, IntGauge: true, - IntMonotonicCumulativeSum: true, IntMonotonicDeltaSum: true, - IntMonotonicUnspecifiedSum: true, IntNonmonotonicCumulativeSum: true, - IntNonmonotonicDeltaSum: true, IntNonmonotonicUnspecifiedSum: true, - Histogram: true, -} - -// ResourceMetrics is a convenience type for testing helpers and assertions. Analogous to pdata form, with the exception that -// InstrumentationScope.Metrics items act as both parent metric container and datapoints -// whose identity is based on differing labels and other fields. -type ResourceMetrics struct { - ResourceMetrics []ResourceMetric `yaml:"resource_metrics"` -} - -// ResourceMetric is the top level metric type for a given Resource (set of attributes) and its associated ScopeMetrics. -type ResourceMetric struct { - Resource Resource `yaml:",inline,omitempty"` - ScopeMetrics []ScopeMetrics `yaml:"scope_metrics"` -} - -// ScopeMetrics are the collection of metrics produced by a given InstrumentationScope -type ScopeMetrics struct { - Scope InstrumentationScope `yaml:"instrumentation_scope,omitempty"` - Metrics []Metric `yaml:"metrics,omitempty"` -} - -// Metric is the metric content, representing both the overall definition and a single datapoint. -// TODO: Timestamps, additional Histogram fields -type Metric struct { - Value any `yaml:"value,omitempty"` - Sum any `yaml:"sum,omitempty"` - Count any `yaml:"count,omitempty"` - Attributes *map[string]any `yaml:"attributes,omitempty"` - Name string `yaml:"name"` - Description string `yaml:"description,omitempty"` - Unit string `yaml:"unit,omitempty"` - Type MetricType `yaml:"type"` -} - -// LoadResourceMetrics returns a ResourceMetrics instance generated via parsing a valid yaml file at the provided path. -func LoadResourceMetrics(path string) (*ResourceMetrics, error) { - metricFile, err := os.Open(path) - if err != nil { - return nil, err - } - defer metricFile.Chdir() - - buffer := new(bytes.Buffer) - if _, err = buffer.ReadFrom(metricFile); err != nil { - return nil, err - } - by := buffer.Bytes() - - var loaded ResourceMetrics - if err = yaml.UnmarshalStrict(by, &loaded); err != nil { - return nil, err - } - - for _, rm := range loaded.ResourceMetrics { - if rm.Resource.Attributes != nil { - maps.IntfaceKeysToStrings(*rm.Resource.Attributes) - } - for _, sm := range rm.ScopeMetrics { - for _, m := range sm.Metrics { - if m.Attributes != nil { - maps.IntfaceKeysToStrings(*m.Attributes) - } - } - } - } - - loaded.FillDefaultValues() - err = loaded.Validate() // in lieu of json/yaml schema adoption - if err != nil { - return nil, err - } - return &loaded, nil -} - -// FillDefaultValues fills ResourceMetrics with default values -func (resourceMetrics *ResourceMetrics) FillDefaultValues() { - for i, rm := range resourceMetrics.ResourceMetrics { - rm.Resource.FillDefaultValues() - for j, sms := range rm.ScopeMetrics { - if sms.Scope.Version == buildVersionPlaceholder { - resourceMetrics.ResourceMetrics[i].ScopeMetrics[j].Scope.Version = version.Version - } - - for _, m := range sms.Metrics { - populateDirectives(m.Attributes) - } - } - } -} - -// Determines if all values in ResourceMetrics item are valid -func (resourceMetrics ResourceMetrics) Validate() error { - for _, rm := range resourceMetrics.ResourceMetrics { - for _, ilm := range rm.ScopeMetrics { - for _, m := range ilm.Metrics { - if _, ok := supportedMetricTypes[m.Type]; m.Type != "" && !ok { - return fmt.Errorf( - "unsupported MetricType for %s - %s. Must be one of [%s]", - m.Name, m.Type, supportedMetricTypeOptions, - ) - } - } - } - } - return nil -} - -func (resourceMetrics ResourceMetrics) String() string { - return marshal(resourceMetrics) -} - -func (resourceMetric ResourceMetric) String() string { - return marshal(resourceMetric) -} - -func (scopeMetrics ScopeMetrics) String() string { - return marshal(scopeMetrics) -} - -func (metric Metric) String() string { - return marshal(metric) -} - -func (metric Metric) MarshalYAML() (any, error) { - // fieldalignment causes the Metric yaml rep to be - // unintuitive so manually unmarshal into map[string]any - ms := map[string]any{ - "name": metric.Name, - "type": metric.Type, - } - if metric.Unit != "" { - ms["unit"] = metric.Unit - } - if metric.Description != "" { - ms["description"] = metric.Description - } - if metric.Attributes != nil && len(*metric.Attributes) > 0 { - ms["attributes"] = directiveMapToMarshal(*metric.Attributes) - } - for _, s := range []struct { - v any - k string - }{ - {k: "sum", v: metric.Sum}, - {k: "count", v: metric.Count}, - {k: "value", v: metric.Value}, - } { - if s.v != nil { - ms[s.k] = s.v - } - - } - return ms, nil -} - -// Provides an md5 hash determined by Metric content. -func (metric Metric) Hash() string { - return fmt.Sprintf("%x", md5.Sum([]byte(metric.String()))) // #nosec -} - -// Confirms that all fields, defined or not, in receiver Metric are equal to toCompare. -// TODO: ensure that Metric.Hash equivalence is valid given all possible field values. -func (metric Metric) Equals(toCompare Metric) bool { - return metric.equals(toCompare, true) -} - -// Confirms that all defined fields in receiver Metric are matched in toCompare, ignoring those not set with the -// exception of Labels. All receiver Metric labels must be equal with those of the candidate to match. -func (metric Metric) RelaxedEquals(toCompare Metric) bool { - return metric.equals(toCompare, false) -} - -// Determines if receiver Metric is equal to toCompare Metric, relaxed if not strict -func (metric Metric) equals(toCompare Metric, strict bool) bool { - if metric.Name != toCompare.Name && (strict || metric.Name != "") { - return false - } - if metric.Description != toCompare.Description && (strict || metric.Description != "") { - return false - } - if metric.Unit != toCompare.Unit && (strict || metric.Unit != "") { - return false - } - if metric.Type != toCompare.Type && (strict || metric.Type != "") { - return false - } - - if !assert.ObjectsAreEqualValues(metric.Value, toCompare.Value) && (strict || metric.Value != nil) { - return false - } - - return attributesAreEqual(metric.Attributes, toCompare.Attributes) -} - -// FlattenResourceMetrics takes multiple instances of ResourceMetrics and flattens them -// to only unique entries by Resource, InstrumentationScope, and Metric content. -// It will preserve order by removing subsequent occurrences of repeated items -// from the returned flattened ResourceMetrics item -func FlattenResourceMetrics(resourceMetrics ...ResourceMetrics) ResourceMetrics { - flattened := ResourceMetrics{} - - var resourceHashes []string - // maps of resource hashes to objects - resources := map[string]Resource{} - scopeMetrics := map[string][]ScopeMetrics{} - - // flatten by Resource - for _, rms := range resourceMetrics { - for _, rm := range rms.ResourceMetrics { - resourceHash := rm.Resource.Hash() - if _, ok := resources[resourceHash]; !ok { - resources[resourceHash] = rm.Resource - resourceHashes = append(resourceHashes, resourceHash) - } - scopeMetrics[resourceHash] = append(scopeMetrics[resourceHash], rm.ScopeMetrics...) - } - } - - // flatten by InstrumentationScope - for _, resourceHash := range resourceHashes { - resource := resources[resourceHash] - resourceMetric := ResourceMetric{ - Resource: resource, - } - - var ilHashes []string - // maps of hashes to objects - ils := map[string]InstrumentationScope{} - ilMetrics := map[string][]Metric{} - for _, ilm := range scopeMetrics[resourceHash] { - ilHash := ilm.Scope.Hash() - if _, ok := ils[ilHash]; !ok { - ils[ilHash] = ilm.Scope - ilHashes = append(ilHashes, ilHash) - } - if ilm.Metrics == nil { - ilm.Metrics = []Metric{} - } - ilMetrics[ilHash] = append(ilMetrics[ilHash], ilm.Metrics...) - } - - // flatten by Metric - for _, ilHash := range ilHashes { - il := ils[ilHash] - - var metricHashes []string - metrics := map[string]Metric{} - allILMetrics := ilMetrics[ilHash] - for _, metric := range allILMetrics { - metricHash := metric.Hash() - if _, ok := metrics[metricHash]; !ok { - metrics[metricHash] = metric - metricHashes = append(metricHashes, metricHash) - } - } - - var flattenedMetrics []Metric - for _, metricHash := range metricHashes { - flattenedMetrics = append(flattenedMetrics, metrics[metricHash]) - } - - if flattenedMetrics == nil { - flattenedMetrics = []Metric{} - } - - sms := ScopeMetrics{ - Scope: il, - Metrics: flattenedMetrics, - } - resourceMetric.ScopeMetrics = append(resourceMetric.ScopeMetrics, sms) - } - - flattened.ResourceMetrics = append(flattened.ResourceMetrics, resourceMetric) - } - - return flattened -} - -// ContainsAll determines if everything in `expected` ResourceMetrics is in the receiver ResourceMetrics -// item (i.e. expected ⊆ resourceMetrics). Neither guarantees equivalence, nor that expected contains all of received -// (i.e. is not an expected ≣ resourceMetrics nor resourceMetrics ⊆ expected check). -// Metric equivalence is based on RelaxedEquals() check: fields not in expected (e.g. unit, type, value, etc.) -// are not compared to received, but all labels must match. -// For better reliability, it's advised that both ResourceMetrics items have been flattened by FlattenResourceMetrics. -func (resourceMetrics ResourceMetrics) ContainsAll(expected ResourceMetrics) (bool, error) { - var missingResources []string - missingInstrumentationScopes := map[string]struct{}{} - var missingMetrics []string - - for _, expectedResourceMetric := range expected.ResourceMetrics { - resourceMatched := false - for _, resourceMetric := range resourceMetrics.ResourceMetrics { - if expectedResourceMetric.Resource.Equals(resourceMetric.Resource) { - resourceMatched = true - innerMissingInstrumentationScopes := map[string]struct{}{} - for _, expectedILM := range expectedResourceMetric.ScopeMetrics { - matchingInstrumentationScope := "" - for _, ilm := range resourceMetric.ScopeMetrics { - if expectedILM.Scope.Equals(ilm.Scope) { - matchingInstrumentationScope = ilm.Scope.String() - for _, expectedMetric := range expectedILM.Metrics { - metricFound := false - for _, metric := range ilm.Metrics { - if expectedMetric.RelaxedEquals(metric) { - metricFound = true - } - } - if !metricFound { - missingMetrics = append(missingMetrics, expectedMetric.String()) - } - } - if len(missingMetrics) != 0 { - return false, fmt.Errorf( - "%v doesn't contain all of %v. Missing Metrics: %s", - ilm, expectedILM, missingMetrics) - } - } - } - if matchingInstrumentationScope != "" { - // no longer globally missing - delete(missingInstrumentationScopes, matchingInstrumentationScope) - } else { - innerMissingInstrumentationScopes[expectedILM.Scope.String()] = struct{}{} - } - } - if len(innerMissingInstrumentationScopes) != 0 { - if expectedResourceMetric.Resource.Attributes == nil { - // since nil attributes will be equal with everything - // keep track of inner missing scopes globally to be - // removed above - for k, v := range innerMissingInstrumentationScopes { - missingInstrumentationScopes[k] = v - } - continue - } - var missingIS []string - for k := range innerMissingInstrumentationScopes { - missingIS = append(missingIS, k) - } - return false, fmt.Errorf( - "%v doesn't contain all of %v. Missing InstrumentationScopes: %s", - resourceMetric, expectedResourceMetric, missingIS, - ) - } - } - } - if !resourceMatched { - missingResources = append(missingResources, expectedResourceMetric.Resource.String()) - } - } - if len(missingInstrumentationScopes) != 0 { - var missingIS []string - for k := range missingInstrumentationScopes { - missingIS = append(missingIS, k) - } - return false, fmt.Errorf( - "%v doesn't contain all of %v. Missing InstrumentationScopes: %s", - resourceMetrics, expected, missingIS, - ) - } - if len(missingResources) != 0 { - return false, fmt.Errorf( - "%v doesn't contain all of %v. Missing resources: %s", - resourceMetrics, expected, missingResources, - ) - } - return true, nil -} - -// ContainsOnly confirms both resourceMetrics.ContainsAll(expected) and that no additional -// metrics are reported -func (resourceMetrics ResourceMetrics) ContainsOnly(expected ResourceMetrics) (bool, error) { - if ok, err := resourceMetrics.ContainsAll(expected); !ok { - return ok, err - } - expectedNames := map[string]struct{}{} - for _, rm := range expected.ResourceMetrics { - for _, sm := range rm.ScopeMetrics { - for _, m := range sm.Metrics { - expectedNames[m.Name] = struct{}{} - } - } - } - - unexpectedNames := map[string]struct{}{} - for _, rm := range resourceMetrics.ResourceMetrics { - for _, sm := range rm.ScopeMetrics { - for _, m := range sm.Metrics { - if _, ok := expectedNames[m.Name]; !ok { - unexpectedNames[m.Name] = struct{}{} - } - } - } - } - - if len(unexpectedNames) == 0 { - return true, nil - } - - var unexpected []string - for name := range unexpectedNames { - unexpected = append(unexpected, name) - } - - sort.Strings(unexpected) - return false, fmt.Errorf("%v contains unexpected metrics %s", resourceMetrics, strings.Join(unexpected, ", ")) -} diff --git a/tests/testutils/telemetry/metrics_test.go b/tests/testutils/telemetry/metrics_test.go deleted file mode 100644 index d22572b8c9..0000000000 --- a/tests/testutils/telemetry/metrics_test.go +++ /dev/null @@ -1,500 +0,0 @@ -// Copyright Splunk, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build testutils - -package telemetry - -import ( - "fmt" - "os" - "path/filepath" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func loadedResourceMetrics(t *testing.T) ResourceMetrics { - resourceMetrics, err := LoadResourceMetrics(filepath.Join(".", "testdata", "metrics", "resource-metrics.yaml")) - require.NoError(t, err) - require.NotNil(t, resourceMetrics) - return *resourceMetrics -} - -func TestResourceMetricsYamlStringRep(t *testing.T) { - b, err := os.ReadFile(filepath.Join(".", "testdata", "metrics", "resource-metrics.yaml")) - require.NoError(t, err) - resourceMetrics := loadedResourceMetrics(t) - require.Equal(t, string(b), fmt.Sprintf("%v", resourceMetrics)) -} - -func TestLoadMetricsHappyPath(t *testing.T) { - resourceMetrics := loadedResourceMetrics(t) - assert.Equal(t, 2, len(resourceMetrics.ResourceMetrics)) - - firstRM := resourceMetrics.ResourceMetrics[0] - firstRMAttrs := *firstRM.Resource.Attributes - require.Equal(t, 2, len(firstRMAttrs)) - require.NotNil(t, firstRMAttrs["one_attr"]) - assert.Equal(t, "one_value", firstRMAttrs["one_attr"]) - require.NotNil(t, firstRMAttrs["two_attr"]) - assert.Equal(t, map[string]any{ - "nested_attr_a": "one_nested_value", - "nested_attr_b": "two_nested_value", - }, firstRMAttrs["two_attr"]) - - assert.Equal(t, 2, len(firstRM.ScopeMetrics)) - firstRMFirstSM := firstRM.ScopeMetrics[0] - require.NotNil(t, firstRMFirstSM) - require.NotNil(t, firstRMFirstSM.Scope) - assert.Equal(t, "without_metrics", firstRMFirstSM.Scope.Name) - assert.Equal(t, "some_version", firstRMFirstSM.Scope.Version) - require.Nil(t, firstRMFirstSM.Metrics) - - firstRMSecondSM := firstRM.ScopeMetrics[1] - require.NotNil(t, firstRMSecondSM) - require.NotNil(t, firstRMSecondSM.Scope) - assert.Empty(t, firstRMSecondSM.Scope.Name) - assert.Empty(t, firstRMSecondSM.Scope.Version) - require.NotNil(t, firstRMSecondSM.Metrics) - - require.Equal(t, 2, len(firstRMSecondSM.Metrics)) - firstRMSecondSMFirstMetric := firstRMSecondSM.Metrics[0] - require.NotNil(t, firstRMSecondSMFirstMetric) - assert.Equal(t, "an_int_gauge", firstRMSecondSMFirstMetric.Name) - assert.Equal(t, IntGauge, firstRMSecondSMFirstMetric.Type) - assert.Equal(t, "an_int_gauge_description", firstRMSecondSMFirstMetric.Description) - assert.Equal(t, "an_int_gauge_unit", firstRMSecondSMFirstMetric.Unit) - assert.Equal(t, 123, firstRMSecondSMFirstMetric.Value) - - firstRMSecondScopeMetricsecondMetric := firstRMSecondSM.Metrics[1] - require.NotNil(t, firstRMSecondScopeMetricsecondMetric) - assert.Equal(t, "a_double_gauge", firstRMSecondScopeMetricsecondMetric.Name) - assert.Equal(t, DoubleGauge, firstRMSecondScopeMetricsecondMetric.Type) - assert.Equal(t, 123.456, firstRMSecondScopeMetricsecondMetric.Value) - assert.Empty(t, firstRMSecondScopeMetricsecondMetric.Unit) - assert.Empty(t, firstRMSecondScopeMetricsecondMetric.Description) - - secondRM := resourceMetrics.ResourceMetrics[1] - require.Nil(t, secondRM.Resource.Attributes) - - assert.Equal(t, 1, len(secondRM.ScopeMetrics)) - secondRMFirstSM := secondRM.ScopeMetrics[0] - require.NotNil(t, secondRMFirstSM) - require.NotNil(t, secondRMFirstSM.Scope) - assert.Equal(t, "with_metrics", secondRMFirstSM.Scope.Name) - assert.Equal(t, "another_version", secondRMFirstSM.Scope.Version) - require.NotNil(t, secondRMFirstSM.Metrics) - - require.Equal(t, 2, len(secondRMFirstSM.Metrics)) - secondRMFirstSMFirstMetric := secondRMFirstSM.Metrics[0] - require.NotNil(t, secondRMFirstSMFirstMetric) - assert.Equal(t, "another_int_gauge", secondRMFirstSMFirstMetric.Name) - assert.Equal(t, IntGauge, secondRMFirstSMFirstMetric.Type) - assert.Empty(t, secondRMFirstSMFirstMetric.Description) - assert.Empty(t, secondRMFirstSMFirstMetric.Unit) - assert.Equal(t, 456, secondRMFirstSMFirstMetric.Value) - - secondRMFirstScopeMetricsecondMetric := secondRMFirstSM.Metrics[1] - require.NotNil(t, secondRMFirstScopeMetricsecondMetric) - assert.Equal(t, "another_double_gauge", secondRMFirstScopeMetricsecondMetric.Name) - assert.Equal(t, DoubleGauge, secondRMFirstScopeMetricsecondMetric.Type) - assert.Empty(t, secondRMFirstScopeMetricsecondMetric.Description) - assert.Empty(t, secondRMFirstScopeMetricsecondMetric.Unit) - assert.Equal(t, 567.89, secondRMFirstScopeMetricsecondMetric.Value) -} - -func TestLoadMetricsNotAValidPath(t *testing.T) { - resourceMetrics, err := LoadResourceMetrics("notafile") - require.Error(t, err) - require.Contains(t, err.Error(), invalidPathErrorMsg()) - require.Nil(t, resourceMetrics) -} - -func TestLoadMetricsInvalidItems(t *testing.T) { - resourceMetrics, err := LoadResourceMetrics(filepath.Join(".", "testdata", "metrics", "invalid-resource-metrics.yaml")) - require.Error(t, err) - require.Contains(t, err.Error(), "field notAttributesOrScopeMetrics not found in type telemetry.ResourceMetric") - require.Nil(t, resourceMetrics) -} - -func TestLoadMetricsInvalidMetricType(t *testing.T) { - resourceMetrics, err := LoadResourceMetrics(filepath.Join(".", "testdata", "metrics", "invalid-metric-type.yaml")) - require.Error(t, err) - require.Contains(t, err.Error(), "unsupported MetricType for of_an_unsupported_type - NotASupportedType") - require.Nil(t, resourceMetrics) -} - -func TestResourceMatchesWithAny(t *testing.T) { - rReference := Resource{Attributes: &map[string]any{ - "one": 1, "two": "", "three": nil, - "four": []int{1, 2, 3, 4}, - "five": map[string]any{ - "true": true, "false": false, "nil": nil, - }, - }} - rShouldEqual := Resource{Attributes: &map[string]any{ - "one": 1, "two": "two", "three": nil, - "four": []int{1, 2, 3, 4}, - "five": map[string]any{ - "true": true, "false": false, "nil": nil, - }, - }} - rMissingTwo := Resource{Attributes: &map[string]any{ - "one": 1, "three": nil, - "four": []int{1, 2, 3, 4}, - "five": map[string]any{ - "true": true, "false": false, "nil": nil, - }, - }} - - assert.True(t, rReference.Equals(rShouldEqual)) - assert.False(t, rReference.Equals(rMissingTwo)) -} - -func TestMetricEquivalence(t *testing.T) { - metric := func() Metric { - return Metric{ - Name: "a_metric", Description: "a_metric_description", - Unit: "a_metric_unit", Type: MetricType("a_metric_type"), - Attributes: &map[string]any{ - "one": "one", "two": "two", - }, Value: 123, - } - } - - mOne := metric() - mOneSelf := metric() - assert.True(t, mOne.Equals(mOneSelf)) - - mTwo := metric() - assert.True(t, mOne.Equals(mTwo)) - assert.True(t, mTwo.Equals(mOne)) - - mTwo.Name = "" - assert.False(t, mOne.Equals(mTwo)) - assert.False(t, mTwo.Equals(mOne)) - mOne.Name = "" - assert.True(t, mOne.Equals(mTwo)) - assert.True(t, mTwo.Equals(mOne)) - - mTwo.Description = "" - assert.False(t, mOne.Equals(mTwo)) - assert.False(t, mTwo.Equals(mOne)) - mOne.Description = "" - assert.True(t, mOne.Equals(mTwo)) - assert.True(t, mTwo.Equals(mOne)) - - mTwo.Unit = "" - assert.False(t, mOne.Equals(mTwo)) - assert.False(t, mTwo.Equals(mOne)) - mOne.Unit = "" - assert.True(t, mOne.Equals(mTwo)) - assert.True(t, mTwo.Equals(mOne)) - - mTwo.Type = "" - assert.False(t, mOne.Equals(mTwo)) - assert.False(t, mTwo.Equals(mOne)) - mOne.Type = "" - assert.True(t, mOne.Equals(mTwo)) - assert.True(t, mTwo.Equals(mOne)) - - mTwo.Value = 0 - assert.False(t, mOne.Equals(mTwo)) - assert.False(t, mTwo.Equals(mOne)) - mOne.Value = 0 - assert.True(t, mOne.Equals(mTwo)) - assert.True(t, mTwo.Equals(mOne)) - - (*mTwo.Attributes)["three"] = "three" - assert.False(t, mOne.Equals(mTwo)) - assert.False(t, mTwo.Equals(mOne)) - (*mOne.Attributes)["three"] = "three" - assert.True(t, mOne.Equals(mTwo)) - assert.True(t, mTwo.Equals(mOne)) -} - -func TestMetricRelaxedEquivalence(t *testing.T) { - lacksDescriptionUnitAndType := Metric{ - Name: "a_metric", - Attributes: &map[string]any{ - "one": "one", "two": "two", - }, Value: 123, - } - - completeMetric := Metric{ - Name: "a_metric", Description: "a_description", - Unit: "a_metric_unit", Type: "a_metric_type", - Attributes: &map[string]any{ - "one": "one", "two": "two", - }, Value: 123, - } - - require.True(t, lacksDescriptionUnitAndType.RelaxedEquals(completeMetric)) - require.False(t, completeMetric.RelaxedEquals(lacksDescriptionUnitAndType)) - - (*lacksDescriptionUnitAndType.Attributes)["three"] = "three" - require.False(t, lacksDescriptionUnitAndType.RelaxedEquals(completeMetric)) - require.False(t, completeMetric.RelaxedEquals(lacksDescriptionUnitAndType)) - (*completeMetric.Attributes)["three"] = "three" - require.True(t, lacksDescriptionUnitAndType.RelaxedEquals(completeMetric)) - require.False(t, completeMetric.RelaxedEquals(lacksDescriptionUnitAndType)) - - lacksDescriptionUnitAndType.Value = 234 - require.False(t, lacksDescriptionUnitAndType.RelaxedEquals(completeMetric)) - require.False(t, completeMetric.RelaxedEquals(lacksDescriptionUnitAndType)) - completeMetric.Value = 234 - require.True(t, lacksDescriptionUnitAndType.RelaxedEquals(completeMetric)) - require.False(t, completeMetric.RelaxedEquals(lacksDescriptionUnitAndType)) - - lacksDescriptionUnitAndType.Value = nil - require.True(t, lacksDescriptionUnitAndType.RelaxedEquals(completeMetric)) - require.False(t, completeMetric.RelaxedEquals(lacksDescriptionUnitAndType)) - - lacksDescriptionUnitAndType.Value = 234 - completeMetric.Description = "" - completeMetric.Unit = "" - completeMetric.Type = "" - require.True(t, lacksDescriptionUnitAndType.RelaxedEquals(completeMetric)) - require.True(t, completeMetric.RelaxedEquals(lacksDescriptionUnitAndType)) -} - -func TestMetricAttributeRelaxedEquivalence(t *testing.T) { - lackingAttributes := Metric{ - Name: "a_metric", Description: "a_description", - Unit: "a_metric_unit", Value: 123, - } - - emptyAttributes := Metric{ - Name: "a_metric", Description: "a_description", - Unit: "a_metric_unit", Attributes: &map[string]any{}, - Value: 123, - } - - completeMetric := Metric{ - Name: "a_metric", Description: "a_description", - Unit: "a_metric_unit", Type: "a_metric_type", - Attributes: &map[string]any{ - "one": "one", "two": "two", - }, Value: 123, - } - - require.True(t, lackingAttributes.RelaxedEquals(completeMetric)) - require.False(t, emptyAttributes.RelaxedEquals(completeMetric)) -} - -func TestMetricHashFunctionConsistency(t *testing.T) { - metric := Metric{ - Name: "some metric", Description: "some description", - Unit: "some unit", Attributes: &map[string]any{ - "attributeOne": "1", "attributeTwo": "two", - }, Type: MetricType("some metric type"), Value: 123.456, - } - for i := 0; i < 100; i++ { - require.Equal(t, "7fb66e09a072a06173f4cd1f2d63bf03", metric.Hash()) - } -} - -func TestFlattenResourceMetricsByResourceIdentity(t *testing.T) { - resource := Resource{Attributes: &map[string]any{"attribute_one": nil, "attribute_two": 123.456}} - resourceMetrics := ResourceMetrics{ - ResourceMetrics: []ResourceMetric{ - {Resource: resource}, - {Resource: resource}, - {Resource: resource}, - }, - } - expectedResourceMetrics := ResourceMetrics{ResourceMetrics: []ResourceMetric{{Resource: resource}}} - require.Equal(t, expectedResourceMetrics, FlattenResourceMetrics(resourceMetrics)) -} - -func TestFlattenResourceMetricsByScopeMetricsIdentity(t *testing.T) { - resource := Resource{Attributes: &map[string]any{"attribute_three": true, "attribute_four": 23456}} - sm := ScopeMetrics{Scope: InstrumentationScope{ - Name: "an instrumentation library", Version: "an instrumentation library version", - }, Metrics: []Metric{}} - resourceMetrics := ResourceMetrics{ - ResourceMetrics: []ResourceMetric{ - {Resource: resource, ScopeMetrics: []ScopeMetrics{}}, - {Resource: resource, ScopeMetrics: []ScopeMetrics{sm}}, - {Resource: resource, ScopeMetrics: []ScopeMetrics{sm, sm}}, - {Resource: resource, ScopeMetrics: []ScopeMetrics{sm, sm, sm}}, - }, - } - expectedResourceMetrics := ResourceMetrics{ - ResourceMetrics: []ResourceMetric{ - {Resource: resource, ScopeMetrics: []ScopeMetrics{sm}}, - }, - } - require.Equal(t, expectedResourceMetrics, FlattenResourceMetrics(resourceMetrics)) -} - -func TestFlattenResourceMetricsByMetricsIdentity(t *testing.T) { - resource := Resource{} - metrics := []Metric{ - {Name: "a metric", Unit: "a unit", Description: "a description", Value: 123}, - {Name: "another metric", Unit: "another unit", Description: "another description", Value: 234}, - {Name: "yet another metric", Unit: "yet anothe unit", Description: "yet anothet description", Value: 345}, - } - sm := ScopeMetrics{Metrics: metrics} - smRepeated := ScopeMetrics{Metrics: append(metrics, metrics...)} - smRepeatedTwice := ScopeMetrics{Metrics: append(metrics, append(metrics, metrics...)...)} - smWithoutMetrics := ScopeMetrics{} - resourceMetrics := ResourceMetrics{ - ResourceMetrics: []ResourceMetric{ - {Resource: resource, ScopeMetrics: []ScopeMetrics{}}, - {Resource: resource, ScopeMetrics: []ScopeMetrics{sm}}, - {Resource: resource, ScopeMetrics: []ScopeMetrics{smRepeated}}, - {Resource: resource, ScopeMetrics: []ScopeMetrics{smRepeatedTwice}}, - {Resource: resource, ScopeMetrics: []ScopeMetrics{smWithoutMetrics}}, - }, - } - expectedResourceMetrics := ResourceMetrics{ - ResourceMetrics: []ResourceMetric{ - {Resource: resource, ScopeMetrics: []ScopeMetrics{sm}}, - }, - } - require.Equal(t, expectedResourceMetrics, FlattenResourceMetrics(resourceMetrics)) -} - -func TestFlattenResourceMetricsConsistency(t *testing.T) { - resourceMetrics, err := PDataToResourceMetrics(PDataMetrics()) - require.NoError(t, err) - require.NotNil(t, resourceMetrics) - require.Equal(t, resourceMetrics, FlattenResourceMetrics(resourceMetrics)) - var rms []ResourceMetrics - for i := 0; i < 50; i++ { - rms = append(rms, resourceMetrics) - } - for i := 0; i < 50; i++ { - require.Equal(t, resourceMetrics, FlattenResourceMetrics(rms...)) - } -} - -func TestMetricContainsAllSelfCheck(t *testing.T) { - resourceMetrics := loadedResourceMetrics(t) - containsAll, err := resourceMetrics.ContainsAll(resourceMetrics) - require.True(t, containsAll, err) - require.NoError(t, err) -} - -func TestMetricContainsOnlySelfCheck(t *testing.T) { - resourceMetrics := loadedResourceMetrics(t) - containsAll, err := resourceMetrics.ContainsOnly(resourceMetrics) - require.True(t, containsAll, err) - require.NoError(t, err) -} - -func TestMetricContainsAllNoBijection(t *testing.T) { - received := loadedResourceMetrics(t) - - expected, err := LoadResourceMetrics(filepath.Join(".", "testdata", "metrics", "expected-metrics.yaml")) - require.NoError(t, err) - require.NotNil(t, expected) - - containsAll, err := received.ContainsAll(*expected) - require.True(t, containsAll, err) - require.NoError(t, err) - - // Since expectedMetrics specify no values, they will never find matches with metrics w/ them. - containsAll, err = expected.ContainsAll(received) - require.False(t, containsAll) - require.Error(t, err) - require.Contains(t, err.Error(), `Missing Metrics: [attributes: - metric_attr_a: one_value - metric_attr_b: this should match an RE2 directive - metric_attr_c: this should match an ANY directive - metric_attr_d: - nested_attr_a: 123 - nested_attr_b: this should match yet another RE2 directive -name: another_int_gauge -type: IntGauge -value: 456 - name: another_double_gauge -type: DoubleGauge -value: 567.89 -]`) -} - -func TestMetricContainsAllValueNeverReceived(t *testing.T) { - received := loadedResourceMetrics(t) - expected, err := LoadResourceMetrics(filepath.Join(".", "testdata", "metrics", "never-received-metrics.yaml")) - require.NoError(t, err) - require.NotNil(t, expected) - - // neverReceivedMetrics.yaml details a Metric with a value that isn't in resourceMetrics.yaml - containsAll, err := received.ContainsAll(*expected) - require.False(t, containsAll) - require.Error(t, err) - require.Contains(t, err.Error(), "Missing Metrics: [name: another_int_gauge\ntype: IntGauge\nvalue: 111\n]") -} - -func TestMetricContainsAllInstrumentationScopeNeverReceived(t *testing.T) { - received := loadedResourceMetrics(t) - expected, err := LoadResourceMetrics(filepath.Join(".", "testdata", "metrics", "never-received-instrumentation-scope.yaml")) - require.NoError(t, err) - require.NotNil(t, expected) - - // neverReceivedMetrics.yaml details an InstrumentationScope that isn't in resourceMetrics.yaml - containsAll, err := received.ContainsAll(*expected) - require.False(t, containsAll) - require.Error(t, err) - require.Contains(t, err.Error(), "Missing InstrumentationScopes: [name: unmatched_instrumentation_scope\n]") -} - -func TestMetricContainsAllResourceNeverReceived(t *testing.T) { - received := loadedResourceMetrics(t) - expected, err := LoadResourceMetrics(filepath.Join(".", "testdata", "metrics", "never-received-resource.yaml")) - require.NoError(t, err) - require.NotNil(t, expected) - - // neverReceivedMetrics.yaml details a Resource that isn't in resourceMetrics.yaml - containsAll, err := received.ContainsAll(*expected) - require.False(t, containsAll) - require.Error(t, err) - require.Contains(t, err.Error(), "Missing resources: [attributes:\n not: matched\n]") -} - -func TestMetricContainsAllWithMissingAndEmptyAttributes(t *testing.T) { - received, err := LoadResourceMetrics(filepath.Join(".", "testdata", "metrics", "attribute-value-resource-metrics.yaml")) - require.NoError(t, err) - require.NotNil(t, received) - - unspecified, err := LoadResourceMetrics(filepath.Join(".", "testdata", "metrics", "unspecified-attributes-allowed.yaml")) - require.NoError(t, err) - require.NotNil(t, unspecified) - - empty, err := LoadResourceMetrics(filepath.Join(".", "testdata", "metrics", "empty-attributes-required.yaml")) - require.NoError(t, err) - require.NotNil(t, empty) - - containsAll, err := received.ContainsAll(*unspecified) - require.True(t, containsAll) - require.NoError(t, err) - - containsAll, err = received.ContainsAll(*empty) - require.False(t, containsAll) - require.Error(t, err) - require.Contains(t, err.Error(), "Missing Metrics: [name: another_int_gauge\ntype: IntGauge\nvalue: 111\n]") -} - -func TestMetricContainsOnlyDetectsUnexpectedMetric(t *testing.T) { - resourceMetrics := loadedResourceMetrics(t) - sm := resourceMetrics.ResourceMetrics[0].ScopeMetrics - sm[0].Metrics = append(sm[0].Metrics, Metric{Name: "unexpected_metric"}) - containsAll, err := resourceMetrics.ContainsOnly(loadedResourceMetrics(t)) - require.False(t, containsAll, err) - require.EqualError(t, err, fmt.Sprintf("%v contains unexpected metrics unexpected_metric", resourceMetrics)) -} diff --git a/tests/testutils/telemetry/pdata_common.go b/tests/testutils/telemetry/pdata_common.go deleted file mode 100644 index d93c6026e8..0000000000 --- a/tests/testutils/telemetry/pdata_common.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright Splunk, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package telemetry - -import ( - "github.com/knadh/koanf/maps" - "gopkg.in/yaml.v2" -) - -// sanitizeAttributes helps ensure that unmarshaled yaml mappings and -// pcommon.Map items have the same map[string]any representation -// suitable for reflect.DeepEquals. -func sanitizeAttributes(attributes map[string]any) map[string]any { - sanitized := map[string]any{} - b, err := yaml.Marshal(attributes) - if err != nil { - panic(err) - } - if err = yaml.Unmarshal(b, &sanitized); err != nil { - panic(err) - } - maps.IntfaceKeysToStrings(sanitized) - return sanitized -} diff --git a/tests/testutils/telemetry/pdata_common_test.go b/tests/testutils/telemetry/pdata_common_test.go deleted file mode 100644 index 52e88cb197..0000000000 --- a/tests/testutils/telemetry/pdata_common_test.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright Splunk, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build testutils - -package telemetry - -import ( - "os" - "path/filepath" - "testing" - - "github.com/stretchr/testify/require" - "go.opentelemetry.io/collector/pdata/pcommon" - "gopkg.in/yaml.v2" -) - -func TestSanitizeAttributes(t *testing.T) { - b, err := os.ReadFile(filepath.Join(".", "testdata", "common", "attributes.yaml")) - require.NoError(t, err) - anyMap := map[string]any{} - require.NoError(t, yaml.Unmarshal(b, &anyMap)) - pMap := pcommon.NewMap() - pMap.PutInt("int", 1) - pMap.PutDouble("float", 1.234) - pMap.PutStr("string", "a\nlong\nstring\n") - pMap.PutBool("bool", false) - pMap.PutEmpty("empty") - require.Equal(t, sanitizeAttributes(pMap.AsRaw()), sanitizeAttributes(anyMap)) -} diff --git a/tests/testutils/telemetry/pdata_metrics.go b/tests/testutils/telemetry/pdata_metrics.go deleted file mode 100644 index 86649f16c4..0000000000 --- a/tests/testutils/telemetry/pdata_metrics.go +++ /dev/null @@ -1,453 +0,0 @@ -// Copyright Splunk, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package telemetry - -import ( - "fmt" - - "go.opentelemetry.io/collector/pdata/pmetric" -) - -// PDataToResourceMetrics returns a ResourceMetrics item generated from pmetric.Metrics content. -// At this time histograms and summaries aren't supported. -func PDataToResourceMetrics(pdataMetrics ...pmetric.Metrics) (ResourceMetrics, error) { - resourceMetrics := ResourceMetrics{} - for _, pdataMetric := range pdataMetrics { - pdataRMs := pdataMetric.ResourceMetrics() - numRM := pdataRMs.Len() - for i := 0; i < numRM; i++ { - rm := ResourceMetric{} - pdataRM := pdataRMs.At(i) - sanitizedAttrs := sanitizeAttributes(pdataRM.Resource().Attributes().AsRaw()) - rm.Resource.Attributes = &sanitizedAttrs - pdataSMs := pdataRM.ScopeMetrics() - for j := 0; j < pdataSMs.Len(); j++ { - ISMs := ScopeMetrics{Metrics: []Metric{}} - pdataSM := pdataSMs.At(j) - attrs := pdataSM.Scope().Attributes().AsRaw() - ISMs.Scope = InstrumentationScope{ - Name: pdataSM.Scope().Name(), - Version: pdataSM.Scope().Version(), - Attributes: &attrs, - } - for k := 0; k < pdataSM.Metrics().Len(); k++ { - pdMetric := pdataSM.Metrics().At(k) - switch t := pdMetric.Type(); t { - case pmetric.MetricTypeGauge: - addGauge(&ISMs, pdMetric) - case pmetric.MetricTypeSum: - addSum(&ISMs, pdMetric) - case pmetric.MetricTypeSummary: - addSummary(&ISMs, pdMetric) - case pmetric.MetricTypeHistogram: - addHistogram(&ISMs, pdMetric) - case pmetric.MetricTypeExponentialHistogram: - addExponentialHistogram(&ISMs, pdMetric) - default: - panic(fmt.Sprintf("unexpected data type: %s", t)) - } - } - rm.ScopeMetrics = append(rm.ScopeMetrics, ISMs) - } - resourceMetrics.ResourceMetrics = append(resourceMetrics.ResourceMetrics, rm) - } - } - return resourceMetrics, nil -} - -func addSum(sms *ScopeMetrics, metric pmetric.Metric) { - sum := metric.Sum() - doubleMetricType := doubleSumMetricType(sum) - intMetricType := intSumMetricType(sum) - for l := 0; l < sum.DataPoints().Len(); l++ { - dp := sum.DataPoints().At(l) - var val any - var metricType MetricType - switch dp.ValueType() { - case pmetric.NumberDataPointValueTypeInt: - val = dp.IntValue() - metricType = intMetricType - case pmetric.NumberDataPointValueTypeDouble: - val = dp.DoubleValue() - metricType = doubleMetricType - } - attributes := sanitizeAttributes(dp.Attributes().AsRaw()) - m := Metric{ - Name: metric.Name(), - Description: metric.Description(), - Unit: metric.Unit(), - Attributes: &attributes, - Type: metricType, - Value: val, - } - sms.Metrics = append(sms.Metrics, m) - } -} - -func addGauge(sms *ScopeMetrics, metric pmetric.Metric) { - doubleGauge := metric.Gauge() - for l := 0; l < doubleGauge.DataPoints().Len(); l++ { - dp := doubleGauge.DataPoints().At(l) - var val any - var metricType MetricType - switch dp.ValueType() { - case pmetric.NumberDataPointValueTypeInt: - val = dp.IntValue() - metricType = IntGauge - case pmetric.NumberDataPointValueTypeDouble: - val = dp.DoubleValue() - metricType = DoubleGauge - } - attributes := sanitizeAttributes(dp.Attributes().AsRaw()) - m := Metric{ - Name: metric.Name(), - Description: metric.Description(), - Unit: metric.Unit(), - Attributes: &attributes, - Type: metricType, - Value: val, - } - sms.Metrics = append(sms.Metrics, m) - } -} - -func addSummary(sms *ScopeMetrics, metric pmetric.Metric) { - summary := metric.Summary() - for l := 0; l < summary.DataPoints().Len(); l++ { - dp := summary.DataPoints().At(l) - attributes := sanitizeAttributes(dp.Attributes().AsRaw()) - m := Metric{ - Name: metric.Name(), - Description: metric.Description(), - Unit: metric.Unit(), - Attributes: &attributes, - Type: Summary, - Sum: dp.Sum(), - Count: dp.Count(), - } - sms.Metrics = append(sms.Metrics, m) - } -} - -func addHistogram(sms *ScopeMetrics, metric pmetric.Metric) { - summary := metric.Histogram() - for l := 0; l < summary.DataPoints().Len(); l++ { - dp := summary.DataPoints().At(l) - attributes := sanitizeAttributes(dp.Attributes().AsRaw()) - m := Metric{ - Name: metric.Name(), - Description: metric.Description(), - Unit: metric.Unit(), - Attributes: &attributes, - Type: Histogram, - Sum: dp.Sum(), - Count: dp.Count(), - } - sms.Metrics = append(sms.Metrics, m) - } -} - -func addExponentialHistogram(sms *ScopeMetrics, metric pmetric.Metric) { - summary := metric.ExponentialHistogram() - for l := 0; l < summary.DataPoints().Len(); l++ { - dp := summary.DataPoints().At(l) - attributes := sanitizeAttributes(dp.Attributes().AsRaw()) - m := Metric{ - Name: metric.Name(), - Description: metric.Description(), - Unit: metric.Unit(), - Attributes: &attributes, - Type: ExponentialHistogram, - Sum: dp.Sum(), - Count: dp.Count(), - } - sms.Metrics = append(sms.Metrics, m) - } -} - -func doubleSumMetricType(sum pmetric.Sum) MetricType { - switch sum.AggregationTemporality() { - case pmetric.AggregationTemporalityCumulative: - if sum.IsMonotonic() { - return DoubleMonotonicCumulativeSum - } - return DoubleNonmonotonicCumulativeSum - case pmetric.AggregationTemporalityDelta: - if sum.IsMonotonic() { - return DoubleMonotonicDeltaSum - } - return DoubleNonmonotonicDeltaSum - case pmetric.AggregationTemporalityUnspecified: - if sum.IsMonotonic() { - return DoubleMonotonicUnspecifiedSum - } - return DoubleNonmonotonicUnspecifiedSum - } - return "unknown" -} - -func intSumMetricType(sum pmetric.Sum) MetricType { - switch sum.AggregationTemporality() { - case pmetric.AggregationTemporalityCumulative: - if sum.IsMonotonic() { - return IntMonotonicCumulativeSum - } - return IntNonmonotonicCumulativeSum - case pmetric.AggregationTemporalityDelta: - if sum.IsMonotonic() { - return IntMonotonicDeltaSum - } - return IntNonmonotonicDeltaSum - case pmetric.AggregationTemporalityUnspecified: - if sum.IsMonotonic() { - return IntMonotonicUnspecifiedSum - } - return IntNonmonotonicUnspecifiedSum - } - return "unknown" -} - -func PDataMetrics() pmetric.Metrics { - metrics := pmetric.NewMetrics() - resourceMetrics := metrics.ResourceMetrics().AppendEmpty() - attrs := resourceMetrics.Resource().Attributes() - attrs.PutBool("bool", true) - attrs.PutStr("string", "a_string") - attrs.PutInt("int", 123) - attrs.PutDouble("double", 123.45) - attrs.PutEmpty("null") - - scopeMetrics := resourceMetrics.ScopeMetrics() - smOne := scopeMetrics.AppendEmpty() - smOne.Scope().SetName("an_instrumentation_scope_name") - smOne.Scope().SetVersion("an_instrumentation_scope_version") - smOneMetrics := smOne.Metrics() - smOneMetricOne := smOneMetrics.AppendEmpty() - smOneMetricOne.SetName("an_int_gauge") - smOneMetricOne.SetDescription("an_int_gauge_description") - smOneMetricOne.SetUnit("an_int_gauge_unit") - smOneMetricOne.SetEmptyGauge() - smOneMetricOneDps := smOneMetricOne.Gauge().DataPoints() - smOneMetricOneDps.AppendEmpty().SetIntValue(12345) - smOneMetricOneDps.At(0).Attributes().PutStr("attribute_name_1", "attribute_value_1") - smOneMetricOneDps.AppendEmpty().SetIntValue(23456) - smOneMetricOneDps.At(1).Attributes().PutStr("attribute_name_2", "attribute_value_2") - - smOneMetricTwo := smOneMetrics.AppendEmpty() - smOneMetricTwo.SetName("a_double_gauge") - smOneMetricTwo.SetDescription("a_double_gauge_description") - smOneMetricTwo.SetUnit("a_double_gauge_unit") - smOneMetricTwo.SetEmptyGauge() - smOneMetricTwoDps := smOneMetricTwo.Gauge().DataPoints() - smOneMetricTwoDps.AppendEmpty().SetDoubleValue(234.56) - smOneMetricTwoDps.At(0).Attributes().PutStr("attribute_name_3", "attribute_value_3") - smOneMetricTwoDps.AppendEmpty().SetDoubleValue(345.67) - smOneMetricTwoDps.At(1).Attributes().PutStr("attribute_name_4", "attribute_value_4") - - scopeMetrics.AppendEmpty().Scope().SetName("an_instrumentation_scope_without_version_or_metrics") - - smThreeMetrics := scopeMetrics.AppendEmpty().Metrics() - - smThreeMetricOne := smThreeMetrics.AppendEmpty() - smThreeMetricOne.SetName("a_monotonic_cumulative_int_sum") - smThreeMetricOne.SetDescription("a_monotonic_cumulative_int_sum_description") - smThreeMetricOne.SetUnit("a_monotonic_cumulative_int_sum_unit") - smThreeMetricOne.SetEmptySum() - smThreeMetricOne.Sum().SetIsMonotonic(true) - smThreeMetricOne.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityCumulative) - smThreeMetricOneDps := smThreeMetricOne.Sum().DataPoints() - smThreeMetricOneDps.AppendEmpty().SetIntValue(34567) - smThreeMetricOneDps.At(0).Attributes().PutStr("attribute_name_5", "attribute_value_5") - smThreeMetricOneDps.AppendEmpty().SetIntValue(45678) - smThreeMetricOneDps.At(1).Attributes().PutStr("attribute_name_6", "attribute_value_6") - - smThreeMetricTwo := smThreeMetrics.AppendEmpty() - smThreeMetricTwo.SetName("a_monotonic_delta_int_sum") - smThreeMetricTwo.SetDescription("a_monotonic_delta_int_sum_description") - smThreeMetricTwo.SetUnit("a_monotonic_delta_int_sum_unit") - smThreeMetricTwo.SetEmptySum() - smThreeMetricTwo.Sum().SetIsMonotonic(true) - smThreeMetricTwo.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityDelta) - smThreeMetricTwoDps := smThreeMetricTwo.Sum().DataPoints() - smThreeMetricTwoDps.AppendEmpty().SetIntValue(56789) - smThreeMetricTwoDps.At(0).Attributes().PutStr("attribute_name_7", "attribute_value_7") - smThreeMetricTwoDps.AppendEmpty().SetIntValue(67890) - smThreeMetricTwoDps.At(1).Attributes().PutStr("attribute_name_8", "attribute_value_8") - - smThreeMetricThree := smThreeMetrics.AppendEmpty() - smThreeMetricThree.SetName("a_monotonic_unspecified_int_sum") - smThreeMetricThree.SetDescription("a_monotonic_unspecified_int_sum_description") - smThreeMetricThree.SetUnit("a_monotonic_unspecified_int_sum_unit") - smThreeMetricThree.SetEmptySum() - smThreeMetricThree.Sum().SetIsMonotonic(true) - smThreeMetricThree.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityUnspecified) - smThreeMetricThreeDps := smThreeMetricThree.Sum().DataPoints() - smThreeMetricThreeDps.AppendEmpty().SetIntValue(78901) - smThreeMetricThreeDps.At(0).Attributes().PutStr("attribute_name_9", "attribute_value_9") - smThreeMetricThreeDps.AppendEmpty().SetIntValue(89012) - smThreeMetricThreeDps.At(1).Attributes().PutStr("attribute_name_10", "attribute_value_10") - - smThreeMetricFour := smThreeMetrics.AppendEmpty() - smThreeMetricFour.SetName("a_monotonic_cumulative_double_sum") - smThreeMetricFour.SetDescription("a_monotonic_cumulative_double_sum_description") - smThreeMetricFour.SetUnit("a_monotonic_cumulative_double_sum_unit") - smThreeMetricFour.SetEmptySum() - smThreeMetricFour.Sum().SetIsMonotonic(true) - smThreeMetricFour.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityCumulative) - smThreeMetricFourDps := smThreeMetricFour.Sum().DataPoints() - smThreeMetricFourDps.AppendEmpty().SetDoubleValue(456.78) - smThreeMetricFourDps.At(0).Attributes().PutStr("attribute_name_11", "attribute_value_11") - smThreeMetricFourDps.AppendEmpty().SetDoubleValue(567.89) - smThreeMetricFourDps.At(1).Attributes().PutStr("attribute_name_12", "attribute_value_12") - - smThreeMetricFive := smThreeMetrics.AppendEmpty() - smThreeMetricFive.SetName("a_monotonic_delta_double_sum") - smThreeMetricFive.SetDescription("a_monotonic_delta_double_sum_description") - smThreeMetricFive.SetUnit("a_monotonic_delta_double_sum_unit") - smThreeMetricFive.SetEmptySum() - smThreeMetricFive.Sum().SetIsMonotonic(true) - smThreeMetricFive.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityDelta) - smThreeMetricFiveDps := smThreeMetricFive.Sum().DataPoints() - smThreeMetricFiveDps.AppendEmpty().SetDoubleValue(678.90) - smThreeMetricFiveDps.At(0).Attributes().PutStr("attribute_name_13", "attribute_value_13") - smThreeMetricFiveDps.AppendEmpty().SetDoubleValue(789.01) - smThreeMetricFiveDps.At(1).Attributes().PutStr("attribute_name_14", "attribute_value_14") - - smThreeMetricSix := smThreeMetrics.AppendEmpty() - smThreeMetricSix.SetName("a_monotonic_unspecified_double_sum") - smThreeMetricSix.SetDescription("a_monotonic_unspecified_double_sum_description") - smThreeMetricSix.SetUnit("a_monotonic_unspecified_double_sum_unit") - smThreeMetricSix.SetEmptySum() - smThreeMetricSix.Sum().SetIsMonotonic(true) - smThreeMetricSix.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityUnspecified) - smThreeMetricSixDps := smThreeMetricSix.Sum().DataPoints() - smThreeMetricSixDps.AppendEmpty().SetDoubleValue(890.12) - smThreeMetricSixDps.At(0).Attributes().PutStr("attribute_name_15", "attribute_value_15") - smThreeMetricSixDps.AppendEmpty().SetDoubleValue(901.23) - smThreeMetricSixDps.At(1).Attributes().PutStr("attribute_name_16", "attribute_value_16") - - smThreeMetricSeven := smThreeMetrics.AppendEmpty() - smThreeMetricSeven.SetName("a_nonmonotonic_cumulative_int_sum") - smThreeMetricSeven.SetDescription("a_nonmonotonic_cumulative_int_sum_description") - smThreeMetricSeven.SetUnit("a_nonmonotonic_cumulative_int_sum_unit") - smThreeMetricSeven.SetEmptySum() - smThreeMetricSeven.Sum().SetIsMonotonic(false) - smThreeMetricSeven.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityCumulative) - smThreeMetricSevenDps := smThreeMetricSeven.Sum().DataPoints() - smThreeMetricSevenDps.AppendEmpty().SetIntValue(90123) - smThreeMetricSevenDps.At(0).Attributes().PutStr("attribute_name_17", "attribute_value_17") - smThreeMetricSevenDps.AppendEmpty().SetIntValue(123456) - smThreeMetricSevenDps.At(1).Attributes().PutStr("attribute_name_18", "attribute_value_18") - - smThreeMetricEight := smThreeMetrics.AppendEmpty() - smThreeMetricEight.SetName("a_nonmonotonic_delta_int_sum") - smThreeMetricEight.SetDescription("a_nonmonotonic_delta_int_sum_description") - smThreeMetricEight.SetUnit("a_nonmonotonic_delta_int_sum_unit") - smThreeMetricEight.SetEmptySum() - smThreeMetricEight.Sum().SetIsMonotonic(false) - smThreeMetricEight.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityDelta) - smThreeMetricEightDps := smThreeMetricEight.Sum().DataPoints() - smThreeMetricEightDps.AppendEmpty().SetIntValue(234567) - smThreeMetricEightDps.At(0).Attributes().PutStr("attribute_name_19", "attribute_value_19") - smThreeMetricEightDps.AppendEmpty().SetIntValue(345678) - smThreeMetricEightDps.At(1).Attributes().PutStr("attribute_name_20", "attribute_value_20") - - smThreeMetricNine := smThreeMetrics.AppendEmpty() - smThreeMetricNine.SetName("a_nonmonotonic_unspecified_int_sum") - smThreeMetricNine.SetDescription("a_nonmonotonic_unspecified_int_sum_description") - smThreeMetricNine.SetUnit("a_nonmonotonic_unspecified_int_sum_unit") - smThreeMetricNine.SetEmptySum() - smThreeMetricNine.Sum().SetIsMonotonic(false) - smThreeMetricNine.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityUnspecified) - smThreeMetricNineDps := smThreeMetricNine.Sum().DataPoints() - smThreeMetricNineDps.AppendEmpty().SetIntValue(456789) - smThreeMetricNineDps.At(0).Attributes().PutStr("attribute_name_21", "attribute_value_21") - smThreeMetricNineDps.AppendEmpty().SetIntValue(567890) - smThreeMetricNineDps.At(1).Attributes().PutStr("attribute_name_22", "attribute_value_22") - - smThreeMetricTen := smThreeMetrics.AppendEmpty() - smThreeMetricTen.SetName("a_nonmonotonic_cumulative_double_sum") - smThreeMetricTen.SetDescription("a_nonmonotonic_cumulative_double_sum_description") - smThreeMetricTen.SetUnit("a_nonmonotonic_cumulative_double_sum_unit") - smThreeMetricTen.SetEmptySum() - smThreeMetricTen.Sum().SetIsMonotonic(false) - smThreeMetricTen.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityCumulative) - smThreeMetricTenDps := smThreeMetricTen.Sum().DataPoints() - smThreeMetricTenDps.AppendEmpty().SetDoubleValue(1234.56) - smThreeMetricTenDps.At(0).Attributes().PutStr("attribute_name_23", "attribute_value_23") - smThreeMetricTenDps.AppendEmpty().SetDoubleValue(2345.67) - smThreeMetricTenDps.At(1).Attributes().PutStr("attribute_name_24", "attribute_value_24") - - smThreeMetricEleven := smThreeMetrics.AppendEmpty() - smThreeMetricEleven.SetName("a_nonmonotonic_delta_double_sum") - smThreeMetricEleven.SetDescription("a_nonmonotonic_delta_double_sum_description") - smThreeMetricEleven.SetUnit("a_nonmonotonic_delta_double_sum_unit") - smThreeMetricEleven.SetEmptySum() - smThreeMetricEleven.Sum().SetIsMonotonic(false) - smThreeMetricEleven.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityDelta) - smThreeMetricElevenDps := smThreeMetricEleven.Sum().DataPoints() - smThreeMetricElevenDps.AppendEmpty().SetDoubleValue(3456.78) - smThreeMetricElevenDps.At(0).Attributes().PutStr("attribute_name_25", "attribute_value_25") - smThreeMetricElevenDps.AppendEmpty().SetDoubleValue(4567.89) - smThreeMetricElevenDps.At(1).Attributes().PutStr("attribute_name_26", "attribute_value_26") - - smThreeMetricTwelve := smThreeMetrics.AppendEmpty() - smThreeMetricTwelve.SetName("a_nonmonotonic_unspecified_double_sum") - smThreeMetricTwelve.SetDescription("a_nonmonotonic_unspecified_double_sum_description") - smThreeMetricTwelve.SetUnit("a_nonmonotonic_unspecified_double_sum_unit") - smThreeMetricTwelve.SetEmptySum() - smThreeMetricTwelve.Sum().SetIsMonotonic(false) - smThreeMetricTwelve.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityUnspecified) - smThreeMetricTwelveDps := smThreeMetricTwelve.Sum().DataPoints() - smThreeMetricTwelveDps.AppendEmpty().SetDoubleValue(5678.90) - smThreeMetricTwelveDps.At(0).Attributes().PutStr("attribute_name_27", "attribute_value_27") - smThreeMetricTwelveDps.AppendEmpty().SetDoubleValue(6789.01) - smThreeMetricTwelveDps.At(1).Attributes().PutStr("attribute_name_28", "attribute_value_28") - - smThreeMetricThirteen := smThreeMetrics.AppendEmpty() - smThreeMetricThirteen.SetName("a_summary") - smThreeMetricThirteen.SetDescription("a_summary_description") - smThreeMetricThirteen.SetUnit("a_summary_unit") - smThreeMetricThirteen.SetEmptySummary() - smThreeMetricThirteenDps := smThreeMetricThirteen.Summary().DataPoints() - smThreeMetricThirteenDpOne := smThreeMetricThirteenDps.AppendEmpty() - smThreeMetricThirteenDpOne.SetSum(1.2345) - smThreeMetricThirteenDpOne.SetCount(100) - smThreeMetricThirteenDpOne.Attributes().PutStr("attribute_name_29", "attribute_value_29") - - smThreeMetricFourteen := smThreeMetrics.AppendEmpty() - smThreeMetricFourteen.SetName("a_histogram") - smThreeMetricFourteen.SetDescription("a_histogram_description") - smThreeMetricFourteen.SetUnit("a_histogram_unit") - smThreeMetricFourteen.SetEmptyHistogram() - smThreeMetricFourteenDps := smThreeMetricFourteen.Histogram().DataPoints() - smThreeMetricFourteenDpOne := smThreeMetricFourteenDps.AppendEmpty() - smThreeMetricFourteenDpOne.SetSum(2.3456) - smThreeMetricFourteenDpOne.SetCount(200) - smThreeMetricFourteenDpOne.Attributes().PutStr("attribute_name_30", "attribute_value_30") - - smThreeMetricFifteen := smThreeMetrics.AppendEmpty() - smThreeMetricFifteen.SetName("an_exponential_histogram") - smThreeMetricFifteen.SetDescription("an_exponential_histogram_description") - smThreeMetricFifteen.SetUnit("an_exponential_histogram_unit") - smThreeMetricFifteen.SetEmptyExponentialHistogram() - smThreeMetricFifteenDps := smThreeMetricFifteen.ExponentialHistogram().DataPoints() - smThreeMetricFifteenDpOne := smThreeMetricFifteenDps.AppendEmpty() - smThreeMetricFifteenDpOne.SetSum(3.4567) - smThreeMetricFifteenDpOne.SetCount(300) - smThreeMetricFifteenDpOne.Attributes().PutStr("attribute_name_31", "attribute_value_31") - - return metrics -} diff --git a/tests/testutils/telemetry/pdata_metrics_test.go b/tests/testutils/telemetry/pdata_metrics_test.go deleted file mode 100644 index 91b216f610..0000000000 --- a/tests/testutils/telemetry/pdata_metrics_test.go +++ /dev/null @@ -1,304 +0,0 @@ -// Copyright Splunk, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build testutils - -package telemetry - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestPDataToResourceMetricsHappyPath(t *testing.T) { - resourceMetrics, err := PDataToResourceMetrics(PDataMetrics()) - assert.NoError(t, err) - require.NotNil(t, resourceMetrics) - - rms := resourceMetrics.ResourceMetrics - assert.Len(t, rms, 1) - rm := rms[0] - attrs := *rm.Resource.Attributes - assert.True(t, attrs["bool"].(bool)) - assert.Equal(t, "a_string", attrs["string"]) - assert.Equal(t, 123, attrs["int"]) - assert.Equal(t, 123.45, attrs["double"]) - assert.Nil(t, attrs["null"]) - - scopeMetrics := rm.ScopeMetrics - assert.Len(t, scopeMetrics, 3) - assert.Equal(t, "an_instrumentation_scope_name", scopeMetrics[0].Scope.Name) - assert.Equal(t, "an_instrumentation_scope_version", scopeMetrics[0].Scope.Version) - - require.Len(t, scopeMetrics[0].Metrics, 4) - - smOneMetricOne := scopeMetrics[0].Metrics[0] - assert.Equal(t, "an_int_gauge", smOneMetricOne.Name) - assert.Equal(t, "an_int_gauge_description", smOneMetricOne.Description) - assert.Equal(t, "an_int_gauge_unit", smOneMetricOne.Unit) - assert.Equal(t, IntGauge, smOneMetricOne.Type) - assert.Equal(t, map[string]any{"attribute_name_1": "attribute_value_1"}, *smOneMetricOne.Attributes) - assert.EqualValues(t, 12345, smOneMetricOne.Value) - - smOneMetricTwo := scopeMetrics[0].Metrics[1] - assert.Equal(t, "an_int_gauge", smOneMetricTwo.Name) - assert.Equal(t, "an_int_gauge_description", smOneMetricTwo.Description) - assert.Equal(t, "an_int_gauge_unit", smOneMetricTwo.Unit) - assert.Equal(t, IntGauge, smOneMetricTwo.Type) - assert.Equal(t, map[string]any{"attribute_name_2": "attribute_value_2"}, *smOneMetricTwo.Attributes) - assert.EqualValues(t, 23456, smOneMetricTwo.Value) - - smOneMetricThree := scopeMetrics[0].Metrics[2] - assert.Equal(t, "a_double_gauge", smOneMetricThree.Name) - assert.Equal(t, "a_double_gauge_description", smOneMetricThree.Description) - assert.Equal(t, "a_double_gauge_unit", smOneMetricThree.Unit) - assert.Equal(t, DoubleGauge, smOneMetricThree.Type) - assert.Equal(t, map[string]any{"attribute_name_3": "attribute_value_3"}, *smOneMetricThree.Attributes) - assert.EqualValues(t, 234.56, smOneMetricThree.Value) - - smOneMetricFour := scopeMetrics[0].Metrics[3] - assert.Equal(t, "a_double_gauge", smOneMetricFour.Name) - assert.Equal(t, "a_double_gauge_description", smOneMetricFour.Description) - assert.Equal(t, "a_double_gauge_unit", smOneMetricFour.Unit) - assert.Equal(t, DoubleGauge, smOneMetricFour.Type) - assert.Equal(t, map[string]any{"attribute_name_4": "attribute_value_4"}, *smOneMetricFour.Attributes) - assert.EqualValues(t, 345.67, smOneMetricFour.Value) - - assert.Equal(t, "an_instrumentation_scope_without_version_or_metrics", scopeMetrics[1].Scope.Name) - assert.Empty(t, scopeMetrics[1].Scope.Version) - assert.Empty(t, scopeMetrics[1].Metrics) - - require.Len(t, scopeMetrics[2].Metrics, 27) - - smThreeMetricOne := scopeMetrics[2].Metrics[0] - assert.Equal(t, "a_monotonic_cumulative_int_sum", smThreeMetricOne.Name) - assert.Equal(t, "a_monotonic_cumulative_int_sum_description", smThreeMetricOne.Description) - assert.Equal(t, "a_monotonic_cumulative_int_sum_unit", smThreeMetricOne.Unit) - assert.Equal(t, IntMonotonicCumulativeSum, smThreeMetricOne.Type) - assert.Equal(t, map[string]any{"attribute_name_5": "attribute_value_5"}, *smThreeMetricOne.Attributes) - assert.EqualValues(t, 34567, smThreeMetricOne.Value) - - smThreeMetricTwo := scopeMetrics[2].Metrics[1] - assert.Equal(t, "a_monotonic_cumulative_int_sum", smThreeMetricTwo.Name) - assert.Equal(t, "a_monotonic_cumulative_int_sum_description", smThreeMetricTwo.Description) - assert.Equal(t, "a_monotonic_cumulative_int_sum_unit", smThreeMetricTwo.Unit) - assert.Equal(t, IntMonotonicCumulativeSum, smThreeMetricTwo.Type) - assert.Equal(t, map[string]any{"attribute_name_6": "attribute_value_6"}, *smThreeMetricTwo.Attributes) - assert.EqualValues(t, 45678, smThreeMetricTwo.Value) - - smThreeMetricThree := scopeMetrics[2].Metrics[2] - assert.Equal(t, "a_monotonic_delta_int_sum", smThreeMetricThree.Name) - assert.Equal(t, "a_monotonic_delta_int_sum_description", smThreeMetricThree.Description) - assert.Equal(t, "a_monotonic_delta_int_sum_unit", smThreeMetricThree.Unit) - assert.Equal(t, IntMonotonicDeltaSum, smThreeMetricThree.Type) - assert.Equal(t, map[string]any{"attribute_name_7": "attribute_value_7"}, *smThreeMetricThree.Attributes) - assert.EqualValues(t, 56789, smThreeMetricThree.Value) - - smThreeMetricFour := scopeMetrics[2].Metrics[3] - assert.Equal(t, "a_monotonic_delta_int_sum", smThreeMetricFour.Name) - assert.Equal(t, "a_monotonic_delta_int_sum_description", smThreeMetricFour.Description) - assert.Equal(t, "a_monotonic_delta_int_sum_unit", smThreeMetricFour.Unit) - assert.Equal(t, IntMonotonicDeltaSum, smThreeMetricFour.Type) - assert.Equal(t, map[string]any{"attribute_name_8": "attribute_value_8"}, *smThreeMetricFour.Attributes) - assert.EqualValues(t, 67890, smThreeMetricFour.Value) - - smThreeMetricFive := scopeMetrics[2].Metrics[4] - assert.Equal(t, "a_monotonic_unspecified_int_sum", smThreeMetricFive.Name) - assert.Equal(t, "a_monotonic_unspecified_int_sum_description", smThreeMetricFive.Description) - assert.Equal(t, "a_monotonic_unspecified_int_sum_unit", smThreeMetricFive.Unit) - assert.Equal(t, IntMonotonicUnspecifiedSum, smThreeMetricFive.Type) - assert.Equal(t, map[string]any{"attribute_name_9": "attribute_value_9"}, *smThreeMetricFive.Attributes) - assert.EqualValues(t, 78901, smThreeMetricFive.Value) - - smThreeMetricSix := scopeMetrics[2].Metrics[5] - assert.Equal(t, "a_monotonic_unspecified_int_sum", smThreeMetricSix.Name) - assert.Equal(t, "a_monotonic_unspecified_int_sum_description", smThreeMetricSix.Description) - assert.Equal(t, "a_monotonic_unspecified_int_sum_unit", smThreeMetricSix.Unit) - assert.Equal(t, IntMonotonicUnspecifiedSum, smThreeMetricSix.Type) - assert.Equal(t, map[string]any{"attribute_name_10": "attribute_value_10"}, *smThreeMetricSix.Attributes) - assert.EqualValues(t, 89012, smThreeMetricSix.Value) - - smThreeMetricSeven := scopeMetrics[2].Metrics[6] - assert.Equal(t, "a_monotonic_cumulative_double_sum", smThreeMetricSeven.Name) - assert.Equal(t, "a_monotonic_cumulative_double_sum_description", smThreeMetricSeven.Description) - assert.Equal(t, "a_monotonic_cumulative_double_sum_unit", smThreeMetricSeven.Unit) - assert.Equal(t, DoubleMonotonicCumulativeSum, smThreeMetricSeven.Type) - assert.Equal(t, map[string]any{"attribute_name_11": "attribute_value_11"}, *smThreeMetricSeven.Attributes) - assert.EqualValues(t, 456.78, smThreeMetricSeven.Value) - - smThreeMetricEight := scopeMetrics[2].Metrics[7] - assert.Equal(t, "a_monotonic_cumulative_double_sum", smThreeMetricEight.Name) - assert.Equal(t, "a_monotonic_cumulative_double_sum_description", smThreeMetricEight.Description) - assert.Equal(t, "a_monotonic_cumulative_double_sum_unit", smThreeMetricEight.Unit) - assert.Equal(t, DoubleMonotonicCumulativeSum, smThreeMetricEight.Type) - assert.Equal(t, map[string]any{"attribute_name_12": "attribute_value_12"}, *smThreeMetricEight.Attributes) - assert.EqualValues(t, 567.89, smThreeMetricEight.Value) - - smThreeMetricNine := scopeMetrics[2].Metrics[8] - assert.Equal(t, "a_monotonic_delta_double_sum", smThreeMetricNine.Name) - assert.Equal(t, "a_monotonic_delta_double_sum_description", smThreeMetricNine.Description) - assert.Equal(t, "a_monotonic_delta_double_sum_unit", smThreeMetricNine.Unit) - assert.Equal(t, DoubleMonotonicDeltaSum, smThreeMetricNine.Type) - assert.Equal(t, map[string]any{"attribute_name_13": "attribute_value_13"}, *smThreeMetricNine.Attributes) - assert.EqualValues(t, 678.90, smThreeMetricNine.Value) - - smThreeMetricTen := scopeMetrics[2].Metrics[9] - assert.Equal(t, "a_monotonic_delta_double_sum", smThreeMetricTen.Name) - assert.Equal(t, "a_monotonic_delta_double_sum_description", smThreeMetricTen.Description) - assert.Equal(t, "a_monotonic_delta_double_sum_unit", smThreeMetricTen.Unit) - assert.Equal(t, DoubleMonotonicDeltaSum, smThreeMetricTen.Type) - assert.Equal(t, map[string]any{"attribute_name_14": "attribute_value_14"}, *smThreeMetricTen.Attributes) - assert.EqualValues(t, 789.01, smThreeMetricTen.Value) - - smThreeMetricEleven := scopeMetrics[2].Metrics[10] - assert.Equal(t, "a_monotonic_unspecified_double_sum", smThreeMetricEleven.Name) - assert.Equal(t, "a_monotonic_unspecified_double_sum_description", smThreeMetricEleven.Description) - assert.Equal(t, "a_monotonic_unspecified_double_sum_unit", smThreeMetricEleven.Unit) - assert.Equal(t, DoubleMonotonicUnspecifiedSum, smThreeMetricEleven.Type) - assert.Equal(t, map[string]any{"attribute_name_15": "attribute_value_15"}, *smThreeMetricEleven.Attributes) - assert.EqualValues(t, 890.12, smThreeMetricEleven.Value) - - smThreeMetricTwelve := scopeMetrics[2].Metrics[11] - assert.Equal(t, "a_monotonic_unspecified_double_sum", smThreeMetricTwelve.Name) - assert.Equal(t, "a_monotonic_unspecified_double_sum_description", smThreeMetricTwelve.Description) - assert.Equal(t, "a_monotonic_unspecified_double_sum_unit", smThreeMetricTwelve.Unit) - assert.Equal(t, DoubleMonotonicUnspecifiedSum, smThreeMetricTwelve.Type) - assert.Equal(t, map[string]any{"attribute_name_16": "attribute_value_16"}, *smThreeMetricTwelve.Attributes) - assert.EqualValues(t, 901.23, smThreeMetricTwelve.Value) - - smThreeMetricThirteen := scopeMetrics[2].Metrics[12] - assert.Equal(t, "a_nonmonotonic_cumulative_int_sum", smThreeMetricThirteen.Name) - assert.Equal(t, "a_nonmonotonic_cumulative_int_sum_description", smThreeMetricThirteen.Description) - assert.Equal(t, "a_nonmonotonic_cumulative_int_sum_unit", smThreeMetricThirteen.Unit) - assert.Equal(t, IntNonmonotonicCumulativeSum, smThreeMetricThirteen.Type) - assert.Equal(t, map[string]any{"attribute_name_17": "attribute_value_17"}, *smThreeMetricThirteen.Attributes) - assert.EqualValues(t, 90123, smThreeMetricThirteen.Value) - - smThreeMetricFourteen := scopeMetrics[2].Metrics[13] - assert.Equal(t, "a_nonmonotonic_cumulative_int_sum", smThreeMetricFourteen.Name) - assert.Equal(t, "a_nonmonotonic_cumulative_int_sum_description", smThreeMetricFourteen.Description) - assert.Equal(t, "a_nonmonotonic_cumulative_int_sum_unit", smThreeMetricFourteen.Unit) - assert.Equal(t, IntNonmonotonicCumulativeSum, smThreeMetricFourteen.Type) - assert.Equal(t, map[string]any{"attribute_name_18": "attribute_value_18"}, *smThreeMetricFourteen.Attributes) - assert.EqualValues(t, 123456, smThreeMetricFourteen.Value) - - smThreeMetricFifteen := scopeMetrics[2].Metrics[14] - assert.Equal(t, "a_nonmonotonic_delta_int_sum", smThreeMetricFifteen.Name) - assert.Equal(t, "a_nonmonotonic_delta_int_sum_description", smThreeMetricFifteen.Description) - assert.Equal(t, "a_nonmonotonic_delta_int_sum_unit", smThreeMetricFifteen.Unit) - assert.Equal(t, IntNonmonotonicDeltaSum, smThreeMetricFifteen.Type) - assert.Equal(t, map[string]any{"attribute_name_19": "attribute_value_19"}, *smThreeMetricFifteen.Attributes) - assert.EqualValues(t, 234567, smThreeMetricFifteen.Value) - - smThreeMetricSixteen := scopeMetrics[2].Metrics[15] - assert.Equal(t, "a_nonmonotonic_delta_int_sum", smThreeMetricSixteen.Name) - assert.Equal(t, "a_nonmonotonic_delta_int_sum_description", smThreeMetricSixteen.Description) - assert.Equal(t, "a_nonmonotonic_delta_int_sum_unit", smThreeMetricSixteen.Unit) - assert.Equal(t, IntNonmonotonicDeltaSum, smThreeMetricSixteen.Type) - assert.Equal(t, map[string]any{"attribute_name_20": "attribute_value_20"}, *smThreeMetricSixteen.Attributes) - assert.EqualValues(t, 345678, smThreeMetricSixteen.Value) - - smThreeMetricSeventeen := scopeMetrics[2].Metrics[16] - assert.Equal(t, "a_nonmonotonic_unspecified_int_sum", smThreeMetricSeventeen.Name) - assert.Equal(t, "a_nonmonotonic_unspecified_int_sum_description", smThreeMetricSeventeen.Description) - assert.Equal(t, "a_nonmonotonic_unspecified_int_sum_unit", smThreeMetricSeventeen.Unit) - assert.Equal(t, IntNonmonotonicUnspecifiedSum, smThreeMetricSeventeen.Type) - assert.Equal(t, map[string]any{"attribute_name_21": "attribute_value_21"}, *smThreeMetricSeventeen.Attributes) - assert.EqualValues(t, 456789, smThreeMetricSeventeen.Value) - - smThreeMetricEighteen := scopeMetrics[2].Metrics[17] - assert.Equal(t, "a_nonmonotonic_unspecified_int_sum", smThreeMetricEighteen.Name) - assert.Equal(t, "a_nonmonotonic_unspecified_int_sum_description", smThreeMetricEighteen.Description) - assert.Equal(t, "a_nonmonotonic_unspecified_int_sum_unit", smThreeMetricEighteen.Unit) - assert.Equal(t, IntNonmonotonicUnspecifiedSum, smThreeMetricEighteen.Type) - assert.Equal(t, map[string]any{"attribute_name_22": "attribute_value_22"}, *smThreeMetricEighteen.Attributes) - assert.EqualValues(t, 567890, smThreeMetricEighteen.Value) - - smThreeMetricNineteen := scopeMetrics[2].Metrics[18] - assert.Equal(t, "a_nonmonotonic_cumulative_double_sum", smThreeMetricNineteen.Name) - assert.Equal(t, "a_nonmonotonic_cumulative_double_sum_description", smThreeMetricNineteen.Description) - assert.Equal(t, "a_nonmonotonic_cumulative_double_sum_unit", smThreeMetricNineteen.Unit) - assert.Equal(t, DoubleNonmonotonicCumulativeSum, smThreeMetricNineteen.Type) - assert.Equal(t, map[string]any{"attribute_name_23": "attribute_value_23"}, *smThreeMetricNineteen.Attributes) - assert.EqualValues(t, 1234.56, smThreeMetricNineteen.Value) - - smThreeMetricTwenty := scopeMetrics[2].Metrics[19] - assert.Equal(t, "a_nonmonotonic_cumulative_double_sum", smThreeMetricTwenty.Name) - assert.Equal(t, "a_nonmonotonic_cumulative_double_sum_description", smThreeMetricTwenty.Description) - assert.Equal(t, "a_nonmonotonic_cumulative_double_sum_unit", smThreeMetricTwenty.Unit) - assert.Equal(t, DoubleNonmonotonicCumulativeSum, smThreeMetricTwenty.Type) - assert.Equal(t, map[string]any{"attribute_name_24": "attribute_value_24"}, *smThreeMetricTwenty.Attributes) - assert.EqualValues(t, 2345.67, smThreeMetricTwenty.Value) - - smThreeMetricTwentyOne := scopeMetrics[2].Metrics[20] - assert.Equal(t, "a_nonmonotonic_delta_double_sum", smThreeMetricTwentyOne.Name) - assert.Equal(t, "a_nonmonotonic_delta_double_sum_description", smThreeMetricTwentyOne.Description) - assert.Equal(t, "a_nonmonotonic_delta_double_sum_unit", smThreeMetricTwentyOne.Unit) - assert.Equal(t, DoubleNonmonotonicDeltaSum, smThreeMetricTwentyOne.Type) - assert.Equal(t, map[string]any{"attribute_name_25": "attribute_value_25"}, *smThreeMetricTwentyOne.Attributes) - assert.EqualValues(t, 3456.78, smThreeMetricTwentyOne.Value) - - smThreeMetricTwentyTwo := scopeMetrics[2].Metrics[21] - assert.Equal(t, "a_nonmonotonic_delta_double_sum", smThreeMetricTwentyTwo.Name) - assert.Equal(t, "a_nonmonotonic_delta_double_sum_description", smThreeMetricTwentyTwo.Description) - assert.Equal(t, "a_nonmonotonic_delta_double_sum_unit", smThreeMetricTwentyTwo.Unit) - assert.Equal(t, DoubleNonmonotonicDeltaSum, smThreeMetricTwentyTwo.Type) - assert.Equal(t, map[string]any{"attribute_name_26": "attribute_value_26"}, *smThreeMetricTwentyTwo.Attributes) - assert.EqualValues(t, 4567.89, smThreeMetricTwentyTwo.Value) - - smThreeMetricTwentyThree := scopeMetrics[2].Metrics[22] - assert.Equal(t, "a_nonmonotonic_unspecified_double_sum", smThreeMetricTwentyThree.Name) - assert.Equal(t, "a_nonmonotonic_unspecified_double_sum_description", smThreeMetricTwentyThree.Description) - assert.Equal(t, "a_nonmonotonic_unspecified_double_sum_unit", smThreeMetricTwentyThree.Unit) - assert.Equal(t, DoubleNonmonotonicUnspecifiedSum, smThreeMetricTwentyThree.Type) - assert.Equal(t, map[string]any{"attribute_name_27": "attribute_value_27"}, *smThreeMetricTwentyThree.Attributes) - assert.EqualValues(t, 5678.90, smThreeMetricTwentyThree.Value) - - smThreeMetricTwentyFour := scopeMetrics[2].Metrics[23] - assert.Equal(t, "a_nonmonotonic_unspecified_double_sum", smThreeMetricTwentyFour.Name) - assert.Equal(t, "a_nonmonotonic_unspecified_double_sum_description", smThreeMetricTwentyFour.Description) - assert.Equal(t, "a_nonmonotonic_unspecified_double_sum_unit", smThreeMetricTwentyFour.Unit) - assert.Equal(t, DoubleNonmonotonicUnspecifiedSum, smThreeMetricTwentyFour.Type) - assert.Equal(t, map[string]any{"attribute_name_28": "attribute_value_28"}, *smThreeMetricTwentyFour.Attributes) - assert.EqualValues(t, 6789.01, smThreeMetricTwentyFour.Value) - - smThreeMetricTwentyFive := scopeMetrics[2].Metrics[24] - assert.Equal(t, "a_summary", smThreeMetricTwentyFive.Name) - assert.Equal(t, "a_summary_description", smThreeMetricTwentyFive.Description) - assert.Equal(t, "a_summary_unit", smThreeMetricTwentyFive.Unit) - assert.Equal(t, Summary, smThreeMetricTwentyFive.Type) - assert.Equal(t, map[string]any{"attribute_name_29": "attribute_value_29"}, *smThreeMetricTwentyFive.Attributes) - assert.EqualValues(t, 1.2345, smThreeMetricTwentyFive.Sum) - assert.EqualValues(t, 100, smThreeMetricTwentyFive.Count) - - smThreeMetricTwentySix := scopeMetrics[2].Metrics[25] - assert.Equal(t, "a_histogram", smThreeMetricTwentySix.Name) - assert.Equal(t, "a_histogram_description", smThreeMetricTwentySix.Description) - assert.Equal(t, "a_histogram_unit", smThreeMetricTwentySix.Unit) - assert.Equal(t, Histogram, smThreeMetricTwentySix.Type) - assert.Equal(t, map[string]any{"attribute_name_30": "attribute_value_30"}, *smThreeMetricTwentySix.Attributes) - assert.EqualValues(t, 2.3456, smThreeMetricTwentySix.Sum) - assert.EqualValues(t, 200, smThreeMetricTwentySix.Count) - - smThreeMetricTwentySeven := scopeMetrics[2].Metrics[26] - assert.Equal(t, "an_exponential_histogram", smThreeMetricTwentySeven.Name) - assert.Equal(t, "an_exponential_histogram_description", smThreeMetricTwentySeven.Description) - assert.Equal(t, "an_exponential_histogram_unit", smThreeMetricTwentySeven.Unit) - assert.Equal(t, ExponentialHistogram, smThreeMetricTwentySeven.Type) - assert.Equal(t, map[string]any{"attribute_name_31": "attribute_value_31"}, *smThreeMetricTwentySeven.Attributes) - assert.EqualValues(t, 3.4567, smThreeMetricTwentySeven.Sum) - assert.EqualValues(t, 300, smThreeMetricTwentySeven.Count) -} diff --git a/tests/testutils/telemetry/testdata/common/attributes.yaml b/tests/testutils/telemetry/testdata/common/attributes.yaml deleted file mode 100644 index d240cc0add..0000000000 --- a/tests/testutils/telemetry/testdata/common/attributes.yaml +++ /dev/null @@ -1,8 +0,0 @@ -int: 1 -float: 1.234 -string: | - a - long - string -bool: false -empty: null \ No newline at end of file diff --git a/tests/testutils/telemetry/testdata/metrics/attribute-value-resource-metrics.yaml b/tests/testutils/telemetry/testdata/metrics/attribute-value-resource-metrics.yaml deleted file mode 100644 index 0e2313a37d..0000000000 --- a/tests/testutils/telemetry/testdata/metrics/attribute-value-resource-metrics.yaml +++ /dev/null @@ -1,9 +0,0 @@ -resource_metrics: - - scope_metrics: - - metrics: - - name: another_int_gauge - type: IntGauge - attributes: - attribute_one: value_one - attribute_two: value_two - value: 111 diff --git a/tests/testutils/telemetry/testdata/metrics/empty-attributes-required.yaml b/tests/testutils/telemetry/testdata/metrics/empty-attributes-required.yaml deleted file mode 100644 index f458a01850..0000000000 --- a/tests/testutils/telemetry/testdata/metrics/empty-attributes-required.yaml +++ /dev/null @@ -1,7 +0,0 @@ -resource_metrics: - - scope_metrics: - - metrics: - - name: another_int_gauge - type: IntGauge - attributes: {} - value: 111 diff --git a/tests/testutils/telemetry/testdata/metrics/expected-metrics.yaml b/tests/testutils/telemetry/testdata/metrics/expected-metrics.yaml deleted file mode 100644 index 8259235e31..0000000000 --- a/tests/testutils/telemetry/testdata/metrics/expected-metrics.yaml +++ /dev/null @@ -1,17 +0,0 @@ -resource_metrics: - - scope_metrics: - - instrumentation_scope: - name: with_metrics - version: another_version - metrics: - - attributes: - metric_attr_a: one_value - metric_attr_b: - metric_attr_c: - metric_attr_d: - nested_attr_a: - nested_attr_b: - name: another_int_gauge - type: IntGauge - - name: another_double_gauge - type: DoubleGauge diff --git a/tests/testutils/telemetry/testdata/metrics/invalid-metric-type.yaml b/tests/testutils/telemetry/testdata/metrics/invalid-metric-type.yaml deleted file mode 100644 index 22eea6598b..0000000000 --- a/tests/testutils/telemetry/testdata/metrics/invalid-metric-type.yaml +++ /dev/null @@ -1,5 +0,0 @@ -resource_metrics: - - scope_metrics: - - metrics: - - name: of_an_unsupported_type - type: NotASupportedType diff --git a/tests/testutils/telemetry/testdata/metrics/invalid-resource-metrics.yaml b/tests/testutils/telemetry/testdata/metrics/invalid-resource-metrics.yaml deleted file mode 100644 index 7d97630fed..0000000000 --- a/tests/testutils/telemetry/testdata/metrics/invalid-resource-metrics.yaml +++ /dev/null @@ -1,3 +0,0 @@ -resource_metrics: - - notAttributesOrScopeMetrics: - - thing: value diff --git a/tests/testutils/telemetry/testdata/metrics/never-received-instrumentation-scope.yaml b/tests/testutils/telemetry/testdata/metrics/never-received-instrumentation-scope.yaml deleted file mode 100644 index 0d8a63ecd8..0000000000 --- a/tests/testutils/telemetry/testdata/metrics/never-received-instrumentation-scope.yaml +++ /dev/null @@ -1,12 +0,0 @@ -resource_metrics: - - scope_metrics: - - instrumentation_scope: - name: with_metrics - version: another_version - metrics: - - name: another_int_gauge - type: IntGauge - - name: another_double_gauge - type: DoubleGauge - - instrumentation_scope: - name: unmatched_instrumentation_scope diff --git a/tests/testutils/telemetry/testdata/metrics/never-received-metrics.yaml b/tests/testutils/telemetry/testdata/metrics/never-received-metrics.yaml deleted file mode 100644 index 3e35f10198..0000000000 --- a/tests/testutils/telemetry/testdata/metrics/never-received-metrics.yaml +++ /dev/null @@ -1,11 +0,0 @@ -resource_metrics: - - scope_metrics: - - instrumentation_scope: - name: with_metrics - version: another_version - metrics: - - name: another_int_gauge - type: IntGauge - value: 111 - - name: another_double_gauge - type: DoubleGauge diff --git a/tests/testutils/telemetry/testdata/metrics/never-received-resource.yaml b/tests/testutils/telemetry/testdata/metrics/never-received-resource.yaml deleted file mode 100644 index 279a939e4c..0000000000 --- a/tests/testutils/telemetry/testdata/metrics/never-received-resource.yaml +++ /dev/null @@ -1,12 +0,0 @@ -resource_metrics: - - attributes: - not: matched - - scope_metrics: - - instrumentation_scope: - name: with_metrics - version: another_version - metrics: - - name: another_int_gauge - type: IntGauge - - name: another_double_gauge - type: DoubleGauge diff --git a/tests/testutils/telemetry/testdata/metrics/resource-metrics.yaml b/tests/testutils/telemetry/testdata/metrics/resource-metrics.yaml deleted file mode 100644 index d53fa9c8db..0000000000 --- a/tests/testutils/telemetry/testdata/metrics/resource-metrics.yaml +++ /dev/null @@ -1,37 +0,0 @@ -resource_metrics: - - attributes: - one_attr: one_value - two_attr: - nested_attr_a: one_nested_value - nested_attr_b: two_nested_value - scope_metrics: - - instrumentation_scope: - name: without_metrics - version: some_version - - metrics: - - description: an_int_gauge_description - name: an_int_gauge - type: IntGauge - unit: an_int_gauge_unit - value: 123 - - name: a_double_gauge - type: DoubleGauge - value: 123.456 - - scope_metrics: - - instrumentation_scope: - name: with_metrics - version: another_version - metrics: - - attributes: - metric_attr_a: one_value - metric_attr_b: this should match an RE2 directive - metric_attr_c: this should match an ANY directive - metric_attr_d: - nested_attr_a: 123 - nested_attr_b: this should match yet another RE2 directive - name: another_int_gauge - type: IntGauge - value: 456 - - name: another_double_gauge - type: DoubleGauge - value: 567.89 diff --git a/tests/testutils/telemetry/testdata/metrics/unspecified-attributes-allowed.yaml b/tests/testutils/telemetry/testdata/metrics/unspecified-attributes-allowed.yaml deleted file mode 100644 index d205e467d7..0000000000 --- a/tests/testutils/telemetry/testdata/metrics/unspecified-attributes-allowed.yaml +++ /dev/null @@ -1,6 +0,0 @@ -resource_metrics: - - scope_metrics: - - metrics: - - name: another_int_gauge - type: IntGauge - value: 111 diff --git a/tests/testutils/testcase.go b/tests/testutils/testcase.go index 1aa9f0bbd4..91e0a740c3 100644 --- a/tests/testutils/testcase.go +++ b/tests/testutils/testcase.go @@ -17,19 +17,17 @@ package testutils import ( "context" "fmt" - "os" - "path" - "runtime" - "strings" - "testing" - "time" - "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.uber.org/zap" "go.uber.org/zap/zapcore" "go.uber.org/zap/zaptest/observer" + "os" + "path" + "runtime" + "strings" + "testing" "github.com/signalfx/splunk-otel-collector/tests/testutils/telemetry" ) @@ -199,26 +197,3 @@ func (t *Testcase) PrintLogsOnFailure() { func (t *Testcase) ShutdownOTLPReceiverSink() { require.NoError(t, t.OTLPReceiverSink.Shutdown()) } - -// AssertAllMetricsReceived is a central helper, designed to avoid most boilerplate. Using the desired -// ResourceMetrics and Collector Config filenames, a slice of Container builders, and a slice of CollectorBuilder -// AssertAllMetricsReceived creates a Testcase, builds and starts all Container and CollectorBuilder-determined Collector -// instances, and asserts that all expected ResourceMetrics are received before running validated cleanup functionality. -func AssertAllMetricsReceived( - t testing.TB, resourceMetricsFilename, collectorConfigFilename string, - containers []Container, builders []CollectorBuilder, -) { - tc := NewTestcase(t) - defer tc.PrintLogsOnFailure() - defer tc.ShutdownOTLPReceiverSink() - - expectedResourceMetrics := tc.ResourceMetrics(resourceMetricsFilename) - - _, stop := tc.Containers(containers...) - defer stop() - - _, shutdown := tc.SplunkOtelCollector(collectorConfigFilename, builders...) - defer shutdown() - - require.NoError(t, tc.OTLPReceiverSink.AssertAllMetricsReceived(t, *expectedResourceMetrics, 30*time.Second)) -} diff --git a/tests/testutils/testdata/collector_process_config.yaml b/tests/testutils/testdata/collector_process_config.yaml deleted file mode 100644 index 5c7eb2a427..0000000000 --- a/tests/testutils/testdata/collector_process_config.yaml +++ /dev/null @@ -1,17 +0,0 @@ -receivers: - hostmetrics: - collection_interval: 1s - scrapers: - memory: - -exporters: - otlp: - endpoint: "${OTLP_ENDPOINT}" - tls: - insecure: true - -service: - pipelines: - metrics: - receivers: [hostmetrics] - exporters: [otlp] diff --git a/tests/testutils/testdata/expected_host_metrics.yaml b/tests/testutils/testdata/expected_host_metrics.yaml deleted file mode 100644 index ef4f48a715..0000000000 --- a/tests/testutils/testdata/expected_host_metrics.yaml +++ /dev/null @@ -1,10 +0,0 @@ -resource_metrics: - - scope_metrics: - - instrumentation_scope: - name: github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal/scraper/memoryscraper - version: - metrics: - - name: system.memory.usage - type: IntNonmonotonicCumulativeSum - attributes: - state: used