diff --git a/.golangci.yml b/.golangci.yml index 28bfb9ead30a..8951500c9f83 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -134,6 +134,15 @@ linters-settings: - suite-subtest-run - encoded-compare # has false positives that cannot be fixed with testifylint-fix enable-all: true + thelper: + test: + begin: false + benchmark: + begin: false + tb: + begin: false + fuzz: + begin: false linters: enable: @@ -156,6 +165,7 @@ linters: - staticcheck - tenv - testifylint + - thelper - unconvert - unparam - unused diff --git a/connector/exceptionsconnector/connector_metrics_test.go b/connector/exceptionsconnector/connector_metrics_test.go index 98b12aec7149..ef0b350a761c 100644 --- a/connector/exceptionsconnector/connector_metrics_test.go +++ b/connector/exceptionsconnector/connector_metrics_test.go @@ -45,7 +45,7 @@ func TestConnectorConsumeTraces(t *testing.T) { testcases := []struct { name string - verifier func(t testing.TB, input pmetric.Metrics) bool + verifier func(tb testing.TB, input pmetric.Metrics) bool traces []ptrace.Traces }{ { @@ -153,8 +153,8 @@ func newTestMetricsConnector(mcon consumer.Metrics, defaultNullValue *string, lo } // verifyConsumeMetricsInputCumulative expects one accumulation of metrics, and marked as cumulative -func verifyConsumeMetricsInputCumulative(t testing.TB, input pmetric.Metrics) bool { - return verifyConsumeMetricsInput(t, input, 1) +func verifyConsumeMetricsInputCumulative(tb testing.TB, input pmetric.Metrics) bool { + return verifyConsumeMetricsInput(tb, input, 1) } func verifyBadMetricsOkay(_ testing.TB, _ pmetric.Metrics) bool { @@ -163,52 +163,52 @@ func verifyBadMetricsOkay(_ testing.TB, _ pmetric.Metrics) bool { // verifyMultipleCumulativeConsumptions expects the amount of accumulations as kept track of by numCumulativeConsumptions. // numCumulativeConsumptions acts as a multiplier for the values, since the cumulative metrics are additive. -func verifyMultipleCumulativeConsumptions() func(t testing.TB, input pmetric.Metrics) bool { +func verifyMultipleCumulativeConsumptions() func(tb testing.TB, input pmetric.Metrics) bool { numCumulativeConsumptions := 0 - return func(t testing.TB, input pmetric.Metrics) bool { + return func(tb testing.TB, input pmetric.Metrics) bool { numCumulativeConsumptions++ - return verifyConsumeMetricsInput(t, input, numCumulativeConsumptions) + return verifyConsumeMetricsInput(tb, input, numCumulativeConsumptions) } } // verifyConsumeMetricsInput verifies the input of the ConsumeMetrics call from this connector. // This is the best point to verify the computed metrics from spans are as expected. -func verifyConsumeMetricsInput(t testing.TB, input pmetric.Metrics, numCumulativeConsumptions int) bool { - require.Equal(t, 3, input.DataPointCount(), "Should be 1 for each generated span") +func verifyConsumeMetricsInput(tb testing.TB, input pmetric.Metrics, numCumulativeConsumptions int) bool { + require.Equal(tb, 3, input.DataPointCount(), "Should be 1 for each generated span") rm := input.ResourceMetrics() - require.Equal(t, 1, rm.Len()) + require.Equal(tb, 1, rm.Len()) ilm := rm.At(0).ScopeMetrics() - require.Equal(t, 1, ilm.Len()) - assert.Equal(t, "exceptionsconnector", ilm.At(0).Scope().Name()) + require.Equal(tb, 1, ilm.Len()) + assert.Equal(tb, "exceptionsconnector", ilm.At(0).Scope().Name()) m := ilm.At(0).Metrics() - require.Equal(t, 1, m.Len()) + require.Equal(tb, 1, m.Len()) seenMetricIDs := make(map[metricID]bool) // The first 3 data points are for call counts. - assert.Equal(t, "exceptions", m.At(0).Name()) - assert.True(t, m.At(0).Sum().IsMonotonic()) + assert.Equal(tb, "exceptions", m.At(0).Name()) + assert.True(tb, m.At(0).Sum().IsMonotonic()) callsDps := m.At(0).Sum().DataPoints() - require.Equal(t, 3, callsDps.Len()) + require.Equal(tb, 3, callsDps.Len()) for dpi := 0; dpi < 3; dpi++ { dp := callsDps.At(dpi) - assert.Equal(t, int64(numCumulativeConsumptions), dp.IntValue(), "There should only be one metric per Service/kind combination") - assert.NotZero(t, dp.StartTimestamp(), "StartTimestamp should be set") - assert.NotZero(t, dp.Timestamp(), "Timestamp should be set") - verifyMetricLabels(dp, t, seenMetricIDs) + assert.Equal(tb, int64(numCumulativeConsumptions), dp.IntValue(), "There should only be one metric per Service/kind combination") + assert.NotZero(tb, dp.StartTimestamp(), "StartTimestamp should be set") + assert.NotZero(tb, dp.Timestamp(), "Timestamp should be set") + verifyMetricLabels(tb, dp, seenMetricIDs) - assert.Equal(t, 1, dp.Exemplars().Len()) + assert.Equal(tb, 1, dp.Exemplars().Len()) exemplar := dp.Exemplars().At(0) - assert.NotZero(t, exemplar.Timestamp()) - assert.NotZero(t, exemplar.TraceID()) - assert.NotZero(t, exemplar.SpanID()) + assert.NotZero(tb, exemplar.Timestamp()) + assert.NotZero(tb, exemplar.TraceID()) + assert.NotZero(tb, exemplar.SpanID()) } return true } -func verifyMetricLabels(dp metricDataPoint, t testing.TB, seenMetricIDs map[metricID]bool) { +func verifyMetricLabels(tb testing.TB, dp metricDataPoint, seenMetricIDs map[metricID]bool) { mID := metricID{} wantDimensions := map[string]pcommon.Value{ stringAttrName: pcommon.NewValueStr("stringAttrValue"), @@ -233,17 +233,17 @@ func verifyMetricLabels(dp metricDataPoint, t testing.TB, seenMetricIDs map[metr case statusCodeKey: mID.statusCode = v.Str() case notInSpanAttrName1: - assert.Fail(t, notInSpanAttrName1+" should not be in this metric") + assert.Fail(tb, notInSpanAttrName1+" should not be in this metric") default: - assert.Equal(t, wantDimensions[k], v) + assert.Equal(tb, wantDimensions[k], v) delete(wantDimensions, k) } return true }) - assert.Empty(t, wantDimensions, "Did not see all expected dimensions in metric. Missing: ", wantDimensions) + assert.Empty(tb, wantDimensions, "Did not see all expected dimensions in metric. Missing: ", wantDimensions) // Service/kind should be a unique metric. - assert.False(t, seenMetricIDs[mID]) + assert.False(tb, seenMetricIDs[mID]) seenMetricIDs[mID] = true } diff --git a/connector/spanmetricsconnector/connector_test.go b/connector/spanmetricsconnector/connector_test.go index 5bd74c85f65a..a17e7d6bf605 100644 --- a/connector/spanmetricsconnector/connector_test.go +++ b/connector/spanmetricsconnector/connector_test.go @@ -78,7 +78,7 @@ type span struct { } // verifyDisabledHistogram expects that histograms are disabled. -func verifyDisabledHistogram(t testing.TB, input pmetric.Metrics) bool { +func verifyDisabledHistogram(tb testing.TB, input pmetric.Metrics) bool { for i := 0; i < input.ResourceMetrics().Len(); i++ { rm := input.ResourceMetrics().At(i) ism := rm.ScopeMetrics() @@ -87,15 +87,15 @@ func verifyDisabledHistogram(t testing.TB, input pmetric.Metrics) bool { m := ism.At(ismC).Metrics() for mC := 0; mC < m.Len(); mC++ { metric := m.At(mC) - assert.NotEqual(t, pmetric.MetricTypeExponentialHistogram, metric.Type()) - assert.NotEqual(t, pmetric.MetricTypeHistogram, metric.Type()) + assert.NotEqual(tb, pmetric.MetricTypeExponentialHistogram, metric.Type()) + assert.NotEqual(tb, pmetric.MetricTypeHistogram, metric.Type()) } } } return true } -func verifyExemplarsExist(t testing.TB, input pmetric.Metrics) bool { +func verifyExemplarsExist(tb testing.TB, input pmetric.Metrics) bool { for i := 0; i < input.ResourceMetrics().Len(); i++ { rm := input.ResourceMetrics().At(i) ism := rm.ScopeMetrics() @@ -113,7 +113,7 @@ func verifyExemplarsExist(t testing.TB, input pmetric.Metrics) bool { dps := metric.Histogram().DataPoints() for dp := 0; dp < dps.Len(); dp++ { d := dps.At(dp) - assert.Positive(t, d.Exemplars().Len()) + assert.Positive(tb, d.Exemplars().Len()) } } } @@ -122,8 +122,8 @@ func verifyExemplarsExist(t testing.TB, input pmetric.Metrics) bool { } // verifyConsumeMetricsInputCumulative expects one accumulation of metrics, and marked as cumulative -func verifyConsumeMetricsInputCumulative(t testing.TB, input pmetric.Metrics) bool { - return verifyConsumeMetricsInput(t, input, pmetric.AggregationTemporalityCumulative, 1) +func verifyConsumeMetricsInputCumulative(tb testing.TB, input pmetric.Metrics) bool { + return verifyConsumeMetricsInput(tb, input, pmetric.AggregationTemporalityCumulative, 1) } func verifyBadMetricsOkay(_ testing.TB, _ pmetric.Metrics) bool { @@ -131,37 +131,37 @@ func verifyBadMetricsOkay(_ testing.TB, _ pmetric.Metrics) bool { } // verifyConsumeMetricsInputDelta expects one accumulation of metrics, and marked as delta -func verifyConsumeMetricsInputDelta(t testing.TB, input pmetric.Metrics) bool { - return verifyConsumeMetricsInput(t, input, pmetric.AggregationTemporalityDelta, 1) +func verifyConsumeMetricsInputDelta(tb testing.TB, input pmetric.Metrics) bool { + return verifyConsumeMetricsInput(tb, input, pmetric.AggregationTemporalityDelta, 1) } // verifyMultipleCumulativeConsumptions expects the amount of accumulations as kept track of by numCumulativeConsumptions. // numCumulativeConsumptions acts as a multiplier for the values, since the cumulative metrics are additive. -func verifyMultipleCumulativeConsumptions() func(t testing.TB, input pmetric.Metrics) bool { +func verifyMultipleCumulativeConsumptions() func(tb testing.TB, input pmetric.Metrics) bool { numCumulativeConsumptions := 0 - return func(t testing.TB, input pmetric.Metrics) bool { + return func(tb testing.TB, input pmetric.Metrics) bool { numCumulativeConsumptions++ - return verifyConsumeMetricsInput(t, input, pmetric.AggregationTemporalityCumulative, numCumulativeConsumptions) + return verifyConsumeMetricsInput(tb, input, pmetric.AggregationTemporalityCumulative, numCumulativeConsumptions) } } // verifyConsumeMetricsInput verifies the input of the ConsumeMetrics call from this connector. // This is the best point to verify the computed metrics from spans are as expected. -func verifyConsumeMetricsInput(t testing.TB, input pmetric.Metrics, expectedTemporality pmetric.AggregationTemporality, numCumulativeConsumptions int) bool { - require.Equal(t, 6, input.DataPointCount(), +func verifyConsumeMetricsInput(tb testing.TB, input pmetric.Metrics, expectedTemporality pmetric.AggregationTemporality, numCumulativeConsumptions int) bool { + require.Equal(tb, 6, input.DataPointCount(), "Should be 3 for each of call count and latency split into two resource scopes defined by: "+ "service-a: service-a (server kind) -> service-a (client kind) and "+ "service-b: service-b (service kind)", ) - require.Equal(t, 2, input.ResourceMetrics().Len()) + require.Equal(tb, 2, input.ResourceMetrics().Len()) for i := 0; i < input.ResourceMetrics().Len(); i++ { rm := input.ResourceMetrics().At(i) var numDataPoints int val, ok := rm.Resource().Attributes().Get(serviceNameKey) - require.True(t, ok) + require.True(tb, ok) serviceName := val.AsString() if serviceName == "service-a" { numDataPoints = 2 @@ -170,68 +170,68 @@ func verifyConsumeMetricsInput(t testing.TB, input pmetric.Metrics, expectedTemp } ilm := rm.ScopeMetrics() - require.Equal(t, 1, ilm.Len()) - assert.Equal(t, "spanmetricsconnector", ilm.At(0).Scope().Name()) + require.Equal(tb, 1, ilm.Len()) + assert.Equal(tb, "spanmetricsconnector", ilm.At(0).Scope().Name()) m := ilm.At(0).Metrics() - require.Equal(t, 2, m.Len(), "only sum and histogram metric types generated") + require.Equal(tb, 2, m.Len(), "only sum and histogram metric types generated") // validate calls - sum metrics metric := m.At(0) - assert.Equal(t, metricNameCalls, metric.Name()) - assert.Equal(t, expectedTemporality, metric.Sum().AggregationTemporality()) - assert.True(t, metric.Sum().IsMonotonic()) + assert.Equal(tb, metricNameCalls, metric.Name()) + assert.Equal(tb, expectedTemporality, metric.Sum().AggregationTemporality()) + assert.True(tb, metric.Sum().IsMonotonic()) seenMetricIDs := make(map[metricID]bool) callsDps := metric.Sum().DataPoints() - require.Equal(t, numDataPoints, callsDps.Len()) + require.Equal(tb, numDataPoints, callsDps.Len()) for dpi := 0; dpi < numDataPoints; dpi++ { dp := callsDps.At(dpi) - assert.Equal(t, + assert.Equal(tb, int64(numCumulativeConsumptions), dp.IntValue(), "There should only be one metric per Service/name/kind combination", ) - assert.NotZero(t, dp.StartTimestamp(), "StartTimestamp should be set") - assert.NotZero(t, dp.Timestamp(), "Timestamp should be set") - verifyMetricLabels(dp, t, seenMetricIDs) + assert.NotZero(tb, dp.StartTimestamp(), "StartTimestamp should be set") + assert.NotZero(tb, dp.Timestamp(), "Timestamp should be set") + verifyMetricLabels(tb, dp, seenMetricIDs) } // validate latency - histogram metrics metric = m.At(1) - assert.Equal(t, metricNameDuration, metric.Name()) - assert.Equal(t, defaultUnit.String(), metric.Unit()) + assert.Equal(tb, metricNameDuration, metric.Name()) + assert.Equal(tb, defaultUnit.String(), metric.Unit()) if metric.Type() == pmetric.MetricTypeExponentialHistogram { hist := metric.ExponentialHistogram() - assert.Equal(t, expectedTemporality, hist.AggregationTemporality()) - verifyExponentialHistogramDataPoints(t, hist.DataPoints(), numDataPoints, numCumulativeConsumptions) + assert.Equal(tb, expectedTemporality, hist.AggregationTemporality()) + verifyExponentialHistogramDataPoints(tb, hist.DataPoints(), numDataPoints, numCumulativeConsumptions) } else { hist := metric.Histogram() - assert.Equal(t, expectedTemporality, hist.AggregationTemporality()) - verifyExplicitHistogramDataPoints(t, hist.DataPoints(), numDataPoints, numCumulativeConsumptions) + assert.Equal(tb, expectedTemporality, hist.AggregationTemporality()) + verifyExplicitHistogramDataPoints(tb, hist.DataPoints(), numDataPoints, numCumulativeConsumptions) } } return true } -func verifyExplicitHistogramDataPoints(t testing.TB, dps pmetric.HistogramDataPointSlice, numDataPoints, numCumulativeConsumptions int) { +func verifyExplicitHistogramDataPoints(tb testing.TB, dps pmetric.HistogramDataPointSlice, numDataPoints, numCumulativeConsumptions int) { seenMetricIDs := make(map[metricID]bool) - require.Equal(t, numDataPoints, dps.Len()) + require.Equal(tb, numDataPoints, dps.Len()) for dpi := 0; dpi < numDataPoints; dpi++ { dp := dps.At(dpi) assert.Equal( - t, + tb, sampleDuration*float64(numCumulativeConsumptions), dp.Sum(), "Should be a 11ms duration measurement, multiplied by the number of stateful accumulations.") - assert.NotZero(t, dp.Timestamp(), "Timestamp should be set") + assert.NotZero(tb, dp.Timestamp(), "Timestamp should be set") // Verify bucket counts. // The bucket counts should be 1 greater than the explicit bounds as documented in: // https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/metrics/v1/metrics.proto. - assert.Equal(t, dp.ExplicitBounds().Len()+1, dp.BucketCounts().Len()) + assert.Equal(tb, dp.ExplicitBounds().Len()+1, dp.BucketCounts().Len()) // Find the bucket index where the 11ms duration should belong in. var foundDurationIndex int @@ -248,31 +248,31 @@ func verifyExplicitHistogramDataPoints(t testing.TB, dps pmetric.HistogramDataPo if bi == foundDurationIndex { wantBucketCount = uint64(numCumulativeConsumptions) } - assert.Equal(t, wantBucketCount, dp.BucketCounts().At(bi)) + assert.Equal(tb, wantBucketCount, dp.BucketCounts().At(bi)) } - verifyMetricLabels(dp, t, seenMetricIDs) + verifyMetricLabels(tb, dp, seenMetricIDs) } } -func verifyExponentialHistogramDataPoints(t testing.TB, dps pmetric.ExponentialHistogramDataPointSlice, numDataPoints, numCumulativeConsumptions int) { +func verifyExponentialHistogramDataPoints(tb testing.TB, dps pmetric.ExponentialHistogramDataPointSlice, numDataPoints, numCumulativeConsumptions int) { seenMetricIDs := make(map[metricID]bool) - require.Equal(t, numDataPoints, dps.Len()) + require.Equal(tb, numDataPoints, dps.Len()) for dpi := 0; dpi < numDataPoints; dpi++ { dp := dps.At(dpi) assert.Equal( - t, + tb, sampleDuration*float64(numCumulativeConsumptions), dp.Sum(), "Should be a 11ms duration measurement, multiplied by the number of stateful accumulations.") - assert.Equal(t, uint64(numCumulativeConsumptions), dp.Count()) - assert.Equal(t, []uint64{uint64(numCumulativeConsumptions)}, dp.Positive().BucketCounts().AsRaw()) - assert.NotZero(t, dp.Timestamp(), "Timestamp should be set") + assert.Equal(tb, uint64(numCumulativeConsumptions), dp.Count()) + assert.Equal(tb, []uint64{uint64(numCumulativeConsumptions)}, dp.Positive().BucketCounts().AsRaw()) + assert.NotZero(tb, dp.Timestamp(), "Timestamp should be set") - verifyMetricLabels(dp, t, seenMetricIDs) + verifyMetricLabels(tb, dp, seenMetricIDs) } } -func verifyMetricLabels(dp metricDataPoint, t testing.TB, seenMetricIDs map[metricID]bool) { +func verifyMetricLabels(tb testing.TB, dp metricDataPoint, seenMetricIDs map[metricID]bool) { mID := metricID{} wantDimensions := map[string]pcommon.Value{ stringAttrName: pcommon.NewValueStr("stringAttrValue"), @@ -296,17 +296,17 @@ func verifyMetricLabels(dp metricDataPoint, t testing.TB, seenMetricIDs map[metr case statusCodeKey: mID.statusCode = v.Str() case notInSpanAttrName1: - assert.Fail(t, notInSpanAttrName1+" should not be in this metric") + assert.Fail(tb, notInSpanAttrName1+" should not be in this metric") default: - assert.Equal(t, wantDimensions[k], v) + assert.Equal(tb, wantDimensions[k], v) delete(wantDimensions, k) } return true }) - assert.Empty(t, wantDimensions, "Did not see all expected dimensions in metric. Missing: ", wantDimensions) + assert.Empty(tb, wantDimensions, "Did not see all expected dimensions in metric. Missing: ", wantDimensions) // Service/name/kind should be a unique metric. - assert.False(t, seenMetricIDs[mID]) + assert.False(tb, seenMetricIDs[mID]) seenMetricIDs[mID] = true } @@ -764,7 +764,7 @@ func TestConsumeTraces(t *testing.T) { aggregationTemporality string histogramConfig func() HistogramConfig exemplarConfig func() ExemplarsConfig - verifier func(t testing.TB, input pmetric.Metrics) bool + verifier func(tb testing.TB, input pmetric.Metrics) bool traces []ptrace.Traces }{ // disabling histogram diff --git a/exporter/awsxrayexporter/awsxray_test.go b/exporter/awsxrayexporter/awsxray_test.go index 90d5c12adff9..63794246febb 100644 --- a/exporter/awsxrayexporter/awsxray_test.go +++ b/exporter/awsxrayexporter/awsxray_test.go @@ -105,8 +105,8 @@ func BenchmarkForTracesExporter(b *testing.B) { } } -func initializeTracesExporter(t testing.TB, exporterConfig *Config, registry telemetry.Registry) exporter.Traces { - t.Helper() +func initializeTracesExporter(tb testing.TB, exporterConfig *Config, registry telemetry.Registry) exporter.Traces { + tb.Helper() mconn := new(awsutil.Conn) traceExporter, err := newTracesExporter(exporterConfig, exportertest.NewNopSettings(), mconn, registry) if err != nil { @@ -115,11 +115,11 @@ func initializeTracesExporter(t testing.TB, exporterConfig *Config, registry tel return traceExporter } -func generateConfig(t testing.TB) *Config { - t.Setenv("AWS_ACCESS_KEY_ID", "AKIASSWVJUY4PZXXXXXX") - t.Setenv("AWS_SECRET_ACCESS_KEY", "XYrudg2H87u+ADAAq19Wqx3D41a09RsTXXXXXXXX") - t.Setenv("AWS_DEFAULT_REGION", "us-east-1") - t.Setenv("AWS_REGION", "us-east-1") +func generateConfig(tb testing.TB) *Config { + tb.Setenv("AWS_ACCESS_KEY_ID", "AKIASSWVJUY4PZXXXXXX") + tb.Setenv("AWS_SECRET_ACCESS_KEY", "XYrudg2H87u+ADAAq19Wqx3D41a09RsTXXXXXXXX") + tb.Setenv("AWS_DEFAULT_REGION", "us-east-1") + tb.Setenv("AWS_REGION", "us-east-1") factory := NewFactory() exporterConfig := factory.CreateDefaultConfig().(*Config) exporterConfig.Region = "us-east-1" diff --git a/exporter/azuremonitorexporter/metricexporter_test.go b/exporter/azuremonitorexporter/metricexporter_test.go index 520f3e627aef..b0acb856de3c 100644 --- a/exporter/azuremonitorexporter/metricexporter_test.go +++ b/exporter/azuremonitorexporter/metricexporter_test.go @@ -105,34 +105,34 @@ func TestSummaryEnvelopes(t *testing.T) { assert.Equal(t, contracts.Aggregation, dataPoint.Kind) } -func getDataPoint(t testing.TB, metric pmetric.Metric) *contracts.DataPoint { +func getDataPoint(tb testing.TB, metric pmetric.Metric) *contracts.DataPoint { var envelopes []*contracts.Envelope = getMetricPacker().MetricToEnvelopes(metric, getResource(), getScope()) - require.Len(t, envelopes, 1) + require.Len(tb, envelopes, 1) envelope := envelopes[0] - require.NotNil(t, envelope) + require.NotNil(tb, envelope) - assert.NotNil(t, envelope.Tags) - assert.Contains(t, envelope.Tags[contracts.InternalSdkVersion], "otelc-") - assert.NotNil(t, envelope.Time) + assert.NotNil(tb, envelope.Tags) + assert.Contains(tb, envelope.Tags[contracts.InternalSdkVersion], "otelc-") + assert.NotNil(tb, envelope.Time) - require.NotNil(t, envelope.Data) + require.NotNil(tb, envelope.Data) envelopeData := envelope.Data.(*contracts.Data) - assert.Equal(t, "MetricData", envelopeData.BaseType) + assert.Equal(tb, "MetricData", envelopeData.BaseType) - require.NotNil(t, envelopeData.BaseData) + require.NotNil(tb, envelopeData.BaseData) metricData := envelopeData.BaseData.(*contracts.MetricData) - require.Len(t, metricData.Metrics, 1) + require.Len(tb, metricData.Metrics, 1) dataPoint := metricData.Metrics[0] - require.NotNil(t, dataPoint) + require.NotNil(tb, dataPoint) actualProperties := metricData.Properties - require.Equal(t, "10", actualProperties["int_attribute"]) - require.Equal(t, "str_value", actualProperties["str_attribute"]) - require.Equal(t, "true", actualProperties["bool_attribute"]) - require.Equal(t, "1.2", actualProperties["double_attribute"]) + require.Equal(tb, "10", actualProperties["int_attribute"]) + require.Equal(tb, "str_value", actualProperties["str_attribute"]) + require.Equal(tb, "true", actualProperties["bool_attribute"]) + require.Equal(tb, "1.2", actualProperties["double_attribute"]) return dataPoint } diff --git a/exporter/elasticsearchexporter/integrationtest/collector.go b/exporter/elasticsearchexporter/integrationtest/collector.go index 61962de8b9ba..5c7dddc00519 100644 --- a/exporter/elasticsearchexporter/integrationtest/collector.go +++ b/exporter/elasticsearchexporter/integrationtest/collector.go @@ -35,7 +35,7 @@ import ( // createConfigYaml creates a yaml config for an otel collector for testing. func createConfigYaml( - t testing.TB, + tb testing.TB, sender testbed.DataSender, receiver testbed.DataReceiver, processors map[string]string, @@ -43,7 +43,7 @@ func createConfigYaml( pipelineType string, debug bool, ) string { - t.Helper() + tb.Helper() processorSection, processorList := createConfigSection(processors) extensionSection, extensionList := createConfigSection(extensions) @@ -90,7 +90,7 @@ service: debugVerbosity, processorSection, extensionSection, - testutil.GetAvailablePort(t), + testutil.GetAvailablePort(tb), logLevel, extensionList, pipelineType, @@ -129,7 +129,7 @@ type recreatableOtelCol struct { col *otelcol.Collector } -func newRecreatableOtelCol(t testing.TB) *recreatableOtelCol { +func newRecreatableOtelCol(tb testing.TB) *recreatableOtelCol { var ( err error factories otelcol.Factories @@ -137,20 +137,20 @@ func newRecreatableOtelCol(t testing.TB) *recreatableOtelCol { factories.Receivers, err = receiver.MakeFactoryMap( otlpreceiver.NewFactory(), ) - require.NoError(t, err) + require.NoError(tb, err) factories.Extensions, err = extension.MakeFactoryMap( filestorage.NewFactory(), ) - require.NoError(t, err) + require.NoError(tb, err) factories.Processors, err = processor.MakeFactoryMap() - require.NoError(t, err) + require.NoError(tb, err) factories.Exporters, err = exporter.MakeFactoryMap( elasticsearchexporter.NewFactory(), debugexporter.NewFactory(), ) - require.NoError(t, err) + require.NoError(tb, err) return &recreatableOtelCol{ - tempDir: t.TempDir(), + tempDir: tb.TempDir(), factories: factories, } } diff --git a/exporter/elasticsearchexporter/integrationtest/config.go b/exporter/elasticsearchexporter/integrationtest/config.go index 8112f805aed6..06713de1101c 100644 --- a/exporter/elasticsearchexporter/integrationtest/config.go +++ b/exporter/elasticsearchexporter/integrationtest/config.go @@ -11,12 +11,12 @@ import ( "github.com/stretchr/testify/require" ) -func getDebugFlag(t testing.TB) bool { +func getDebugFlag(tb testing.TB) bool { raw := os.Getenv("DEBUG") if raw == "" { return false } debug, err := strconv.ParseBool(raw) - require.NoError(t, err, "debug flag parsing failed") + require.NoError(tb, err, "debug flag parsing failed") return debug } diff --git a/exporter/elasticsearchexporter/integrationtest/datareceiver.go b/exporter/elasticsearchexporter/integrationtest/datareceiver.go index 0039b1fd893e..bf237f86524b 100644 --- a/exporter/elasticsearchexporter/integrationtest/datareceiver.go +++ b/exporter/elasticsearchexporter/integrationtest/datareceiver.go @@ -60,12 +60,12 @@ type esDataReceiver struct { type dataReceiverOption func(*esDataReceiver) -func newElasticsearchDataReceiver(t testing.TB, opts ...dataReceiverOption) *esDataReceiver { +func newElasticsearchDataReceiver(tb testing.TB, opts ...dataReceiverOption) *esDataReceiver { r := &esDataReceiver{ DataReceiverBase: testbed.DataReceiverBase{}, - endpoint: fmt.Sprintf("http://%s:%d", testbed.DefaultHost, testutil.GetAvailablePort(t)), + endpoint: fmt.Sprintf("http://%s:%d", testbed.DefaultHost, testutil.GetAvailablePort(tb)), decodeBulkRequest: true, - t: t, + t: tb, } for _, opt := range opts { opt(r) diff --git a/exporter/elasticsearchexporter/integrationtest/validator.go b/exporter/elasticsearchexporter/integrationtest/validator.go index cb9b411aecd9..0d8b48cac7a3 100644 --- a/exporter/elasticsearchexporter/integrationtest/validator.go +++ b/exporter/elasticsearchexporter/integrationtest/validator.go @@ -18,9 +18,9 @@ type countValidator struct { } // newCountValidator creates a new instance of the CountValidator. -func newCountValidator(t testing.TB, provider testbed.DataProvider) *countValidator { +func newCountValidator(tb testing.TB, provider testbed.DataProvider) *countValidator { return &countValidator{ - t: t, + t: tb, dataProvider: provider, } } diff --git a/exporter/fileexporter/file_exporter_test.go b/exporter/fileexporter/file_exporter_test.go index 9639eec9264c..f4d559693273 100644 --- a/exporter/fileexporter/file_exporter_test.go +++ b/exporter/fileexporter/file_exporter_test.go @@ -612,8 +612,8 @@ func TestExportMessageAsBuffer(t *testing.T) { } // tempFileName provides a temporary file name for testing. -func tempFileName(t testing.TB) string { - return filepath.Join(t.TempDir(), "fileexporter_test.tmp") +func tempFileName(tb testing.TB) string { + return filepath.Join(tb.TempDir(), "fileexporter_test.tmp") } // errorWriter is an io.Writer that will return an error all ways diff --git a/exporter/logzioexporter/exporter_test.go b/exporter/logzioexporter/exporter_test.go index 40047dfa58bd..2943c50a9413 100644 --- a/exporter/logzioexporter/exporter_test.go +++ b/exporter/logzioexporter/exporter_test.go @@ -97,7 +97,7 @@ func generateLogsOneEmptyTimestamp() plog.Logs { return ld } -func testLogsExporter(ld plog.Logs, t *testing.T, cfg *Config) error { +func testLogsExporter(t *testing.T, ld plog.Logs, cfg *Config) error { var err error params := exportertest.NewNopSettings() exporter, err := createLogsExporter(context.Background(), params, cfg) @@ -146,7 +146,7 @@ func newTestTraces() ptrace.Traces { return td } -func testTracesExporter(td ptrace.Traces, t *testing.T, cfg *Config) error { +func testTracesExporter(t *testing.T, td ptrace.Traces, cfg *Config) error { params := exportertest.NewNopSettings() exporter, err := createTracesExporter(context.Background(), params, cfg) if err != nil { @@ -196,10 +196,10 @@ func TestExportErrors(tester *testing.T) { } td := newTestTracesWithAttributes() ld := testdata.GenerateLogs(10) - err := testTracesExporter(td, tester, cfg) + err := testTracesExporter(tester, td, cfg) fmt.Println(err.Error()) require.Error(tester, err) - err = testLogsExporter(ld, tester, cfg) + err = testLogsExporter(tester, ld, cfg) fmt.Println(err.Error()) server.Close() require.Error(tester, err) @@ -253,7 +253,7 @@ func TestPushTraceData(tester *testing.T) { res := td.ResourceSpans().At(0).Resource() res.Attributes().PutStr(conventions.AttributeServiceName, testService) res.Attributes().PutStr(conventions.AttributeHostName, testHost) - err := testTracesExporter(td, tester, &cfg) + err := testTracesExporter(tester, td, &cfg) require.NoError(tester, err) var newSpan logzioSpan decoded, _ := gUnzipData(recordedRequests) @@ -286,7 +286,7 @@ func TestPushLogsData(tester *testing.T) { res := ld.ResourceLogs().At(0).Resource() res.Attributes().PutStr(conventions.AttributeServiceName, testService) res.Attributes().PutStr(conventions.AttributeHostName, testHost) - err := testLogsExporter(ld, tester, &cfg) + err := testLogsExporter(tester, ld, &cfg) require.NoError(tester, err) var jsonLog map[string]any decoded, _ := gUnzipData(recordedRequests) diff --git a/exporter/rabbitmqexporter/internal/publisher/publisher_test.go b/exporter/rabbitmqexporter/internal/publisher/publisher_test.go index 7eddda97a99d..96b2c99ad6d6 100644 --- a/exporter/rabbitmqexporter/internal/publisher/publisher_test.go +++ b/exporter/rabbitmqexporter/internal/publisher/publisher_test.go @@ -93,7 +93,7 @@ func TestPublishAckedWithinTimeout(t *testing.T) { func TestPublishNackedWithinTimeout(t *testing.T) { client, connection, channel, confirmation := setupMocksForSuccessfulPublish() - resetCall(confirmation.ExpectedCalls, "Acked", t) + resetCall(t, confirmation.ExpectedCalls, "Acked") confirmation.On("Acked").Return(false) publisher, err := NewConnection(zap.NewNop(), client, makeDialConfig()) @@ -111,8 +111,8 @@ func TestPublishNackedWithinTimeout(t *testing.T) { func TestPublishTimeoutBeforeAck(t *testing.T) { client, connection, channel, confirmation := setupMocksForSuccessfulPublish() - resetCall(confirmation.ExpectedCalls, "Done", t) - resetCall(confirmation.ExpectedCalls, "Acked", t) + resetCall(t, confirmation.ExpectedCalls, "Done") + resetCall(t, confirmation.ExpectedCalls, "Acked") emptyConfirmationChan := make(<-chan struct{}) confirmation.On("Done").Return(emptyConfirmationChan) @@ -136,7 +136,7 @@ func TestPublishTwiceReusingSameConnection(t *testing.T) { confirmationChan <- struct{}{} confirmationChan <- struct{}{} var confirmationChanRet <-chan struct{} = confirmationChan - resetCall(confirmation.ExpectedCalls, "Done", t) + resetCall(t, confirmation.ExpectedCalls, "Done") confirmation.On("Done").Return(confirmationChanRet) publisher, err := NewConnection(zap.NewNop(), client, makeDialConfig()) @@ -158,7 +158,7 @@ func TestRestoreUnhealthyConnectionDuringPublish(t *testing.T) { client, connection, channel, confirmation := setupMocksForSuccessfulPublish() // Capture the channel that the amqp library uses to notify about connection issues so that we can simulate the notification - resetCall(connection.ExpectedCalls, "NotifyClose", t) + resetCall(t, connection.ExpectedCalls, "NotifyClose") var connectionErrChan chan *amqp.Error connection.On("NotifyClose", mock.Anything).Return(make(chan *amqp.Error)).Run(func(args mock.Arguments) { connectionErrChan = args.Get(0).(chan *amqp.Error) @@ -175,7 +175,7 @@ func TestRestoreUnhealthyConnectionDuringPublish(t *testing.T) { require.NoError(t, err) connection.AssertNumberOfCalls(t, "ReconnectIfUnhealthy", 1) client.AssertExpectations(t) - resetCall(connection.ExpectedCalls, "Close", t) + resetCall(t, connection.ExpectedCalls, "Close") connection.AssertExpectations(t) channel.AssertExpectations(t) confirmation.AssertExpectations(t) @@ -206,7 +206,7 @@ func TestFailRestoreConnectionDuringPublishing(t *testing.T) { connection.On("IsClosed").Return(true) - resetCall(client.ExpectedCalls, "DialConfig", t) + resetCall(t, client.ExpectedCalls, "DialConfig") client.On("DialConfig", connectURL, mock.Anything).Return(nil, errors.New("simulated connection error")) _ = publisher.Publish(context.Background(), makePublishMessage()) @@ -216,7 +216,7 @@ func TestFailRestoreConnectionDuringPublishing(t *testing.T) { func TestErrCreatingChannel(t *testing.T) { client, connection, _, _ := setupMocksForSuccessfulPublish() - resetCall(connection.ExpectedCalls, "Channel", t) + resetCall(t, connection.ExpectedCalls, "Channel") connection.On("Channel").Return(nil, errors.New("simulated error creating channel")) publisher, err := NewConnection(zap.NewNop(), client, makeDialConfig()) @@ -229,7 +229,7 @@ func TestErrCreatingChannel(t *testing.T) { func TestErrSettingChannelConfirmMode(t *testing.T) { client, _, channel, _ := setupMocksForSuccessfulPublish() - resetCall(channel.ExpectedCalls, "Confirm", t) + resetCall(t, channel.ExpectedCalls, "Confirm") channel.On("Confirm", false).Return(errors.New("simulated error setting channel confirm mode")) publisher, err := NewConnection(zap.NewNop(), client, makeDialConfig()) @@ -246,7 +246,7 @@ func TestErrPublishing(t *testing.T) { channel.On("Confirm", false).Return(nil) channel.On("PublishWithDeferredConfirmWithContext", mock.Anything, exchange, routingKey, true, false, mock.MatchedBy(isPersistentDeliverMode)).Return(nil, errors.New("simulated error publishing")) channel.On("Close").Return(nil) - resetCall(connection.ExpectedCalls, "Channel", t) + resetCall(t, connection.ExpectedCalls, "Channel") connection.On("Channel").Return(&channel, nil) publisher, err := NewConnection(zap.NewNop(), client, makeDialConfig()) @@ -286,7 +286,7 @@ func isPersistentDeliverMode(p amqp.Publishing) bool { return p.DeliveryMode == amqp.Persistent } -func resetCall(calls []*mock.Call, methodName string, t *testing.T) { +func resetCall(t *testing.T, calls []*mock.Call, methodName string) { for _, call := range calls { if call.Method == methodName { call.Unset() diff --git a/exporter/splunkhecexporter/client_test.go b/exporter/splunkhecexporter/client_test.go index 0f4ccd1e349f..97ee1b577d63 100644 --- a/exporter/splunkhecexporter/client_test.go +++ b/exporter/splunkhecexporter/client_test.go @@ -209,7 +209,7 @@ func (c *capturingData) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.WriteHeader(c.statusCode) } -func runMetricsExport(cfg *Config, metrics pmetric.Metrics, expectedBatchesNum int, useMultiMetricsFormat bool, t *testing.T) ([]receivedRequest, error) { +func runMetricsExport(t *testing.T, cfg *Config, metrics pmetric.Metrics, expectedBatchesNum int, useMultiMetricsFormat bool) ([]receivedRequest, error) { listener, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { panic(err) @@ -260,7 +260,7 @@ func runMetricsExport(cfg *Config, metrics pmetric.Metrics, expectedBatchesNum i } } -func runTraceExport(testConfig *Config, traces ptrace.Traces, expectedBatchesNum int, t *testing.T) ([]receivedRequest, error) { +func runTraceExport(t *testing.T, testConfig *Config, traces ptrace.Traces, expectedBatchesNum int) ([]receivedRequest, error) { listener, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { panic(err) @@ -324,7 +324,7 @@ func runTraceExport(testConfig *Config, traces ptrace.Traces, expectedBatchesNum } } -func runLogExport(cfg *Config, ld plog.Logs, expectedBatchesNum int, t *testing.T) ([]receivedRequest, error) { +func runLogExport(t *testing.T, cfg *Config, ld plog.Logs, expectedBatchesNum int) ([]receivedRequest, error) { listener, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { panic(err) @@ -502,7 +502,7 @@ func TestReceiveTracesBatches(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - got, err := runTraceExport(test.conf, test.traces, test.want.numBatches, t) + got, err := runTraceExport(t, test.conf, test.traces, test.want.numBatches) require.NoError(t, err) require.Len(t, got, test.want.numBatches, "expected exact number of batches") @@ -784,7 +784,7 @@ func TestReceiveLogs(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - got, err := runLogExport(test.conf, test.logs, test.want.numBatches, t) + got, err := runLogExport(t, test.conf, test.logs, test.want.numBatches) if test.want.wantErr != "" { require.EqualError(t, err, test.want.wantErr) return @@ -937,7 +937,7 @@ func TestReceiveRaw(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - got, err := runLogExport(test.conf, test.logs, 1, t) + got, err := runLogExport(t, test.conf, test.logs, 1) require.NoError(t, err) req := got[0] assert.Equal(t, test.text, string(req.body)) @@ -950,7 +950,7 @@ func TestReceiveLogEvent(t *testing.T) { cfg := NewFactory().CreateDefaultConfig().(*Config) cfg.DisableCompression = true - actual, err := runLogExport(cfg, logs, 1, t) + actual, err := runLogExport(t, cfg, logs, 1) assert.Len(t, actual, 1) assert.NoError(t, err) @@ -962,7 +962,7 @@ func TestReceiveMetricEvent(t *testing.T) { cfg := NewFactory().CreateDefaultConfig().(*Config) cfg.DisableCompression = true - actual, err := runMetricsExport(cfg, metrics, 1, false, t) + actual, err := runMetricsExport(t, cfg, metrics, 1, false) assert.Len(t, actual, 1) assert.NoError(t, err) @@ -974,7 +974,7 @@ func TestReceiveSpanEvent(t *testing.T) { cfg := NewFactory().CreateDefaultConfig().(*Config) cfg.DisableCompression = true - actual, err := runTraceExport(cfg, traces, 1, t) + actual, err := runTraceExport(t, cfg, traces, 1) assert.Len(t, actual, 1) assert.NoError(t, err) @@ -999,7 +999,7 @@ func TestReceiveMetrics(t *testing.T) { md := createMetricsData(1, 3) cfg := NewFactory().CreateDefaultConfig().(*Config) cfg.DisableCompression = true - actual, err := runMetricsExport(cfg, md, 1, false, t) + actual, err := runMetricsExport(t, cfg, md, 1, false) assert.Len(t, actual, 1) assert.NoError(t, err) msg := string(actual[0].body) @@ -1159,7 +1159,7 @@ func TestReceiveBatchedMetrics(t *testing.T) { for _, test := range tests { testFn := func(multiMetric bool) func(*testing.T) { return func(t *testing.T) { - got, err := runMetricsExport(test.conf, test.metrics, test.want.numBatches, multiMetric, t) + got, err := runMetricsExport(t, test.conf, test.metrics, test.want.numBatches, multiMetric) require.NoError(t, err) require.Len(t, got, test.want.numBatches) @@ -1270,7 +1270,7 @@ func Test_PushMetricsData_Summary_NaN_Sum(t *testing.T) { func TestReceiveMetricsWithCompression(t *testing.T) { cfg := NewFactory().CreateDefaultConfig().(*Config) cfg.MaxContentLengthMetrics = 1800 - request, err := runMetricsExport(cfg, createMetricsData(1, 100), 2, false, t) + request, err := runMetricsExport(t, cfg, createMetricsData(1, 100), 2, false) assert.NoError(t, err) assert.Equal(t, "gzip", request[0].headers.Get("Content-Encoding")) assert.NotEqual(t, "", request) @@ -1327,19 +1327,19 @@ func TestErrorReceived(t *testing.T) { func TestInvalidLogs(t *testing.T) { config := NewFactory().CreateDefaultConfig().(*Config) config.DisableCompression = false - _, err := runLogExport(config, createLogData(1, 1, 0), 1, t) + _, err := runLogExport(t, config, createLogData(1, 1, 0), 1) assert.Error(t, err) } func TestInvalidMetrics(t *testing.T) { cfg := NewFactory().CreateDefaultConfig().(*Config) - _, err := runMetricsExport(cfg, pmetric.NewMetrics(), 1, false, t) + _, err := runMetricsExport(t, cfg, pmetric.NewMetrics(), 1, false) assert.Error(t, err) } func TestInvalidMetricsMultiMetric(t *testing.T) { cfg := NewFactory().CreateDefaultConfig().(*Config) - _, err := runMetricsExport(cfg, pmetric.NewMetrics(), 1, true, t) + _, err := runMetricsExport(t, cfg, pmetric.NewMetrics(), 1, true) assert.Error(t, err) } @@ -1994,7 +1994,7 @@ func TestAllowedLogDataTypes(t *testing.T) { numBatches = 2 } - requests, err := runLogExport(cfg, logs, numBatches, t) + requests, err := runLogExport(t, cfg, logs, numBatches) assert.NoError(t, err) seenLogs := false diff --git a/extension/encoding/otlpencodingextension/extension_test.go b/extension/encoding/otlpencodingextension/extension_test.go index f50142cb8b19..44d6aa5fa1f0 100644 --- a/extension/encoding/otlpencodingextension/extension_test.go +++ b/extension/encoding/otlpencodingextension/extension_test.go @@ -62,7 +62,7 @@ func TestExtension_Start(t *testing.T) { } } -func testOTLPMarshal(ex *otlpExtension, t *testing.T) { +func testOTLPMarshal(t *testing.T, ex *otlpExtension) { traces := generateTraces() _, err := ex.MarshalTraces(traces) require.NoError(t, err) @@ -80,7 +80,7 @@ func testOTLPMarshal(ex *otlpExtension, t *testing.T) { require.NoError(t, err) } -func testOTLPUnmarshal(ex *otlpExtension, t *testing.T) { +func testOTLPUnmarshal(t *testing.T, ex *otlpExtension) { traces := generateTraces() logs := generateLogs() metrics := generateMetrics() @@ -112,33 +112,33 @@ func testOTLPUnmarshal(ex *otlpExtension, t *testing.T) { func TestOTLPJSONMarshal(t *testing.T) { conf := &Config{Protocol: otlpJSON} - ex := createAndExtension0(conf, t) + ex := createAndExtension0(t, conf) - testOTLPMarshal(ex, t) + testOTLPMarshal(t, ex) } func TestOTLPProtoMarshal(t *testing.T) { conf := &Config{Protocol: otlpProto} - ex := createAndExtension0(conf, t) + ex := createAndExtension0(t, conf) - testOTLPMarshal(ex, t) + testOTLPMarshal(t, ex) } func TestOTLPJSONUnmarshal(t *testing.T) { conf := &Config{Protocol: otlpJSON} - ex := createAndExtension0(conf, t) - testOTLPUnmarshal(ex, t) + ex := createAndExtension0(t, conf) + testOTLPUnmarshal(t, ex) } func TestOTLPProtoUnmarshal(t *testing.T) { conf := &Config{Protocol: otlpProto} - ex := createAndExtension0(conf, t) + ex := createAndExtension0(t, conf) - testOTLPUnmarshal(ex, t) + testOTLPUnmarshal(t, ex) } // createAndExtension0 Create extension -func createAndExtension0(c *Config, t *testing.T) *otlpExtension { +func createAndExtension0(t *testing.T, c *Config) *otlpExtension { ex, err := newExtension(c) require.NoError(t, err) err = ex.Start(context.TODO(), nil) diff --git a/extension/observer/cfgardenobserver/config_test.go b/extension/observer/cfgardenobserver/config_test.go index d3cd919a06e9..e747d003c218 100644 --- a/extension/observer/cfgardenobserver/config_test.go +++ b/extension/observer/cfgardenobserver/config_test.go @@ -206,18 +206,18 @@ func TestConfigValidate(t *testing.T) { } } -func loadRawConf(t testing.TB, path string, id component.ID) *confmap.Conf { +func loadRawConf(tb testing.TB, path string, id component.ID) *confmap.Conf { cm, err := confmaptest.LoadConf(filepath.Join("testdata", path)) - require.NoError(t, err) + require.NoError(tb, err) sub, err := cm.Sub(id.String()) - require.NoError(t, err) + require.NoError(tb, err) return sub } -func loadConfig(t testing.TB, id component.ID) *Config { +func loadConfig(tb testing.TB, id component.ID) *Config { factory := NewFactory() cfg := factory.CreateDefaultConfig() - sub := loadRawConf(t, "config.yaml", id) - require.NoError(t, sub.Unmarshal(cfg)) + sub := loadRawConf(tb, "config.yaml", id) + require.NoError(tb, sub.Unmarshal(cfg)) return cfg.(*Config) } diff --git a/extension/observer/dockerobserver/config_test.go b/extension/observer/dockerobserver/config_test.go index a00c82925634..5a9d9d686571 100644 --- a/extension/observer/dockerobserver/config_test.go +++ b/extension/observer/dockerobserver/config_test.go @@ -78,19 +78,19 @@ func TestValidateConfig(t *testing.T) { assert.NoError(t, component.ValidateConfig(cfg)) } -func loadConf(t testing.TB, path string, id component.ID) *confmap.Conf { +func loadConf(tb testing.TB, path string, id component.ID) *confmap.Conf { cm, err := confmaptest.LoadConf(filepath.Join("testdata", path)) - require.NoError(t, err) + require.NoError(tb, err) sub, err := cm.Sub(id.String()) - require.NoError(t, err) + require.NoError(tb, err) return sub } -func loadConfig(t testing.TB, id component.ID) *Config { +func loadConfig(tb testing.TB, id component.ID) *Config { factory := NewFactory() cfg := factory.CreateDefaultConfig() - sub := loadConf(t, "config.yaml", id) - require.NoError(t, sub.Unmarshal(cfg)) + sub := loadConf(tb, "config.yaml", id) + require.NoError(tb, sub.Unmarshal(cfg)) return cfg.(*Config) } diff --git a/extension/observer/endpointswatcher_test.go b/extension/observer/endpointswatcher_test.go index d34dc25284dc..8e4db5ee976b 100644 --- a/extension/observer/endpointswatcher_test.go +++ b/extension/observer/endpointswatcher_test.go @@ -165,21 +165,21 @@ func TestNotifyOfLatestEndpointsMultipleNotify(t *testing.T) { require.Nil(t, existingEndpoints(t, watcher, notifyTwo.ID())) } -func existingEndpoints(t testing.TB, watcher *EndpointsWatcher, id NotifyID) map[EndpointID]Endpoint { +func existingEndpoints(tb testing.TB, watcher *EndpointsWatcher, id NotifyID) map[EndpointID]Endpoint { if existing, ok := watcher.existingEndpoints.Load(id); ok { endpoints, ok := existing.(map[EndpointID]Endpoint) - assert.True(t, ok) + assert.True(tb, ok) return endpoints } return nil } -func setup(t testing.TB) (*mockEndpointsLister, *EndpointsWatcher, *mockNotifier) { +func setup(tb testing.TB) (*mockEndpointsLister, *EndpointsWatcher, *mockNotifier) { ml := &mockEndpointsLister{ endpointsMap: map[EndpointID]Endpoint{}, } - ew := NewEndpointsWatcher(ml, 2*time.Second, zaptest.NewLogger(t)) + ew := NewEndpointsWatcher(ml, 2*time.Second, zaptest.NewLogger(tb)) mn := &mockNotifier{id: "mockNotifier"} return ml, ew, mn diff --git a/extension/observer/k8sobserver/extension_test.go b/extension/observer/k8sobserver/extension_test.go index 24d825d0f976..8e58659f4a66 100644 --- a/extension/observer/k8sobserver/extension_test.go +++ b/extension/observer/k8sobserver/extension_test.go @@ -24,10 +24,10 @@ const ( servicePortEnv = "KUBERNETES_SERVICE_PORT" ) -func mockServiceHost(t testing.TB, c *Config) { +func mockServiceHost(tb testing.TB, c *Config) { c.AuthType = k8sconfig.AuthTypeNone - t.Setenv(serviceHostEnv, "mock") - t.Setenv(servicePortEnv, "12345") + tb.Setenv(serviceHostEnv, "mock") + tb.Setenv(servicePortEnv, "12345") } func TestNewExtension(t *testing.T) { diff --git a/extension/solarwindsapmsettingsextension/extension_test.go b/extension/solarwindsapmsettingsextension/extension_test.go index 247101805f26..b553dd7973a3 100644 --- a/extension/solarwindsapmsettingsextension/extension_test.go +++ b/extension/solarwindsapmsettingsextension/extension_test.go @@ -51,7 +51,7 @@ func TestCreate(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - ex := createAnExtension(tt.cfg, t) + ex := createAnExtension(t, tt.cfg) require.NoError(t, ex.Shutdown(context.TODO())) }) } @@ -67,7 +67,7 @@ func newNopSettings() extension.Settings { } // create extension -func createAnExtension(c *Config, t *testing.T) extension.Extension { +func createAnExtension(t *testing.T, c *Config) extension.Extension { ex, err := newSolarwindsApmSettingsExtension(c, newNopSettings()) require.NoError(t, err) require.NoError(t, ex.Start(context.TODO(), nil)) diff --git a/internal/common/testutil/testutil.go b/internal/common/testutil/testutil.go index 1968e44d7a33..823815fbb6c9 100644 --- a/internal/common/testutil/testutil.go +++ b/internal/common/testutil/testutil.go @@ -26,15 +26,15 @@ type portpair struct { // describing it. The port is available for opening when this function returns // provided that there is no race by some other code to grab the same port // immediately. -func GetAvailableLocalAddress(t testing.TB) string { - return GetAvailableLocalNetworkAddress(t, "tcp") +func GetAvailableLocalAddress(tb testing.TB) string { + return GetAvailableLocalNetworkAddress(tb, "tcp") } // GetAvailableLocalNetworkAddress finds an available local port on specified network and returns an endpoint // describing it. The port is available for opening when this function returns // provided that there is no race by some other code to grab the same port // immediately. -func GetAvailableLocalNetworkAddress(t testing.TB, network string) string { +func GetAvailableLocalNetworkAddress(tb testing.TB, network string) string { // Retry has been added for windows as net.Listen can return a port that is not actually available. Details can be // found in https://github.com/docker/for-win/issues/3171 but to summarize Hyper-V will reserve ranges of ports // which do not show up under the "netstat -ano" but can only be found by @@ -44,14 +44,14 @@ func GetAvailableLocalNetworkAddress(t testing.TB, network string) string { portFound := false if runtime.GOOS == "windows" { - exclusions = getExclusionsList(t) + exclusions = getExclusionsList(tb) } var endpoint string for !portFound { - endpoint = findAvailableAddress(t, network) + endpoint = findAvailableAddress(tb, network) _, port, err := net.SplitHostPort(endpoint) - require.NoError(t, err) + require.NoError(tb, err) portFound = true if runtime.GOOS == "windows" { for _, pair := range exclusions { @@ -66,26 +66,26 @@ func GetAvailableLocalNetworkAddress(t testing.TB, network string) string { return endpoint } -func findAvailableAddress(t testing.TB, network string) string { +func findAvailableAddress(tb testing.TB, network string) string { switch network { // net.Listen supported network strings case "tcp", "tcp4", "tcp6", "unix", "unixpacket": ln, err := net.Listen(network, "localhost:0") - require.NoError(t, err, "Failed to get a free local port") + require.NoError(tb, err, "Failed to get a free local port") // There is a possible race if something else takes this same port before // the test uses it, however, that is unlikely in practice. defer func() { - assert.NoError(t, ln.Close()) + assert.NoError(tb, ln.Close()) }() return ln.Addr().String() // net.ListenPacket supported network strings case "udp", "udp4", "udp6", "unixgram": ln, err := net.ListenPacket(network, "localhost:0") - require.NoError(t, err, "Failed to get a free local port") + require.NoError(tb, err, "Failed to get a free local port") // There is a possible race if something else takes this same port before // the test uses it, however, that is unlikely in practice. defer func() { - assert.NoError(t, ln.Close()) + assert.NoError(tb, ln.Close()) }() return ln.LocalAddr().String() } @@ -93,32 +93,32 @@ func findAvailableAddress(t testing.TB, network string) string { } // Get excluded ports on Windows from the command: netsh interface ipv4 show excludedportrange protocol=tcp -func getExclusionsList(t testing.TB) []portpair { +func getExclusionsList(tb testing.TB) []portpair { cmdTCP := exec.Command("netsh", "interface", "ipv4", "show", "excludedportrange", "protocol=tcp") outputTCP, errTCP := cmdTCP.CombinedOutput() - require.NoError(t, errTCP) - exclusions := createExclusionsList(t, string(outputTCP)) + require.NoError(tb, errTCP) + exclusions := createExclusionsList(tb, string(outputTCP)) cmdUDP := exec.Command("netsh", "interface", "ipv4", "show", "excludedportrange", "protocol=udp") outputUDP, errUDP := cmdUDP.CombinedOutput() - require.NoError(t, errUDP) - exclusions = append(exclusions, createExclusionsList(t, string(outputUDP))...) + require.NoError(tb, errUDP) + exclusions = append(exclusions, createExclusionsList(tb, string(outputUDP))...) return exclusions } -func createExclusionsList(t testing.TB, exclusionsText string) []portpair { +func createExclusionsList(tb testing.TB, exclusionsText string) []portpair { var exclusions []portpair parts := strings.Split(exclusionsText, "--------") - require.Len(t, parts, 3) + require.Len(tb, parts, 3) portsText := strings.Split(parts[2], "*") - require.Greater(t, len(portsText), 1) // original text may have a suffix like " - Administered port exclusions." + require.Greater(tb, len(portsText), 1) // original text may have a suffix like " - Administered port exclusions." lines := strings.Split(portsText[0], "\n") for _, line := range lines { if strings.TrimSpace(line) != "" { entries := strings.Fields(strings.TrimSpace(line)) - require.Len(t, entries, 2) + require.Len(tb, entries, 2) pair := portpair{entries[0], entries[1]} exclusions = append(exclusions, pair) } @@ -128,21 +128,21 @@ func createExclusionsList(t testing.TB, exclusionsText string) []portpair { // Force the state of feature gate for a test // usage: defer SetFeatureGateForTest("gateName", true)() -func SetFeatureGateForTest(t testing.TB, gate *featuregate.Gate, enabled bool) func() { +func SetFeatureGateForTest(tb testing.TB, gate *featuregate.Gate, enabled bool) func() { originalValue := gate.IsEnabled() - require.NoError(t, featuregate.GlobalRegistry().Set(gate.ID(), enabled)) + require.NoError(tb, featuregate.GlobalRegistry().Set(gate.ID(), enabled)) return func() { - require.NoError(t, featuregate.GlobalRegistry().Set(gate.ID(), originalValue)) + require.NoError(tb, featuregate.GlobalRegistry().Set(gate.ID(), originalValue)) } } -func GetAvailablePort(t testing.TB) int { - endpoint := GetAvailableLocalAddress(t) +func GetAvailablePort(tb testing.TB) int { + endpoint := GetAvailableLocalAddress(tb) _, port, err := net.SplitHostPort(endpoint) - require.NoError(t, err) + require.NoError(tb, err) portInt, err := strconv.Atoi(port) - require.NoError(t, err) + require.NoError(tb, err) return portInt } diff --git a/internal/otelarrow/testutil/testutil.go b/internal/otelarrow/testutil/testutil.go index 1943ff6e9e03..1ad0a852d9b9 100644 --- a/internal/otelarrow/testutil/testutil.go +++ b/internal/otelarrow/testutil/testutil.go @@ -25,7 +25,7 @@ type portpair struct { // describing it. The port is available for opening when this function returns // provided that there is no race by some other code to grab the same port // immediately. -func GetAvailableLocalAddress(t testing.TB) string { +func GetAvailableLocalAddress(tb testing.TB) string { // Retry has been added for windows as net.Listen can return a port that is not actually available. Details can be // found in https://github.com/docker/for-win/issues/3171 but to summarize Hyper-V will reserve ranges of ports // which do not show up under the "netstat -ano" but can only be found by @@ -34,14 +34,14 @@ func GetAvailableLocalAddress(t testing.TB) string { var exclusions []portpair portFound := false if runtime.GOOS == "windows" { - exclusions = getExclusionsList(t) + exclusions = getExclusionsList(tb) } var endpoint string for !portFound { - endpoint = findAvailableAddress(t) + endpoint = findAvailableAddress(tb) _, port, err := net.SplitHostPort(endpoint) - require.NoError(t, err) + require.NoError(tb, err) portFound = true if runtime.GOOS == "windows" { for _, pair := range exclusions { @@ -56,44 +56,44 @@ func GetAvailableLocalAddress(t testing.TB) string { return endpoint } -func findAvailableAddress(t testing.TB) string { +func findAvailableAddress(tb testing.TB) string { ln, err := net.Listen("tcp", "localhost:0") - require.NoError(t, err, "Failed to get a free local port") + require.NoError(tb, err, "Failed to get a free local port") // There is a possible race if something else takes this same port before // the test uses it, however, that is unlikely in practice. defer func() { - assert.NoError(t, ln.Close()) + assert.NoError(tb, ln.Close()) }() return ln.Addr().String() } // Get excluded ports on Windows from the command: netsh interface ipv4 show excludedportrange protocol=tcp -func getExclusionsList(t testing.TB) []portpair { +func getExclusionsList(tb testing.TB) []portpair { cmdTCP := exec.Command("netsh", "interface", "ipv4", "show", "excludedportrange", "protocol=tcp") outputTCP, errTCP := cmdTCP.CombinedOutput() - require.NoError(t, errTCP) - exclusions := createExclusionsList(string(outputTCP), t) + require.NoError(tb, errTCP) + exclusions := createExclusionsList(tb, string(outputTCP)) cmdUDP := exec.Command("netsh", "interface", "ipv4", "show", "excludedportrange", "protocol=udp") outputUDP, errUDP := cmdUDP.CombinedOutput() - require.NoError(t, errUDP) - exclusions = append(exclusions, createExclusionsList(string(outputUDP), t)...) + require.NoError(tb, errUDP) + exclusions = append(exclusions, createExclusionsList(tb, string(outputUDP))...) return exclusions } -func createExclusionsList(exclusionsText string, t testing.TB) []portpair { +func createExclusionsList(tb testing.TB, exclusionsText string) []portpair { var exclusions []portpair parts := strings.Split(exclusionsText, "--------") - require.Len(t, parts, 3) + require.Len(tb, parts, 3) portsText := strings.Split(parts[2], "*") - require.Greater(t, len(portsText), 1) // original text may have a suffix like " - Administered port exclusions." + require.Greater(tb, len(portsText), 1) // original text may have a suffix like " - Administered port exclusions." lines := strings.Split(portsText[0], "\n") for _, line := range lines { if strings.TrimSpace(line) != "" { entries := strings.Fields(strings.TrimSpace(line)) - require.Len(t, entries, 2) + require.Len(tb, entries, 2) pair := portpair{entries[0], entries[1]} exclusions = append(exclusions, pair) } diff --git a/internal/otelarrow/testutil/testutil_test.go b/internal/otelarrow/testutil/testutil_test.go index 49bdf47d6ec9..0e692637f10a 100644 --- a/internal/otelarrow/testutil/testutil_test.go +++ b/internal/otelarrow/testutil/testutil_test.go @@ -49,9 +49,9 @@ Start Port End Port * - Administered port exclusions. ` - exclusions := createExclusionsList(exclusionsText, t) + exclusions := createExclusionsList(t, exclusionsText) require.Len(t, exclusions, 2) - emptyExclusions := createExclusionsList(emptyExclusionsText, t) + emptyExclusions := createExclusionsList(t, emptyExclusionsText) require.Empty(t, emptyExclusions) } diff --git a/pkg/golden/golden.go b/pkg/golden/golden.go index 7255f5117f1e..ac66a1c57465 100644 --- a/pkg/golden/golden.go +++ b/pkg/golden/golden.go @@ -37,13 +37,13 @@ func ReadMetrics(filePath string) (pmetric.Metrics, error) { } // WriteMetrics writes a pmetric.Metrics to the specified file in YAML format. -func WriteMetrics(t testing.TB, filePath string, metrics pmetric.Metrics, opts ...WriteMetricsOption) error { +func WriteMetrics(tb testing.TB, filePath string, metrics pmetric.Metrics, opts ...WriteMetricsOption) error { if err := writeMetrics(filePath, metrics, opts...); err != nil { return err } - t.Logf("Golden file successfully written to %s.", filePath) - t.Log("NOTE: The WriteMetrics call must be removed in order to pass the test.") - t.Fail() + tb.Logf("Golden file successfully written to %s.", filePath) + tb.Log("NOTE: The WriteMetrics call must be removed in order to pass the test.") + tb.Fail() return nil } @@ -110,13 +110,13 @@ func ReadLogs(filePath string) (plog.Logs, error) { } // WriteLogs writes a plog.Logs to the specified file in YAML format. -func WriteLogs(t testing.TB, filePath string, logs plog.Logs) error { +func WriteLogs(tb testing.TB, filePath string, logs plog.Logs) error { if err := writeLogs(filePath, logs); err != nil { return err } - t.Logf("Golden file successfully written to %s.", filePath) - t.Log("NOTE: The WriteLogs call must be removed in order to pass the test.") - t.Fail() + tb.Logf("Golden file successfully written to %s.", filePath) + tb.Log("NOTE: The WriteLogs call must be removed in order to pass the test.") + tb.Fail() return nil } @@ -161,13 +161,13 @@ func ReadTraces(filePath string) (ptrace.Traces, error) { } // WriteTraces writes a ptrace.Traces to the specified file in YAML format. -func WriteTraces(t testing.TB, filePath string, traces ptrace.Traces) error { +func WriteTraces(tb testing.TB, filePath string, traces ptrace.Traces) error { if err := writeTraces(filePath, traces); err != nil { return err } - t.Logf("Golden file successfully written to %s.", filePath) - t.Log("NOTE: The WriteTraces call must be removed in order to pass the test.") - t.Fail() + tb.Logf("Golden file successfully written to %s.", filePath) + tb.Log("NOTE: The WriteTraces call must be removed in order to pass the test.") + tb.Fail() return nil } diff --git a/pkg/stanza/fileconsumer/internal/filetest/filetest.go b/pkg/stanza/fileconsumer/internal/filetest/filetest.go index 309ba2910d6e..76ba3b9cfab9 100644 --- a/pkg/stanza/fileconsumer/internal/filetest/filetest.go +++ b/pkg/stanza/fileconsumer/internal/filetest/filetest.go @@ -19,24 +19,24 @@ func OpenFile(tb testing.TB, path string) *os.File { return file } -func OpenTemp(t testing.TB, tempDir string) *os.File { - return OpenTempWithPattern(t, tempDir, "") +func OpenTemp(tb testing.TB, tempDir string) *os.File { + return OpenTempWithPattern(tb, tempDir, "") } -func ReopenTemp(t testing.TB, name string) *os.File { - return OpenTempWithPattern(t, filepath.Dir(name), filepath.Base(name)) +func ReopenTemp(tb testing.TB, name string) *os.File { + return OpenTempWithPattern(tb, filepath.Dir(name), filepath.Base(name)) } -func OpenTempWithPattern(t testing.TB, tempDir, pattern string) *os.File { +func OpenTempWithPattern(tb testing.TB, tempDir, pattern string) *os.File { file, err := os.CreateTemp(tempDir, pattern) - require.NoError(t, err) - t.Cleanup(func() { _ = file.Close() }) + require.NoError(tb, err) + tb.Cleanup(func() { _ = file.Close() }) return file } -func WriteString(t testing.TB, file *os.File, s string) { +func WriteString(tb testing.TB, file *os.File, s string) { _, err := file.WriteString(s) - require.NoError(t, err) + require.NoError(tb, err) } func TokenWithLength(length int) []byte { diff --git a/pkg/stanza/operator/input/file/util_test.go b/pkg/stanza/operator/input/file/util_test.go index a74aea301b0f..36a0501a899d 100644 --- a/pkg/stanza/operator/input/file/util_test.go +++ b/pkg/stanza/operator/input/file/util_test.go @@ -45,20 +45,20 @@ func newTestFileOperator(t *testing.T, cfgMod func(*Config)) (*Input, chan *entr return op.(*Input), fakeOutput.Received, tempDir } -func openTemp(t testing.TB, tempDir string) *os.File { - return openTempWithPattern(t, tempDir, "") +func openTemp(tb testing.TB, tempDir string) *os.File { + return openTempWithPattern(tb, tempDir, "") } -func openTempWithPattern(t testing.TB, tempDir, pattern string) *os.File { +func openTempWithPattern(tb testing.TB, tempDir, pattern string) *os.File { file, err := os.CreateTemp(tempDir, pattern) - require.NoError(t, err) - t.Cleanup(func() { _ = file.Close() }) + require.NoError(tb, err) + tb.Cleanup(func() { _ = file.Close() }) return file } -func writeString(t testing.TB, file *os.File, s string) { +func writeString(tb testing.TB, file *os.File, s string) { _, err := file.WriteString(s) - require.NoError(t, err) + require.NoError(tb, err) } func waitForOne(t *testing.T, c chan *entry.Entry) *entry.Entry { diff --git a/pkg/stanza/operator/input/namedpipe/input_test.go b/pkg/stanza/operator/input/namedpipe/input_test.go index 5afd84813360..ef441a816aa1 100644 --- a/pkg/stanza/operator/input/namedpipe/input_test.go +++ b/pkg/stanza/operator/input/namedpipe/input_test.go @@ -22,15 +22,15 @@ import ( ) // filename attempts to get an unused filename. -func filename(t testing.TB) string { - t.Helper() +func filename(tb testing.TB) string { + tb.Helper() file, err := os.CreateTemp("", "") - require.NoError(t, err) + require.NoError(tb, err) name := file.Name() - require.NoError(t, file.Close()) - require.NoError(t, os.Remove(name)) + require.NoError(tb, file.Close()) + require.NoError(tb, os.Remove(name)) return name } diff --git a/pkg/stanza/testutil/mocks.go b/pkg/stanza/testutil/mocks.go index 1347ed940139..185f5871d6c2 100644 --- a/pkg/stanza/testutil/mocks.go +++ b/pkg/stanza/testutil/mocks.go @@ -34,18 +34,18 @@ type FakeOutput struct { } // NewFakeOutput creates a new fake output with default settings -func NewFakeOutput(t testing.TB) *FakeOutput { +func NewFakeOutput(tb testing.TB) *FakeOutput { return &FakeOutput{ Received: make(chan *entry.Entry, 100), - logger: zaptest.NewLogger(t), + logger: zaptest.NewLogger(tb), } } // NewFakeOutputWithProcessError creates a new fake output with default settings, which returns error on Process -func NewFakeOutputWithProcessError(t testing.TB) *FakeOutput { +func NewFakeOutputWithProcessError(tb testing.TB) *FakeOutput { return &FakeOutput{ Received: make(chan *entry.Entry, 100), - logger: zaptest.NewLogger(t), + logger: zaptest.NewLogger(tb), processWithError: true, } } @@ -94,48 +94,48 @@ func (f *FakeOutput) Process(_ context.Context, entry *entry.Entry) error { // ExpectBody expects that a body will be received by the fake operator within a second // and that it is equal to the given body -func (f *FakeOutput) ExpectBody(t testing.TB, body any) { +func (f *FakeOutput) ExpectBody(tb testing.TB, body any) { select { case e := <-f.Received: - require.Equal(t, body, e.Body) + require.Equal(tb, body, e.Body) case <-time.After(time.Second): - require.FailNowf(t, "Timed out waiting for entry", "%s", body) + require.FailNowf(tb, "Timed out waiting for entry", "%s", body) } } // ExpectEntry expects that an entry will be received by the fake operator within a second // and that it is equal to the given body -func (f *FakeOutput) ExpectEntry(t testing.TB, expected *entry.Entry) { +func (f *FakeOutput) ExpectEntry(tb testing.TB, expected *entry.Entry) { select { case e := <-f.Received: - require.Equal(t, expected, e) + require.Equal(tb, expected, e) case <-time.After(time.Second): - require.FailNowf(t, "Timed out waiting for entry", "%v", expected) + require.FailNowf(tb, "Timed out waiting for entry", "%v", expected) } } // ExpectEntries expects that the given entries will be received in any order -func (f *FakeOutput) ExpectEntries(t testing.TB, expected []*entry.Entry) { +func (f *FakeOutput) ExpectEntries(tb testing.TB, expected []*entry.Entry) { entries := make([]*entry.Entry, 0, len(expected)) for i := 0; i < len(expected); i++ { select { case e := <-f.Received: entries = append(entries, e) case <-time.After(time.Second): - require.Fail(t, "Timed out waiting for entry") + require.Fail(tb, "Timed out waiting for entry") } - if t.Failed() { + if tb.Failed() { break } } - require.ElementsMatch(t, expected, entries) + require.ElementsMatch(tb, expected, entries) } // ExpectNoEntry expects that no entry will be received within the specified time -func (f *FakeOutput) ExpectNoEntry(t testing.TB, timeout time.Duration) { +func (f *FakeOutput) ExpectNoEntry(tb testing.TB, timeout time.Duration) { select { case <-f.Received: - require.FailNow(t, "Should not have received entry") + require.FailNow(tb, "Should not have received entry") case <-time.After(timeout): return } diff --git a/processor/deltatocumulativeprocessor/internal/data/datatest/equal.go b/processor/deltatocumulativeprocessor/internal/data/datatest/equal.go index a5aabb91b59e..1ad4f2d23569 100644 --- a/processor/deltatocumulativeprocessor/internal/data/datatest/equal.go +++ b/processor/deltatocumulativeprocessor/internal/data/datatest/equal.go @@ -20,8 +20,8 @@ type T struct { testing.TB } -func New(t testing.TB) T { - return T{TB: t} +func New(tb testing.TB) T { + return T{TB: tb} } // Equal reports whether want and got are deeply equal. @@ -50,9 +50,9 @@ func (is T) Equalf(want, got any, name string) { equal(is.TB, want, got, name) } -func equal(t testing.TB, want, got any, name string) bool { - t.Helper() - require.IsType(t, want, got) +func equal(tb testing.TB, want, got any, name string) bool { + tb.Helper() + require.IsType(tb, want, got) vw := reflect.ValueOf(want) vg := reflect.ValueOf(got) @@ -60,7 +60,7 @@ func equal(t testing.TB, want, got any, name string) bool { if vw.Kind() != reflect.Struct { ok := compare.Equal(want, got) if !ok { - t.Errorf("%s: %+v != %+v", name, want, got) + tb.Errorf("%s: %+v != %+v", name, want, got) } return ok } @@ -86,7 +86,7 @@ func equal(t testing.TB, want, got any, name string) bool { rw := mw.Call(nil)[0].Interface() rg := mg.Call(nil)[0].Interface() - ok = equal(t, rw, rg, fname) && ok + ok = equal(tb, rw, rg, fname) && ok } // compare all exported fields of the struct @@ -97,7 +97,7 @@ func equal(t testing.TB, want, got any, name string) bool { fname := name + "." + vw.Type().Field(i).Name fw := vw.Field(i).Interface() fg := vg.Field(i).Interface() - ok = equal(t, fw, fg, fname) && ok + ok = equal(tb, fw, fg, fname) && ok } if !ok { return false @@ -106,13 +106,13 @@ func equal(t testing.TB, want, got any, name string) bool { if _, ok := want.(expo.DataPoint); ok { err := pmetrictest.CompareExponentialHistogramDataPoint(want.(expo.DataPoint), got.(expo.DataPoint)) if err != nil { - t.Error(err) + tb.Error(err) } } // fallback to a full deep-equal for rare cases (unexported fields, etc) if diff := compare.Diff(want, got); diff != "" { - t.Error(diff) + tb.Error(diff) return false } diff --git a/processor/deltatocumulativeprocessor/internal/data/datatest/equal_test.go b/processor/deltatocumulativeprocessor/internal/data/datatest/equal_test.go index 48837b4cdb8b..d2522a16e4d1 100644 --- a/processor/deltatocumulativeprocessor/internal/data/datatest/equal_test.go +++ b/processor/deltatocumulativeprocessor/internal/data/datatest/equal_test.go @@ -15,12 +15,12 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/processor/deltatocumulativeprocessor/internal/data/expo/expotest" ) -var t testing.TB = fakeT{} +var tb testing.TB = fakeT{} -var datatest = struct{ New func(t testing.TB) T }{New: New} +var datatest = struct{ New func(tb testing.TB) T }{New: New} func ExampleT_Equal() { - is := datatest.New(t) + is := datatest.New(tb) want := expotest.Histogram{ PosNeg: expotest.Observe(expo.Scale(0), 1, 2, 3, 4), diff --git a/processor/deltatocumulativeprocessor/processor_test.go b/processor/deltatocumulativeprocessor/processor_test.go index 23b05dcaa1ad..daaacda42d56 100644 --- a/processor/deltatocumulativeprocessor/processor_test.go +++ b/processor/deltatocumulativeprocessor/processor_test.go @@ -97,8 +97,8 @@ func config(t *testing.T, file string) *Config { return cfg } -func setup(t testing.TB, cfg *Config) State { - t.Helper() +func setup(tb testing.TB, cfg *Config) State { + tb.Helper() next := &consumertest.MetricsSink{} if cfg == nil { @@ -112,7 +112,7 @@ func setup(t testing.TB, cfg *Config) State { cfg, next, ) - require.NoError(t, err) + require.NoError(tb, err) return State{ proc: proc, diff --git a/receiver/awsxrayreceiver/internal/translator/translator_test.go b/receiver/awsxrayreceiver/internal/translator/translator_test.go index c9cdc8bfd944..4f9fbe9609ed 100644 --- a/receiver/awsxrayreceiver/internal/translator/translator_test.go +++ b/receiver/awsxrayreceiver/internal/translator/translator_test.go @@ -66,7 +66,7 @@ func TestTranslation(t *testing.T) { samplePath string expectedResourceAttrs func(seg *awsxray.Segment) map[string]any expectedRecord xray.TelemetryRecord - propsPerSpan func(testCase string, t *testing.T, seg *awsxray.Segment) []perSpanProperties + propsPerSpan func(t *testing.T, testCase string, seg *awsxray.Segment) []perSpanProperties verification func(testCase string, actualSeg *awsxray.Segment, expectedRs ptrace.ResourceSpans, @@ -92,7 +92,7 @@ func TestTranslation(t *testing.T) { SegmentsReceivedCount: aws.Int64(1), SegmentsRejectedCount: aws.Int64(0), }, - propsPerSpan: func(_ string, _ *testing.T, seg *awsxray.Segment) []perSpanProperties { + propsPerSpan: func(_ *testing.T, _ string, seg *awsxray.Segment) []perSpanProperties { attrs := defaultServerSpanAttrs(seg) res := perSpanProperties{ traceID: *seg.TraceID, @@ -136,7 +136,7 @@ func TestTranslation(t *testing.T) { SegmentsReceivedCount: aws.Int64(18), SegmentsRejectedCount: aws.Int64(0), }, - propsPerSpan: func(testCase string, t *testing.T, seg *awsxray.Segment) []perSpanProperties { + propsPerSpan: func(t *testing.T, testCase string, seg *awsxray.Segment) []perSpanProperties { rootSpanAttrs := pcommon.NewMap() rootSpanAttrs.PutStr(conventions.AttributeEnduserID, *seg.User) rootSpanEvts := initExceptionEvents(seg) @@ -542,7 +542,7 @@ func TestTranslation(t *testing.T) { SegmentsReceivedCount: aws.Int64(1), SegmentsRejectedCount: aws.Int64(0), }, - propsPerSpan: func(_ string, _ *testing.T, seg *awsxray.Segment) []perSpanProperties { + propsPerSpan: func(_ *testing.T, _ string, seg *awsxray.Segment) []perSpanProperties { attrs := defaultServerSpanAttrs(seg) res := perSpanProperties{ traceID: *seg.TraceID, @@ -596,7 +596,7 @@ func TestTranslation(t *testing.T) { SegmentsReceivedCount: aws.Int64(1), SegmentsRejectedCount: aws.Int64(0), }, - propsPerSpan: func(_ string, _ *testing.T, seg *awsxray.Segment) []perSpanProperties { + propsPerSpan: func(_ *testing.T, _ string, seg *awsxray.Segment) []perSpanProperties { attrs := defaultServerSpanAttrs(seg) attrs.PutStr(awsxray.AWSAccountAttribute, *seg.AWS.AccountID) res := perSpanProperties{ @@ -638,7 +638,7 @@ func TestTranslation(t *testing.T) { SegmentsReceivedCount: aws.Int64(1), SegmentsRejectedCount: aws.Int64(0), }, - propsPerSpan: func(_ string, _ *testing.T, seg *awsxray.Segment) []perSpanProperties { + propsPerSpan: func(_ *testing.T, _ string, seg *awsxray.Segment) []perSpanProperties { res := perSpanProperties{ traceID: *seg.TraceID, spanID: *seg.ID, @@ -676,7 +676,7 @@ func TestTranslation(t *testing.T) { SegmentsReceivedCount: aws.Int64(18), SegmentsRejectedCount: aws.Int64(18), }, - propsPerSpan: func(string, *testing.T, *awsxray.Segment) []perSpanProperties { + propsPerSpan: func(*testing.T, string, *awsxray.Segment) []perSpanProperties { return nil }, verification: func(testCase string, @@ -701,7 +701,7 @@ func TestTranslation(t *testing.T) { SegmentsReceivedCount: aws.Int64(1), SegmentsRejectedCount: aws.Int64(0), }, - propsPerSpan: func(_ string, _ *testing.T, seg *awsxray.Segment) []perSpanProperties { + propsPerSpan: func(_ *testing.T, _ string, seg *awsxray.Segment) []perSpanProperties { attrs := pcommon.NewMap() assert.NoError(t, attrs.FromRaw(map[string]any{ conventions.AttributeHTTPMethod: *seg.HTTP.Request.Method, @@ -750,7 +750,7 @@ func TestTranslation(t *testing.T) { SegmentsReceivedCount: aws.Int64(1), SegmentsRejectedCount: aws.Int64(0), }, - propsPerSpan: func(_ string, _ *testing.T, seg *awsxray.Segment) []perSpanProperties { + propsPerSpan: func(_ *testing.T, _ string, seg *awsxray.Segment) []perSpanProperties { attrs := pcommon.NewMap() assert.NoError(t, attrs.FromRaw(map[string]any{ conventions.AttributeHTTPMethod: *seg.HTTP.Request.Method, @@ -800,7 +800,7 @@ func TestTranslation(t *testing.T) { SegmentsReceivedCount: aws.Int64(1), SegmentsRejectedCount: aws.Int64(0), }, - propsPerSpan: func(_ string, _ *testing.T, seg *awsxray.Segment) []perSpanProperties { + propsPerSpan: func(_ *testing.T, _ string, seg *awsxray.Segment) []perSpanProperties { attrs := pcommon.NewMap() assert.NoError(t, attrs.FromRaw(map[string]any{ conventions.AttributeDBConnectionString: "jdbc:postgresql://aawijb5u25wdoy.cpamxznpdoq8.us-west-2." + @@ -847,7 +847,7 @@ func TestTranslation(t *testing.T) { SegmentsReceivedCount: aws.Int64(1), SegmentsRejectedCount: aws.Int64(1), }, - propsPerSpan: func(string, *testing.T, *awsxray.Segment) []perSpanProperties { + propsPerSpan: func(*testing.T, string, *awsxray.Segment) []perSpanProperties { return nil }, verification: func(testCase string, @@ -872,7 +872,7 @@ func TestTranslation(t *testing.T) { SegmentsReceivedCount: aws.Int64(1), SegmentsRejectedCount: aws.Int64(0), }, - propsPerSpan: func(_ string, _ *testing.T, seg *awsxray.Segment) []perSpanProperties { + propsPerSpan: func(_ *testing.T, _ string, seg *awsxray.Segment) []perSpanProperties { attrs := pcommon.NewMap() assert.NoError(t, attrs.FromRaw(map[string]any{ awsxray.AWSXRayTracedAttribute: true, @@ -916,7 +916,7 @@ func TestTranslation(t *testing.T) { SegmentsReceivedCount: aws.Int64(0), SegmentsRejectedCount: aws.Int64(0), }, - propsPerSpan: func(string, *testing.T, *awsxray.Segment) []perSpanProperties { + propsPerSpan: func(*testing.T, string, *awsxray.Segment) []perSpanProperties { return nil }, verification: func(testCase string, @@ -941,7 +941,7 @@ func TestTranslation(t *testing.T) { SegmentsReceivedCount: aws.Int64(1), SegmentsRejectedCount: aws.Int64(1), }, - propsPerSpan: func(string, *testing.T, *awsxray.Segment) []perSpanProperties { + propsPerSpan: func(*testing.T, string, *awsxray.Segment) []perSpanProperties { return nil }, verification: func(testCase string, @@ -972,7 +972,7 @@ func TestTranslation(t *testing.T) { expectedRs = initResourceSpans(t, &actualSeg, tc.expectedResourceAttrs(&actualSeg), - tc.propsPerSpan(tc.testCase, t, &actualSeg), + tc.propsPerSpan(t, tc.testCase, &actualSeg), ) } diff --git a/receiver/dockerstatsreceiver/config_test.go b/receiver/dockerstatsreceiver/config_test.go index 1fd7602e06df..30775206b092 100644 --- a/receiver/dockerstatsreceiver/config_test.go +++ b/receiver/dockerstatsreceiver/config_test.go @@ -21,11 +21,11 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/dockerstatsreceiver/internal/metadata" ) -func loadConf(t testing.TB, path string, id component.ID) *confmap.Conf { +func loadConf(tb testing.TB, path string, id component.ID) *confmap.Conf { cm, err := confmaptest.LoadConf(filepath.Join("testdata", path)) - require.NoError(t, err) + require.NoError(tb, err) sub, err := cm.Sub(id.String()) - require.NoError(t, err) + require.NoError(tb, err) return sub } diff --git a/receiver/k8sclusterreceiver/internal/testutils/metrics.go b/receiver/k8sclusterreceiver/internal/testutils/metrics.go index bd19391536a0..529dfe754407 100644 --- a/receiver/k8sclusterreceiver/internal/testutils/metrics.go +++ b/receiver/k8sclusterreceiver/internal/testutils/metrics.go @@ -10,15 +10,15 @@ import ( "go.opentelemetry.io/collector/pdata/pmetric" ) -func AssertMetricInt(t testing.TB, m pmetric.Metric, expectedMetric string, expectedType pmetric.MetricType, expectedValue any) { - dps := assertMetric(t, m, expectedMetric, expectedType) - require.EqualValues(t, expectedValue, dps.At(0).IntValue(), "mismatching metric values") +func AssertMetricInt(tb testing.TB, m pmetric.Metric, expectedMetric string, expectedType pmetric.MetricType, expectedValue any) { + dps := assertMetric(tb, m, expectedMetric, expectedType) + require.EqualValues(tb, expectedValue, dps.At(0).IntValue(), "mismatching metric values") } -func assertMetric(t testing.TB, m pmetric.Metric, expectedMetric string, expectedType pmetric.MetricType) pmetric.NumberDataPointSlice { - require.Equal(t, expectedMetric, m.Name(), "mismatching metric names") - require.NotEmpty(t, m.Description(), "empty description on metric") - require.Equal(t, expectedType, m.Type(), "mismatching metric types") +func assertMetric(tb testing.TB, m pmetric.Metric, expectedMetric string, expectedType pmetric.MetricType) pmetric.NumberDataPointSlice { + require.Equal(tb, expectedMetric, m.Name(), "mismatching metric names") + require.NotEmpty(tb, m.Description(), "empty description on metric") + require.Equal(tb, expectedType, m.Type(), "mismatching metric types") var dps pmetric.NumberDataPointSlice //exhaustive:enforce switch expectedType { @@ -27,14 +27,14 @@ func assertMetric(t testing.TB, m pmetric.Metric, expectedMetric string, expecte case pmetric.MetricTypeSum: dps = m.Sum().DataPoints() case pmetric.MetricTypeHistogram: - require.Fail(t, "unsupported") + require.Fail(tb, "unsupported") case pmetric.MetricTypeExponentialHistogram: - require.Fail(t, "unsupported") + require.Fail(tb, "unsupported") case pmetric.MetricTypeSummary: - require.Fail(t, "unsupported") + require.Fail(tb, "unsupported") case pmetric.MetricTypeEmpty: - require.Fail(t, "unsupported") + require.Fail(tb, "unsupported") } - require.Equal(t, 1, dps.Len()) + require.Equal(tb, 1, dps.Len()) return dps } diff --git a/receiver/nsxtreceiver/client_mock_test.go b/receiver/nsxtreceiver/client_mock_test.go index f2cd4fe60890..939b9b29dbb1 100644 --- a/receiver/nsxtreceiver/client_mock_test.go +++ b/receiver/nsxtreceiver/client_mock_test.go @@ -133,11 +133,11 @@ func (m *MockClient) TransportNodes(ctx context.Context) ([]model.TransportNode, } // newMockClient creates a new instance of MockClient. It also registers the testing.TB interface on the mock and a cleanup function to assert the mocks expectations. -func newMockClient(t testing.TB) *MockClient { +func newMockClient(tb testing.TB) *MockClient { mock := &MockClient{} - mock.Mock.Test(t) + mock.Mock.Test(tb) - t.Cleanup(func() { mock.AssertExpectations(t) }) + tb.Cleanup(func() { mock.AssertExpectations(tb) }) return mock } diff --git a/receiver/statsdreceiver/internal/transport/server_test.go b/receiver/statsdreceiver/internal/transport/server_test.go index f8cb0ba516d8..527ed51c2350 100644 --- a/receiver/statsdreceiver/internal/transport/server_test.go +++ b/receiver/statsdreceiver/internal/transport/server_test.go @@ -24,7 +24,7 @@ func Test_Server_ListenAndServe(t *testing.T) { name string transport Transport buildServerFn func(transport Transport, addr string) (Server, error) - getFreeEndpointFn func(t testing.TB, transport string) string + getFreeEndpointFn func(tb testing.TB, transport string) string buildClientFn func(transport string, address string) (*client.StatsD, error) }{ { diff --git a/testbed/correctnesstests/utils.go b/testbed/correctnesstests/utils.go index 8ffd41ad0330..97a88f074c1e 100644 --- a/testbed/correctnesstests/utils.go +++ b/testbed/correctnesstests/utils.go @@ -27,7 +27,7 @@ type ProcessorNameAndConfigBody struct { // processors, and a pipeline type. A collector created from the resulting yaml string should be able to talk // the specified sender and receiver. func CreateConfigYaml( - t testing.TB, + tb testing.TB, sender testbed.DataSender, receiver testbed.DataReceiver, connector testbed.DataConnector, @@ -58,7 +58,7 @@ func CreateConfigYaml( case testbed.LogDataSender: pipeline1 = "logs" default: - t.Error("Invalid DataSender type") + tb.Error("Invalid DataSender type") } if connector != nil { @@ -96,7 +96,7 @@ service: receiver.GenConfigYAMLStr(), processorsSections, connector.GenConfigYAMLStr(), - testutil.GetAvailablePort(t), + testutil.GetAvailablePort(tb), pipeline1, sender.ProtocolName(), processorsList, @@ -132,7 +132,7 @@ service: sender.GenConfigYAMLStr(), receiver.GenConfigYAMLStr(), processorsSections, - testutil.GetAvailablePort(t), + testutil.GetAvailablePort(tb), pipeline1, sender.ProtocolName(), processorsList,