From ebda8c1b806347ef9d51b3f0284ed340d446aba1 Mon Sep 17 00:00:00 2001 From: Bogdan Drutu Date: Wed, 18 Sep 2024 12:33:12 -0700 Subject: [PATCH 1/8] [chore] remove duplicate code in testutil (#11210) Signed-off-by: Bogdan Drutu --- internal/testutil/testutil.go | 38 +++++++++-------------------------- 1 file changed, 9 insertions(+), 29 deletions(-) diff --git a/internal/testutil/testutil.go b/internal/testutil/testutil.go index 60980e840e7..8d0882d04e6 100644 --- a/internal/testutil/testutil.go +++ b/internal/testutil/testutil.go @@ -25,40 +25,20 @@ type portpair struct { // provided that there is no race by some other code to grab the same port // immediately. func GetAvailableLocalAddress(t testing.TB) string { + return findAvailable(t, "tcp4") +} + +// GetAvailableLocalIPv6Address is IPv6 version of GetAvailableLocalAddress. +func GetAvailableLocalIPv6Address(t testing.TB) string { + return findAvailable(t, "tcp6") +} + +func findAvailable(t 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 // "netsh interface ipv4 show excludedportrange protocol=tcp". We'll use []exclusions to hold those ranges and // retry if the port returned by GetAvailableLocalAddress falls in one of those them. - network := "tcp4" - var exclusions []portpair - portFound := false - if runtime.GOOS == "windows" { - exclusions = getExclusionsList(network, t) - } - - var endpoint string - for !portFound { - endpoint = findAvailableAddress(network, t) - _, port, err := net.SplitHostPort(endpoint) - require.NoError(t, err) - portFound = true - if runtime.GOOS == "windows" { - for _, pair := range exclusions { - if port >= pair.first && port <= pair.last { - portFound = false - break - } - } - } - } - - return endpoint -} - -// GetAvailableLocalIPv6Address is IPv6 version of GetAvailableLocalAddress. -func GetAvailableLocalIPv6Address(t testing.TB) string { - network := "tcp6" var exclusions []portpair portFound := false if runtime.GOOS == "windows" { From a3c0565031b046cd97a339ee5cc4b35e540fa4c4 Mon Sep 17 00:00:00 2001 From: Alex Boten <223565+codeboten@users.noreply.github.com> Date: Wed, 18 Sep 2024 12:33:45 -0700 Subject: [PATCH 2/8] [processorhelper] deprecated accepted/refused/dropped metrics (#11201) These were only used by the memory limiter processor and were never automatically calculated by the processorhelper. It's better to move them to processor specific metrics that can be managed within the component itself. --------- Signed-off-by: Alex Boten <223565+codeboten@users.noreply.github.com> --- .chloggen/codeboten_deprecate-metrics.yaml | 36 +++++++++++++++++++ .../memorylimiterprocessor/memorylimiter.go | 6 ++++ processor/processorhelper/documentation.md | 18 +++++----- .../internal/metadata/generated_telemetry.go | 18 +++++----- processor/processorhelper/metadata.yaml | 27 ++++++++++++++ processor/processorhelper/obsreport.go | 18 ++++++++++ 6 files changed, 105 insertions(+), 18 deletions(-) create mode 100644 .chloggen/codeboten_deprecate-metrics.yaml diff --git a/.chloggen/codeboten_deprecate-metrics.yaml b/.chloggen/codeboten_deprecate-metrics.yaml new file mode 100644 index 00000000000..6cd18940929 --- /dev/null +++ b/.chloggen/codeboten_deprecate-metrics.yaml @@ -0,0 +1,36 @@ +# Use this changelog template to create an entry for release notes. + +# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix' +change_type: deprecation + +# The name of the component, or a single word describing the area of concern, (e.g. otlpreceiver) +component: processorhelper + +# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`). +note: deprecate accepted/refused/dropped metrics + +# One or more tracking issues or pull requests related to the change +issues: [11201] + +# (Optional) One or more lines of additional information to render under the primary note. +# These lines will be padded with 2 spaces and then inserted directly into the document. +# Use pipe (|) for multiline entries. +subtext: | + The following metrics are being deprecated as they were only used in a single + processor: + - `otelcol_processor_accepted_log_records` + - `otelcol_processor_accepted_metric_points` + - `otelcol_processor_accepted_spans` + - `otelcol_processor_dropped_log_records` + - `otelcol_processor_dropped_metric_points` + - `otelcol_processor_dropped_spans` + - `otelcol_processor_refused_log_records` + - `otelcol_processor_refused_metric_points` + - `otelcol_processor_refused_spans` + +# Optional: The change log or logs in which this entry should be included. +# e.g. '[user]' or '[user, api]' +# Include 'user' if the change is relevant to end users. +# Include 'api' if there is a change to a library API. +# Default: '[user]' +change_logs: [] diff --git a/processor/memorylimiterprocessor/memorylimiter.go b/processor/memorylimiterprocessor/memorylimiter.go index 8cb1576038a..748437a6f7a 100644 --- a/processor/memorylimiterprocessor/memorylimiter.go +++ b/processor/memorylimiterprocessor/memorylimiter.go @@ -58,12 +58,14 @@ func (p *memoryLimiterProcessor) processTraces(ctx context.Context, td ptrace.Tr // to a receiver (ie.: a receiver is on the call stack). For now it // assumes that the pipeline is properly configured and a receiver is on the // callstack and that the receiver will correctly retry the refused data again. + // nolint SA1019 p.obsrep.TracesRefused(ctx, numSpans) return td, memorylimiter.ErrDataRefused } // Even if the next consumer returns error record the data as accepted by // this processor. + // nolint SA1019 p.obsrep.TracesAccepted(ctx, numSpans) return td, nil } @@ -76,12 +78,14 @@ func (p *memoryLimiterProcessor) processMetrics(ctx context.Context, md pmetric. // to a receiver (ie.: a receiver is on the call stack). For now it // assumes that the pipeline is properly configured and a receiver is on the // callstack. + // nolint SA1019 p.obsrep.MetricsRefused(ctx, numDataPoints) return md, memorylimiter.ErrDataRefused } // Even if the next consumer returns error record the data as accepted by // this processor. + // nolint SA1019 p.obsrep.MetricsAccepted(ctx, numDataPoints) return md, nil } @@ -94,12 +98,14 @@ func (p *memoryLimiterProcessor) processLogs(ctx context.Context, ld plog.Logs) // to a receiver (ie.: a receiver is on the call stack). For now it // assumes that the pipeline is properly configured and a receiver is on the // callstack. + // nolint SA1019 p.obsrep.LogsRefused(ctx, numRecords) return ld, memorylimiter.ErrDataRefused } // Even if the next consumer returns error record the data as accepted by // this processor. + // nolint SA1019 p.obsrep.LogsAccepted(ctx, numRecords) return ld, nil } diff --git a/processor/processorhelper/documentation.md b/processor/processorhelper/documentation.md index 1f91fb037cb..2b2027cd747 100644 --- a/processor/processorhelper/documentation.md +++ b/processor/processorhelper/documentation.md @@ -8,7 +8,7 @@ The following telemetry is emitted by this component. ### otelcol_processor_accepted_log_records -Number of log records successfully pushed into the next component in the pipeline. +Number of log records successfully pushed into the next component in the pipeline. [deprecated since v0.110.0] | Unit | Metric Type | Value Type | Monotonic | | ---- | ----------- | ---------- | --------- | @@ -16,7 +16,7 @@ Number of log records successfully pushed into the next component in the pipelin ### otelcol_processor_accepted_metric_points -Number of metric points successfully pushed into the next component in the pipeline. +Number of metric points successfully pushed into the next component in the pipeline. [deprecated since v0.110.0] | Unit | Metric Type | Value Type | Monotonic | | ---- | ----------- | ---------- | --------- | @@ -24,7 +24,7 @@ Number of metric points successfully pushed into the next component in the pipel ### otelcol_processor_accepted_spans -Number of spans successfully pushed into the next component in the pipeline. +Number of spans successfully pushed into the next component in the pipeline. [deprecated since v0.110.0] | Unit | Metric Type | Value Type | Monotonic | | ---- | ----------- | ---------- | --------- | @@ -32,7 +32,7 @@ Number of spans successfully pushed into the next component in the pipeline. ### otelcol_processor_dropped_log_records -Number of log records that were dropped. +Number of log records that were dropped. [deprecated since v0.110.0] | Unit | Metric Type | Value Type | Monotonic | | ---- | ----------- | ---------- | --------- | @@ -40,7 +40,7 @@ Number of log records that were dropped. ### otelcol_processor_dropped_metric_points -Number of metric points that were dropped. +Number of metric points that were dropped. [deprecated since v0.110.0] | Unit | Metric Type | Value Type | Monotonic | | ---- | ----------- | ---------- | --------- | @@ -48,7 +48,7 @@ Number of metric points that were dropped. ### otelcol_processor_dropped_spans -Number of spans that were dropped. +Number of spans that were dropped. [deprecated since v0.110.0] | Unit | Metric Type | Value Type | Monotonic | | ---- | ----------- | ---------- | --------- | @@ -72,7 +72,7 @@ Number of items emitted from the processor. [alpha] ### otelcol_processor_refused_log_records -Number of log records that were rejected by the next component in the pipeline. +Number of log records that were rejected by the next component in the pipeline. [deprecated since v0.110.0] | Unit | Metric Type | Value Type | Monotonic | | ---- | ----------- | ---------- | --------- | @@ -80,7 +80,7 @@ Number of log records that were rejected by the next component in the pipeline. ### otelcol_processor_refused_metric_points -Number of metric points that were rejected by the next component in the pipeline. +Number of metric points that were rejected by the next component in the pipeline. [deprecated since v0.110.0] | Unit | Metric Type | Value Type | Monotonic | | ---- | ----------- | ---------- | --------- | @@ -88,7 +88,7 @@ Number of metric points that were rejected by the next component in the pipeline ### otelcol_processor_refused_spans -Number of spans that were rejected by the next component in the pipeline. +Number of spans that were rejected by the next component in the pipeline. [deprecated since v0.110.0] | Unit | Metric Type | Value Type | Monotonic | | ---- | ----------- | ---------- | --------- | diff --git a/processor/processorhelper/internal/metadata/generated_telemetry.go b/processor/processorhelper/internal/metadata/generated_telemetry.go index 504fade54de..e264707395e 100644 --- a/processor/processorhelper/internal/metadata/generated_telemetry.go +++ b/processor/processorhelper/internal/metadata/generated_telemetry.go @@ -65,37 +65,37 @@ func NewTelemetryBuilder(settings component.TelemetrySettings, options ...Teleme var err, errs error builder.ProcessorAcceptedLogRecords, err = builder.meters[configtelemetry.LevelBasic].Int64Counter( "otelcol_processor_accepted_log_records", - metric.WithDescription("Number of log records successfully pushed into the next component in the pipeline."), + metric.WithDescription("Number of log records successfully pushed into the next component in the pipeline. [deprecated since v0.110.0]"), metric.WithUnit("{records}"), ) errs = errors.Join(errs, err) builder.ProcessorAcceptedMetricPoints, err = builder.meters[configtelemetry.LevelBasic].Int64Counter( "otelcol_processor_accepted_metric_points", - metric.WithDescription("Number of metric points successfully pushed into the next component in the pipeline."), + metric.WithDescription("Number of metric points successfully pushed into the next component in the pipeline. [deprecated since v0.110.0]"), metric.WithUnit("{datapoints}"), ) errs = errors.Join(errs, err) builder.ProcessorAcceptedSpans, err = builder.meters[configtelemetry.LevelBasic].Int64Counter( "otelcol_processor_accepted_spans", - metric.WithDescription("Number of spans successfully pushed into the next component in the pipeline."), + metric.WithDescription("Number of spans successfully pushed into the next component in the pipeline. [deprecated since v0.110.0]"), metric.WithUnit("{spans}"), ) errs = errors.Join(errs, err) builder.ProcessorDroppedLogRecords, err = builder.meters[configtelemetry.LevelBasic].Int64Counter( "otelcol_processor_dropped_log_records", - metric.WithDescription("Number of log records that were dropped."), + metric.WithDescription("Number of log records that were dropped. [deprecated since v0.110.0]"), metric.WithUnit("{records}"), ) errs = errors.Join(errs, err) builder.ProcessorDroppedMetricPoints, err = builder.meters[configtelemetry.LevelBasic].Int64Counter( "otelcol_processor_dropped_metric_points", - metric.WithDescription("Number of metric points that were dropped."), + metric.WithDescription("Number of metric points that were dropped. [deprecated since v0.110.0]"), metric.WithUnit("{datapoints}"), ) errs = errors.Join(errs, err) builder.ProcessorDroppedSpans, err = builder.meters[configtelemetry.LevelBasic].Int64Counter( "otelcol_processor_dropped_spans", - metric.WithDescription("Number of spans that were dropped."), + metric.WithDescription("Number of spans that were dropped. [deprecated since v0.110.0]"), metric.WithUnit("{spans}"), ) errs = errors.Join(errs, err) @@ -113,19 +113,19 @@ func NewTelemetryBuilder(settings component.TelemetrySettings, options ...Teleme errs = errors.Join(errs, err) builder.ProcessorRefusedLogRecords, err = builder.meters[configtelemetry.LevelBasic].Int64Counter( "otelcol_processor_refused_log_records", - metric.WithDescription("Number of log records that were rejected by the next component in the pipeline."), + metric.WithDescription("Number of log records that were rejected by the next component in the pipeline. [deprecated since v0.110.0]"), metric.WithUnit("{records}"), ) errs = errors.Join(errs, err) builder.ProcessorRefusedMetricPoints, err = builder.meters[configtelemetry.LevelBasic].Int64Counter( "otelcol_processor_refused_metric_points", - metric.WithDescription("Number of metric points that were rejected by the next component in the pipeline."), + metric.WithDescription("Number of metric points that were rejected by the next component in the pipeline. [deprecated since v0.110.0]"), metric.WithUnit("{datapoints}"), ) errs = errors.Join(errs, err) builder.ProcessorRefusedSpans, err = builder.meters[configtelemetry.LevelBasic].Int64Counter( "otelcol_processor_refused_spans", - metric.WithDescription("Number of spans that were rejected by the next component in the pipeline."), + metric.WithDescription("Number of spans that were rejected by the next component in the pipeline. [deprecated since v0.110.0]"), metric.WithUnit("{spans}"), ) errs = errors.Join(errs, err) diff --git a/processor/processorhelper/metadata.yaml b/processor/processorhelper/metadata.yaml index d6be91a6663..93c4c82085c 100644 --- a/processor/processorhelper/metadata.yaml +++ b/processor/processorhelper/metadata.yaml @@ -33,6 +33,9 @@ telemetry: processor_accepted_spans: enabled: true description: Number of spans successfully pushed into the next component in the pipeline. + stability: + level: deprecated + from: v0.110.0 unit: "{spans}" sum: value_type: int @@ -41,6 +44,9 @@ telemetry: processor_refused_spans: enabled: true description: Number of spans that were rejected by the next component in the pipeline. + stability: + level: deprecated + from: v0.110.0 unit: "{spans}" sum: value_type: int @@ -49,6 +55,9 @@ telemetry: processor_dropped_spans: enabled: true description: Number of spans that were dropped. + stability: + level: deprecated + from: v0.110.0 unit: "{spans}" sum: value_type: int @@ -57,6 +66,9 @@ telemetry: processor_accepted_metric_points: enabled: true description: Number of metric points successfully pushed into the next component in the pipeline. + stability: + level: deprecated + from: v0.110.0 unit: "{datapoints}" sum: value_type: int @@ -65,6 +77,9 @@ telemetry: processor_refused_metric_points: enabled: true description: Number of metric points that were rejected by the next component in the pipeline. + stability: + level: deprecated + from: v0.110.0 unit: "{datapoints}" sum: value_type: int @@ -73,6 +88,9 @@ telemetry: processor_dropped_metric_points: enabled: true description: Number of metric points that were dropped. + stability: + level: deprecated + from: v0.110.0 unit: "{datapoints}" sum: value_type: int @@ -81,6 +99,9 @@ telemetry: processor_accepted_log_records: enabled: true description: Number of log records successfully pushed into the next component in the pipeline. + stability: + level: deprecated + from: v0.110.0 unit: "{records}" sum: value_type: int @@ -89,6 +110,9 @@ telemetry: processor_refused_log_records: enabled: true description: Number of log records that were rejected by the next component in the pipeline. + stability: + level: deprecated + from: v0.110.0 unit: "{records}" sum: value_type: int @@ -97,6 +121,9 @@ telemetry: processor_dropped_log_records: enabled: true description: Number of log records that were dropped. + stability: + level: deprecated + from: v0.110.0 unit: "{records}" sum: value_type: int diff --git a/processor/processorhelper/obsreport.go b/processor/processorhelper/obsreport.go index 791822e0aa7..dfbc2971ec5 100644 --- a/processor/processorhelper/obsreport.go +++ b/processor/processorhelper/obsreport.go @@ -88,46 +88,64 @@ func (or *ObsReport) recordData(ctx context.Context, dataType component.DataType } // TracesAccepted reports that the trace data was accepted. +// +// Deprecated: [v0.110.0] Processor helper automatically calculates incoming/outgoing metrics only. func (or *ObsReport) TracesAccepted(ctx context.Context, numSpans int) { or.recordData(ctx, component.DataTypeTraces, int64(numSpans), int64(0), int64(0)) } // TracesRefused reports that the trace data was refused. +// +// Deprecated: [v0.110.0] Processor helper automatically calculates incoming/outgoing metrics only. func (or *ObsReport) TracesRefused(ctx context.Context, numSpans int) { or.recordData(ctx, component.DataTypeTraces, int64(0), int64(numSpans), int64(0)) } // TracesDropped reports that the trace data was dropped. +// +// Deprecated: [v0.110.0] Processor helper automatically calculates incoming/outgoing metrics only. func (or *ObsReport) TracesDropped(ctx context.Context, numSpans int) { or.recordData(ctx, component.DataTypeTraces, int64(0), int64(0), int64(numSpans)) } // MetricsAccepted reports that the metrics were accepted. +// +// Deprecated: [v0.110.0] Processor helper automatically calculates incoming/outgoing metrics only. func (or *ObsReport) MetricsAccepted(ctx context.Context, numPoints int) { or.recordData(ctx, component.DataTypeMetrics, int64(numPoints), int64(0), int64(0)) } // MetricsRefused reports that the metrics were refused. +// +// Deprecated: [v0.110.0] Processor helper automatically calculates incoming/outgoing metrics only. func (or *ObsReport) MetricsRefused(ctx context.Context, numPoints int) { or.recordData(ctx, component.DataTypeMetrics, int64(0), int64(numPoints), int64(0)) } // MetricsDropped reports that the metrics were dropped. +// +// Deprecated: [v0.110.0] Processor helper automatically calculates incoming/outgoing metrics only. func (or *ObsReport) MetricsDropped(ctx context.Context, numPoints int) { or.recordData(ctx, component.DataTypeMetrics, int64(0), int64(0), int64(numPoints)) } // LogsAccepted reports that the logs were accepted. +// +// Deprecated: [v0.110.0] Processor helper automatically calculates incoming/outgoing metrics only. func (or *ObsReport) LogsAccepted(ctx context.Context, numRecords int) { or.recordData(ctx, component.DataTypeLogs, int64(numRecords), int64(0), int64(0)) } // LogsRefused reports that the logs were refused. +// +// Deprecated: [v0.110.0] Processor helper automatically calculates incoming/outgoing metrics only. func (or *ObsReport) LogsRefused(ctx context.Context, numRecords int) { or.recordData(ctx, component.DataTypeLogs, int64(0), int64(numRecords), int64(0)) } // LogsDropped reports that the logs were dropped. +// +// Deprecated: [v0.110.0] Processor helper automatically calculates incoming/outgoing metrics only. func (or *ObsReport) LogsDropped(ctx context.Context, numRecords int) { or.recordData(ctx, component.DataTypeLogs, int64(0), int64(0), int64(numRecords)) } From fbffbb0820bb943a92ad2ce4ca0c86da3ab75125 Mon Sep 17 00:00:00 2001 From: Alex Boten <223565+codeboten@users.noreply.github.com> Date: Wed, 18 Sep 2024 13:47:25 -0700 Subject: [PATCH 3/8] [chore] small test improvements (#11211) Clean up some inconsistencies in the test code across the components. Signed-off-by: Alex Boten <223565+codeboten@users.noreply.github.com> --- client/client_test.go | 28 ++-- cmd/builder/internal/builder/main_test.go | 40 ++--- .../generated_component_test.go | 12 +- .../metadata/generated_metrics_test.go | 26 ++-- .../metadata/generated_resource_test.go | 14 +- .../internal/templates/component_test.go.tmpl | 48 +++--- .../internal/templates/metrics_test.go.tmpl | 24 +-- .../internal/templates/resource_test.go.tmpl | 12 +- component/identifiable_test.go | 46 +++--- config/configauth/configauth_test.go | 32 ++-- config/configgrpc/configgrpc_test.go | 24 +-- config/confighttp/clientinfohandler_test.go | 16 +- config/confighttp/confighttp_test.go | 146 +++++++++--------- .../configtelemetry/configtelemetry_test.go | 10 +- .../converter/expandconverter/expand_test.go | 14 +- confmap/expand_test.go | 6 +- confmap/internal/mapstructure/encoder_test.go | 39 +++-- confmap/provider/envprovider/provider_test.go | 16 +- .../configurablehttpprovider/provider_test.go | 16 +- connector/connector_test.go | 3 +- .../generated_component_test.go | 12 +- .../debugexporter/generated_component_test.go | 12 +- exporter/exporter_test.go | 3 +- .../internal/queue/persistent_queue_test.go | 42 ++--- .../generated_component_test.go | 12 +- .../nopexporter/generated_component_test.go | 12 +- exporter/otlpexporter/config_test.go | 8 +- .../otlpexporter/generated_component_test.go | 12 +- .../generated_component_test.go | 12 +- exporter/otlphttpexporter/otlp_test.go | 48 +++--- .../auth/authtest/mock_clientauth_test.go | 16 +- extension/extension_test.go | 3 +- internal/e2e/otlphttp_test.go | 18 +-- otelcol/config_test.go | 8 +- pdata/pcommon/value_test.go | 16 +- .../generated_component_test.go | 12 +- .../generated_component_test.go | 8 +- processor/processor_test.go | 3 +- .../nopreceiver/generated_component_test.go | 12 +- receiver/otlpreceiver/config_test.go | 6 +- .../otlpreceiver/generated_component_test.go | 12 +- receiver/receiver_test.go | 3 +- receiver/scrapererror/scrapeerror_test.go | 14 +- .../scraperhelper/scrapercontroller_test.go | 4 +- service/config_test.go | 8 +- service/extensions/extensions_test.go | 14 +- service/internal/graph/graph_test.go | 60 +++---- service/internal/status/status_test.go | 18 +-- service/pipelines/config_test.go | 8 +- service/telemetry/metrics_test.go | 22 +-- 50 files changed, 506 insertions(+), 504 deletions(-) diff --git a/client/client_test.go b/client/client_test.go index 37f300de496..c3d33c9f40d 100644 --- a/client/client_test.go +++ b/client/client_test.go @@ -15,11 +15,11 @@ import ( func TestNewContext(t *testing.T) { testCases := []struct { - desc string + name string cl Info }{ { - desc: "valid client", + name: "valid client", cl: Info{ Addr: &net.IPAddr{ IP: net.IPv4(1, 2, 3, 4), @@ -27,26 +27,26 @@ func TestNewContext(t *testing.T) { }, }, { - desc: "nil client", + name: "nil client", cl: Info{}, }, } - for _, tC := range testCases { - t.Run(tC.desc, func(t *testing.T) { - ctx := NewContext(context.Background(), tC.cl) - assert.Equal(t, ctx.Value(ctxKey{}), tC.cl) + for _, tt := range testCases { + t.Run(tt.name, func(t *testing.T) { + ctx := NewContext(context.Background(), tt.cl) + assert.Equal(t, ctx.Value(ctxKey{}), tt.cl) }) } } func TestFromContext(t *testing.T) { testCases := []struct { - desc string + name string input context.Context expected Info }{ { - desc: "context with client", + name: "context with client", input: context.WithValue(context.Background(), ctxKey{}, Info{ Addr: &net.IPAddr{ IP: net.IPv4(1, 2, 3, 4), @@ -59,19 +59,19 @@ func TestFromContext(t *testing.T) { }, }, { - desc: "context without client", + name: "context without client", input: context.Background(), expected: Info{}, }, { - desc: "context with something else in the key", + name: "context with something else in the key", input: context.WithValue(context.Background(), ctxKey{}, "unexpected!"), expected: Info{}, }, } - for _, tC := range testCases { - t.Run(tC.desc, func(t *testing.T) { - assert.Equal(t, tC.expected, FromContext(tC.input)) + for _, tt := range testCases { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.expected, FromContext(tt.input)) }) } } diff --git a/cmd/builder/internal/builder/main_test.go b/cmd/builder/internal/builder/main_test.go index 400740610cf..aa90c99ca4f 100644 --- a/cmd/builder/internal/builder/main_test.go +++ b/cmd/builder/internal/builder/main_test.go @@ -128,12 +128,12 @@ func TestGenerateInvalidOutputPath(t *testing.T) { func TestVersioning(t *testing.T) { replaces := generateReplaces() tests := []struct { - description string + name string cfgBuilder func() Config expectedErr error }{ { - description: "defaults", + name: "defaults", cfgBuilder: func() Config { cfg := newTestConfig() cfg.Distribution.Go = "go" @@ -143,7 +143,7 @@ func TestVersioning(t *testing.T) { expectedErr: nil, }, { - description: "require otelcol", + name: "require otelcol", cfgBuilder: func() Config { cfg := newTestConfig() cfg.Distribution.Go = "go" @@ -154,7 +154,7 @@ func TestVersioning(t *testing.T) { expectedErr: nil, }, { - description: "only gomod file, skip generate", + name: "only gomod file, skip generate", cfgBuilder: func() Config { cfg := newTestConfig() tempDir := t.TempDir() @@ -168,7 +168,7 @@ func TestVersioning(t *testing.T) { expectedErr: ErrDepNotFound, }, { - description: "old otel version", + name: "old otel version", cfgBuilder: func() Config { cfg := newTestConfig() cfg.Verbose = true @@ -200,7 +200,7 @@ func TestVersioning(t *testing.T) { expectedErr: nil, }, { - description: "old component version", + name: "old component version", cfgBuilder: func() Config { cfg := newTestConfig() cfg.Distribution.Go = "go" @@ -216,7 +216,7 @@ func TestVersioning(t *testing.T) { expectedErr: nil, }, { - description: "old component version without strict mode", + name: "old component version without strict mode", cfgBuilder: func() Config { cfg := newTestConfig() cfg.Distribution.Go = "go" @@ -233,14 +233,14 @@ func TestVersioning(t *testing.T) { expectedErr: nil, }, } - for _, tc := range tests { - t.Run(tc.description, func(t *testing.T) { - cfg := tc.cfgBuilder() + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cfg := tt.cfgBuilder() require.NoError(t, cfg.SetBackwardsCompatibility()) require.NoError(t, cfg.Validate()) require.NoError(t, cfg.ParseModules()) err := GenerateAndCompile(cfg) - require.ErrorIs(t, err, tc.expectedErr) + require.ErrorIs(t, err, tt.expectedErr) }) } } @@ -263,11 +263,11 @@ func TestSkipGenerate(t *testing.T) { func TestGenerateAndCompile(t *testing.T) { replaces := generateReplaces() testCases := []struct { - testCase string + name string cfgBuilder func(t *testing.T) Config }{ { - testCase: "Default Configuration Compilation", + name: "Default Configuration Compilation", cfgBuilder: func(t *testing.T) Config { cfg := newTestConfig() err := cfg.SetBackwardsCompatibility() @@ -278,7 +278,7 @@ func TestGenerateAndCompile(t *testing.T) { }, }, { - testCase: "LDFlags Compilation", + name: "LDFlags Compilation", cfgBuilder: func(t *testing.T) Config { cfg := newTestConfig() err := cfg.SetBackwardsCompatibility() @@ -290,7 +290,7 @@ func TestGenerateAndCompile(t *testing.T) { }, }, { - testCase: "Debug Compilation", + name: "Debug Compilation", cfgBuilder: func(t *testing.T) Config { cfg := newTestConfig() err := cfg.SetBackwardsCompatibility() @@ -303,7 +303,7 @@ func TestGenerateAndCompile(t *testing.T) { }, }, { - testCase: "No providers", + name: "No providers", cfgBuilder: func(t *testing.T) Config { cfg := newTestConfig() err := cfg.SetBackwardsCompatibility() @@ -315,7 +315,7 @@ func TestGenerateAndCompile(t *testing.T) { }, }, { - testCase: "Pre-confmap factories", + name: "Pre-confmap factories", cfgBuilder: func(t *testing.T) Config { cfg := newTestConfig() err := cfg.SetBackwardsCompatibility() @@ -328,7 +328,7 @@ func TestGenerateAndCompile(t *testing.T) { }, }, { - testCase: "With confmap factories", + name: "With confmap factories", cfgBuilder: func(t *testing.T) Config { cfg := newTestConfig() err := cfg.SetBackwardsCompatibility() @@ -341,7 +341,7 @@ func TestGenerateAndCompile(t *testing.T) { }, }, { - testCase: "ConfResolverDefaultURIScheme set", + name: "ConfResolverDefaultURIScheme set", cfgBuilder: func(t *testing.T) Config { cfg := newTestConfig() err := cfg.SetBackwardsCompatibility() @@ -357,7 +357,7 @@ func TestGenerateAndCompile(t *testing.T) { } for _, tt := range testCases { - t.Run(tt.testCase, func(t *testing.T) { + t.Run(tt.name, func(t *testing.T) { cfg := tt.cfgBuilder(t) assert.NoError(t, cfg.Validate()) assert.NoError(t, cfg.SetGoPath()) diff --git a/cmd/mdatagen/internal/samplereceiver/generated_component_test.go b/cmd/mdatagen/internal/samplereceiver/generated_component_test.go index 46616a207e5..ce37390aecd 100644 --- a/cmd/mdatagen/internal/samplereceiver/generated_component_test.go +++ b/cmd/mdatagen/internal/samplereceiver/generated_component_test.go @@ -62,21 +62,21 @@ func TestComponentLifecycle(t *testing.T) { require.NoError(t, err) require.NoError(t, sub.Unmarshal(&cfg)) - for _, test := range tests { - t.Run(test.name+"-shutdown", func(t *testing.T) { - c, err := test.createFn(context.Background(), receivertest.NewNopSettings(), cfg) + for _, tt := range tests { + t.Run(tt.name+"-shutdown", func(t *testing.T) { + c, err := tt.createFn(context.Background(), receivertest.NewNopSettings(), cfg) require.NoError(t, err) err = c.Shutdown(context.Background()) require.NoError(t, err) }) - t.Run(test.name+"-lifecycle", func(t *testing.T) { - firstRcvr, err := test.createFn(context.Background(), receivertest.NewNopSettings(), cfg) + t.Run(tt.name+"-lifecycle", func(t *testing.T) { + firstRcvr, err := tt.createFn(context.Background(), receivertest.NewNopSettings(), cfg) require.NoError(t, err) host := componenttest.NewNopHost() require.NoError(t, err) require.NoError(t, firstRcvr.Start(context.Background(), host)) require.NoError(t, firstRcvr.Shutdown(context.Background())) - secondRcvr, err := test.createFn(context.Background(), receivertest.NewNopSettings(), cfg) + secondRcvr, err := tt.createFn(context.Background(), receivertest.NewNopSettings(), cfg) require.NoError(t, err) require.NoError(t, secondRcvr.Start(context.Background(), host)) require.NoError(t, secondRcvr.Shutdown(context.Background())) diff --git a/cmd/mdatagen/internal/samplereceiver/internal/metadata/generated_metrics_test.go b/cmd/mdatagen/internal/samplereceiver/internal/metadata/generated_metrics_test.go index f4e2bd4ec4c..c271171d643 100644 --- a/cmd/mdatagen/internal/samplereceiver/internal/metadata/generated_metrics_test.go +++ b/cmd/mdatagen/internal/samplereceiver/internal/metadata/generated_metrics_test.go @@ -53,41 +53,41 @@ func TestMetricsBuilder(t *testing.T) { expectEmpty: true, }, } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { start := pcommon.Timestamp(1_000_000_000) ts := pcommon.Timestamp(1_000_001_000) observedZapCore, observedLogs := observer.New(zap.WarnLevel) settings := receivertest.NewNopSettings() settings.Logger = zap.New(observedZapCore) - mb := NewMetricsBuilder(loadMetricsBuilderConfig(t, test.name), settings, WithStartTime(start)) + mb := NewMetricsBuilder(loadMetricsBuilderConfig(t, tt.name), settings, WithStartTime(start)) expectedWarnings := 0 - if test.metricsSet == testDataSetDefault { + if tt.metricsSet == testDataSetDefault { assert.Equal(t, "[WARNING] Please set `enabled` field explicitly for `default.metric`: This metric will be disabled by default soon.", observedLogs.All()[expectedWarnings].Message) expectedWarnings++ } - if test.metricsSet == testDataSetDefault || test.metricsSet == testDataSetAll { + if tt.metricsSet == testDataSetDefault || tt.metricsSet == testDataSetAll { assert.Equal(t, "[WARNING] `default.metric.to_be_removed` should not be enabled: This metric is deprecated and will be removed soon.", observedLogs.All()[expectedWarnings].Message) expectedWarnings++ } - if test.metricsSet == testDataSetAll || test.metricsSet == testDataSetNone { + if tt.metricsSet == testDataSetAll || tt.metricsSet == testDataSetNone { assert.Equal(t, "[WARNING] `optional.metric` should not be configured: This metric is deprecated and will be removed soon.", observedLogs.All()[expectedWarnings].Message) expectedWarnings++ } - if test.metricsSet == testDataSetAll || test.metricsSet == testDataSetNone { + if tt.metricsSet == testDataSetAll || tt.metricsSet == testDataSetNone { assert.Equal(t, "[WARNING] `optional.metric.empty_unit` should not be configured: This metric is deprecated and will be removed soon.", observedLogs.All()[expectedWarnings].Message) expectedWarnings++ } - if test.resAttrsSet == testDataSetDefault { + if tt.resAttrsSet == testDataSetDefault { assert.Equal(t, "[WARNING] Please set `enabled` field explicitly for `string.resource.attr_disable_warning`: This resource_attribute will be disabled by default soon.", observedLogs.All()[expectedWarnings].Message) expectedWarnings++ } - if test.resAttrsSet == testDataSetAll || test.resAttrsSet == testDataSetNone { + if tt.resAttrsSet == testDataSetAll || tt.resAttrsSet == testDataSetNone { assert.Equal(t, "[WARNING] `string.resource.attr_remove_warning` should not be configured: This resource_attribute is deprecated and will be removed soon.", observedLogs.All()[expectedWarnings].Message) expectedWarnings++ } - if test.resAttrsSet == testDataSetDefault || test.resAttrsSet == testDataSetAll { + if tt.resAttrsSet == testDataSetDefault || tt.resAttrsSet == testDataSetAll { assert.Equal(t, "[WARNING] `string.resource.attr_to_be_removed` should not be enabled: This resource_attribute is deprecated and will be removed soon.", observedLogs.All()[expectedWarnings].Message) expectedWarnings++ } @@ -127,7 +127,7 @@ func TestMetricsBuilder(t *testing.T) { res := rb.Emit() metrics := mb.Emit(WithResource(res)) - if test.expectEmpty { + if tt.expectEmpty { assert.Equal(t, 0, metrics.ResourceMetrics().Len()) return } @@ -137,10 +137,10 @@ func TestMetricsBuilder(t *testing.T) { assert.Equal(t, res, rm.Resource()) assert.Equal(t, 1, rm.ScopeMetrics().Len()) ms := rm.ScopeMetrics().At(0).Metrics() - if test.metricsSet == testDataSetDefault { + if tt.metricsSet == testDataSetDefault { assert.Equal(t, defaultMetricsCount, ms.Len()) } - if test.metricsSet == testDataSetAll { + if tt.metricsSet == testDataSetAll { assert.Equal(t, allMetricsCount, ms.Len()) } validatedMetrics := make(map[string]bool) diff --git a/cmd/mdatagen/internal/samplereceiver/internal/metadata/generated_resource_test.go b/cmd/mdatagen/internal/samplereceiver/internal/metadata/generated_resource_test.go index c0bde40a087..162e83a991a 100644 --- a/cmd/mdatagen/internal/samplereceiver/internal/metadata/generated_resource_test.go +++ b/cmd/mdatagen/internal/samplereceiver/internal/metadata/generated_resource_test.go @@ -9,9 +9,9 @@ import ( ) func TestResourceBuilder(t *testing.T) { - for _, test := range []string{"default", "all_set", "none_set"} { - t.Run(test, func(t *testing.T) { - cfg := loadResourceAttributesConfig(t, test) + for _, tt := range []string{"default", "all_set", "none_set"} { + t.Run(tt, func(t *testing.T) { + cfg := loadResourceAttributesConfig(t, tt) rb := NewResourceBuilder(cfg) rb.SetMapResourceAttr(map[string]any{"key1": "map.resource.attr-val1", "key2": "map.resource.attr-val2"}) rb.SetOptionalResourceAttr("optional.resource.attr-val") @@ -25,7 +25,7 @@ func TestResourceBuilder(t *testing.T) { res := rb.Emit() assert.Equal(t, 0, rb.Emit().Attributes().Len()) // Second call should return empty Resource - switch test { + switch tt { case "default": assert.Equal(t, 6, res.Attributes().Len()) case "all_set": @@ -34,7 +34,7 @@ func TestResourceBuilder(t *testing.T) { assert.Equal(t, 0, res.Attributes().Len()) return default: - assert.Failf(t, "unexpected test case: %s", test) + assert.Failf(t, "unexpected test case: %s", tt) } val, ok := res.Attributes().Get("map.resource.attr") @@ -43,7 +43,7 @@ func TestResourceBuilder(t *testing.T) { assert.EqualValues(t, map[string]any{"key1": "map.resource.attr-val1", "key2": "map.resource.attr-val2"}, val.Map().AsRaw()) } val, ok = res.Attributes().Get("optional.resource.attr") - assert.Equal(t, test == "all_set", ok) + assert.Equal(t, tt == "all_set", ok) if ok { assert.EqualValues(t, "optional.resource.attr-val", val.Str()) } @@ -68,7 +68,7 @@ func TestResourceBuilder(t *testing.T) { assert.EqualValues(t, "string.resource.attr_disable_warning-val", val.Str()) } val, ok = res.Attributes().Get("string.resource.attr_remove_warning") - assert.Equal(t, test == "all_set", ok) + assert.Equal(t, tt == "all_set", ok) if ok { assert.EqualValues(t, "string.resource.attr_remove_warning-val", val.Str()) } diff --git a/cmd/mdatagen/internal/templates/component_test.go.tmpl b/cmd/mdatagen/internal/templates/component_test.go.tmpl index be75cb1bae9..734286ebff1 100644 --- a/cmd/mdatagen/internal/templates/component_test.go.tmpl +++ b/cmd/mdatagen/internal/templates/component_test.go.tmpl @@ -104,10 +104,10 @@ func TestComponentLifecycle(t *testing.T) { require.NoError(t, err) require.NoError(t, sub.Unmarshal(&cfg)) - for _, test := range tests { + for _, tt := range tests { {{- if not .Tests.SkipShutdown }} - t.Run(test.name + "-shutdown", func(t *testing.T) { - c, err := test.createFn(context.Background(), exportertest.NewNopSettings(), cfg) + t.Run(tt.name + "-shutdown", func(t *testing.T) { + c, err := tt.createFn(context.Background(), exportertest.NewNopSettings(), cfg) require.NoError(t, err) err = c.Shutdown(context.Background()) require.NoError(t, err) @@ -115,14 +115,14 @@ func TestComponentLifecycle(t *testing.T) { {{- end }} {{- if not .Tests.SkipLifecycle }} - t.Run(test.name + "-lifecycle", func(t *testing.T) { - c, err := test.createFn(context.Background(), exportertest.NewNopSettings(), cfg) + t.Run(tt.name + "-lifecycle", func(t *testing.T) { + c, err := tt.createFn(context.Background(), exportertest.NewNopSettings(), cfg) require.NoError(t, err) host := {{ .Tests.Host }} err = c.Start(context.Background(), host) require.NoError(t, err) require.NotPanics(t, func() { - switch test.name { + switch tt.name { case "logs": e, ok := c.(exporter.Logs) require.True(t, ok) @@ -201,10 +201,10 @@ func TestComponentLifecycle(t *testing.T) { require.NoError(t, err) require.NoError(t, sub.Unmarshal(&cfg)) - for _, test := range tests { + for _, tt := range tests { {{- if not .Tests.SkipShutdown }} - t.Run(test.name + "-shutdown", func(t *testing.T) { - c, err := test.createFn(context.Background(), processortest.NewNopSettings(), cfg) + t.Run(tt.name + "-shutdown", func(t *testing.T) { + c, err := tt.createFn(context.Background(), processortest.NewNopSettings(), cfg) require.NoError(t, err) err = c.Shutdown(context.Background()) require.NoError(t, err) @@ -212,14 +212,14 @@ func TestComponentLifecycle(t *testing.T) { {{- end }} {{- if not .Tests.SkipLifecycle }} - t.Run(test.name + "-lifecycle", func(t *testing.T) { - c, err := test.createFn(context.Background(), processortest.NewNopSettings(), cfg) + t.Run(tt.name + "-lifecycle", func(t *testing.T) { + c, err := tt.createFn(context.Background(), processortest.NewNopSettings(), cfg) require.NoError(t, err) host := {{ .Tests.Host }} err = c.Start(context.Background(), host) require.NoError(t, err) require.NotPanics(t, func() { - switch test.name { + switch tt.name { case "logs": e, ok := c.(processor.Logs) require.True(t, ok) @@ -296,10 +296,10 @@ func TestComponentLifecycle(t *testing.T) { require.NoError(t, err) require.NoError(t, sub.Unmarshal(&cfg)) - for _, test := range tests { + for _, tt := range tests { {{- if not .Tests.SkipShutdown }} - t.Run(test.name + "-shutdown", func(t *testing.T) { - c, err := test.createFn(context.Background(), receivertest.NewNopSettings(), cfg) + t.Run(tt.name + "-shutdown", func(t *testing.T) { + c, err := tt.createFn(context.Background(), receivertest.NewNopSettings(), cfg) require.NoError(t, err) err = c.Shutdown(context.Background()) require.NoError(t, err) @@ -307,14 +307,14 @@ func TestComponentLifecycle(t *testing.T) { {{- end }} {{- if not .Tests.SkipLifecycle }} - t.Run(test.name + "-lifecycle", func(t *testing.T) { - firstRcvr, err := test.createFn(context.Background(), receivertest.NewNopSettings(), cfg) + t.Run(tt.name + "-lifecycle", func(t *testing.T) { + firstRcvr, err := tt.createFn(context.Background(), receivertest.NewNopSettings(), cfg) require.NoError(t, err) host := {{ .Tests.Host }} require.NoError(t, err) require.NoError(t, firstRcvr.Start(context.Background(), host)) require.NoError(t, firstRcvr.Shutdown(context.Background())) - secondRcvr, err := test.createFn(context.Background(), receivertest.NewNopSettings(), cfg) + secondRcvr, err := tt.createFn(context.Background(), receivertest.NewNopSettings(), cfg) require.NoError(t, err) require.NoError(t, secondRcvr.Start(context.Background(), host)) require.NoError(t, secondRcvr.Shutdown(context.Background())) @@ -458,10 +458,10 @@ func TestComponentLifecycle(t *testing.T) { require.NoError(t, err) require.NoError(t, sub.Unmarshal(&cfg)) - for _, test := range tests { + for _, tt := range tests { {{- if not .Tests.SkipShutdown }} - t.Run(test.name + "-shutdown", func(t *testing.T) { - c, err := test.createFn(context.Background(), connectortest.NewNopSettings(), cfg) + t.Run(tt.name + "-shutdown", func(t *testing.T) { + c, err := tt.createFn(context.Background(), connectortest.NewNopSettings(), cfg) require.NoError(t, err) err = c.Shutdown(context.Background()) require.NoError(t, err) @@ -469,14 +469,14 @@ func TestComponentLifecycle(t *testing.T) { {{- end }} {{- if not .Tests.SkipLifecycle }} - t.Run(test.name + "-lifecycle", func(t *testing.T) { - firstConnector, err := test.createFn(context.Background(), connectortest.NewNopSettings(), cfg) + t.Run(tt.name + "-lifecycle", func(t *testing.T) { + firstConnector, err := tt.createFn(context.Background(), connectortest.NewNopSettings(), cfg) require.NoError(t, err) host := {{ .Tests.Host }} require.NoError(t, err) require.NoError(t, firstConnector.Start(context.Background(), host)) require.NoError(t, firstConnector.Shutdown(context.Background())) - secondConnector, err := test.createFn(context.Background(), connectortest.NewNopSettings(), cfg) + secondConnector, err := tt.createFn(context.Background(), connectortest.NewNopSettings(), cfg) require.NoError(t, err) require.NoError(t, secondConnector.Start(context.Background(), host)) require.NoError(t, secondConnector.Shutdown(context.Background())) diff --git a/cmd/mdatagen/internal/templates/metrics_test.go.tmpl b/cmd/mdatagen/internal/templates/metrics_test.go.tmpl index 8afd0178b4d..476ddaf2ec4 100644 --- a/cmd/mdatagen/internal/templates/metrics_test.go.tmpl +++ b/cmd/mdatagen/internal/templates/metrics_test.go.tmpl @@ -55,31 +55,31 @@ func TestMetricsBuilder(t *testing.T) { }, {{- end }} } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { start := pcommon.Timestamp(1_000_000_000) ts := pcommon.Timestamp(1_000_001_000) observedZapCore, observedLogs := observer.New(zap.WarnLevel) settings := receivertest.NewNopSettings() settings.Logger = zap.New(observedZapCore) - mb := NewMetricsBuilder(loadMetricsBuilderConfig(t, test.name), settings, WithStartTime(start)) + mb := NewMetricsBuilder(loadMetricsBuilderConfig(t, tt.name), settings, WithStartTime(start)) expectedWarnings := 0 {{- range $name, $metric := .Metrics }} {{- if and $metric.Enabled $metric.Warnings.IfEnabled }} - if test.metricsSet == testDataSetDefault || test.metricsSet == testDataSetAll { + if tt.metricsSet == testDataSetDefault || tt.metricsSet == testDataSetAll { assert.Equal(t, "[WARNING] `{{ $name }}` should not be enabled: {{ $metric.Warnings.IfEnabled }}", observedLogs.All()[expectedWarnings].Message) expectedWarnings++ } {{- end }} {{- if $metric.Warnings.IfEnabledNotSet }} - if test.metricsSet == testDataSetDefault { + if tt.metricsSet == testDataSetDefault { assert.Equal(t, "[WARNING] Please set `enabled` field explicitly for `{{ $name }}`: {{ $metric.Warnings.IfEnabledNotSet }}", observedLogs.All()[expectedWarnings].Message) expectedWarnings++ } {{- end }} {{- if $metric.Warnings.IfConfigured }} - if test.metricsSet == testDataSetAll || test.metricsSet == testDataSetNone { + if tt.metricsSet == testDataSetAll || tt.metricsSet == testDataSetNone { assert.Equal(t, "[WARNING] `{{ $name }}` should not be configured: {{ $metric.Warnings.IfConfigured }}", observedLogs.All()[expectedWarnings].Message) expectedWarnings++ } @@ -87,19 +87,19 @@ func TestMetricsBuilder(t *testing.T) { {{- end }} {{- range $name, $attr := .ResourceAttributes }} {{- if and $attr.Enabled $attr.Warnings.IfEnabled }} - if test.resAttrsSet == testDataSetDefault || test.resAttrsSet == testDataSetAll { + if tt.resAttrsSet == testDataSetDefault || tt.resAttrsSet == testDataSetAll { assert.Equal(t, "[WARNING] `{{ $name }}` should not be enabled: {{ $attr.Warnings.IfEnabled }}", observedLogs.All()[expectedWarnings].Message) expectedWarnings++ } {{- end }} {{- if $attr.Warnings.IfEnabledNotSet }} - if test.resAttrsSet == testDataSetDefault { + if tt.resAttrsSet == testDataSetDefault { assert.Equal(t, "[WARNING] Please set `enabled` field explicitly for `{{ $name }}`: {{ $attr.Warnings.IfEnabledNotSet }}", observedLogs.All()[expectedWarnings].Message) expectedWarnings++ } {{- end }} {{- if $attr.Warnings.IfConfigured }} - if test.resAttrsSet == testDataSetAll || test.resAttrsSet == testDataSetNone { + if tt.resAttrsSet == testDataSetAll || tt.resAttrsSet == testDataSetNone { assert.Equal(t, "[WARNING] `{{ $name }}` should not be configured: {{ $attr.Warnings.IfConfigured }}", observedLogs.All()[expectedWarnings].Message) expectedWarnings++ } @@ -136,7 +136,7 @@ func TestMetricsBuilder(t *testing.T) { {{- end }} metrics := mb.Emit(WithResource(res)) - if test.expectEmpty { + if tt.expectEmpty { assert.Equal(t, 0, metrics.ResourceMetrics().Len()) return } @@ -146,10 +146,10 @@ func TestMetricsBuilder(t *testing.T) { assert.Equal(t, res, rm.Resource()) assert.Equal(t, 1, rm.ScopeMetrics().Len()) ms := rm.ScopeMetrics().At(0).Metrics() - if test.metricsSet == testDataSetDefault { + if tt.metricsSet == testDataSetDefault { assert.Equal(t, defaultMetricsCount, ms.Len()) } - if test.metricsSet == testDataSetAll { + if tt.metricsSet == testDataSetAll { assert.Equal(t, allMetricsCount, ms.Len()) } validatedMetrics := make(map[string]bool) diff --git a/cmd/mdatagen/internal/templates/resource_test.go.tmpl b/cmd/mdatagen/internal/templates/resource_test.go.tmpl index 7c1422e3d3b..3fc104551ca 100644 --- a/cmd/mdatagen/internal/templates/resource_test.go.tmpl +++ b/cmd/mdatagen/internal/templates/resource_test.go.tmpl @@ -16,9 +16,9 @@ import ( {{- end }} func TestResourceBuilder(t *testing.T) { - for _, test := range []string{"default", "all_set", "none_set"} { - t.Run(test, func(t *testing.T) { - cfg := loadResourceAttributesConfig(t, test) + for _, tt := range []string{"default", "all_set", "none_set"} { + t.Run(tt, func(t *testing.T) { + cfg := loadResourceAttributesConfig(t, tt) rb := NewResourceBuilder(cfg) {{- range $name, $attr := .ResourceAttributes }} {{- if $attr.Enum }} @@ -31,7 +31,7 @@ func TestResourceBuilder(t *testing.T) { res := rb.Emit() assert.Equal(t, 0, rb.Emit().Attributes().Len()) // Second call should return empty Resource - switch test { + switch tt { case "default": assert.Equal(t, {{ $enabledAttrCount }}, res.Attributes().Len()) case "all_set": @@ -40,7 +40,7 @@ func TestResourceBuilder(t *testing.T) { assert.Equal(t, 0, res.Attributes().Len()) return default: - assert.Failf(t, "unexpected test case: %s", test) + assert.Failf(t, "unexpected test case: %s", tt) } {{ $assignSign := ":=" }} @@ -49,7 +49,7 @@ func TestResourceBuilder(t *testing.T) { {{- if $attr.Enabled }} assert.True(t, ok) {{- else }} - assert.Equal(t, test == "all_set", ok) + assert.Equal(t, tt == "all_set", ok) {{- end }} if ok { assert.EqualValues(t, {{ $attr.TestValue }}, val.{{ $attr.Type }}() diff --git a/component/identifiable_test.go b/component/identifiable_test.go index f4e3595f23d..f6ad1d2768a 100644 --- a/component/identifiable_test.go +++ b/component/identifiable_test.go @@ -20,83 +20,83 @@ func TestMarshalText(t *testing.T) { func TestUnmarshalText(t *testing.T) { validType := MustNewType("valid_type") var testCases = []struct { - idStr string + name string expectedErr bool expectedID ID }{ { - idStr: "valid_type", + name: "valid_type", expectedID: ID{typeVal: validType, nameVal: ""}, }, { - idStr: "valid_type/valid_name", + name: "valid_type/valid_name", expectedID: ID{typeVal: validType, nameVal: "valid_name"}, }, { - idStr: " valid_type / valid_name ", + name: " valid_type / valid_name ", expectedID: ID{typeVal: validType, nameVal: "valid_name"}, }, { - idStr: "valid_type/中文好", + name: "valid_type/中文好", expectedID: ID{typeVal: validType, nameVal: "中文好"}, }, { - idStr: "valid_type/name-with-dashes", + name: "valid_type/name-with-dashes", expectedID: ID{typeVal: validType, nameVal: "name-with-dashes"}, }, // issue 10816 { - idStr: "valid_type/Linux-Messages-File_01J49HCH3SWFXRVASWFZFRT3J2__processor0__logs", + name: "valid_type/Linux-Messages-File_01J49HCH3SWFXRVASWFZFRT3J2__processor0__logs", expectedID: ID{typeVal: validType, nameVal: "Linux-Messages-File_01J49HCH3SWFXRVASWFZFRT3J2__processor0__logs"}, }, { - idStr: "valid_type/1", + name: "valid_type/1", expectedID: ID{typeVal: validType, nameVal: "1"}, }, { - idStr: "/valid_name", + name: "/valid_name", expectedErr: true, }, { - idStr: " /valid_name", + name: " /valid_name", expectedErr: true, }, { - idStr: "valid_type/", + name: "valid_type/", expectedErr: true, }, { - idStr: "valid_type/ ", + name: "valid_type/ ", expectedErr: true, }, { - idStr: " ", + name: " ", expectedErr: true, }, { - idStr: "valid_type/invalid name", + name: "valid_type/invalid name", expectedErr: true, }, { - idStr: "valid_type/" + strings.Repeat("a", 1025), + name: "valid_type/" + strings.Repeat("a", 1025), expectedErr: true, }, } - for _, test := range testCases { - t.Run(test.idStr, func(t *testing.T) { + for _, tt := range testCases { + t.Run(tt.name, func(t *testing.T) { id := ID{} - err := id.UnmarshalText([]byte(test.idStr)) - if test.expectedErr { + err := id.UnmarshalText([]byte(tt.name)) + if tt.expectedErr { assert.Error(t, err) return } assert.NoError(t, err) - assert.Equal(t, test.expectedID, id) - assert.Equal(t, test.expectedID.Type(), id.Type()) - assert.Equal(t, test.expectedID.Name(), id.Name()) - assert.Equal(t, test.expectedID.String(), id.String()) + assert.Equal(t, tt.expectedID, id) + assert.Equal(t, tt.expectedID.Type(), id.Type()) + assert.Equal(t, tt.expectedID.Name(), id.Name()) + assert.Equal(t, tt.expectedID.String(), id.String()) }) } } diff --git a/config/configauth/configauth_test.go b/config/configauth/configauth_test.go index a19577f9d98..d5504a7707e 100644 --- a/config/configauth/configauth_test.go +++ b/config/configauth/configauth_test.go @@ -24,36 +24,36 @@ func TestNewDefaultAuthentication(t *testing.T) { func TestGetServer(t *testing.T) { testCases := []struct { - desc string + name string authenticator extension.Extension expected error }{ { - desc: "obtain server authenticator", + name: "obtain server authenticator", authenticator: auth.NewServer(), expected: nil, }, { - desc: "not a server authenticator", + name: "not a server authenticator", authenticator: auth.NewClient(), expected: errNotServer, }, } - for _, tC := range testCases { - t.Run(tC.desc, func(t *testing.T) { + for _, tt := range testCases { + t.Run(tt.name, func(t *testing.T) { // prepare cfg := &Authentication{ AuthenticatorID: mockID, } ext := map[component.ID]component.Component{ - mockID: tC.authenticator, + mockID: tt.authenticator, } authenticator, err := cfg.GetServerAuthenticator(context.Background(), ext) // verify - if tC.expected != nil { - assert.ErrorIs(t, err, tC.expected) + if tt.expected != nil { + assert.ErrorIs(t, err, tt.expected) assert.Nil(t, authenticator) } else { assert.NoError(t, err) @@ -75,36 +75,36 @@ func TestGetServerFails(t *testing.T) { func TestGetClient(t *testing.T) { testCases := []struct { - desc string + name string authenticator extension.Extension expected error }{ { - desc: "obtain client authenticator", + name: "obtain client authenticator", authenticator: auth.NewClient(), expected: nil, }, { - desc: "not a client authenticator", + name: "not a client authenticator", authenticator: auth.NewServer(), expected: errNotClient, }, } - for _, tC := range testCases { - t.Run(tC.desc, func(t *testing.T) { + for _, tt := range testCases { + t.Run(tt.name, func(t *testing.T) { // prepare cfg := &Authentication{ AuthenticatorID: mockID, } ext := map[component.ID]component.Component{ - mockID: tC.authenticator, + mockID: tt.authenticator, } authenticator, err := cfg.GetClientAuthenticator(context.Background(), ext) // verify - if tC.expected != nil { - assert.ErrorIs(t, err, tC.expected) + if tt.expected != nil { + assert.ErrorIs(t, err, tt.expected) assert.Nil(t, authenticator) } else { assert.NoError(t, err) diff --git a/config/configgrpc/configgrpc_test.go b/config/configgrpc/configgrpc_test.go index da97997545c..588123bb974 100644 --- a/config/configgrpc/configgrpc_test.go +++ b/config/configgrpc/configgrpc_test.go @@ -905,10 +905,10 @@ func TestContextWithClient(t *testing.T) { }, }, } - for _, tC := range testCases { - t.Run(tC.desc, func(t *testing.T) { - cl := client.FromContext(contextWithClient(tC.input, tC.doMetadata)) - assert.Equal(t, tC.expected, cl) + for _, tt := range testCases { + t.Run(tt.desc, func(t *testing.T) { + cl := client.FromContext(contextWithClient(tt.input, tt.doMetadata)) + assert.Equal(t, tt.expected, cl) }) } } @@ -950,13 +950,13 @@ func (ms *mockedStream) Context() context.Context { func TestClientInfoInterceptors(t *testing.T) { testCases := []struct { - desc string + name string tester func(context.Context, ptraceotlp.GRPCClient) }{ { // we only have unary services, we don't have any clients we could use // to test with streaming services - desc: "unary", + name: "unary", tester: func(ctx context.Context, cl ptraceotlp.GRPCClient) { resp, errResp := cl.Export(ctx, ptraceotlp.NewExportRequest()) require.NoError(t, errResp) @@ -964,8 +964,8 @@ func TestClientInfoInterceptors(t *testing.T) { }, }, } - for _, tC := range testCases { - t.Run(tC.desc, func(t *testing.T) { + for _, tt := range testCases { + t.Run(tt.name, func(t *testing.T) { mock := &grpcTraceServer{} var l net.Listener @@ -1000,13 +1000,13 @@ func TestClientInfoInterceptors(t *testing.T) { }, } - tt, err := componenttest.SetupTelemetry(componentID) + tel, err := componenttest.SetupTelemetry(componentID) require.NoError(t, err) defer func() { - require.NoError(t, tt.Shutdown(context.Background())) + require.NoError(t, tel.Shutdown(context.Background())) }() - grpcClientConn, errClient := gcs.ToClientConn(context.Background(), componenttest.NewNopHost(), tt.TelemetrySettings()) + grpcClientConn, errClient := gcs.ToClientConn(context.Background(), componenttest.NewNopHost(), tel.TelemetrySettings()) require.NoError(t, errClient) defer func() { assert.NoError(t, grpcClientConn.Close()) }() @@ -1015,7 +1015,7 @@ func TestClientInfoInterceptors(t *testing.T) { defer cancelFunc() // test - tC.tester(ctx, cl) + tt.tester(ctx, cl) } // verify diff --git a/config/confighttp/clientinfohandler_test.go b/config/confighttp/clientinfohandler_test.go index bbd18ec52fd..492a96c9c3f 100644 --- a/config/confighttp/clientinfohandler_test.go +++ b/config/confighttp/clientinfohandler_test.go @@ -15,38 +15,38 @@ var _ http.Handler = (*clientInfoHandler)(nil) func TestParseIP(t *testing.T) { testCases := []struct { - desc string + name string input string expected *net.IPAddr }{ { - desc: "addr", + name: "addr", input: "1.2.3.4", expected: &net.IPAddr{ IP: net.IPv4(1, 2, 3, 4), }, }, { - desc: "addr:port", + name: "addr:port", input: "1.2.3.4:33455", expected: &net.IPAddr{ IP: net.IPv4(1, 2, 3, 4), }, }, { - desc: "protocol://addr:port", + name: "protocol://addr:port", input: "http://1.2.3.4:33455", expected: nil, }, { - desc: "addr/path", + name: "addr/path", input: "1.2.3.4/orders", expected: nil, }, } - for _, tC := range testCases { - t.Run(tC.desc, func(t *testing.T) { - assert.Equal(t, tC.expected, parseIP(tC.input)) + for _, tt := range testCases { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.expected, parseIP(tt.input)) }) } } diff --git a/config/confighttp/confighttp_test.go b/config/confighttp/confighttp_test.go index 4fbe16be8cb..c1af07c0f62 100644 --- a/config/confighttp/confighttp_test.go +++ b/config/confighttp/confighttp_test.go @@ -156,12 +156,12 @@ func TestAllHTTPClientSettings(t *testing.T) { }, } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - tt := componenttest.NewNopTelemetrySettings() - tt.TracerProvider = nil - client, err := test.settings.ToClient(context.Background(), host, tt) - if test.shouldError { + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tel := componenttest.NewNopTelemetrySettings() + tel.TracerProvider = nil + client, err := tt.settings.ToClient(context.Background(), host, tel) + if tt.shouldError { assert.Error(t, err) return } @@ -208,11 +208,11 @@ func TestPartialHTTPClientSettings(t *testing.T) { }, } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - tt := componenttest.NewNopTelemetrySettings() - tt.TracerProvider = nil - client, err := test.settings.ToClient(context.Background(), host, tt) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tel := componenttest.NewNopTelemetrySettings() + tel.TracerProvider = nil + client, err := tt.settings.ToClient(context.Background(), host, tel) assert.NoError(t, err) transport := client.Transport.(*http.Transport) assert.EqualValues(t, 1024, transport.ReadBufferSize) @@ -235,36 +235,36 @@ func TestDefaultHTTPClientSettings(t *testing.T) { func TestProxyURL(t *testing.T) { testCases := []struct { - desc string + name string proxyURL string expectedURL *url.URL err bool }{ { - desc: "default config", + name: "default config", expectedURL: nil, }, { - desc: "proxy is set", + name: "proxy is set", proxyURL: "http://proxy.example.com:8080", expectedURL: &url.URL{Scheme: "http", Host: "proxy.example.com:8080"}, }, { - desc: "proxy is invalid", + name: "proxy is invalid", proxyURL: "://example.com", err: true, }, } - for _, tC := range testCases { - t.Run(tC.desc, func(t *testing.T) { + for _, tt := range testCases { + t.Run(tt.name, func(t *testing.T) { s := NewDefaultClientConfig() - s.ProxyURL = tC.proxyURL + s.ProxyURL = tt.proxyURL - tt := componenttest.NewNopTelemetrySettings() - tt.TracerProvider = nil - client, err := s.ToClient(context.Background(), componenttest.NewNopHost(), tt) + tel := componenttest.NewNopTelemetrySettings() + tel.TracerProvider = nil + client, err := s.ToClient(context.Background(), componenttest.NewNopHost(), tel) - if tC.err { + if tt.err { require.Error(t, err) } else { require.NoError(t, err) @@ -277,11 +277,11 @@ func TestProxyURL(t *testing.T) { url, err := transport.Proxy(&http.Request{URL: &url.URL{Scheme: "http", Host: "example.com"}}) require.NoError(t, err) - if tC.expectedURL == nil { + if tt.expectedURL == nil { assert.Nil(t, url) } else { require.NotNil(t, url) - assert.Equal(t, tC.expectedURL, url) + assert.Equal(t, tt.expectedURL, url) } } }) @@ -330,10 +330,10 @@ func TestHTTPClientSettingsError(t *testing.T) { }, }, } - for _, test := range tests { - t.Run(test.err, func(t *testing.T) { - _, err := test.settings.ToClient(context.Background(), host, componenttest.NewNopTelemetrySettings()) - assert.Regexp(t, test.err, err) + for _, tt := range tests { + t.Run(tt.err, func(t *testing.T) { + _, err := tt.settings.ToClient(context.Background(), host, componenttest.NewNopTelemetrySettings()) + assert.Regexp(t, tt.err, err) }) } } @@ -438,11 +438,11 @@ func TestHTTPClientSettingWithAuthConfig(t *testing.T) { }, }, } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { // Omit TracerProvider and MeterProvider in TelemetrySettings as otelhttp.Transport cannot be introspected - client, err := test.settings.ToClient(context.Background(), test.host, nilProvidersSettings) - if test.shouldErr { + client, err := tt.settings.ToClient(context.Background(), tt.host, nilProvidersSettings) + if tt.shouldErr { assert.Error(t, err) return } @@ -451,22 +451,22 @@ func TestHTTPClientSettingWithAuthConfig(t *testing.T) { transport := client.Transport // Compression should wrap Auth, unwrap it - if test.settings.Compression.IsCompressed() { + if tt.settings.Compression.IsCompressed() { ct, ok := transport.(*compressRoundTripper) assert.True(t, ok) - assert.Equal(t, test.settings.Compression, ct.compressionType) + assert.Equal(t, tt.settings.Compression, ct.compressionType) transport = ct.rt } // Headers should wrap Auth, unwrap it - if test.settings.Headers != nil { + if tt.settings.Headers != nil { ht, ok := transport.(*headerRoundTripper) assert.True(t, ok) - assert.Equal(t, test.settings.Headers, ht.headers) + assert.Equal(t, tt.settings.Headers, ht.headers) transport = ht.transport } - if test.settings.Auth != nil { + if tt.settings.Auth != nil { _, ok := transport.(*customRoundTripper) assert.True(t, ok) } @@ -511,10 +511,10 @@ func TestHTTPServerSettingsError(t *testing.T) { }, }, } - for _, test := range tests { - t.Run(test.err, func(t *testing.T) { - _, err := test.settings.ToListener(context.Background()) - assert.Regexp(t, test.err, err) + for _, tt := range tests { + t.Run(tt.err, func(t *testing.T) { + _, err := tt.settings.ToListener(context.Background()) + assert.Regexp(t, tt.err, err) }) } } @@ -545,22 +545,22 @@ func TestHTTPServerWarning(t *testing.T) { len: 0, }, } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { set := componenttest.NewNopTelemetrySettings() logger, observed := observer.New(zap.DebugLevel) set.Logger = zap.New(logger) - _, err := test.settings.ToServer( + _, err := tt.settings.ToServer( context.Background(), componenttest.NewNopHost(), set, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - _, errWrite := fmt.Fprint(w, "test") + _, errWrite := fmt.Fprint(w, "tt") assert.NoError(t, errWrite) })) require.NoError(t, err) - require.Len(t, observed.FilterLevelExact(zap.WarnLevel).All(), test.len) + require.Len(t, observed.FilterLevelExact(zap.WarnLevel).All(), tt.len) }) } @@ -703,7 +703,7 @@ func TestHttpReception(t *testing.T) { componenttest.NewNopHost(), componenttest.NewNopTelemetrySettings(), http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - _, errWrite := fmt.Fprint(w, "test") + _, errWrite := fmt.Fprint(w, "tt") assert.NoError(t, errWrite) })) require.NoError(t, err) @@ -739,7 +739,7 @@ func TestHttpReception(t *testing.T) { assert.NoError(t, errResp) body, errRead := io.ReadAll(resp.Body) assert.NoError(t, errRead) - assert.Equal(t, "test", string(body)) + assert.Equal(t, "tt", string(body)) assert.Equal(t, expectedProto, resp.Proto) } require.NoError(t, s.Close()) @@ -1109,18 +1109,18 @@ func TestHttpClientHostHeader(t *testing.T) { func TestContextWithClient(t *testing.T) { testCases := []struct { - desc string + name string input *http.Request doMetadata bool expected client.Info }{ { - desc: "request without client IP or headers", + name: "request without client IP or headers", input: &http.Request{}, expected: client.Info{}, }, { - desc: "request with client IP", + name: "request with client IP", input: &http.Request{ RemoteAddr: "1.2.3.4:55443", }, @@ -1131,39 +1131,39 @@ func TestContextWithClient(t *testing.T) { }, }, { - desc: "request with client headers, no metadata processing", + name: "request with client headers, no metadata processing", input: &http.Request{ - Header: map[string][]string{"x-test-header": {"test-value"}}, + Header: map[string][]string{"x-tt-header": {"tt-value"}}, }, doMetadata: false, expected: client.Info{}, }, { - desc: "request with client headers", + name: "request with client headers", input: &http.Request{ - Header: map[string][]string{"x-test-header": {"test-value"}}, + Header: map[string][]string{"x-tt-header": {"tt-value"}}, }, doMetadata: true, expected: client.Info{ - Metadata: client.NewMetadata(map[string][]string{"x-test-header": {"test-value"}}), + Metadata: client.NewMetadata(map[string][]string{"x-tt-header": {"tt-value"}}), }, }, { - desc: "request with Host and client headers", + name: "request with Host and client headers", input: &http.Request{ - Header: map[string][]string{"x-test-header": {"test-value"}}, + Header: map[string][]string{"x-tt-header": {"tt-value"}}, Host: "localhost:55443", }, doMetadata: true, expected: client.Info{ - Metadata: client.NewMetadata(map[string][]string{"x-test-header": {"test-value"}, "Host": {"localhost:55443"}}), + Metadata: client.NewMetadata(map[string][]string{"x-tt-header": {"tt-value"}, "Host": {"localhost:55443"}}), }, }, } - for _, tC := range testCases { - t.Run(tC.desc, func(t *testing.T) { - ctx := contextWithClient(tC.input, tC.doMetadata) - assert.Equal(t, tC.expected, client.FromContext(ctx)) + for _, tt := range testCases { + t.Run(tt.name, func(t *testing.T) { + ctx := contextWithClient(tt.input, tt.doMetadata) + assert.Equal(t, tt.expected, client.FromContext(ctx)) }) } } @@ -1199,7 +1199,7 @@ func TestServerAuth(t *testing.T) { srv, err := hss.ToServer(context.Background(), host, componenttest.NewNopTelemetrySettings(), handler) require.NoError(t, err) - // test + // tt srv.Handler.ServeHTTP(&httptest.ResponseRecorder{}, httptest.NewRequest("GET", "/", nil)) // verify @@ -1244,7 +1244,7 @@ func TestFailedServerAuth(t *testing.T) { srv, err := hss.ToServer(context.Background(), host, componenttest.NewNopTelemetrySettings(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) require.NoError(t, err) - // test + // tt response := &httptest.ResponseRecorder{} srv.Handler.ServeHTTP(response, httptest.NewRequest("GET", "/", nil)) @@ -1272,7 +1272,7 @@ func TestServerWithErrorHandler(t *testing.T) { WithErrorHandler(eh), ) require.NoError(t, err) - // test + // tt response := &httptest.ResponseRecorder{} req, err := http.NewRequest(http.MethodGet, srv.Addr, nil) @@ -1300,7 +1300,7 @@ func TestServerWithDecoder(t *testing.T) { WithDecoder("something-else", decoder), ) require.NoError(t, err) - // test + // tt response := &httptest.ResponseRecorder{} req, err := http.NewRequest(http.MethodGet, srv.Addr, bytes.NewBuffer([]byte("something"))) @@ -1346,7 +1346,7 @@ func TestServerWithDecompression(t *testing.T) { req.Header.Set("Content-Encoding", "zstd") - // test + // tt c := http.Client{} resp, err := c.Do(req) require.NoError(t, err, "Error sending request: %v", err) @@ -1354,8 +1354,8 @@ func TestServerWithDecompression(t *testing.T) { _, err = io.ReadAll(resp.Body) require.NoError(t, err, "Error reading response body: %v", err) - // verifications is done mostly within the test, but this is only a sanity check - // that we got into the test handler + // verifications is done mostly within the tt, but this is only a sanity check + // that we got into the tt handler assert.Equal(t, http.StatusBadRequest, resp.StatusCode) } @@ -1434,7 +1434,7 @@ func TestAuthWithQueryParams(t *testing.T) { srv, err := hss.ToServer(context.Background(), host, componenttest.NewNopTelemetrySettings(), handler) require.NoError(t, err) - // test + // tt srv.Handler.ServeHTTP(&httptest.ResponseRecorder{}, httptest.NewRequest("GET", "/?auth=1", nil)) // verify @@ -1503,7 +1503,7 @@ func BenchmarkHttpRequest(b *testing.B) { componenttest.NewNopHost(), componenttest.NewNopTelemetrySettings(), http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - _, errWrite := fmt.Fprint(w, "test") + _, errWrite := fmt.Fprint(w, "tt") assert.NoError(b, errWrite) })) require.NoError(b, err) @@ -1545,7 +1545,7 @@ func BenchmarkHttpRequest(b *testing.B) { body, errRead := io.ReadAll(resp.Body) _ = resp.Body.Close() require.NoError(b, errRead) - require.Equal(b, "test", string(body)) + require.Equal(b, "tt", string(body)) } c.CloseIdleConnections() }) diff --git a/config/configtelemetry/configtelemetry_test.go b/config/configtelemetry/configtelemetry_test.go index 27236bbe32b..d9fc2550c2d 100644 --- a/config/configtelemetry/configtelemetry_test.go +++ b/config/configtelemetry/configtelemetry_test.go @@ -90,12 +90,12 @@ func TestLevelStringMarshal(t *testing.T) { level: LevelDetailed, }, } - for _, test := range tests { - t.Run(test.str, func(t *testing.T) { - assert.Equal(t, test.str, test.level.String()) - got, err := test.level.MarshalText() + for _, tt := range tests { + t.Run(tt.str, func(t *testing.T) { + assert.Equal(t, tt.str, tt.level.String()) + got, err := tt.level.MarshalText() assert.NoError(t, err) - assert.Equal(t, test.str, string(got)) + assert.Equal(t, tt.str, string(got)) }) } } diff --git a/confmap/converter/expandconverter/expand_test.go b/confmap/converter/expandconverter/expand_test.go index 4934bb5a008..c86c44aeb75 100644 --- a/confmap/converter/expandconverter/expand_test.go +++ b/confmap/converter/expandconverter/expand_test.go @@ -44,9 +44,9 @@ func TestNewExpandConverter(t *testing.T) { expectedCfgMap, errExpected := confmaptest.LoadConf(filepath.Join("testdata", "expand-with-no-env.yaml")) require.NoError(t, errExpected, "Unable to get expected config") - for _, test := range testCases { - t.Run(test.name, func(t *testing.T) { - conf, err := confmaptest.LoadConf(filepath.Join("testdata", test.name)) + for _, tt := range testCases { + t.Run(tt.name, func(t *testing.T) { + conf, err := confmaptest.LoadConf(filepath.Join("testdata", tt.name)) require.NoError(t, err, "Unable to get config") // Test that expanded configs are the same with the simple config with no env vars. @@ -271,15 +271,15 @@ func TestNewExpandConverterWithErrors(t *testing.T) { }, } - for _, test := range testCases { - t.Run(test.name, func(t *testing.T) { - conf, err := confmaptest.LoadConf(filepath.Join("testdata", "errors", test.name)) + for _, tt := range testCases { + t.Run(tt.name, func(t *testing.T) { + conf, err := confmaptest.LoadConf(filepath.Join("testdata", "errors", tt.name)) require.NoError(t, err, "Unable to get config") // Test that expanded configs are the same with the simple config with no env vars. err = createConverter().Convert(context.Background(), conf) - assert.Equal(t, test.expectedError, err) + assert.Equal(t, tt.expectedError, err) }) } } diff --git a/confmap/expand_test.go b/confmap/expand_test.go index 211b1254d5b..a9a3b49b850 100644 --- a/confmap/expand_test.go +++ b/confmap/expand_test.go @@ -40,9 +40,9 @@ func TestResolverExpandEnvVars(t *testing.T) { return NewRetrieved(envs[uri[4:]]) }) - for _, test := range testCases { - t.Run(test.name, func(t *testing.T) { - resolver, err := NewResolver(ResolverSettings{URIs: []string{filepath.Join("testdata", test.name)}, ProviderFactories: []ProviderFactory{fileProvider, envProvider}, ConverterFactories: nil}) + for _, tt := range testCases { + t.Run(tt.name, func(t *testing.T) { + resolver, err := NewResolver(ResolverSettings{URIs: []string{filepath.Join("testdata", tt.name)}, ProviderFactories: []ProviderFactory{fileProvider, envProvider}, ConverterFactories: nil}) require.NoError(t, err) // Test that expanded configs are the same with the simple config with no env vars. diff --git a/confmap/internal/mapstructure/encoder_test.go b/confmap/internal/mapstructure/encoder_test.go index e6da809703a..f680441bb2e 100644 --- a/confmap/internal/mapstructure/encoder_test.go +++ b/confmap/internal/mapstructure/encoder_test.go @@ -213,33 +213,38 @@ func TestEncode(t *testing.T) { } func TestGetTagInfo(t *testing.T) { - testCases := map[string]struct { + testCases := []struct { + name string field reflect.StructField wantName string wantOmit bool wantSquash bool }{ - "WithoutTags": { + { + name: "WithoutTags", field: reflect.StructField{ Name: "Test", }, wantName: "test", }, - "WithoutMapStructureTag": { + { + name: "WithoutMapStructureTag", field: reflect.StructField{ Tag: `yaml:"hello,inline"`, Name: "YAML", }, wantName: "yaml", }, - "WithRename": { + { + name: "WithRename", field: reflect.StructField{ Tag: `mapstructure:"hello"`, Name: "Test", }, wantName: "hello", }, - "WithOmitEmpty": { + { + name: "WithOmitEmpty", field: reflect.StructField{ Tag: `mapstructure:"hello,omitempty"`, Name: "Test", @@ -247,14 +252,16 @@ func TestGetTagInfo(t *testing.T) { wantName: "hello", wantOmit: true, }, - "WithSquash": { + { + name: "WithSquash", field: reflect.StructField{ Tag: `mapstructure:",squash"`, Name: "Test", }, wantSquash: true, }, - "WithRemain": { + { + name: "WithRemain", field: reflect.StructField{ Tag: `mapstructure:",remain"`, Name: "Test", @@ -262,12 +269,12 @@ func TestGetTagInfo(t *testing.T) { wantSquash: true, }, } - for name, testCase := range testCases { - t.Run(name, func(t *testing.T) { - got := getTagInfo(testCase.field) - require.Equal(t, testCase.wantName, got.name) - require.Equal(t, testCase.wantOmit, got.omitEmpty) - require.Equal(t, testCase.wantSquash, got.squash) + for _, tt := range testCases { + t.Run(tt.name, func(t *testing.T) { + got := getTagInfo(tt.field) + require.Equal(t, tt.wantName, got.name) + require.Equal(t, tt.wantOmit, got.omitEmpty) + require.Equal(t, tt.wantSquash, got.squash) }) } } @@ -283,10 +290,10 @@ func TestEncodeValueError(t *testing.T) { {encodeFn: enc.encodeStruct, wantErr: &reflect.ValueError{Method: "encodeStruct", Kind: reflect.String}}, {encodeFn: enc.encodeSlice, wantErr: &reflect.ValueError{Method: "encodeSlice", Kind: reflect.String}}, } - for _, testCase := range testCases { - got, err := testCase.encodeFn(testValue) + for _, tt := range testCases { + got, err := tt.encodeFn(testValue) require.Error(t, err) - require.Equal(t, testCase.wantErr, err) + require.Equal(t, tt.wantErr, err) require.Nil(t, got) } } diff --git a/confmap/provider/envprovider/provider_test.go b/confmap/provider/envprovider/provider_test.go index 482c7c03431..75564430cca 100644 --- a/confmap/provider/envprovider/provider_test.go +++ b/confmap/provider/envprovider/provider_test.go @@ -171,20 +171,20 @@ func TestEnvWithDefaultValue(t *testing.T) { {name: "syntax1", unset: true, uri: "env:-MY_VAR", expectedErr: "invalid name"}, {name: "syntax2", unset: true, uri: "env:MY_VAR:-test:-test", expectedVal: "test:-test"}, } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - if !test.unset { - t.Setenv("MY_VAR", test.value) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if !tt.unset { + t.Setenv("MY_VAR", tt.value) } - ret, err := env.Retrieve(context.Background(), test.uri, nil) - if test.expectedErr != "" { - require.ErrorContains(t, err, test.expectedErr) + ret, err := env.Retrieve(context.Background(), tt.uri, nil) + if tt.expectedErr != "" { + require.ErrorContains(t, err, tt.expectedErr) return } require.NoError(t, err) str, err := ret.AsString() require.NoError(t, err) - assert.Equal(t, test.expectedVal, str) + assert.Equal(t, tt.expectedVal, str) }) } assert.NoError(t, env.Shutdown(context.Background())) diff --git a/confmap/provider/internal/configurablehttpprovider/provider_test.go b/confmap/provider/internal/configurablehttpprovider/provider_test.go index f140a2bce86..fc26051a265 100644 --- a/confmap/provider/internal/configurablehttpprovider/provider_test.go +++ b/confmap/provider/internal/configurablehttpprovider/provider_test.go @@ -152,7 +152,7 @@ func TestFunctionalityDownloadFileHTTPS(t *testing.T) { defer ts.Close() tests := []struct { - testName string + name string certPath string hostName string useCertificate bool @@ -160,7 +160,7 @@ func TestFunctionalityDownloadFileHTTPS(t *testing.T) { shouldError bool }{ { - testName: "Test valid certificate and name", + name: "Test valid certificate and name", certPath: certPath, hostName: "localhost", useCertificate: true, @@ -168,7 +168,7 @@ func TestFunctionalityDownloadFileHTTPS(t *testing.T) { shouldError: false, }, { - testName: "Test valid certificate with invalid name", + name: "Test valid certificate with invalid name", certPath: certPath, hostName: "127.0.0.1", useCertificate: true, @@ -176,7 +176,7 @@ func TestFunctionalityDownloadFileHTTPS(t *testing.T) { shouldError: true, }, { - testName: "Test valid certificate with invalid name, skip validation", + name: "Test valid certificate with invalid name, skip validation", certPath: certPath, hostName: "127.0.0.1", useCertificate: true, @@ -184,7 +184,7 @@ func TestFunctionalityDownloadFileHTTPS(t *testing.T) { shouldError: false, }, { - testName: "Test no certificate should fail", + name: "Test no certificate should fail", certPath: certPath, hostName: "localhost", useCertificate: false, @@ -192,7 +192,7 @@ func TestFunctionalityDownloadFileHTTPS(t *testing.T) { shouldError: true, }, { - testName: "Test invalid cert", + name: "Test invalid cert", certPath: invalidCert.Name(), hostName: "localhost", useCertificate: true, @@ -200,7 +200,7 @@ func TestFunctionalityDownloadFileHTTPS(t *testing.T) { shouldError: true, }, { - testName: "Test no cert", + name: "Test no cert", certPath: "no_certificate", hostName: "localhost", useCertificate: true, @@ -210,7 +210,7 @@ func TestFunctionalityDownloadFileHTTPS(t *testing.T) { } for _, tt := range tests { - t.Run(tt.testName, func(t *testing.T) { + t.Run(tt.name, func(t *testing.T) { fp := newConfigurableHTTPProvider(HTTPSScheme, confmaptest.NewNopProviderSettings()) // Parse url of the test server to get the port number. tsURL, err := url.Parse(ts.URL) diff --git a/connector/connector_test.go b/connector/connector_test.go index 08337f78568..23f253db320 100644 --- a/connector/connector_test.go +++ b/connector/connector_test.go @@ -199,8 +199,7 @@ func TestMakeFactoryMap(t *testing.T) { }, } - for i := range testCases { - tt := testCases[i] + for _, tt := range testCases { t.Run(tt.name, func(t *testing.T) { out, err := MakeFactoryMap(tt.in...) if tt.out == nil { diff --git a/connector/forwardconnector/generated_component_test.go b/connector/forwardconnector/generated_component_test.go index ec49a1d505d..8c7da3bc1fb 100644 --- a/connector/forwardconnector/generated_component_test.go +++ b/connector/forwardconnector/generated_component_test.go @@ -65,21 +65,21 @@ func TestComponentLifecycle(t *testing.T) { require.NoError(t, err) require.NoError(t, sub.Unmarshal(&cfg)) - for _, test := range tests { - t.Run(test.name+"-shutdown", func(t *testing.T) { - c, err := test.createFn(context.Background(), connectortest.NewNopSettings(), cfg) + for _, tt := range tests { + t.Run(tt.name+"-shutdown", func(t *testing.T) { + c, err := tt.createFn(context.Background(), connectortest.NewNopSettings(), cfg) require.NoError(t, err) err = c.Shutdown(context.Background()) require.NoError(t, err) }) - t.Run(test.name+"-lifecycle", func(t *testing.T) { - firstConnector, err := test.createFn(context.Background(), connectortest.NewNopSettings(), cfg) + t.Run(tt.name+"-lifecycle", func(t *testing.T) { + firstConnector, err := tt.createFn(context.Background(), connectortest.NewNopSettings(), cfg) require.NoError(t, err) host := componenttest.NewNopHost() require.NoError(t, err) require.NoError(t, firstConnector.Start(context.Background(), host)) require.NoError(t, firstConnector.Shutdown(context.Background())) - secondConnector, err := test.createFn(context.Background(), connectortest.NewNopSettings(), cfg) + secondConnector, err := tt.createFn(context.Background(), connectortest.NewNopSettings(), cfg) require.NoError(t, err) require.NoError(t, secondConnector.Start(context.Background(), host)) require.NoError(t, secondConnector.Shutdown(context.Background())) diff --git a/exporter/debugexporter/generated_component_test.go b/exporter/debugexporter/generated_component_test.go index b4c5d25ec7d..be4ae54a0f6 100644 --- a/exporter/debugexporter/generated_component_test.go +++ b/exporter/debugexporter/generated_component_test.go @@ -65,21 +65,21 @@ func TestComponentLifecycle(t *testing.T) { require.NoError(t, err) require.NoError(t, sub.Unmarshal(&cfg)) - for _, test := range tests { - t.Run(test.name+"-shutdown", func(t *testing.T) { - c, err := test.createFn(context.Background(), exportertest.NewNopSettings(), cfg) + for _, tt := range tests { + t.Run(tt.name+"-shutdown", func(t *testing.T) { + c, err := tt.createFn(context.Background(), exportertest.NewNopSettings(), cfg) require.NoError(t, err) err = c.Shutdown(context.Background()) require.NoError(t, err) }) - t.Run(test.name+"-lifecycle", func(t *testing.T) { - c, err := test.createFn(context.Background(), exportertest.NewNopSettings(), cfg) + t.Run(tt.name+"-lifecycle", func(t *testing.T) { + c, err := tt.createFn(context.Background(), exportertest.NewNopSettings(), cfg) require.NoError(t, err) host := componenttest.NewNopHost() err = c.Start(context.Background(), host) require.NoError(t, err) require.NotPanics(t, func() { - switch test.name { + switch tt.name { case "logs": e, ok := c.(exporter.Logs) require.True(t, ok) diff --git a/exporter/exporter_test.go b/exporter/exporter_test.go index 1580638df2b..879933fdab9 100644 --- a/exporter/exporter_test.go +++ b/exporter/exporter_test.go @@ -78,8 +78,7 @@ func TestMakeFactoryMap(t *testing.T) { }, } - for i := range testCases { - tt := testCases[i] + for _, tt := range testCases { t.Run(tt.name, func(t *testing.T) { out, err := MakeFactoryMap(tt.in...) if tt.out == nil { diff --git a/exporter/internal/queue/persistent_queue_test.go b/exporter/internal/queue/persistent_queue_test.go index 230d20f3f56..9742b464f3b 100644 --- a/exporter/internal/queue/persistent_queue_test.go +++ b/exporter/internal/queue/persistent_queue_test.go @@ -259,7 +259,7 @@ func newTracesRequest(numTraces int, numSpans int) tracesRequest { func TestToStorageClient(t *testing.T) { getStorageClientError := errors.New("unable to create storage client") testCases := []struct { - desc string + name string storage storage.Extension numStorages int storageIndex int @@ -267,25 +267,25 @@ func TestToStorageClient(t *testing.T) { getClientError error }{ { - desc: "obtain storage extension by name", + name: "obtain storage extension by name", numStorages: 2, storageIndex: 0, expectedError: nil, }, { - desc: "fail on not existing storage extension", + name: "fail on not existing storage extension", numStorages: 2, storageIndex: 100, expectedError: errNoStorageClient, }, { - desc: "invalid extension type", + name: "invalid extension type", numStorages: 2, storageIndex: 100, expectedError: errNoStorageClient, }, { - desc: "fail on error getting storage client from extension", + name: "fail on error getting storage client from extension", numStorages: 1, storageIndex: 0, expectedError: getStorageClientError, @@ -293,13 +293,13 @@ func TestToStorageClient(t *testing.T) { }, } - for _, tC := range testCases { - t.Run(tC.desc, func(t *testing.T) { - storageID := component.MustNewIDWithName("file_storage", strconv.Itoa(tC.storageIndex)) + for _, tt := range testCases { + t.Run(tt.name, func(t *testing.T) { + storageID := component.MustNewIDWithName("file_storage", strconv.Itoa(tt.storageIndex)) var extensions = map[component.ID]component.Component{} - for i := 0; i < tC.numStorages; i++ { - extensions[component.MustNewIDWithName("file_storage", strconv.Itoa(i))] = NewMockStorageExtension(tC.getClientError) + for i := 0; i < tt.numStorages; i++ { + extensions[component.MustNewIDWithName("file_storage", strconv.Itoa(i))] = NewMockStorageExtension(tt.getClientError) } host := &mockHost{ext: extensions} ownerID := component.MustNewID("foo_exporter") @@ -308,8 +308,8 @@ func TestToStorageClient(t *testing.T) { client, err := toStorageClient(context.Background(), storageID, host, ownerID, component.DataTypeTraces) // verify - if tC.expectedError != nil { - assert.ErrorIs(t, err, tC.expectedError) + if tt.expectedError != nil { + assert.ErrorIs(t, err, tt.expectedError) assert.Nil(t, client) } else { assert.NoError(t, err) @@ -794,22 +794,22 @@ func TestPersistentQueue_ItemDispatchingFinish_ErrorHandling(t *testing.T) { testCases := []struct { storageErrors []error expectedError error - description string + name string }{ { - description: "no errors", + name: "no errors", storageErrors: []error{}, expectedError: nil, }, { - description: "error on first transaction, success afterwards", + name: "error on first transaction, success afterwards", storageErrors: []error{ errUpdatingDispatched, }, expectedError: nil, }, { - description: "error on first and second transaction", + name: "error on first and second transaction", storageErrors: []error{ errUpdatingDispatched, errDeletingItem, @@ -817,7 +817,7 @@ func TestPersistentQueue_ItemDispatchingFinish_ErrorHandling(t *testing.T) { expectedError: errDeletingItem, }, { - description: "error on first and third transaction", + name: "error on first and third transaction", storageErrors: []error{ errUpdatingDispatched, nil, @@ -827,15 +827,15 @@ func TestPersistentQueue_ItemDispatchingFinish_ErrorHandling(t *testing.T) { }, } - for _, testCase := range testCases { - t.Run(testCase.description, func(t *testing.T) { - client := newFakeStorageClientWithErrors(testCase.storageErrors) + for _, tt := range testCases { + t.Run(tt.name, func(t *testing.T) { + client := newFakeStorageClientWithErrors(tt.storageErrors) ps := createTestPersistentQueueWithClient(client) client.Reset() err := ps.itemDispatchingFinish(context.Background(), 0) - require.ErrorIs(t, err, testCase.expectedError) + require.ErrorIs(t, err, tt.expectedError) }) } } diff --git a/exporter/loggingexporter/generated_component_test.go b/exporter/loggingexporter/generated_component_test.go index 06c2095963b..be058ef46c5 100644 --- a/exporter/loggingexporter/generated_component_test.go +++ b/exporter/loggingexporter/generated_component_test.go @@ -65,21 +65,21 @@ func TestComponentLifecycle(t *testing.T) { require.NoError(t, err) require.NoError(t, sub.Unmarshal(&cfg)) - for _, test := range tests { - t.Run(test.name+"-shutdown", func(t *testing.T) { - c, err := test.createFn(context.Background(), exportertest.NewNopSettings(), cfg) + for _, tt := range tests { + t.Run(tt.name+"-shutdown", func(t *testing.T) { + c, err := tt.createFn(context.Background(), exportertest.NewNopSettings(), cfg) require.NoError(t, err) err = c.Shutdown(context.Background()) require.NoError(t, err) }) - t.Run(test.name+"-lifecycle", func(t *testing.T) { - c, err := test.createFn(context.Background(), exportertest.NewNopSettings(), cfg) + t.Run(tt.name+"-lifecycle", func(t *testing.T) { + c, err := tt.createFn(context.Background(), exportertest.NewNopSettings(), cfg) require.NoError(t, err) host := componenttest.NewNopHost() err = c.Start(context.Background(), host) require.NoError(t, err) require.NotPanics(t, func() { - switch test.name { + switch tt.name { case "logs": e, ok := c.(exporter.Logs) require.True(t, ok) diff --git a/exporter/nopexporter/generated_component_test.go b/exporter/nopexporter/generated_component_test.go index 8a25fd60d4b..52c0247cba1 100644 --- a/exporter/nopexporter/generated_component_test.go +++ b/exporter/nopexporter/generated_component_test.go @@ -65,21 +65,21 @@ func TestComponentLifecycle(t *testing.T) { require.NoError(t, err) require.NoError(t, sub.Unmarshal(&cfg)) - for _, test := range tests { - t.Run(test.name+"-shutdown", func(t *testing.T) { - c, err := test.createFn(context.Background(), exportertest.NewNopSettings(), cfg) + for _, tt := range tests { + t.Run(tt.name+"-shutdown", func(t *testing.T) { + c, err := tt.createFn(context.Background(), exportertest.NewNopSettings(), cfg) require.NoError(t, err) err = c.Shutdown(context.Background()) require.NoError(t, err) }) - t.Run(test.name+"-lifecycle", func(t *testing.T) { - c, err := test.createFn(context.Background(), exportertest.NewNopSettings(), cfg) + t.Run(tt.name+"-lifecycle", func(t *testing.T) { + c, err := tt.createFn(context.Background(), exportertest.NewNopSettings(), cfg) require.NoError(t, err) host := componenttest.NewNopHost() err = c.Start(context.Background(), host) require.NoError(t, err) require.NotPanics(t, func() { - switch test.name { + switch tt.name { case "logs": e, ok := c.(exporter.Logs) require.True(t, ok) diff --git a/exporter/otlpexporter/config_test.go b/exporter/otlpexporter/config_test.go index f3941c83d97..32e3e9aa613 100644 --- a/exporter/otlpexporter/config_test.go +++ b/exporter/otlpexporter/config_test.go @@ -94,7 +94,7 @@ func TestUnmarshalInvalidConfig(t *testing.T) { cm, err := confmaptest.LoadConf(filepath.Join("testdata", "invalid_configs.yaml")) require.NoError(t, err) factory := NewFactory() - for _, test := range []struct { + for _, tt := range []struct { name string errorMsg string }{ @@ -131,12 +131,12 @@ func TestUnmarshalInvalidConfig(t *testing.T) { errorMsg: `invalid port "port"`, }, } { - t.Run(test.name, func(t *testing.T) { + t.Run(tt.name, func(t *testing.T) { cfg := factory.CreateDefaultConfig() - sub, err := cm.Sub(test.name) + sub, err := cm.Sub(tt.name) require.NoError(t, err) assert.NoError(t, sub.Unmarshal(&cfg)) - assert.ErrorContains(t, component.ValidateConfig(cfg), test.errorMsg) + assert.ErrorContains(t, component.ValidateConfig(cfg), tt.errorMsg) }) } diff --git a/exporter/otlpexporter/generated_component_test.go b/exporter/otlpexporter/generated_component_test.go index 8d0fd821a76..7cc9c55b7b0 100644 --- a/exporter/otlpexporter/generated_component_test.go +++ b/exporter/otlpexporter/generated_component_test.go @@ -65,21 +65,21 @@ func TestComponentLifecycle(t *testing.T) { require.NoError(t, err) require.NoError(t, sub.Unmarshal(&cfg)) - for _, test := range tests { - t.Run(test.name+"-shutdown", func(t *testing.T) { - c, err := test.createFn(context.Background(), exportertest.NewNopSettings(), cfg) + for _, tt := range tests { + t.Run(tt.name+"-shutdown", func(t *testing.T) { + c, err := tt.createFn(context.Background(), exportertest.NewNopSettings(), cfg) require.NoError(t, err) err = c.Shutdown(context.Background()) require.NoError(t, err) }) - t.Run(test.name+"-lifecycle", func(t *testing.T) { - c, err := test.createFn(context.Background(), exportertest.NewNopSettings(), cfg) + t.Run(tt.name+"-lifecycle", func(t *testing.T) { + c, err := tt.createFn(context.Background(), exportertest.NewNopSettings(), cfg) require.NoError(t, err) host := componenttest.NewNopHost() err = c.Start(context.Background(), host) require.NoError(t, err) require.NotPanics(t, func() { - switch test.name { + switch tt.name { case "logs": e, ok := c.(exporter.Logs) require.True(t, ok) diff --git a/exporter/otlphttpexporter/generated_component_test.go b/exporter/otlphttpexporter/generated_component_test.go index 8c995ca1b34..e6662421e5e 100644 --- a/exporter/otlphttpexporter/generated_component_test.go +++ b/exporter/otlphttpexporter/generated_component_test.go @@ -65,21 +65,21 @@ func TestComponentLifecycle(t *testing.T) { require.NoError(t, err) require.NoError(t, sub.Unmarshal(&cfg)) - for _, test := range tests { - t.Run(test.name+"-shutdown", func(t *testing.T) { - c, err := test.createFn(context.Background(), exportertest.NewNopSettings(), cfg) + for _, tt := range tests { + t.Run(tt.name+"-shutdown", func(t *testing.T) { + c, err := tt.createFn(context.Background(), exportertest.NewNopSettings(), cfg) require.NoError(t, err) err = c.Shutdown(context.Background()) require.NoError(t, err) }) - t.Run(test.name+"-lifecycle", func(t *testing.T) { - c, err := test.createFn(context.Background(), exportertest.NewNopSettings(), cfg) + t.Run(tt.name+"-lifecycle", func(t *testing.T) { + c, err := tt.createFn(context.Background(), exportertest.NewNopSettings(), cfg) require.NoError(t, err) host := componenttest.NewNopHost() err = c.Start(context.Background(), host) require.NoError(t, err) require.NotPanics(t, func() { - switch test.name { + switch tt.name { case "logs": e, ok := c.(exporter.Logs) require.True(t, ok) diff --git a/exporter/otlphttpexporter/otlp_test.go b/exporter/otlphttpexporter/otlp_test.go index edf85f5d405..4d5099b9bbd 100644 --- a/exporter/otlphttpexporter/otlp_test.go +++ b/exporter/otlphttpexporter/otlp_test.go @@ -279,10 +279,10 @@ func TestUserAgent(t *testing.T) { } t.Run("traces", func(t *testing.T) { - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { srv := createBackend("/v1/traces", func(writer http.ResponseWriter, request *http.Request) { - assert.Contains(t, request.Header.Get("user-agent"), test.expectedUA) + assert.Contains(t, request.Header.Get("user-agent"), tt.expectedUA) writer.WriteHeader(200) }) defer srv.Close() @@ -291,7 +291,7 @@ func TestUserAgent(t *testing.T) { Encoding: EncodingProto, TracesEndpoint: fmt.Sprintf("%s/v1/traces", srv.URL), ClientConfig: confighttp.ClientConfig{ - Headers: test.headers, + Headers: tt.headers, }, } exp, err := createTracesExporter(context.Background(), set, cfg) @@ -313,10 +313,10 @@ func TestUserAgent(t *testing.T) { }) t.Run("metrics", func(t *testing.T) { - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { srv := createBackend("/v1/metrics", func(writer http.ResponseWriter, request *http.Request) { - assert.Contains(t, request.Header.Get("user-agent"), test.expectedUA) + assert.Contains(t, request.Header.Get("user-agent"), tt.expectedUA) writer.WriteHeader(200) }) defer srv.Close() @@ -325,7 +325,7 @@ func TestUserAgent(t *testing.T) { Encoding: EncodingProto, MetricsEndpoint: fmt.Sprintf("%s/v1/metrics", srv.URL), ClientConfig: confighttp.ClientConfig{ - Headers: test.headers, + Headers: tt.headers, }, } exp, err := createMetricsExporter(context.Background(), set, cfg) @@ -347,10 +347,10 @@ func TestUserAgent(t *testing.T) { }) t.Run("logs", func(t *testing.T) { - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { srv := createBackend("/v1/logs", func(writer http.ResponseWriter, request *http.Request) { - assert.Contains(t, request.Header.Get("user-agent"), test.expectedUA) + assert.Contains(t, request.Header.Get("user-agent"), tt.expectedUA) writer.WriteHeader(200) }) defer srv.Close() @@ -359,7 +359,7 @@ func TestUserAgent(t *testing.T) { Encoding: EncodingProto, LogsEndpoint: fmt.Sprintf("%s/v1/logs", srv.URL), ClientConfig: confighttp.ClientConfig{ - Headers: test.headers, + Headers: tt.headers, }, } exp, err := createLogsExporter(context.Background(), set, cfg) @@ -897,17 +897,17 @@ func TestEncoding(t *testing.T) { } t.Run("traces", func(t *testing.T) { - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { srv := createBackend("/v1/traces", func(writer http.ResponseWriter, request *http.Request) { - assert.Contains(t, request.Header.Get("content-type"), test.expectedEncoding) + assert.Contains(t, request.Header.Get("content-type"), tt.expectedEncoding) writer.WriteHeader(200) }) defer srv.Close() cfg := &Config{ TracesEndpoint: fmt.Sprintf("%s/v1/traces", srv.URL), - Encoding: test.encoding, + Encoding: tt.encoding, } exp, err := createTracesExporter(context.Background(), set, cfg) require.NoError(t, err) @@ -928,17 +928,17 @@ func TestEncoding(t *testing.T) { }) t.Run("metrics", func(t *testing.T) { - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { srv := createBackend("/v1/metrics", func(writer http.ResponseWriter, request *http.Request) { - assert.Contains(t, request.Header.Get("content-type"), test.expectedEncoding) + assert.Contains(t, request.Header.Get("content-type"), tt.expectedEncoding) writer.WriteHeader(200) }) defer srv.Close() cfg := &Config{ MetricsEndpoint: fmt.Sprintf("%s/v1/metrics", srv.URL), - Encoding: test.encoding, + Encoding: tt.encoding, } exp, err := createMetricsExporter(context.Background(), set, cfg) require.NoError(t, err) @@ -959,17 +959,17 @@ func TestEncoding(t *testing.T) { }) t.Run("logs", func(t *testing.T) { - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { srv := createBackend("/v1/logs", func(writer http.ResponseWriter, request *http.Request) { - assert.Contains(t, request.Header.Get("content-type"), test.expectedEncoding) + assert.Contains(t, request.Header.Get("content-type"), tt.expectedEncoding) writer.WriteHeader(200) }) defer srv.Close() cfg := &Config{ LogsEndpoint: fmt.Sprintf("%s/v1/logs", srv.URL), - Encoding: test.encoding, + Encoding: tt.encoding, } exp, err := createLogsExporter(context.Background(), set, cfg) require.NoError(t, err) diff --git a/extension/auth/authtest/mock_clientauth_test.go b/extension/auth/authtest/mock_clientauth_test.go index 873d62e8384..2797174095a 100644 --- a/extension/auth/authtest/mock_clientauth_test.go +++ b/extension/auth/authtest/mock_clientauth_test.go @@ -56,10 +56,10 @@ func TestMockRoundTripper(t *testing.T) { }, } - for _, testcase := range testcases { - t.Run(testcase.name, func(t *testing.T) { - tripper, err := testcase.clientAuth.RoundTripper(nil) - if testcase.expectedErr { + for _, tt := range testcases { + t.Run(tt.name, func(t *testing.T) { + tripper, err := tt.clientAuth.RoundTripper(nil) + if tt.expectedErr { assert.Error(t, err) return } @@ -108,13 +108,13 @@ func TestMockPerRPCCredential(t *testing.T) { }, } - for _, testcase := range testcases { - t.Run(testcase.name, func(t *testing.T) { - credential, err := testcase.clientAuth.PerRPCCredentials() + for _, tt := range testcases { + t.Run(tt.name, func(t *testing.T) { + credential, err := tt.clientAuth.PerRPCCredentials() if err != nil { return } - if testcase.expectedErr { + if tt.expectedErr { assert.Error(t, err) return } diff --git a/extension/extension_test.go b/extension/extension_test.go index 3eba5e38df0..2c6065cc60e 100644 --- a/extension/extension_test.go +++ b/extension/extension_test.go @@ -62,8 +62,7 @@ func TestMakeFactoryMap(t *testing.T) { in: []Factory{p1, p2, NewFactory(component.MustNewType("p1"), nil, nil, component.StabilityLevelAlpha)}, }, } - for i := range testCases { - tt := testCases[i] + for _, tt := range testCases { t.Run(tt.name, func(t *testing.T) { out, err := MakeFactoryMap(tt.in...) if tt.out == nil { diff --git a/internal/e2e/otlphttp_test.go b/internal/e2e/otlphttp_test.go index 620c76d3d6a..d7e0a6f6078 100644 --- a/internal/e2e/otlphttp_test.go +++ b/internal/e2e/otlphttp_test.go @@ -104,11 +104,11 @@ func TestTraceRoundTrip(t *testing.T) { }, } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { sink := new(consumertest.TracesSink) startTracesReceiver(t, addr, sink) - exp := startTracesExporter(t, test.baseURL, test.overrideURL) + exp := startTracesExporter(t, tt.baseURL, tt.overrideURL) td := testdata.GenerateTraces(1) assert.NoError(t, exp.ConsumeTraces(context.Background(), td)) @@ -157,11 +157,11 @@ func TestMetricsRoundTrip(t *testing.T) { }, } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { sink := new(consumertest.MetricsSink) startMetricsReceiver(t, addr, sink) - exp := startMetricsExporter(t, test.baseURL, test.overrideURL) + exp := startMetricsExporter(t, tt.baseURL, tt.overrideURL) md := testdata.GenerateMetrics(1) assert.NoError(t, exp.ConsumeMetrics(context.Background(), md)) @@ -210,11 +210,11 @@ func TestLogsRoundTrip(t *testing.T) { }, } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { sink := new(consumertest.LogsSink) startLogsReceiver(t, addr, sink) - exp := startLogsExporter(t, test.baseURL, test.overrideURL) + exp := startLogsExporter(t, tt.baseURL, tt.overrideURL) md := testdata.GenerateLogs(1) assert.NoError(t, exp.ConsumeLogs(context.Background(), md)) diff --git a/otelcol/config_test.go b/otelcol/config_test.go index c1677c07220..1de5369759c 100644 --- a/otelcol/config_test.go +++ b/otelcol/config_test.go @@ -236,10 +236,10 @@ func TestConfigValidate(t *testing.T) { }, } - for _, test := range testCases { - t.Run(test.name, func(t *testing.T) { - cfg := test.cfgFn() - assert.Equal(t, test.expected, cfg.Validate()) + for _, tt := range testCases { + t.Run(tt.name, func(t *testing.T) { + cfg := tt.cfgFn() + assert.Equal(t, tt.expected, cfg.Validate()) }) } } diff --git a/pdata/pcommon/value_test.go b/pdata/pcommon/value_test.go index e2b5cfca23f..bc6b0b3e5fd 100644 --- a/pdata/pcommon/value_test.go +++ b/pdata/pcommon/value_test.go @@ -347,10 +347,10 @@ func TestValueAsString(t *testing.T) { expected: base64.StdEncoding.EncodeToString([]byte("String bytes")), }, } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - actual := test.input.AsString() - assert.Equal(t, test.expected, actual) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + actual := tt.input.AsString() + assert.Equal(t, tt.expected, actual) }) } } @@ -405,10 +405,10 @@ func TestValueAsRaw(t *testing.T) { }, }, } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - actual := test.input.AsRaw() - assert.Equal(t, test.expected, actual) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + actual := tt.input.AsRaw() + assert.Equal(t, tt.expected, actual) }) } } diff --git a/processor/batchprocessor/generated_component_test.go b/processor/batchprocessor/generated_component_test.go index af68a5bf9a8..0de5ebd38a2 100644 --- a/processor/batchprocessor/generated_component_test.go +++ b/processor/batchprocessor/generated_component_test.go @@ -66,21 +66,21 @@ func TestComponentLifecycle(t *testing.T) { require.NoError(t, err) require.NoError(t, sub.Unmarshal(&cfg)) - for _, test := range tests { - t.Run(test.name+"-shutdown", func(t *testing.T) { - c, err := test.createFn(context.Background(), processortest.NewNopSettings(), cfg) + for _, tt := range tests { + t.Run(tt.name+"-shutdown", func(t *testing.T) { + c, err := tt.createFn(context.Background(), processortest.NewNopSettings(), cfg) require.NoError(t, err) err = c.Shutdown(context.Background()) require.NoError(t, err) }) - t.Run(test.name+"-lifecycle", func(t *testing.T) { - c, err := test.createFn(context.Background(), processortest.NewNopSettings(), cfg) + t.Run(tt.name+"-lifecycle", func(t *testing.T) { + c, err := tt.createFn(context.Background(), processortest.NewNopSettings(), cfg) require.NoError(t, err) host := componenttest.NewNopHost() err = c.Start(context.Background(), host) require.NoError(t, err) require.NotPanics(t, func() { - switch test.name { + switch tt.name { case "logs": e, ok := c.(processor.Logs) require.True(t, ok) diff --git a/processor/memorylimiterprocessor/generated_component_test.go b/processor/memorylimiterprocessor/generated_component_test.go index 1820e3e0a8c..598a82be167 100644 --- a/processor/memorylimiterprocessor/generated_component_test.go +++ b/processor/memorylimiterprocessor/generated_component_test.go @@ -66,15 +66,15 @@ func TestComponentLifecycle(t *testing.T) { require.NoError(t, err) require.NoError(t, sub.Unmarshal(&cfg)) - for _, test := range tests { - t.Run(test.name+"-lifecycle", func(t *testing.T) { - c, err := test.createFn(context.Background(), processortest.NewNopSettings(), cfg) + for _, tt := range tests { + t.Run(tt.name+"-lifecycle", func(t *testing.T) { + c, err := tt.createFn(context.Background(), processortest.NewNopSettings(), cfg) require.NoError(t, err) host := componenttest.NewNopHost() err = c.Start(context.Background(), host) require.NoError(t, err) require.NotPanics(t, func() { - switch test.name { + switch tt.name { case "logs": e, ok := c.(processor.Logs) require.True(t, ok) diff --git a/processor/processor_test.go b/processor/processor_test.go index f22ae1e76e7..ea131f442b0 100644 --- a/processor/processor_test.go +++ b/processor/processor_test.go @@ -79,8 +79,7 @@ func TestMakeFactoryMap(t *testing.T) { }, } - for i := range testCases { - tt := testCases[i] + for _, tt := range testCases { t.Run(tt.name, func(t *testing.T) { out, err := MakeFactoryMap(tt.in...) if tt.out == nil { diff --git a/receiver/nopreceiver/generated_component_test.go b/receiver/nopreceiver/generated_component_test.go index 9f4d59328e2..14c94434412 100644 --- a/receiver/nopreceiver/generated_component_test.go +++ b/receiver/nopreceiver/generated_component_test.go @@ -61,21 +61,21 @@ func TestComponentLifecycle(t *testing.T) { require.NoError(t, err) require.NoError(t, sub.Unmarshal(&cfg)) - for _, test := range tests { - t.Run(test.name+"-shutdown", func(t *testing.T) { - c, err := test.createFn(context.Background(), receivertest.NewNopSettings(), cfg) + for _, tt := range tests { + t.Run(tt.name+"-shutdown", func(t *testing.T) { + c, err := tt.createFn(context.Background(), receivertest.NewNopSettings(), cfg) require.NoError(t, err) err = c.Shutdown(context.Background()) require.NoError(t, err) }) - t.Run(test.name+"-lifecycle", func(t *testing.T) { - firstRcvr, err := test.createFn(context.Background(), receivertest.NewNopSettings(), cfg) + t.Run(tt.name+"-lifecycle", func(t *testing.T) { + firstRcvr, err := tt.createFn(context.Background(), receivertest.NewNopSettings(), cfg) require.NoError(t, err) host := componenttest.NewNopHost() require.NoError(t, err) require.NoError(t, firstRcvr.Start(context.Background(), host)) require.NoError(t, firstRcvr.Shutdown(context.Background())) - secondRcvr, err := test.createFn(context.Background(), receivertest.NewNopSettings(), cfg) + secondRcvr, err := tt.createFn(context.Background(), receivertest.NewNopSettings(), cfg) require.NoError(t, err) require.NoError(t, secondRcvr.Start(context.Background(), host)) require.NoError(t, secondRcvr.Shutdown(context.Background())) diff --git a/receiver/otlpreceiver/config_test.go b/receiver/otlpreceiver/config_test.go index 64a9f576523..b9c2349ae96 100644 --- a/receiver/otlpreceiver/config_test.go +++ b/receiver/otlpreceiver/config_test.go @@ -216,9 +216,9 @@ func TestUnmarshalConfigInvalidSignalPath(t *testing.T) { }, } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - cm, err := confmaptest.LoadConf(filepath.Join("testdata", test.testDataFn)) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cm, err := confmaptest.LoadConf(filepath.Join("testdata", tt.testDataFn)) require.NoError(t, err) factory := NewFactory() cfg := factory.CreateDefaultConfig() diff --git a/receiver/otlpreceiver/generated_component_test.go b/receiver/otlpreceiver/generated_component_test.go index 6a4de81c668..2e1ed747ee8 100644 --- a/receiver/otlpreceiver/generated_component_test.go +++ b/receiver/otlpreceiver/generated_component_test.go @@ -61,21 +61,21 @@ func TestComponentLifecycle(t *testing.T) { require.NoError(t, err) require.NoError(t, sub.Unmarshal(&cfg)) - for _, test := range tests { - t.Run(test.name+"-shutdown", func(t *testing.T) { - c, err := test.createFn(context.Background(), receivertest.NewNopSettings(), cfg) + for _, tt := range tests { + t.Run(tt.name+"-shutdown", func(t *testing.T) { + c, err := tt.createFn(context.Background(), receivertest.NewNopSettings(), cfg) require.NoError(t, err) err = c.Shutdown(context.Background()) require.NoError(t, err) }) - t.Run(test.name+"-lifecycle", func(t *testing.T) { - firstRcvr, err := test.createFn(context.Background(), receivertest.NewNopSettings(), cfg) + t.Run(tt.name+"-lifecycle", func(t *testing.T) { + firstRcvr, err := tt.createFn(context.Background(), receivertest.NewNopSettings(), cfg) require.NoError(t, err) host := componenttest.NewNopHost() require.NoError(t, err) require.NoError(t, firstRcvr.Start(context.Background(), host)) require.NoError(t, firstRcvr.Shutdown(context.Background())) - secondRcvr, err := test.createFn(context.Background(), receivertest.NewNopSettings(), cfg) + secondRcvr, err := tt.createFn(context.Background(), receivertest.NewNopSettings(), cfg) require.NoError(t, err) require.NoError(t, secondRcvr.Start(context.Background(), host)) require.NoError(t, secondRcvr.Shutdown(context.Background())) diff --git a/receiver/receiver_test.go b/receiver/receiver_test.go index efb27a699ac..cf0bf128a81 100644 --- a/receiver/receiver_test.go +++ b/receiver/receiver_test.go @@ -79,8 +79,7 @@ func TestMakeFactoryMap(t *testing.T) { }, } - for i := range testCases { - tt := testCases[i] + for _, tt := range testCases { t.Run(tt.name, func(t *testing.T) { out, err := MakeFactoryMap(tt.in...) if tt.out == nil { diff --git a/receiver/scrapererror/scrapeerror_test.go b/receiver/scrapererror/scrapeerror_test.go index 6fd68a7c257..2568e4e28b5 100644 --- a/receiver/scrapererror/scrapeerror_test.go +++ b/receiver/scrapererror/scrapeerror_test.go @@ -86,19 +86,19 @@ func TestScrapeErrorsCombine(t *testing.T) { }, } - for _, tc := range testCases { - scrapeErrs := tc.errs() - if tc.expectNil { + for _, tt := range testCases { + scrapeErrs := tt.errs() + if tt.expectNil { assert.NoError(t, scrapeErrs.Combine()) continue } - assert.EqualError(t, scrapeErrs.Combine(), tc.expectedErr) - if tc.expectedScrape { + assert.EqualError(t, scrapeErrs.Combine(), tt.expectedErr) + if tt.expectedScrape { var partialScrapeErr PartialScrapeError if !errors.As(scrapeErrs.Combine(), &partialScrapeErr) { t.Errorf("%+v.Combine() = %q. Want: PartialScrapeError", scrapeErrs, scrapeErrs.Combine()) - } else if tc.expectedFailedCount != partialScrapeErr.Failed { - t.Errorf("%+v.Combine().Failed. Got %d Failed count. Want: %d", scrapeErrs, partialScrapeErr.Failed, tc.expectedFailedCount) + } else if tt.expectedFailedCount != partialScrapeErr.Failed { + t.Errorf("%+v.Combine().Failed. Got %d Failed count. Want: %d", scrapeErrs, partialScrapeErr.Failed, tt.expectedFailedCount) } } } diff --git a/receiver/scraperhelper/scrapercontroller_test.go b/receiver/scraperhelper/scrapercontroller_test.go index eb8c37bb16c..d611581b5e3 100644 --- a/receiver/scraperhelper/scrapercontroller_test.go +++ b/receiver/scraperhelper/scrapercontroller_test.go @@ -123,8 +123,8 @@ func TestScrapeController(t *testing.T) { }, } - for _, test := range testCases { - test := test + for _, tt := range testCases { + test := tt t.Run(test.name, func(t *testing.T) { receiverID := component.MustNewID("receiver") tt, err := componenttest.SetupTelemetry(receiverID) diff --git a/service/config_test.go b/service/config_test.go index 6ac9d6e625a..efe4db66d1d 100644 --- a/service/config_test.go +++ b/service/config_test.go @@ -73,10 +73,10 @@ func TestConfigValidate(t *testing.T) { }, } - for _, test := range testCases { - t.Run(test.name, func(t *testing.T) { - cfg := test.cfgFn() - assert.Equal(t, test.expected, cfg.Validate()) + for _, tt := range testCases { + t.Run(tt.name, func(t *testing.T) { + cfg := tt.cfgFn() + assert.Equal(t, tt.expected, cfg.Validate()) }) } } diff --git a/service/extensions/extensions_test.go b/service/extensions/extensions_test.go index 1dd86596def..f159533fd3f 100644 --- a/service/extensions/extensions_test.go +++ b/service/extensions/extensions_test.go @@ -367,7 +367,7 @@ func TestStatusReportedOnStartupShutdown(t *testing.T) { } } - for _, tc := range []struct { + for _, tt := range []struct { name string expectedStatuses []*componentstatus.Event startErr error @@ -405,10 +405,10 @@ func TestStatusReportedOnStartupShutdown(t *testing.T) { shutdownErr: assert.AnError, }, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(tt.name, func(t *testing.T) { statusType := component.MustNewType("statustest") compID := component.NewID(statusType) - factory := newStatusTestExtensionFactory(statusType, tc.startErr, tc.shutdownErr) + factory := newStatusTestExtensionFactory(statusType, tt.startErr, tt.shutdownErr) config := factory.CreateDefaultConfig() extensionsConfigs := map[component.ID]component.Config{ compID: config, @@ -438,11 +438,11 @@ func TestStatusReportedOnStartupShutdown(t *testing.T) { rep.Ready() - assert.Equal(t, tc.startErr, extensions.Start(context.Background(), componenttest.NewNopHost())) - if tc.startErr == nil { - assert.Equal(t, tc.shutdownErr, extensions.Shutdown(context.Background())) + assert.Equal(t, tt.startErr, extensions.Start(context.Background(), componenttest.NewNopHost())) + if tt.startErr == nil { + assert.Equal(t, tt.shutdownErr, extensions.Shutdown(context.Background())) } - assertEqualStatuses(t, tc.expectedStatuses, actualStatuses) + assertEqualStatuses(t, tt.expectedStatuses, actualStatuses) }) } } diff --git a/service/internal/graph/graph_test.go b/service/internal/graph/graph_test.go index 460f2a86bb6..71f4d2c3536 100644 --- a/service/internal/graph/graph_test.go +++ b/service/internal/graph/graph_test.go @@ -932,8 +932,8 @@ func TestConnectorPipelinesGraph(t *testing.T) { }, } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { // Build the pipeline set := Settings{ Telemetry: componenttest.NewNopTelemetrySettings(), @@ -978,21 +978,21 @@ func TestConnectorPipelinesGraph(t *testing.T) { testcomponents.MockForwardConnectorFactory.Type(): testcomponents.MockForwardConnectorFactory, }, ), - PipelineConfigs: test.pipelineConfigs, + PipelineConfigs: tt.pipelineConfigs, } pg, err := Build(context.Background(), set) require.NoError(t, err) - assert.Equal(t, len(test.pipelineConfigs), len(pg.pipelines)) + assert.Equal(t, len(tt.pipelineConfigs), len(pg.pipelines)) assert.NoError(t, pg.StartAll(context.Background(), &Host{Reporter: status.NewReporter(func(*componentstatus.InstanceID, *componentstatus.Event) {}, func(error) {})})) - mutatingPipelines := make(map[component.ID]bool, len(test.pipelineConfigs)) + mutatingPipelines := make(map[component.ID]bool, len(tt.pipelineConfigs)) // Check each pipeline individually, ensuring that all components are started // and that they have observed no signals yet. - for pipelineID, pipelineCfg := range test.pipelineConfigs { + for pipelineID, pipelineCfg := range tt.pipelineConfigs { pipeline, ok := pg.pipelines[pipelineID] require.True(t, ok, "expected to find pipeline: %s", pipelineID.String()) @@ -1011,7 +1011,7 @@ func TestConnectorPipelinesGraph(t *testing.T) { assert.Equal(t, expectMutatesData, pipeline.capabilitiesNode.getConsumer().Capabilities().MutatesData) mutatingPipelines[pipelineID] = expectMutatesData - expectedReceivers, expectedExporters := expectedInstances(test.pipelineConfigs, pipelineID) + expectedReceivers, expectedExporters := expectedInstances(tt.pipelineConfigs, pipelineID) require.Len(t, pipeline.receivers, expectedReceivers) require.Equal(t, len(pipelineCfg.Processors), len(pipeline.processors)) require.Len(t, pipeline.exporters, expectedExporters) @@ -1122,7 +1122,7 @@ func TestConnectorPipelinesGraph(t *testing.T) { assert.NoError(t, pg.ShutdownAll(context.Background(), statustest.NewNopStatusReporter())) // Check each pipeline individually, ensuring that all components are stopped. - for pipelineID := range test.pipelineConfigs { + for pipelineID := range tt.pipelineConfigs { pipeline, ok := pg.pipelines[pipelineID] require.True(t, ok, "expected to find pipeline: %s", pipelineID.String()) @@ -1179,11 +1179,11 @@ func TestConnectorPipelinesGraph(t *testing.T) { allExporters := pg.GetExporters() for _, e := range allExporters[component.DataTypeTraces] { tracesExporter := e.(*testcomponents.ExampleExporter) - assert.Len(t, tracesExporter.Traces, test.expectedPerExporter) + assert.Len(t, tracesExporter.Traces, tt.expectedPerExporter) expectedMutable := testdata.GenerateTraces(1) expectedReadOnly := testdata.GenerateTraces(1) expectedReadOnly.MarkReadOnly() - for i := 0; i < test.expectedPerExporter; i++ { + for i := 0; i < tt.expectedPerExporter; i++ { if tracesExporter.Traces[i].IsReadOnly() { assert.EqualValues(t, expectedReadOnly, tracesExporter.Traces[i]) } else { @@ -1193,11 +1193,11 @@ func TestConnectorPipelinesGraph(t *testing.T) { } for _, e := range allExporters[component.DataTypeMetrics] { metricsExporter := e.(*testcomponents.ExampleExporter) - assert.Len(t, metricsExporter.Metrics, test.expectedPerExporter) + assert.Len(t, metricsExporter.Metrics, tt.expectedPerExporter) expectedMutable := testdata.GenerateMetrics(1) expectedReadOnly := testdata.GenerateMetrics(1) expectedReadOnly.MarkReadOnly() - for i := 0; i < test.expectedPerExporter; i++ { + for i := 0; i < tt.expectedPerExporter; i++ { if metricsExporter.Metrics[i].IsReadOnly() { assert.EqualValues(t, expectedReadOnly, metricsExporter.Metrics[i]) } else { @@ -1207,11 +1207,11 @@ func TestConnectorPipelinesGraph(t *testing.T) { } for _, e := range allExporters[component.DataTypeLogs] { logsExporter := e.(*testcomponents.ExampleExporter) - assert.Len(t, logsExporter.Logs, test.expectedPerExporter) + assert.Len(t, logsExporter.Logs, tt.expectedPerExporter) expectedMutable := testdata.GenerateLogs(1) expectedReadOnly := testdata.GenerateLogs(1) expectedReadOnly.MarkReadOnly() - for i := 0; i < test.expectedPerExporter; i++ { + for i := 0; i < tt.expectedPerExporter; i++ { if logsExporter.Logs[i].IsReadOnly() { assert.EqualValues(t, expectedReadOnly, logsExporter.Logs[i]) } else { @@ -1221,11 +1221,11 @@ func TestConnectorPipelinesGraph(t *testing.T) { } for _, e := range allExporters[componentprofiles.DataTypeProfiles] { profilesExporter := e.(*testcomponents.ExampleExporter) - assert.Len(t, profilesExporter.Profiles, test.expectedPerExporter) + assert.Len(t, profilesExporter.Profiles, tt.expectedPerExporter) expectedMutable := testdata.GenerateProfiles(1) expectedReadOnly := testdata.GenerateProfiles(1) expectedReadOnly.MarkReadOnly() - for i := 0; i < test.expectedPerExporter; i++ { + for i := 0; i < tt.expectedPerExporter; i++ { if profilesExporter.Profiles[i].IsReadOnly() { assert.EqualValues(t, expectedReadOnly, profilesExporter.Profiles[i]) } else { @@ -2628,40 +2628,40 @@ func TestGraphBuildErrors(t *testing.T) { }, } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { set := Settings{ BuildInfo: component.NewDefaultBuildInfo(), Telemetry: componenttest.NewNopTelemetrySettings(), ReceiverBuilder: builders.NewReceiver( - test.receiverCfgs, + tt.receiverCfgs, map[component.Type]receiver.Factory{ nopReceiverFactory.Type(): nopReceiverFactory, badReceiverFactory.Type(): badReceiverFactory, }), ProcessorBuilder: builders.NewProcessor( - test.processorCfgs, + tt.processorCfgs, map[component.Type]processor.Factory{ nopProcessorFactory.Type(): nopProcessorFactory, badProcessorFactory.Type(): badProcessorFactory, }), ExporterBuilder: builders.NewExporter( - test.exporterCfgs, + tt.exporterCfgs, map[component.Type]exporter.Factory{ nopExporterFactory.Type(): nopExporterFactory, badExporterFactory.Type(): badExporterFactory, }), ConnectorBuilder: builders.NewConnector( - test.connectorCfgs, + tt.connectorCfgs, map[component.Type]connector.Factory{ nopConnectorFactory.Type(): nopConnectorFactory, badConnectorFactory.Type(): badConnectorFactory, mfConnectorFactory.Type(): mfConnectorFactory, }), - PipelineConfigs: test.pipelineCfgs, + PipelineConfigs: tt.pipelineCfgs, } _, err := Build(context.Background(), set) - assert.EqualError(t, err, test.expected) + assert.EqualError(t, err, tt.expected) }) } } @@ -2821,7 +2821,7 @@ func TestStatusReportedOnStartupShutdown(t *testing.T) { } - for _, tc := range []struct { + for _, tt := range []struct { name string edge [2]*testNode expectedStatuses map[*componentstatus.InstanceID][]*componentstatus.Event @@ -2913,7 +2913,7 @@ func TestStatusReportedOnStartupShutdown(t *testing.T) { shutdownErr: assert.AnError, }, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(tt.name, func(t *testing.T) { pg := &Graph{componentGraph: simple.NewDirectedGraph()} pg.telemetry = componenttest.NewNopTelemetrySettings() @@ -2925,16 +2925,16 @@ func TestStatusReportedOnStartupShutdown(t *testing.T) { rep.Ready() - e0, e1 := tc.edge[0], tc.edge[1] + e0, e1 := tt.edge[0], tt.edge[1] pg.instanceIDs = map[int64]*componentstatus.InstanceID{ e0.ID(): instanceIDs[e0], e1.ID(): instanceIDs[e1], } pg.componentGraph.SetEdge(simple.Edge{F: e0, T: e1}) - assert.Equal(t, tc.startupErr, pg.StartAll(context.Background(), &Host{Reporter: rep})) - assert.Equal(t, tc.shutdownErr, pg.ShutdownAll(context.Background(), rep)) - assertEqualStatuses(t, tc.expectedStatuses, actualStatuses) + assert.Equal(t, tt.startupErr, pg.StartAll(context.Background(), &Host{Reporter: rep})) + assert.Equal(t, tt.shutdownErr, pg.ShutdownAll(context.Background(), rep)) + assertEqualStatuses(t, tt.expectedStatuses, actualStatuses) }) } } diff --git a/service/internal/status/status_test.go b/service/internal/status/status_test.go index ff61e138242..932acc82f82 100644 --- a/service/internal/status/status_test.go +++ b/service/internal/status/status_test.go @@ -14,7 +14,7 @@ import ( ) func TestStatusFSM(t *testing.T) { - for _, tc := range []struct { + for _, tt := range []struct { name string reportedStatuses []componentstatus.Status expectedStatuses []componentstatus.Status @@ -122,7 +122,7 @@ func TestStatusFSM(t *testing.T) { expectedErrorCount: 1, }, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(tt.name, func(t *testing.T) { var receivedStatuses []componentstatus.Status fsm := newFSM( func(ev *componentstatus.Event) { @@ -131,15 +131,15 @@ func TestStatusFSM(t *testing.T) { ) errorCount := 0 - for _, status := range tc.reportedStatuses { + for _, status := range tt.reportedStatuses { if err := fsm.transition(componentstatus.NewEvent(status)); err != nil { errorCount++ require.ErrorIs(t, err, errInvalidStateTransition) } } - require.Equal(t, tc.expectedErrorCount, errorCount) - require.Equal(t, tc.expectedStatuses, receivedStatuses) + require.Equal(t, tt.expectedErrorCount, errorCount) + require.Equal(t, tt.expectedStatuses, receivedStatuses) }) } } @@ -278,7 +278,7 @@ func TestReporterReady(t *testing.T) { } func TestReportComponentOKIfStarting(t *testing.T) { - for _, tc := range []struct { + for _, tt := range []struct { name string initialStatuses []componentstatus.Status expectedStatuses []componentstatus.Status @@ -327,7 +327,7 @@ func TestReportComponentOKIfStarting(t *testing.T) { }, }, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(tt.name, func(t *testing.T) { var receivedStatuses []componentstatus.Status rep := NewReporter( @@ -341,13 +341,13 @@ func TestReportComponentOKIfStarting(t *testing.T) { rep.Ready() id := &componentstatus.InstanceID{} - for _, status := range tc.initialStatuses { + for _, status := range tt.initialStatuses { rep.ReportStatus(id, componentstatus.NewEvent(status)) } rep.ReportOKIfStarting(id) - require.Equal(t, tc.expectedStatuses, receivedStatuses) + require.Equal(t, tt.expectedStatuses, receivedStatuses) }) } } diff --git a/service/pipelines/config_test.go b/service/pipelines/config_test.go index 7ad94d5ab3f..d4b5503e3a9 100644 --- a/service/pipelines/config_test.go +++ b/service/pipelines/config_test.go @@ -74,10 +74,10 @@ func TestConfigValidate(t *testing.T) { }, } - for _, test := range testCases { - t.Run(test.name, func(t *testing.T) { - cfg := test.cfgFn() - assert.Equal(t, test.expected, cfg.Validate()) + for _, tt := range testCases { + t.Run(tt.name, func(t *testing.T) { + cfg := tt.cfgFn() + assert.Equal(t, tt.expected, cfg.Validate()) }) } } diff --git a/service/telemetry/metrics_test.go b/service/telemetry/metrics_test.go index c40fbc325c1..f3bb140b1f3 100644 --- a/service/telemetry/metrics_test.go +++ b/service/telemetry/metrics_test.go @@ -40,7 +40,7 @@ func TestTelemetryInit(t *testing.T) { labels map[string]string } - for _, tc := range []struct { + for _, tt := range []struct { name string disableHighCard bool expectedMetrics map[string]metricValue @@ -190,9 +190,9 @@ func TestTelemetryInit(t *testing.T) { }, }, } { - t.Run(tc.name, func(t *testing.T) { - if tc.extendedConfig { - tc.cfg.Metrics.Readers = []config.MetricReader{ + t.Run(tt.name, func(t *testing.T) { + if tt.extendedConfig { + tt.cfg.Metrics.Readers = []config.MetricReader{ { Pull: &config.PullMetricReader{ Exporter: config.MetricExporter{ @@ -202,8 +202,8 @@ func TestTelemetryInit(t *testing.T) { }, } } - if tc.cfg == nil { - tc.cfg = &Config{ + if tt.cfg == nil { + tt.cfg = &Config{ Resource: map[string]*string{ semconv.AttributeServiceInstanceID: &testInstanceID, }, @@ -214,11 +214,11 @@ func TestTelemetryInit(t *testing.T) { } } set := meterProviderSettings{ - res: resource.New(component.NewDefaultBuildInfo(), tc.cfg.Resource), - cfg: tc.cfg.Metrics, + res: resource.New(component.NewDefaultBuildInfo(), tt.cfg.Resource), + cfg: tt.cfg.Metrics, asyncErrorChannel: make(chan error), } - mp, err := newMeterProvider(set, tc.disableHighCard) + mp, err := newMeterProvider(set, tt.disableHighCard) require.NoError(t, err) defer func() { if prov, ok := mp.(interface{ Shutdown(context.Context) error }); ok { @@ -229,9 +229,9 @@ func TestTelemetryInit(t *testing.T) { createTestMetrics(t, mp) metrics := getMetricsFromPrometheus(t, mp.(*meterProvider).servers[0].Handler) - require.Equal(t, len(tc.expectedMetrics), len(metrics)) + require.Equal(t, len(tt.expectedMetrics), len(metrics)) - for metricName, metricValue := range tc.expectedMetrics { + for metricName, metricValue := range tt.expectedMetrics { mf, present := metrics[metricName] require.True(t, present, "expected metric %q was not present", metricName) require.Len(t, mf.Metric, 1, "only one measure should exist for metric %q", metricName) From a0d596640ce6224b19fc5bccbaa9b10e6455dfb9 Mon Sep 17 00:00:00 2001 From: AdamKorcz <44787359+AdamKorcz@users.noreply.github.com> Date: Wed, 18 Sep 2024 22:11:12 +0100 Subject: [PATCH 4/8] Add marshal calls to fuzzers (#11119) #### Description #### Link to tracking issue Fixes # #### Testing #### Documentation Adds both a marshal call and another unmarshal -> marshal round to the fuzzers to test for more potential bugs. Signed-off-by: Adam Korczynski --- pdata/plog/fuzz_test.go | 65 ++++++++++++-- pdata/plog/plogotlp/fuzz_test.go | 108 +++++++++++++++++++--- pdata/pprofile/fuzz_test.go | 35 +++++++- pdata/pprofile/pprofileotlp/fuzz_test.go | 109 ++++++++++++++++++++--- pdata/ptrace/fuzz_test.go | 67 ++++++++++++-- pdata/ptrace/ptraceotlp/fuzz_test.go | 109 ++++++++++++++++++++--- 6 files changed, 440 insertions(+), 53 deletions(-) diff --git a/pdata/plog/fuzz_test.go b/pdata/plog/fuzz_test.go index aed808a2ef4..c47fed13fba 100644 --- a/pdata/plog/fuzz_test.go +++ b/pdata/plog/fuzz_test.go @@ -4,21 +4,70 @@ package plog // import "go.opentelemetry.io/collector/pdata/plog" import ( + "bytes" "testing" ) +var ( + unexpectedBytes = "expected the same bytes from unmarshaling and marshaling." +) + func FuzzUnmarshalJsonLogs(f *testing.F) { - f.Fuzz(func(_ *testing.T, data []byte) { - u := &JSONUnmarshaler{} - //nolint: errcheck - _, _ = u.UnmarshalLogs(data) + f.Fuzz(func(t *testing.T, data []byte) { + u1 := &JSONUnmarshaler{} + ld1, err := u1.UnmarshalLogs(data) + if err != nil { + return + } + m1 := &JSONMarshaler{} + b1, err := m1.MarshalLogs(ld1) + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + u2 := &JSONUnmarshaler{} + ld2, err := u2.UnmarshalLogs(b1) + if err != nil { + t.Fatalf("failed to unmarshal valid bytes: %v", err) + } + m2 := &JSONMarshaler{} + b2, err := m2.MarshalLogs(ld2) + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + if !bytes.Equal(b1, b2) { + t.Fatalf("%s. \nexpected %d but got %d\n", unexpectedBytes, b1, b2) + } }) } func FuzzUnmarshalPBLogs(f *testing.F) { - f.Fuzz(func(_ *testing.T, data []byte) { - u := &ProtoUnmarshaler{} - //nolint: errcheck - _, _ = u.UnmarshalLogs(data) + f.Fuzz(func(t *testing.T, data []byte) { + u1 := &ProtoUnmarshaler{} + ld1, err := u1.UnmarshalLogs(data) + if err != nil { + return + } + m1 := &ProtoMarshaler{} + b1, err := m1.MarshalLogs(ld1) + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + u2 := &ProtoUnmarshaler{} + ld2, err := u2.UnmarshalLogs(b1) + if err != nil { + t.Fatalf("failed to unmarshal valid bytes: %v", err) + } + m2 := &ProtoMarshaler{} + b2, err := m2.MarshalLogs(ld2) + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + if !bytes.Equal(b1, b2) { + t.Fatalf("%s. \nexpected %d but got %d\n", unexpectedBytes, b1, b2) + } }) } diff --git a/pdata/plog/plogotlp/fuzz_test.go b/pdata/plog/plogotlp/fuzz_test.go index af73d07e970..3203ee8e344 100644 --- a/pdata/plog/plogotlp/fuzz_test.go +++ b/pdata/plog/plogotlp/fuzz_test.go @@ -4,37 +4,121 @@ package plogotlp // import "go.opentelemetry.io/collector/pdata/plog/plogotlp" import ( + "bytes" "testing" ) +var ( + unexpectedBytes = "expected the same bytes from unmarshaling and marshaling." +) + func FuzzRequestUnmarshalJSON(f *testing.F) { - f.Fuzz(func(_ *testing.T, data []byte) { + f.Fuzz(func(t *testing.T, data []byte) { er := NewExportRequest() - //nolint: errcheck - er.UnmarshalJSON(data) + err := er.UnmarshalJSON(data) + if err != nil { + return + } + b1, err := er.MarshalJSON() + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + er = NewExportRequest() + err = er.UnmarshalJSON(b1) + if err != nil { + t.Fatalf("failed to unmarshal valid bytes: %v", err) + } + b2, err := er.MarshalJSON() + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + if !bytes.Equal(b1, b2) { + t.Fatalf("%s. \nexpected %d but got %d\n", unexpectedBytes, b1, b2) + } }) } func FuzzResponseUnmarshalJSON(f *testing.F) { - f.Fuzz(func(_ *testing.T, data []byte) { + f.Fuzz(func(t *testing.T, data []byte) { er := NewExportResponse() - //nolint: errcheck - er.UnmarshalJSON(data) + err := er.UnmarshalJSON(data) + if err != nil { + return + } + b1, err := er.MarshalJSON() + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + er = NewExportResponse() + err = er.UnmarshalJSON(b1) + if err != nil { + t.Fatalf("failed to unmarshal valid bytes: %v", err) + } + b2, err := er.MarshalJSON() + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + if !bytes.Equal(b1, b2) { + t.Fatalf("%s. \nexpected %d but got %d\n", unexpectedBytes, b1, b2) + } }) } func FuzzRequestUnmarshalProto(f *testing.F) { - f.Fuzz(func(_ *testing.T, data []byte) { + f.Fuzz(func(t *testing.T, data []byte) { er := NewExportRequest() - //nolint: errcheck - er.UnmarshalProto(data) + err := er.UnmarshalProto(data) + if err != nil { + return + } + b1, err := er.MarshalProto() + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + er = NewExportRequest() + err = er.UnmarshalProto(b1) + if err != nil { + t.Fatalf("failed to unmarshal valid bytes: %v", err) + } + b2, err := er.MarshalProto() + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + if !bytes.Equal(b1, b2) { + t.Fatalf("%s. \nexpected %d but got %d\n", unexpectedBytes, b1, b2) + } }) } func FuzzResponseUnmarshalProto(f *testing.F) { - f.Fuzz(func(_ *testing.T, data []byte) { + f.Fuzz(func(t *testing.T, data []byte) { er := NewExportResponse() - //nolint: errcheck - er.UnmarshalProto(data) + err := er.UnmarshalProto(data) + if err != nil { + return + } + b1, err := er.MarshalProto() + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + er = NewExportResponse() + err = er.UnmarshalProto(b1) + if err != nil { + t.Fatalf("failed to unmarshal valid bytes: %v", err) + } + b2, err := er.MarshalProto() + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + if !bytes.Equal(b1, b2) { + t.Fatalf("%s. \nexpected %d but got %d\n", unexpectedBytes, b1, b2) + } }) } diff --git a/pdata/pprofile/fuzz_test.go b/pdata/pprofile/fuzz_test.go index fcb1927a231..46b204a845e 100644 --- a/pdata/pprofile/fuzz_test.go +++ b/pdata/pprofile/fuzz_test.go @@ -4,13 +4,40 @@ package pprofile // import "go.opentelemetry.io/collector/pdata/pprofile" import ( + "bytes" "testing" ) +var ( + unexpectedBytes = "expected the same bytes from unmarshaling and marshaling." +) + func FuzzUnmarshalProfiles(f *testing.F) { - f.Fuzz(func(_ *testing.T, data []byte) { - u := &JSONUnmarshaler{} - //nolint: errcheck - _, _ = u.UnmarshalProfiles(data) + f.Fuzz(func(t *testing.T, data []byte) { + u1 := &JSONUnmarshaler{} + ld1, err := u1.UnmarshalProfiles(data) + if err != nil { + return + } + m1 := &JSONMarshaler{} + b1, err := m1.MarshalProfiles(ld1) + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + u2 := &JSONUnmarshaler{} + ld2, err := u2.UnmarshalProfiles(b1) + if err != nil { + t.Fatalf("failed to unmarshal valid bytes: %v", err) + } + m2 := &JSONMarshaler{} + b2, err := m2.MarshalProfiles(ld2) + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + if !bytes.Equal(b1, b2) { + t.Fatalf("%s. \nexpected %d but got %d\n", unexpectedBytes, b1, b2) + } }) } diff --git a/pdata/pprofile/pprofileotlp/fuzz_test.go b/pdata/pprofile/pprofileotlp/fuzz_test.go index 02f0cf57683..c3e8a1b9372 100644 --- a/pdata/pprofile/pprofileotlp/fuzz_test.go +++ b/pdata/pprofile/pprofileotlp/fuzz_test.go @@ -4,37 +4,122 @@ package pprofileotlp // import "go.opentelemetry.io/collector/pdata/pprofile/pprofileotlp" import ( + "bytes" "testing" ) +var ( + unexpectedBytes = "expected the same bytes from unmarshaling and marshaling." +) + func FuzzRequestUnmarshalJSON(f *testing.F) { - f.Fuzz(func(_ *testing.T, data []byte) { + f.Fuzz(func(t *testing.T, data []byte) { er := NewExportRequest() - //nolint: errcheck - er.UnmarshalJSON(data) + err := er.UnmarshalJSON(data) + if err != nil { + return + } + b1, err := er.MarshalJSON() + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + er = NewExportRequest() + err = er.UnmarshalJSON(b1) + if err != nil { + t.Fatalf("failed to unmarshal valid bytes: %v", err) + } + b2, err := er.MarshalJSON() + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + if !bytes.Equal(b1, b2) { + t.Fatalf("%s. \nexpected %d but got %d\n", unexpectedBytes, b1, b2) + } }) } func FuzzResponseUnmarshalJSON(f *testing.F) { - f.Fuzz(func(_ *testing.T, data []byte) { + f.Fuzz(func(t *testing.T, data []byte) { er := NewExportResponse() - //nolint: errcheck - er.UnmarshalJSON(data) + err := er.UnmarshalJSON(data) + if err != nil { + return + } + b1, err := er.MarshalJSON() + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + er = NewExportResponse() + err = er.UnmarshalJSON(b1) + if err != nil { + t.Fatalf("failed to unmarshal valid bytes: %v", err) + } + b2, err := er.MarshalJSON() + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + if !bytes.Equal(b1, b2) { + t.Fatalf("%s. \nexpected %d but got %d\n", unexpectedBytes, b1, b2) + } }) } func FuzzRequestUnmarshalProto(f *testing.F) { - f.Fuzz(func(_ *testing.T, data []byte) { + f.Fuzz(func(t *testing.T, data []byte) { er := NewExportRequest() - //nolint: errcheck - er.UnmarshalProto(data) + err := er.UnmarshalProto(data) + if err != nil { + return + } + b1, err := er.MarshalProto() + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + er = NewExportRequest() + err = er.UnmarshalProto(b1) + if err != nil { + t.Fatalf("failed to unmarshal valid bytes: %v", err) + } + b2, err := er.MarshalProto() + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + if !bytes.Equal(b1, b2) { + t.Fatalf("%s. \nexpected %d but got %d\n", unexpectedBytes, b1, b2) + } }) } func FuzzResponseUnmarshalProto(f *testing.F) { - f.Fuzz(func(_ *testing.T, data []byte) { + f.Fuzz(func(t *testing.T, data []byte) { er := NewExportResponse() - //nolint: errcheck - er.UnmarshalProto(data) + err := er.UnmarshalProto(data) + if err != nil { + return + } + b1, err := er.MarshalProto() + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + er = NewExportResponse() + err = er.UnmarshalProto(b1) + if err != nil { + t.Fatalf("failed to unmarshal valid bytes: %v", err) + } + b2, err := er.MarshalProto() + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + if !bytes.Equal(b1, b2) { + t.Fatalf("%s. \nexpected %d but got %d\n", unexpectedBytes, b1, b2) + } }) } diff --git a/pdata/ptrace/fuzz_test.go b/pdata/ptrace/fuzz_test.go index 7047c781eff..d35a00c80b7 100644 --- a/pdata/ptrace/fuzz_test.go +++ b/pdata/ptrace/fuzz_test.go @@ -4,13 +4,70 @@ package ptrace // import "go.opentelemetry.io/collector/pdata/ptrace" import ( + "bytes" "testing" ) -func FuzzUnmarshalTraces(f *testing.F) { - f.Fuzz(func(_ *testing.T, data []byte) { - u := &JSONUnmarshaler{} - //nolint: errcheck - _, _ = u.UnmarshalTraces(data) +var ( + unexpectedBytes = "expected the same bytes from unmarshaling and marshaling." +) + +func FuzzUnmarshalJSONTraces(f *testing.F) { + f.Fuzz(func(t *testing.T, data []byte) { + u1 := &JSONUnmarshaler{} + ld1, err := u1.UnmarshalTraces(data) + if err != nil { + return + } + m1 := &JSONMarshaler{} + b1, err := m1.MarshalTraces(ld1) + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + u2 := &JSONUnmarshaler{} + ld2, err := u2.UnmarshalTraces(b1) + if err != nil { + t.Fatalf("failed to unmarshal valid bytes: %v", err) + } + m2 := &JSONMarshaler{} + b2, err := m2.MarshalTraces(ld2) + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + if !bytes.Equal(b1, b2) { + t.Fatalf("%s. \nexpected %d but got %d\n", unexpectedBytes, b1, b2) + } + }) +} + +func FuzzUnmarshalPBTraces(f *testing.F) { + f.Fuzz(func(t *testing.T, data []byte) { + u1 := &ProtoUnmarshaler{} + ld1, err := u1.UnmarshalTraces(data) + if err != nil { + return + } + m1 := &ProtoMarshaler{} + b1, err := m1.MarshalTraces(ld1) + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + u2 := &ProtoUnmarshaler{} + ld2, err := u2.UnmarshalTraces(b1) + if err != nil { + t.Fatalf("failed to unmarshal valid bytes: %v", err) + } + m2 := &ProtoMarshaler{} + b2, err := m2.MarshalTraces(ld2) + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + if !bytes.Equal(b1, b2) { + t.Fatalf("%s. \nexpected %d but got %d\n", unexpectedBytes, b1, b2) + } }) } diff --git a/pdata/ptrace/ptraceotlp/fuzz_test.go b/pdata/ptrace/ptraceotlp/fuzz_test.go index 473eb39b2cd..d6d866e9de4 100644 --- a/pdata/ptrace/ptraceotlp/fuzz_test.go +++ b/pdata/ptrace/ptraceotlp/fuzz_test.go @@ -4,37 +4,122 @@ package ptraceotlp // import "go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp" import ( + "bytes" "testing" ) +var ( + unexpectedBytes = "expected the same bytes from unmarshaling and marshaling." +) + func FuzzRequestUnmarshalJSON(f *testing.F) { - f.Fuzz(func(_ *testing.T, data []byte) { + f.Fuzz(func(t *testing.T, data []byte) { er := NewExportRequest() - //nolint: errcheck - er.UnmarshalJSON(data) + err := er.UnmarshalJSON(data) + if err != nil { + return + } + b1, err := er.MarshalJSON() + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + er = NewExportRequest() + err = er.UnmarshalJSON(b1) + if err != nil { + t.Fatalf("failed to unmarshal valid bytes: %v", err) + } + b2, err := er.MarshalJSON() + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + if !bytes.Equal(b1, b2) { + t.Fatalf("%s. \nexpected %d but got %d\n", unexpectedBytes, b1, b2) + } }) } func FuzzResponseUnmarshalJSON(f *testing.F) { - f.Fuzz(func(_ *testing.T, data []byte) { + f.Fuzz(func(t *testing.T, data []byte) { er := NewExportResponse() - //nolint: errcheck - er.UnmarshalJSON(data) + err := er.UnmarshalJSON(data) + if err != nil { + return + } + b1, err := er.MarshalJSON() + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + er = NewExportResponse() + err = er.UnmarshalJSON(b1) + if err != nil { + t.Fatalf("failed to unmarshal valid bytes: %v", err) + } + b2, err := er.MarshalJSON() + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + if !bytes.Equal(b1, b2) { + t.Fatalf("%s. \nexpected %d but got %d\n", unexpectedBytes, b1, b2) + } }) } func FuzzRequestUnmarshalProto(f *testing.F) { - f.Fuzz(func(_ *testing.T, data []byte) { + f.Fuzz(func(t *testing.T, data []byte) { er := NewExportRequest() - //nolint: errcheck - er.UnmarshalProto(data) + err := er.UnmarshalProto(data) + if err != nil { + return + } + b1, err := er.MarshalProto() + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + er = NewExportRequest() + err = er.UnmarshalProto(b1) + if err != nil { + t.Fatalf("failed to unmarshal valid bytes: %v", err) + } + b2, err := er.MarshalProto() + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + if !bytes.Equal(b1, b2) { + t.Fatalf("%s. \nexpected %d but got %d\n", unexpectedBytes, b1, b2) + } }) } func FuzzResponseUnmarshalProto(f *testing.F) { - f.Fuzz(func(_ *testing.T, data []byte) { + f.Fuzz(func(t *testing.T, data []byte) { er := NewExportResponse() - //nolint: errcheck - er.UnmarshalProto(data) + err := er.UnmarshalProto(data) + if err != nil { + return + } + b1, err := er.MarshalProto() + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + er = NewExportResponse() + err = er.UnmarshalProto(b1) + if err != nil { + t.Fatalf("failed to unmarshal valid bytes: %v", err) + } + b2, err := er.MarshalProto() + if err != nil { + t.Fatalf("failed to marshal valid struct: %v", err) + } + + if !bytes.Equal(b1, b2) { + t.Fatalf("%s. \nexpected %d but got %d\n", unexpectedBytes, b1, b2) + } }) } From 37f783308e50a893296a4fe46cf8290729cbf7d5 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Thu, 19 Sep 2024 00:02:22 +0200 Subject: [PATCH 5/8] [chore]: enable require-error rule from testifylint (#11199) #### Description Testifylint is a linter that provides best practices with the use of testify. This PR enables [require-error](https://github.com/Antonboom/testifylint?tab=readme-ov-file#require-error) rule from [testifylint](https://github.com/Antonboom/testifylint) Signed-off-by: Matthieu MOREL --- .golangci.yml | 3 - Makefile.Common | 2 +- cmd/builder/internal/builder/config_test.go | 10 +-- .../internal/embeded_templates_test.go | 3 +- component/identifiable_test.go | 5 +- config/configauth/configauth_test.go | 13 ++-- config/configgrpc/configgrpc_test.go | 44 +++++------ config/confighttp/confighttp_test.go | 16 ++-- config/confignet/confignet_test.go | 16 ++-- config/configretry/backoff_test.go | 21 ++--- .../configtelemetry/configtelemetry_test.go | 5 +- .../configtls/clientcasfilereloader_test.go | 15 ++-- config/configtls/configtls_test.go | 78 +++++++++---------- confmap/confmap_test.go | 44 +++++------ confmap/confmaptest/configtest_test.go | 4 +- confmap/provider/envprovider/provider_test.go | 18 ++--- .../provider/fileprovider/provider_test.go | 10 +-- .../configurablehttpprovider/provider_test.go | 18 ++--- .../provider/yamlprovider/provider_test.go | 26 +++---- confmap/provider_test.go | 4 +- confmap/resolver_test.go | 16 ++-- connector/connector_test.go | 35 +++++---- connector/connectorprofiles/connector_test.go | 13 ++-- .../connectorprofiles/profiles_router_test.go | 3 +- connector/forwardconnector/forward_test.go | 7 +- connector/logs_router_test.go | 3 +- connector/metrics_router_test.go | 3 +- connector/traces_router_test.go | 3 +- consumer/consumererror/signalerrors_test.go | 6 +- consumer/consumerprofiles/profiles_test.go | 3 +- consumer/logs_test.go | 3 +- consumer/metrics_test.go | 3 +- consumer/traces_test.go | 3 +- exporter/debugexporter/config_test.go | 10 +-- exporter/debugexporter/factory_test.go | 7 +- .../internal/normal/logs_test.go | 3 +- .../internal/normal/metrics_test.go | 3 +- .../internal/normal/traces_test.go | 3 +- exporter/exporter_test.go | 11 +-- exporter/exporterbatcher/config_test.go | 9 ++- exporter/exporterhelper/batch_sender_test.go | 4 +- exporter/exporterhelper/logs_batch_test.go | 5 +- exporter/exporterhelper/logs_test.go | 12 +-- exporter/exporterhelper/metrics_batch_test.go | 5 +- exporter/exporterhelper/metrics_test.go | 10 +-- exporter/exporterhelper/obsexporter_test.go | 18 ++--- exporter/exporterhelper/queue_sender_test.go | 12 +-- .../exporterhelper/timeout_sender_test.go | 5 +- exporter/exporterhelper/traces_batch_test.go | 5 +- exporter/exporterhelper/traces_test.go | 12 +-- exporter/exporterqueue/config_test.go | 7 +- exporter/exportertest/mock_consumer_test.go | 19 ++--- exporter/internal/common/factory_test.go | 7 +- exporter/internal/otlptext/logs_test.go | 2 +- exporter/internal/otlptext/metrics_test.go | 2 +- exporter/internal/otlptext/traces_test.go | 2 +- .../queue/bounded_memory_queue_test.go | 16 ++-- .../internal/queue/persistent_queue_test.go | 46 +++++------ exporter/internal/queue/sized_channel_test.go | 13 ++-- exporter/loggingexporter/config_test.go | 10 +-- exporter/loggingexporter/factory_test.go | 7 +- exporter/otlpexporter/config_test.go | 4 +- exporter/otlpexporter/factory_test.go | 8 +- exporter/otlpexporter/otlp_test.go | 54 ++++++------- exporter/otlphttpexporter/config_test.go | 6 +- exporter/otlphttpexporter/factory_test.go | 6 +- exporter/otlphttpexporter/otlp_test.go | 4 +- .../auth/authtest/mock_clientauth_test.go | 7 +- extension/extension_test.go | 5 +- .../memorylimiterextension/factory_test.go | 4 +- .../memorylimiter_test.go | 3 +- extension/zpagesextension/config_test.go | 4 +- extension/zpagesextension/factory_test.go | 2 +- featuregate/registry_test.go | 26 +++---- filter/config_test.go | 4 +- internal/cgroups/cgroups_test.go | 7 +- internal/cgroups/mountpoint_test.go | 7 +- internal/e2e/opaque_test.go | 3 +- internal/e2e/otlphttp_test.go | 8 +- internal/fanoutconsumer/logs_test.go | 3 +- internal/fanoutconsumer/metrics_test.go | 3 +- internal/fanoutconsumer/profiles_test.go | 3 +- internal/fanoutconsumer/traces_test.go | 3 +- internal/iruntime/mem_info_test.go | 3 +- .../sharedcomponent/sharedcomponent_test.go | 8 +- otelcol/buffered_core_test.go | 2 +- otelcol/collector_test.go | 2 +- otelcol/internal/grpclog/logger_test.go | 5 +- otelcol/otelcoltest/config_test.go | 4 +- otelcol/unmarshaler_test.go | 8 +- pdata/internal/data/profileid_test.go | 27 +++---- pdata/internal/data/spanid_test.go | 25 +++--- pdata/internal/data/traceid_test.go | 27 +++---- pdata/internal/json/attribute_test.go | 15 ++-- pdata/internal/json/enum_test.go | 3 +- pdata/internal/json/number_test.go | 11 +-- pdata/internal/json/resource_test.go | 3 +- pdata/internal/json/scope_test.go | 3 +- pdata/pcommon/map_test.go | 9 ++- pdata/pcommon/value_test.go | 6 +- pdata/plog/json_test.go | 18 ++--- pdata/plog/logs_test.go | 9 ++- pdata/plog/plogotlp/grpc_test.go | 6 +- pdata/plog/plogotlp/request_test.go | 5 +- pdata/plog/plogotlp/response_test.go | 7 +- pdata/pmetric/json_test.go | 33 ++++---- pdata/pmetric/metrics_test.go | 9 ++- pdata/pmetric/pmetricotlp/grpc_test.go | 6 +- pdata/pmetric/pmetricotlp/request_test.go | 5 +- pdata/pmetric/pmetricotlp/response_test.go | 7 +- pdata/pprofile/json_test.go | 33 ++++---- pdata/pprofile/pprofileotlp/grpc_test.go | 6 +- pdata/pprofile/pprofileotlp/request_test.go | 5 +- pdata/pprofile/pprofileotlp/response_test.go | 7 +- pdata/ptrace/json_test.go | 21 ++--- pdata/ptrace/ptraceotlp/grpc_test.go | 6 +- pdata/ptrace/ptraceotlp/request_test.go | 5 +- pdata/ptrace/ptraceotlp/response_test.go | 7 +- pdata/ptrace/traces_test.go | 9 ++- .../batchprocessor/batch_processor_test.go | 38 ++++----- processor/batchprocessor/config_test.go | 4 +- .../memorylimiterprocessor/factory_test.go | 14 ++-- .../memorylimiter_test.go | 6 +- processor/processor_test.go | 11 +-- processor/processorhelper/logs_test.go | 2 +- processor/processorhelper/metrics_test.go | 2 +- processor/processorhelper/obsreport_test.go | 78 +++++++++---------- processor/processorhelper/traces_test.go | 2 +- receiver/otlpreceiver/config_test.go | 18 ++--- receiver/otlpreceiver/factory_test.go | 16 ++-- .../otlpreceiver/internal/logs/otlp_test.go | 6 +- .../internal/metrics/otlp_test.go | 4 +- .../internal/profiles/otlp_test.go | 6 +- .../otlpreceiver/internal/trace/otlp_test.go | 6 +- receiver/otlpreceiver/otlp_test.go | 14 ++-- receiver/receiver_test.go | 11 +-- receiver/receiverhelper/obsreport_test.go | 18 ++--- receiver/receivertest/contract_checker.go | 2 +- receiver/scrapererror/scrapeerror_test.go | 5 +- receiver/scraperhelper/obsreport_test.go | 6 +- .../scraperhelper/scrapercontroller_test.go | 6 +- semconv/semconv_test.go | 9 ++- service/extensions/extensions_test.go | 4 +- service/internal/builders/connector_test.go | 32 ++++---- service/internal/builders/exporter_test.go | 24 +++--- service/internal/builders/extension_test.go | 6 +- service/internal/builders/processor_test.go | 24 +++--- service/internal/builders/receiver_test.go | 24 +++--- .../capabilityconsumer/capabilities_test.go | 8 +- service/internal/graph/graph_test.go | 50 ++++++------ service/internal/resource/config_test.go | 3 +- .../testcomponents/example_connector_test.go | 5 +- .../testcomponents/example_exporter_test.go | 13 ++-- .../testcomponents/example_processor_test.go | 5 +- .../testcomponents/example_receiver_test.go | 5 +- .../testcomponents/example_router_test.go | 29 +++---- service/internal/zpages/templates_test.go | 3 +- service/service_test.go | 4 +- .../internal/otelinit/config_test.go | 2 +- service/telemetry/telemetry_test.go | 7 +- 160 files changed, 933 insertions(+), 859 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 958bd88d595..1af55d5af28 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -122,9 +122,6 @@ linters-settings: - "!**/*_test.go" testifylint: - # TODO: enable all rules - disable: - - require-error enable-all: true linters: diff --git a/Makefile.Common b/Makefile.Common index 39c40702ac8..91cd57b2dc8 100644 --- a/Makefile.Common +++ b/Makefile.Common @@ -38,7 +38,7 @@ SEMCONVGEN := $(TOOLS_BIN_DIR)/semconvgen SEMCONVKIT := $(TOOLS_BIN_DIR)/semconvkit TESTIFYLINT := $(TOOLS_BIN_DIR)/testifylint -TESTIFYLINT_OPT?= --enable-all --disable=require-error +TESTIFYLINT_OPT?= --enable-all .PHONY: install-tools install-tools: $(TOOLS_BIN_NAMES) diff --git a/cmd/builder/internal/builder/config_test.go b/cmd/builder/internal/builder/config_test.go index 60e1b426ee2..856e60061e6 100644 --- a/cmd/builder/internal/builder/config_test.go +++ b/cmd/builder/internal/builder/config_test.go @@ -28,7 +28,7 @@ func TestParseModules(t *testing.T) { // test err := cfg.ParseModules() - assert.NoError(t, err) + require.NoError(t, err) // verify assert.Equal(t, "github.com/org/repo v0.1.2", cfg.Extensions[0].GoMod) @@ -47,7 +47,7 @@ func TestRelativePath(t *testing.T) { // test err := cfg.ParseModules() - assert.NoError(t, err) + require.NoError(t, err) // verify cwd, err := os.Getwd() @@ -72,7 +72,7 @@ func TestModuleFromCore(t *testing.T) { // test err := cfg.ParseModules() - assert.NoError(t, err) + require.NoError(t, err) // verify assert.True(t, strings.HasPrefix(cfg.Extensions[0].Name, "otlpreceiver")) @@ -206,7 +206,7 @@ func TestDebugOptionSetConfig(t *testing.T) { SkipCompilation: true, SkipGetModules: true, } - assert.NoError(t, cfg.Validate()) + require.NoError(t, cfg.Validate()) assert.True(t, cfg.Distribution.DebugCompilation) } @@ -314,7 +314,7 @@ func TestConfmapFactoryVersions(t *testing.T) { func TestAddsDefaultProviders(t *testing.T) { cfg := NewDefaultConfig() cfg.Providers = nil - assert.NoError(t, cfg.ParseModules()) + require.NoError(t, cfg.ParseModules()) assert.Len(t, *cfg.Providers, 5) } diff --git a/cmd/mdatagen/internal/embeded_templates_test.go b/cmd/mdatagen/internal/embeded_templates_test.go index ab4124f3d6b..97bc268edb3 100644 --- a/cmd/mdatagen/internal/embeded_templates_test.go +++ b/cmd/mdatagen/internal/embeded_templates_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestEnsureTemplatesLoaded(t *testing.T) { @@ -38,7 +39,7 @@ func TestEnsureTemplatesLoaded(t *testing.T) { } count = 0 ) - assert.NoError(t, fs.WalkDir(TemplateFS, ".", func(path string, d fs.DirEntry, _ error) error { + require.NoError(t, fs.WalkDir(TemplateFS, ".", func(path string, d fs.DirEntry, _ error) error { if d != nil && d.IsDir() { return nil } diff --git a/component/identifiable_test.go b/component/identifiable_test.go index f6ad1d2768a..883e3c891a8 100644 --- a/component/identifiable_test.go +++ b/component/identifiable_test.go @@ -8,12 +8,13 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMarshalText(t *testing.T) { id := NewIDWithName(MustNewType("test"), "name") got, err := id.MarshalText() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, id.String(), string(got)) } @@ -92,7 +93,7 @@ func TestUnmarshalText(t *testing.T) { return } - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tt.expectedID, id) assert.Equal(t, tt.expectedID.Type(), id.Type()) assert.Equal(t, tt.expectedID.Name(), id.Name()) diff --git a/config/configauth/configauth_test.go b/config/configauth/configauth_test.go index d5504a7707e..89551d952ab 100644 --- a/config/configauth/configauth_test.go +++ b/config/configauth/configauth_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/extension" @@ -53,10 +54,10 @@ func TestGetServer(t *testing.T) { // verify if tt.expected != nil { - assert.ErrorIs(t, err, tt.expected) + require.ErrorIs(t, err, tt.expected) assert.Nil(t, authenticator) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, authenticator) } }) @@ -69,7 +70,7 @@ func TestGetServerFails(t *testing.T) { } authenticator, err := cfg.GetServerAuthenticator(context.Background(), map[component.ID]component.Component{}) - assert.ErrorIs(t, err, errAuthenticatorNotFound) + require.ErrorIs(t, err, errAuthenticatorNotFound) assert.Nil(t, authenticator) } @@ -104,10 +105,10 @@ func TestGetClient(t *testing.T) { // verify if tt.expected != nil { - assert.ErrorIs(t, err, tt.expected) + require.ErrorIs(t, err, tt.expected) assert.Nil(t, authenticator) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, authenticator) } }) @@ -119,6 +120,6 @@ func TestGetClientFails(t *testing.T) { AuthenticatorID: component.MustNewID("does_not_exist"), } authenticator, err := cfg.GetClientAuthenticator(context.Background(), map[component.ID]component.Component{}) - assert.ErrorIs(t, err, errAuthenticatorNotFound) + require.ErrorIs(t, err, errAuthenticatorNotFound) assert.Nil(t, authenticator) } diff --git a/config/configgrpc/configgrpc_test.go b/config/configgrpc/configgrpc_test.go index 588123bb974..d2a6b1c15e0 100644 --- a/config/configgrpc/configgrpc_test.go +++ b/config/configgrpc/configgrpc_test.go @@ -127,7 +127,7 @@ func TestDefaultGrpcClientSettings(t *testing.T) { }, } opts, err := gcs.toDialOptions(context.Background(), componenttest.NewNopHost(), tt.TelemetrySettings()) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, opts, 2) } @@ -232,7 +232,7 @@ func TestAllGrpcClientSettings(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { opts, err := test.settings.toDialOptions(context.Background(), test.host, tt.TelemetrySettings()) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, opts, 9) }) } @@ -245,7 +245,7 @@ func TestDefaultGrpcServerSettings(t *testing.T) { }, } opts, err := gss.toServerOption(componenttest.NewNopHost(), componenttest.NewNopTelemetrySettings()) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, opts, 3) } @@ -295,7 +295,7 @@ func TestGrpcServerValidate(t *testing.T) { for _, tt := range tests { t.Run(tt.err, func(t *testing.T) { err := tt.gss.Validate() - assert.Error(t, err) + require.Error(t, err) assert.Regexp(t, tt.err, err) }) } @@ -330,7 +330,7 @@ func TestAllGrpcServerSettingsExceptAuth(t *testing.T) { }, } opts, err := gss.toServerOption(componenttest.NewNopHost(), componenttest.NewNopTelemetrySettings()) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, opts, 10) } @@ -349,7 +349,7 @@ func TestGrpcServerAuthSettings(t *testing.T) { }, } srv, err := gss.ToServer(context.Background(), host, componenttest.NewNopTelemetrySettings()) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, srv) } @@ -470,7 +470,7 @@ func TestGRPCClientSettingsError(t *testing.T) { for _, test := range tests { t.Run(test.err, func(t *testing.T) { _, err := test.settings.ToClientConn(context.Background(), test.host, tt.TelemetrySettings()) - assert.Error(t, err) + require.Error(t, err) assert.Regexp(t, test.err, err) }) } @@ -489,7 +489,7 @@ func TestUseSecure(t *testing.T) { Keepalive: nil, } dialOpts, err := gcs.toDialOptions(context.Background(), componenttest.NewNopHost(), tt.TelemetrySettings()) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, dialOpts, 2) } @@ -735,9 +735,9 @@ func TestHttpReception(t *testing.T) { TLSSetting: test.tlsServerCreds, } ln, err := gss.NetAddr.Listen(context.Background()) - assert.NoError(t, err) + require.NoError(t, err) s, err := gss.ToServer(context.Background(), componenttest.NewNopHost(), componenttest.NewNopTelemetrySettings()) - assert.NoError(t, err) + require.NoError(t, err) ptraceotlp.RegisterGRPCServer(s, &grpcTraceServer{}) go func() { @@ -749,15 +749,15 @@ func TestHttpReception(t *testing.T) { TLSSetting: *test.tlsClientCreds, } grpcClientConn, errClient := gcs.ToClientConn(context.Background(), componenttest.NewNopHost(), tt.TelemetrySettings()) - assert.NoError(t, errClient) + require.NoError(t, errClient) defer func() { assert.NoError(t, grpcClientConn.Close()) }() c := ptraceotlp.NewGRPCClient(grpcClientConn) ctx, cancelFunc := context.WithTimeout(context.Background(), 2*time.Second) resp, errResp := c.Export(ctx, ptraceotlp.NewExportRequest(), grpc.WaitForReady(true)) if test.hasError { - assert.Error(t, errResp) + require.Error(t, errResp) } else { - assert.NoError(t, errResp) + require.NoError(t, errResp) assert.NotNil(t, resp) } cancelFunc() @@ -782,9 +782,9 @@ func TestReceiveOnUnixDomainSocket(t *testing.T) { }, } ln, err := gss.NetAddr.Listen(context.Background()) - assert.NoError(t, err) + require.NoError(t, err) srv, err := gss.ToServer(context.Background(), componenttest.NewNopHost(), componenttest.NewNopTelemetrySettings()) - assert.NoError(t, err) + require.NoError(t, err) ptraceotlp.RegisterGRPCServer(srv, &grpcTraceServer{}) go func() { @@ -798,12 +798,12 @@ func TestReceiveOnUnixDomainSocket(t *testing.T) { }, } grpcClientConn, errClient := gcs.ToClientConn(context.Background(), componenttest.NewNopHost(), tt.TelemetrySettings()) - assert.NoError(t, errClient) + require.NoError(t, errClient) defer func() { assert.NoError(t, grpcClientConn.Close()) }() c := ptraceotlp.NewGRPCClient(grpcClientConn) ctx, cancelFunc := context.WithTimeout(context.Background(), 2*time.Second) resp, errResp := c.Export(ctx, ptraceotlp.NewExportRequest(), grpc.WaitForReady(true)) - assert.NoError(t, errResp) + require.NoError(t, errResp) assert.NotNil(t, resp) cancelFunc() srv.Stop() @@ -933,7 +933,7 @@ func TestStreamInterceptorEnhancesClient(t *testing.T) { err := enhanceStreamWithClientInformation(false)(nil, stream, nil, handler) // verify - assert.NoError(t, err) + require.NoError(t, err) cl := client.FromContext(outContext) assert.Equal(t, "1.1.1.1", cl.Addr.String()) @@ -1052,7 +1052,7 @@ func TestDefaultUnaryInterceptorAuthSucceeded(t *testing.T) { // verify assert.Nil(t, res) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, authCalled) assert.True(t, handlerCalled) } @@ -1076,7 +1076,7 @@ func TestDefaultUnaryInterceptorAuthFailure(t *testing.T) { // verify assert.Nil(t, res) - assert.ErrorContains(t, err, expectedErr.Error()) + require.ErrorContains(t, err, expectedErr.Error()) assert.Equal(t, codes.Unauthenticated, status.Code(err)) assert.True(t, authCalled) } @@ -1127,7 +1127,7 @@ func TestDefaultStreamInterceptorAuthSucceeded(t *testing.T) { err := authStreamServerInterceptor(nil, streamServer, &grpc.StreamServerInfo{}, handler, auth.NewServer(auth.WithServerAuthenticate(authFunc))) // verify - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, authCalled) assert.True(t, handlerCalled) } @@ -1153,7 +1153,7 @@ func TestDefaultStreamInterceptorAuthFailure(t *testing.T) { err := authStreamServerInterceptor(nil, streamServer, &grpc.StreamServerInfo{}, handler, auth.NewServer(auth.WithServerAuthenticate(authFunc))) // verify - assert.ErrorContains(t, err, expectedErr.Error()) // unfortunately, grpc errors don't wrap the original ones + require.ErrorContains(t, err, expectedErr.Error()) // unfortunately, grpc errors don't wrap the original ones assert.Equal(t, codes.Unauthenticated, status.Code(err)) assert.True(t, authCalled) } diff --git a/config/confighttp/confighttp_test.go b/config/confighttp/confighttp_test.go index c1af07c0f62..29ca8e6ef04 100644 --- a/config/confighttp/confighttp_test.go +++ b/config/confighttp/confighttp_test.go @@ -165,7 +165,7 @@ func TestAllHTTPClientSettings(t *testing.T) { assert.Error(t, err) return } - assert.NoError(t, err) + require.NoError(t, err) switch transport := client.Transport.(type) { case *http.Transport: assert.EqualValues(t, 1024, transport.ReadBufferSize) @@ -213,7 +213,7 @@ func TestPartialHTTPClientSettings(t *testing.T) { tel := componenttest.NewNopTelemetrySettings() tel.TracerProvider = nil client, err := tt.settings.ToClient(context.Background(), host, tel) - assert.NoError(t, err) + require.NoError(t, err) transport := client.Transport.(*http.Transport) assert.EqualValues(t, 1024, transport.ReadBufferSize) assert.EqualValues(t, 512, transport.WriteBufferSize) @@ -446,7 +446,7 @@ func TestHTTPClientSettingWithAuthConfig(t *testing.T) { assert.Error(t, err) return } - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, client) transport := client.Transport @@ -734,11 +734,11 @@ func TestHttpReception(t *testing.T) { resp, errResp := client.Get(hcs.Endpoint) if tt.hasError { - assert.Error(t, errResp) + require.Error(t, errResp) } else { - assert.NoError(t, errResp) + require.NoError(t, errResp) body, errRead := io.ReadAll(resp.Body) - assert.NoError(t, errRead) + require.NoError(t, errRead) assert.Equal(t, "tt", string(body)) assert.Equal(t, expectedProto, resp.Proto) } @@ -1065,7 +1065,7 @@ func TestHttpClientHeaders(t *testing.T) { } client, _ := setting.ToClient(context.Background(), componenttest.NewNopHost(), componenttest.NewNopTelemetrySettings()) req, err := http.NewRequest(http.MethodGet, setting.Endpoint, nil) - assert.NoError(t, err) + require.NoError(t, err) _, err = client.Do(req) assert.NoError(t, err) }) @@ -1101,7 +1101,7 @@ func TestHttpClientHostHeader(t *testing.T) { } client, _ := setting.ToClient(context.Background(), componenttest.NewNopHost(), componenttest.NewNopTelemetrySettings()) req, err := http.NewRequest(http.MethodGet, setting.Endpoint, nil) - assert.NoError(t, err) + require.NoError(t, err) _, err = client.Do(req) assert.NoError(t, err) }) diff --git a/config/confignet/confignet_test.go b/config/confignet/confignet_test.go index 9375561dc39..84ea79373d8 100644 --- a/config/confignet/confignet_test.go +++ b/config/confignet/confignet_test.go @@ -41,7 +41,7 @@ func TestAddrConfigTimeout(t *testing.T) { }, } _, err := nac.Dial(context.Background()) - assert.Error(t, err) + require.Error(t, err) var netErr net.Error if errors.As(err, &netErr) { assert.True(t, netErr.Timeout()) @@ -58,7 +58,7 @@ func TestTCPAddrConfigTimeout(t *testing.T) { }, } _, err := nac.Dial(context.Background()) - assert.Error(t, err) + require.Error(t, err) var netErr net.Error if errors.As(err, &netErr) { assert.True(t, netErr.Timeout()) @@ -73,7 +73,7 @@ func TestAddrConfig(t *testing.T) { Transport: TransportTypeTCP, } ln, err := nas.Listen(context.Background()) - assert.NoError(t, err) + require.NoError(t, err) done := make(chan bool, 1) go func() { @@ -94,7 +94,7 @@ func TestAddrConfig(t *testing.T) { } var conn net.Conn conn, err = nac.Dial(context.Background()) - assert.NoError(t, err) + require.NoError(t, err) _, err = conn.Write([]byte("test")) assert.NoError(t, err) assert.NoError(t, conn.Close()) @@ -106,12 +106,12 @@ func Test_NetAddr_Validate(t *testing.T) { na := &AddrConfig{ Transport: TransportTypeTCP, } - assert.NoError(t, na.Validate()) + require.NoError(t, na.Validate()) na = &AddrConfig{ Transport: transportTypeEmpty, } - assert.Error(t, na.Validate()) + require.Error(t, na.Validate()) na = &AddrConfig{ Transport: "random string", @@ -124,7 +124,7 @@ func TestTCPAddrConfig(t *testing.T) { Endpoint: "localhost:0", } ln, err := nas.Listen(context.Background()) - assert.NoError(t, err) + require.NoError(t, err) done := make(chan bool, 1) go func() { @@ -144,7 +144,7 @@ func TestTCPAddrConfig(t *testing.T) { } var conn net.Conn conn, err = nac.Dial(context.Background()) - assert.NoError(t, err) + require.NoError(t, err) _, err = conn.Write([]byte("test")) assert.NoError(t, err) assert.NoError(t, conn.Close()) diff --git a/config/configretry/backoff_test.go b/config/configretry/backoff_test.go index a0adb3ceaf3..dcf449d0eb8 100644 --- a/config/configretry/backoff_test.go +++ b/config/configretry/backoff_test.go @@ -8,11 +8,12 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestNewDefaultBackOffSettings(t *testing.T) { cfg := NewDefaultBackOffConfig() - assert.NoError(t, cfg.Validate()) + require.NoError(t, cfg.Validate()) assert.Equal(t, BackOffConfig{ Enabled: true, @@ -26,23 +27,23 @@ func TestNewDefaultBackOffSettings(t *testing.T) { func TestInvalidInitialInterval(t *testing.T) { cfg := NewDefaultBackOffConfig() - assert.NoError(t, cfg.Validate()) + require.NoError(t, cfg.Validate()) cfg.InitialInterval = -1 assert.Error(t, cfg.Validate()) } func TestInvalidRandomizationFactor(t *testing.T) { cfg := NewDefaultBackOffConfig() - assert.NoError(t, cfg.Validate()) + require.NoError(t, cfg.Validate()) cfg.RandomizationFactor = -1 - assert.Error(t, cfg.Validate()) + require.Error(t, cfg.Validate()) cfg.RandomizationFactor = 2 assert.Error(t, cfg.Validate()) } func TestInvalidMultiplier(t *testing.T) { cfg := NewDefaultBackOffConfig() - assert.NoError(t, cfg.Validate()) + require.NoError(t, cfg.Validate()) cfg.Multiplier = -1 assert.Error(t, cfg.Validate()) } @@ -56,22 +57,22 @@ func TestZeroMultiplierIsValid(t *testing.T) { func TestInvalidMaxInterval(t *testing.T) { cfg := NewDefaultBackOffConfig() - assert.NoError(t, cfg.Validate()) + require.NoError(t, cfg.Validate()) cfg.MaxInterval = -1 assert.Error(t, cfg.Validate()) } func TestInvalidMaxElapsedTime(t *testing.T) { cfg := NewDefaultBackOffConfig() - assert.NoError(t, cfg.Validate()) + require.NoError(t, cfg.Validate()) cfg.MaxElapsedTime = -1 - assert.Error(t, cfg.Validate()) + require.Error(t, cfg.Validate()) cfg.MaxElapsedTime = 60 // MaxElapsedTime is 60, InitialInterval is 5s, so it should be invalid - assert.Error(t, cfg.Validate()) + require.Error(t, cfg.Validate()) cfg.InitialInterval = 0 // MaxElapsedTime is 60, MaxInterval is 30s, so it should be invalid - assert.Error(t, cfg.Validate()) + require.Error(t, cfg.Validate()) cfg.MaxInterval = 0 assert.NoError(t, cfg.Validate()) cfg.InitialInterval = 50 diff --git a/config/configtelemetry/configtelemetry_test.go b/config/configtelemetry/configtelemetry_test.go index d9fc2550c2d..1832fc0e175 100644 --- a/config/configtelemetry/configtelemetry_test.go +++ b/config/configtelemetry/configtelemetry_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var _ encoding.TextMarshaler = (*Level)(nil) @@ -50,7 +51,7 @@ func TestUnmarshalText(t *testing.T) { if test.err { assert.Error(t, err) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, test.level, lvl) } }) @@ -94,7 +95,7 @@ func TestLevelStringMarshal(t *testing.T) { t.Run(tt.str, func(t *testing.T) { assert.Equal(t, tt.str, tt.level.String()) got, err := tt.level.MarshalText() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tt.str, string(got)) }) } diff --git a/config/configtls/clientcasfilereloader_test.go b/config/configtls/clientcasfilereloader_test.go index 7eb77da8a2c..074e0e72022 100644 --- a/config/configtls/clientcasfilereloader_test.go +++ b/config/configtls/clientcasfilereloader_test.go @@ -13,6 +13,7 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCannotShutdownIfNotWatching(t *testing.T) { @@ -25,10 +26,10 @@ func TestCannotStartIfAlreadyWatching(t *testing.T) { reloader, _, _ := createReloader(t) err := reloader.startWatching() - assert.NoError(t, err) + require.NoError(t, err) err = reloader.startWatching() - assert.Error(t, err) + require.Error(t, err) err = reloader.shutdown() assert.NoError(t, err) @@ -38,12 +39,12 @@ func TestClosingWatcherDoesntBreakReloader(t *testing.T) { reloader, loader, _ := createReloader(t) err := reloader.startWatching() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 1, loader.reloadNumber()) err = reloader.watcher.Close() - assert.NoError(t, err) + require.NoError(t, err) err = reloader.shutdown() assert.NoError(t, err) @@ -53,14 +54,14 @@ func TestErrorRecordedIfFileDeleted(t *testing.T) { reloader, loader, filePath := createReloader(t) err := reloader.startWatching() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 1, loader.reloadNumber()) loader.returnErrorOnSubsequentCalls("test error on reload") err = os.WriteFile(filePath, []byte("some_data"), 0600) - assert.NoError(t, err) + require.NoError(t, err) assert.Eventually(t, func() bool { return loader.reloadNumber() > 1 && reloader.getLastError() != nil @@ -82,7 +83,7 @@ func createReloader(t *testing.T) (*clientCAsFileReloader, *testLoader, string) func createTempFile(t *testing.T) string { tmpCa, err := os.CreateTemp("", "clientCAs.crt") - assert.NoError(t, err) + require.NoError(t, err) tmpCaPath, err := filepath.Abs(tmpCa.Name()) assert.NoError(t, err) assert.NoError(t, tmpCa.Close()) diff --git a/config/configtls/configtls_test.go b/config/configtls/configtls_test.go index cbcd7433db4..1bd871b3e1b 100644 --- a/config/configtls/configtls_test.go +++ b/config/configtls/configtls_test.go @@ -286,19 +286,19 @@ func TestLoadTLSClientConfig(t *testing.T) { Insecure: true, } tlsCfg, err := tlsSetting.LoadTLSConfig(context.Background()) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, tlsCfg) tlsSetting = ClientConfig{} tlsCfg, err = tlsSetting.LoadTLSConfig(context.Background()) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, tlsCfg) tlsSetting = ClientConfig{ InsecureSkipVerify: true, } tlsCfg, err = tlsSetting.LoadTLSConfig(context.Background()) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, tlsCfg) assert.True(t, tlsCfg.InsecureSkipVerify) } @@ -311,7 +311,7 @@ func TestLoadTLSServerConfigError(t *testing.T) { }, } _, err := tlsSetting.LoadTLSConfig(context.Background()) - assert.Error(t, err) + require.Error(t, err) tlsSetting = ServerConfig{ ClientCAFile: "doesnt/exist", @@ -323,7 +323,7 @@ func TestLoadTLSServerConfigError(t *testing.T) { func TestLoadTLSServerConfig(t *testing.T) { tlsSetting := ServerConfig{} tlsCfg, err := tlsSetting.LoadTLSConfig(context.Background()) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, tlsCfg) } @@ -339,11 +339,11 @@ func TestLoadTLSServerConfigReload(t *testing.T) { } tlsCfg, err := tlsSetting.LoadTLSConfig(context.Background()) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, tlsCfg) firstClient, err := tlsCfg.GetConfigForClient(nil) - assert.NoError(t, err) + require.NoError(t, err) overwriteClientCA(t, tmpCaPath, "ca-2.crt") @@ -353,7 +353,7 @@ func TestLoadTLSServerConfigReload(t *testing.T) { }, 5*time.Second, 10*time.Millisecond) secondClient, err := tlsCfg.GetConfigForClient(nil) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEqual(t, firstClient.ClientCAs, secondClient.ClientCAs) } @@ -370,11 +370,11 @@ func TestLoadTLSServerConfigFailingReload(t *testing.T) { } tlsCfg, err := tlsSetting.LoadTLSConfig(context.Background()) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, tlsCfg) firstClient, err := tlsCfg.GetConfigForClient(nil) - assert.NoError(t, err) + require.NoError(t, err) overwriteClientCA(t, tmpCaPath, "testCA-bad.txt") @@ -384,7 +384,7 @@ func TestLoadTLSServerConfigFailingReload(t *testing.T) { }, 5*time.Second, 10*time.Millisecond) secondClient, err := tlsCfg.GetConfigForClient(nil) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, firstClient.ClientCAs, secondClient.ClientCAs) } @@ -401,7 +401,7 @@ func TestLoadTLSServerConfigFailingInitialLoad(t *testing.T) { } tlsCfg, err := tlsSetting.LoadTLSConfig(context.Background()) - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, tlsCfg) } @@ -415,7 +415,7 @@ func TestLoadTLSServerConfigWrongPath(t *testing.T) { } tlsCfg, err := tlsSetting.LoadTLSConfig(context.Background()) - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, tlsCfg) } @@ -431,28 +431,28 @@ func TestLoadTLSServerConfigFailing(t *testing.T) { } tlsCfg, err := tlsSetting.LoadTLSConfig(context.Background()) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, tlsCfg) firstClient, err := tlsCfg.GetConfigForClient(nil) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, firstClient) err = os.Remove(tmpCaPath) - assert.NoError(t, err) + require.NoError(t, err) firstClient, err = tlsCfg.GetConfigForClient(nil) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, firstClient) } func overwriteClientCA(t *testing.T, targetFilePath string, testdataFileName string) { targetFile, err := os.OpenFile(filepath.Clean(targetFilePath), os.O_RDWR, 0600) - assert.NoError(t, err) + require.NoError(t, err) testdataFilePath := filepath.Join("testdata", testdataFileName) testdataFile, err := os.OpenFile(filepath.Clean(testdataFilePath), os.O_RDONLY, 0200) - assert.NoError(t, err) + require.NoError(t, err) _, err = io.Copy(targetFile, testdataFile) assert.NoError(t, err) @@ -463,7 +463,7 @@ func overwriteClientCA(t *testing.T, targetFilePath string, testdataFileName str func createTempClientCaFile(t *testing.T) string { tmpCa, err := os.CreateTemp("", "ca-tmp.crt") - assert.NoError(t, err) + require.NoError(t, err) tmpCaPath, err := filepath.Abs(tmpCa.Name()) assert.NoError(t, err) assert.NoError(t, tmpCa.Close()) @@ -476,13 +476,13 @@ func TestEagerlyLoadCertificate(t *testing.T) { KeyFile: filepath.Join("testdata", "client-1.key"), } cfg, err := options.loadTLSConfig() - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, cfg) cert, err := cfg.GetCertificate(&tls.ClientHelloInfo{}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, cert) pCert, err := x509.ParseCertificate(cert.Certificate[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, pCert) assert.ElementsMatch(t, []string{"example1"}, pCert.DNSNames) } @@ -540,20 +540,20 @@ func TestCertificateReload(t *testing.T) { t.Run(test.name, func(t *testing.T) { // Copy certs into a temp dir so we can safely modify them certFile, err := os.CreateTemp("", "cert") - assert.NoError(t, err) + require.NoError(t, err) defer os.Remove(certFile.Name()) keyFile, err := os.CreateTemp("", "key") - assert.NoError(t, err) + require.NoError(t, err) defer os.Remove(keyFile.Name()) fdc, err := os.Open(filepath.Join("testdata", "client-1.crt")) - assert.NoError(t, err) + require.NoError(t, err) _, err = io.Copy(certFile, fdc) - assert.NoError(t, err) + require.NoError(t, err) fdk, err := os.Open(filepath.Join("testdata", "client-1.key")) - assert.NoError(t, err) + require.NoError(t, err) _, err = io.Copy(keyFile, fdk) assert.NoError(t, err) assert.NoError(t, fdk.Close()) @@ -564,15 +564,15 @@ func TestCertificateReload(t *testing.T) { ReloadInterval: test.reloadInterval, } cfg, err := options.loadTLSConfig() - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, cfg) // Asssert that we loaded the original certificate cert, err := cfg.GetCertificate(&tls.ClientHelloInfo{}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, cert) pCert, err := x509.ParseCertificate(cert.Certificate[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, pCert) assert.Equal(t, test.dns1, pCert.DNSNames[0]) @@ -580,18 +580,18 @@ func TestCertificateReload(t *testing.T) { assert.NoError(t, certFile.Truncate(0)) assert.NoError(t, keyFile.Truncate(0)) _, err = certFile.Seek(0, 0) - assert.NoError(t, err) + require.NoError(t, err) _, err = keyFile.Seek(0, 0) - assert.NoError(t, err) + require.NoError(t, err) fdc2, err := os.Open(filepath.Join("testdata", test.cert2)) - assert.NoError(t, err) + require.NoError(t, err) _, err = io.Copy(certFile, fdc2) assert.NoError(t, err) assert.NoError(t, fdc2.Close()) fdk2, err := os.Open(filepath.Join("testdata", test.key2)) - assert.NoError(t, err) + require.NoError(t, err) _, err = io.Copy(keyFile, fdk2) assert.NoError(t, err) assert.NoError(t, fdk2.Close()) @@ -602,10 +602,10 @@ func TestCertificateReload(t *testing.T) { // Assert that we loaded the new certificate cert, err = cfg.GetCertificate(&tls.ClientHelloInfo{}) if test.errText == "" { - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, cert) pCert, err = x509.ParseCertificate(cert.Certificate[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, pCert) assert.Equal(t, test.dns2, pCert.DNSNames[0]) } else { @@ -729,7 +729,7 @@ invalid TLS cipher suite: "BAR"`, if test.wantErr != "" { assert.EqualError(t, err, test.wantErr) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, test.result, config.CipherSuites) } }) @@ -798,7 +798,7 @@ func TestSystemCertPool(t *testing.T) { } c, err := serverConfig.LoadTLSConfig(context.Background()) if test.wantErr != nil { - assert.ErrorContains(t, err, test.wantErr.Error()) + require.ErrorContains(t, err, test.wantErr.Error()) } else { assert.NotNil(t, c.RootCAs) } diff --git a/confmap/confmap_test.go b/confmap/confmap_test.go index 24682c20347..355dea2b998 100644 --- a/confmap/confmap_test.go +++ b/confmap/confmap_test.go @@ -109,7 +109,7 @@ func TestExpandNilStructPointersHookFunc(t *testing.T) { conf := NewFromStringMap(stringMap) cfg := &TestConfig{} assert.Nil(t, cfg.Struct) - assert.NoError(t, conf.Unmarshal(cfg)) + require.NoError(t, conf.Unmarshal(cfg)) assert.Nil(t, cfg.Boolean) // assert.False(t, *cfg.Boolean) assert.Nil(t, cfg.Struct) @@ -134,7 +134,7 @@ func TestExpandNilStructPointersHookFuncDefaultNotNilConfigNil(t *testing.T) { Struct: s1, MapStruct: map[string]*Struct{"struct": s2}, } - assert.NoError(t, conf.Unmarshal(cfg)) + require.NoError(t, conf.Unmarshal(cfg)) assert.NotNil(t, cfg.Boolean) assert.True(t, *cfg.Boolean) assert.NotNil(t, cfg.Struct) @@ -149,7 +149,7 @@ func TestUnmarshalWithIgnoreUnused(t *testing.T) { "string": "this is a string", } conf := NewFromStringMap(stringMap) - assert.Error(t, conf.Unmarshal(&TestIDConfig{})) + require.Error(t, conf.Unmarshal(&TestIDConfig{})) assert.NoError(t, conf.Unmarshal(&TestIDConfig{}, WithIgnoreUnused())) } @@ -208,7 +208,7 @@ func TestMapKeyStringToMapKeyTextUnmarshalerHookFunc(t *testing.T) { conf := NewFromStringMap(stringMap) cfg := &TestIDConfig{} - assert.NoError(t, conf.Unmarshal(cfg)) + require.NoError(t, conf.Unmarshal(cfg)) assert.True(t, cfg.Boolean) assert.Equal(t, map[TestID]string{"string": "this is a string"}, cfg.Map) } @@ -243,7 +243,7 @@ func TestUintUnmarshalerSuccess(t *testing.T) { cfg := &UintConfig{} err := conf.Unmarshal(cfg) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, cfg.UintTest, uint32(tt.testValue)) }) } @@ -264,7 +264,7 @@ func TestUint64Unmarshaler(t *testing.T) { cfg := &Uint64Config{} err := conf.Unmarshal(cfg) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, cfg.UintTest, testValue) } @@ -277,7 +277,7 @@ func TestUintUnmarshalerFailure(t *testing.T) { cfg := &UintConfig{} err := conf.Unmarshal(cfg) - assert.Error(t, err) + require.Error(t, err) assert.Contains(t, err.Error(), fmt.Sprintf("decoding failed due to the following error(s):\n\ncannot parse 'uint_test', %d overflows uint", testValue)) } @@ -316,7 +316,7 @@ func TestMarshal(t *testing.T) { "string": "this is a string", }, } - assert.NoError(t, conf.Marshal(cfg)) + require.NoError(t, conf.Marshal(cfg)) assert.Equal(t, true, conf.Get("bool")) assert.Equal(t, map[string]any{"string_": "this is a string"}, conf.Get("map")) } @@ -345,7 +345,7 @@ func TestMarshaler(t *testing.T) { Name: "StructName", }, } - assert.NoError(t, conf.Marshal(cfg)) + require.NoError(t, conf.Marshal(cfg)) assert.Equal(t, "field", conf.Get("additional")) conf = New() @@ -355,9 +355,9 @@ func TestMarshaler(t *testing.T) { nmCfg := &NestedMarshaler{ TestConfig: cfg, } - assert.NoError(t, conf.Marshal(nmCfg)) + require.NoError(t, conf.Marshal(nmCfg)) sub, err := conf.Sub("testconfig") - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, sub.IsSet("additional")) assert.Equal(t, "field", sub.Get("additional")) varBool := false @@ -483,7 +483,7 @@ func TestUnmarshaler(t *testing.T) { }) tc := &testConfig{} - assert.NoError(t, cfgMap.Unmarshal(tc)) + require.NoError(t, cfgMap.Unmarshal(tc)) assert.Equal(t, "make sure this is only called directly", tc.Another) assert.Equal(t, "make sure this is called", tc.Next.String) assert.Equal(t, "make sure this is also called", tc.EmbeddedConfig.Some) @@ -501,7 +501,7 @@ func TestEmbeddedUnmarshaler(t *testing.T) { }) tc := &testConfigWithoutUnmarshaler{} - assert.NoError(t, cfgMap.Unmarshal(tc)) + require.NoError(t, cfgMap.Unmarshal(tc)) assert.Equal(t, "make sure this", tc.Another) assert.Equal(t, "make sure this is called", tc.Next.String) assert.Equal(t, "make sure this is also called", tc.EmbeddedConfig.Some) @@ -545,7 +545,7 @@ func TestUnmarshalerKeepAlreadyInitialized(t *testing.T) { tc := &testConfig{Next: &nextConfig{ private: "keep already configured members", }} - assert.NoError(t, cfgMap.Unmarshal(tc)) + require.NoError(t, cfgMap.Unmarshal(tc)) assert.Equal(t, "make sure this is only called directly", tc.Another) assert.Equal(t, "make sure this is called", tc.Next.String) assert.Equal(t, "keep already configured members", tc.Next.private) @@ -562,7 +562,7 @@ func TestDirectUnmarshaler(t *testing.T) { tc := &testConfig{Next: &nextConfig{ private: "keep already configured members", }} - assert.NoError(t, tc.Unmarshal(cfgMap)) + require.NoError(t, tc.Unmarshal(cfgMap)) assert.Equal(t, "make sure this is only called directly is only called directly", tc.Another) assert.Equal(t, "make sure this is called", tc.Next.String) assert.Equal(t, "keep already configured members", tc.Next.private) @@ -588,7 +588,7 @@ func TestUnmarshalerErr(t *testing.T) { }) tc := &testErrConfig{} - assert.EqualError(t, cfgMap.Unmarshal(tc), "decoding failed due to the following error(s):\n\nerror decoding 'err': never works") + require.EqualError(t, cfgMap.Unmarshal(tc), "decoding failed due to the following error(s):\n\nerror decoding 'err': never works") assert.Empty(t, tc.Err.Foo) } @@ -736,7 +736,7 @@ func TestNestedUnmarshalerImplementations(t *testing.T) { // Use a wrapper struct until we deprecate component.UnmarshalConfig w := &Wrapper{} - assert.NoError(t, conf.Unmarshal(w)) + require.NoError(t, conf.Unmarshal(w)) a := w.A assert.Equal(t, []string{"conf.Unmarshal", "A.Unmarshal"}, a.Modifiers) @@ -754,14 +754,14 @@ func TestUnmarshalDouble(t *testing.T) { Str string `mapstructure:"str"` } s := &Struct{} - assert.NoError(t, conf.Unmarshal(s)) + require.NoError(t, conf.Unmarshal(s)) assert.Equal(t, "test", s.Str) type Struct2 struct { Str string `mapstructure:"str"` } s2 := &Struct2{} - assert.NoError(t, conf.Unmarshal(s2)) + require.NoError(t, conf.Unmarshal(s2)) assert.Equal(t, "test", s2.Str) } @@ -859,14 +859,14 @@ func TestExpandedValue(t *testing.T) { } cfgStr := ConfigStr{} - assert.NoError(t, cm.Unmarshal(&cfgStr)) + require.NoError(t, cm.Unmarshal(&cfgStr)) assert.Equal(t, "original", cfgStr.Key) type ConfigInt struct { Key int `mapstructure:"key"` } cfgInt := ConfigInt{} - assert.NoError(t, cm.Unmarshal(&cfgInt)) + require.NoError(t, cm.Unmarshal(&cfgInt)) assert.Equal(t, 0xdeadbeef, cfgInt.Key) type ConfigBool struct { @@ -891,7 +891,7 @@ func TestSubExpandedValue(t *testing.T) { assert.Equal(t, map[string]any{"subsubkey": "value"}, cm.Get("key::subkey")) sub, err := cm.Sub("key::subkey") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, map[string]any{"subsubkey": "value"}, sub.ToStringMap()) // This should return value, but currently `Get` does not support keys within expanded values. diff --git a/confmap/confmaptest/configtest_test.go b/confmap/confmaptest/configtest_test.go index 34d97d6b009..cf7717071cf 100644 --- a/confmap/confmaptest/configtest_test.go +++ b/confmap/confmaptest/configtest_test.go @@ -42,9 +42,9 @@ func TestValidateProviderScheme(t *testing.T) { assert.NoError(t, ValidateProviderScheme(&schemeProvider{scheme: "s3"})) assert.NoError(t, ValidateProviderScheme(&schemeProvider{scheme: "a.l-l+"})) // Too short. - assert.Error(t, ValidateProviderScheme(&schemeProvider{scheme: "a"})) + require.Error(t, ValidateProviderScheme(&schemeProvider{scheme: "a"})) // Invalid first character. - assert.Error(t, ValidateProviderScheme(&schemeProvider{scheme: "3s"})) + require.Error(t, ValidateProviderScheme(&schemeProvider{scheme: "3s"})) // Invalid underscore character. assert.Error(t, ValidateProviderScheme(&schemeProvider{scheme: "all_"})) } diff --git a/confmap/provider/envprovider/provider_test.go b/confmap/provider/envprovider/provider_test.go index 75564430cca..70b68842ffe 100644 --- a/confmap/provider/envprovider/provider_test.go +++ b/confmap/provider/envprovider/provider_test.go @@ -42,7 +42,7 @@ func TestEmptyName(t *testing.T) { func TestUnsupportedScheme(t *testing.T) { env := createProvider() _, err := env.Retrieve(context.Background(), "https://", nil) - assert.Error(t, err) + require.Error(t, err) assert.NoError(t, env.Shutdown(context.Background())) } @@ -66,7 +66,7 @@ func TestEnv(t *testing.T) { ret, err := env.Retrieve(context.Background(), envSchemePrefix+envName, nil) require.NoError(t, err) retMap, err := ret.AsConf() - assert.NoError(t, err) + require.NoError(t, err) expectedMap := confmap.NewFromStringMap(map[string]any{ "processors::batch": nil, "exporters::otlp::endpoint": "localhost:4317", @@ -86,14 +86,14 @@ func TestEnvWithLogger(t *testing.T) { ret, err := env.Retrieve(context.Background(), envSchemePrefix+envName, nil) require.NoError(t, err) retMap, err := ret.AsConf() - assert.NoError(t, err) + require.NoError(t, err) expectedMap := confmap.NewFromStringMap(map[string]any{ "processors::batch": nil, "exporters::otlp::endpoint": "localhost:4317", }) assert.Equal(t, expectedMap.ToStringMap(), retMap.ToStringMap()) - assert.NoError(t, env.Shutdown(context.Background())) + require.NoError(t, env.Shutdown(context.Background())) assert.Equal(t, 0, ol.Len()) } @@ -106,11 +106,11 @@ func TestUnsetEnvWithLoggerWarn(t *testing.T) { ret, err := env.Retrieve(context.Background(), envSchemePrefix+envName, nil) require.NoError(t, err) retMap, err := ret.AsConf() - assert.NoError(t, err) + require.NoError(t, err) expectedMap := confmap.NewFromStringMap(map[string]any{}) assert.Equal(t, expectedMap.ToStringMap(), retMap.ToStringMap()) - assert.NoError(t, env.Shutdown(context.Background())) + require.NoError(t, env.Shutdown(context.Background())) assert.Equal(t, 1, ol.Len()) logLine := ol.All()[0] @@ -126,7 +126,7 @@ func TestEnvVarNameRestriction(t *testing.T) { env := createProvider() ret, err := env.Retrieve(context.Background(), envSchemePrefix+envName, nil) assert.Equal(t, err, fmt.Errorf("environment variable \"default%%config\" has invalid name: must match regex %s", envvar.ValidationRegexp)) - assert.NoError(t, env.Shutdown(context.Background())) + require.NoError(t, env.Shutdown(context.Background())) assert.Nil(t, ret) } @@ -141,11 +141,11 @@ func TestEmptyEnvWithLoggerWarn(t *testing.T) { ret, err := env.Retrieve(context.Background(), envSchemePrefix+envName, nil) require.NoError(t, err) retMap, err := ret.AsConf() - assert.NoError(t, err) + require.NoError(t, err) expectedMap := confmap.NewFromStringMap(map[string]any{}) assert.Equal(t, expectedMap.ToStringMap(), retMap.ToStringMap()) - assert.NoError(t, env.Shutdown(context.Background())) + require.NoError(t, env.Shutdown(context.Background())) assert.Equal(t, 1, ol.Len()) logLine := ol.All()[0] diff --git a/confmap/provider/fileprovider/provider_test.go b/confmap/provider/fileprovider/provider_test.go index 6d1182b00d1..06119411885 100644 --- a/confmap/provider/fileprovider/provider_test.go +++ b/confmap/provider/fileprovider/provider_test.go @@ -32,16 +32,16 @@ func TestEmptyName(t *testing.T) { func TestUnsupportedScheme(t *testing.T) { fp := createProvider() _, err := fp.Retrieve(context.Background(), "https://", nil) - assert.Error(t, err) + require.Error(t, err) assert.NoError(t, fp.Shutdown(context.Background())) } func TestNonExistent(t *testing.T) { fp := createProvider() _, err := fp.Retrieve(context.Background(), fileSchemePrefix+filepath.Join("testdata", "non-existent.yaml"), nil) - assert.Error(t, err) + require.Error(t, err) _, err = fp.Retrieve(context.Background(), fileSchemePrefix+absolutePath(t, filepath.Join("testdata", "non-existent.yaml")), nil) - assert.Error(t, err) + require.Error(t, err) require.NoError(t, fp.Shutdown(context.Background())) } @@ -67,7 +67,7 @@ func TestRelativePath(t *testing.T) { ret, err := fp.Retrieve(context.Background(), fileSchemePrefix+filepath.Join("testdata", "default-config.yaml"), nil) require.NoError(t, err) retMap, err := ret.AsConf() - assert.NoError(t, err) + require.NoError(t, err) expectedMap := confmap.NewFromStringMap(map[string]any{ "processors::batch": nil, "exporters::otlp::endpoint": "localhost:4317", @@ -81,7 +81,7 @@ func TestAbsolutePath(t *testing.T) { ret, err := fp.Retrieve(context.Background(), fileSchemePrefix+absolutePath(t, filepath.Join("testdata", "default-config.yaml")), nil) require.NoError(t, err) retMap, err := ret.AsConf() - assert.NoError(t, err) + require.NoError(t, err) expectedMap := confmap.NewFromStringMap(map[string]any{ "processors::batch": nil, "exporters::otlp::endpoint": "localhost:4317", diff --git a/confmap/provider/internal/configurablehttpprovider/provider_test.go b/confmap/provider/internal/configurablehttpprovider/provider_test.go index fc26051a265..0011cd2674d 100644 --- a/confmap/provider/internal/configurablehttpprovider/provider_test.go +++ b/confmap/provider/internal/configurablehttpprovider/provider_test.go @@ -133,15 +133,15 @@ func TestFunctionalityDownloadFileHTTP(t *testing.T) { func TestFunctionalityDownloadFileHTTPS(t *testing.T) { certPath, keyPath, err := generateCertificate("localhost") - assert.NoError(t, err) + require.NoError(t, err) invalidCert, err := os.CreateTemp("", "cert*.crt") - assert.NoError(t, err) + require.NoError(t, err) _, err = invalidCert.Write([]byte{0, 1, 2}) - assert.NoError(t, err) + require.NoError(t, err) cert, err := tls.LoadX509KeyPair(certPath, keyPath) - assert.NoError(t, err) + require.NoError(t, err) ts := httptest.NewUnstartedServer(http.HandlerFunc(answerGet)) ts.TLS = &tls.Config{Certificates: []tls.Certificate{cert}} ts.StartTLS() @@ -232,12 +232,12 @@ func TestFunctionalityDownloadFileHTTPS(t *testing.T) { func TestUnsupportedScheme(t *testing.T) { fp := New(HTTPScheme, confmaptest.NewNopProviderSettings()) _, err := fp.Retrieve(context.Background(), "https://...", nil) - assert.Error(t, err) - assert.NoError(t, fp.Shutdown(context.Background())) + require.Error(t, err) + require.NoError(t, fp.Shutdown(context.Background())) fp = New(HTTPSScheme, confmaptest.NewNopProviderSettings()) _, err = fp.Retrieve(context.Background(), "http://...", nil) - assert.Error(t, err) + require.Error(t, err) assert.NoError(t, fp.Shutdown(context.Background())) } @@ -257,7 +257,7 @@ func TestRetrieveFromShutdownServer(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) ts.Close() _, err := fp.Retrieve(context.Background(), ts.URL, nil) - assert.Error(t, err) + require.Error(t, err) require.NoError(t, fp.Shutdown(context.Background())) } @@ -268,7 +268,7 @@ func TestNonExistent(t *testing.T) { })) defer ts.Close() _, err := fp.Retrieve(context.Background(), ts.URL, nil) - assert.Error(t, err) + require.Error(t, err) require.NoError(t, fp.Shutdown(context.Background())) } diff --git a/confmap/provider/yamlprovider/provider_test.go b/confmap/provider/yamlprovider/provider_test.go index 8959bb0de5a..c56ba8e6069 100644 --- a/confmap/provider/yamlprovider/provider_test.go +++ b/confmap/provider/yamlprovider/provider_test.go @@ -21,7 +21,7 @@ func TestValidateProviderScheme(t *testing.T) { func TestEmpty(t *testing.T) { sp := createProvider() _, err := sp.Retrieve(context.Background(), "", nil) - assert.Error(t, err) + require.Error(t, err) assert.NoError(t, sp.Shutdown(context.Background())) } @@ -39,9 +39,9 @@ func TestInvalidYAML(t *testing.T) { func TestOneValue(t *testing.T) { sp := createProvider() ret, err := sp.Retrieve(context.Background(), "yaml:processors::batch::timeout: 2s", nil) - assert.NoError(t, err) + require.NoError(t, err) retMap, err := ret.AsConf() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, map[string]any{ "processors": map[string]any{ "batch": map[string]any{ @@ -55,9 +55,9 @@ func TestOneValue(t *testing.T) { func TestNamedComponent(t *testing.T) { sp := createProvider() ret, err := sp.Retrieve(context.Background(), "yaml:processors::batch/foo::timeout: 3s", nil) - assert.NoError(t, err) + require.NoError(t, err) retMap, err := ret.AsConf() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, map[string]any{ "processors": map[string]any{ "batch/foo": map[string]any{ @@ -71,9 +71,9 @@ func TestNamedComponent(t *testing.T) { func TestMapEntry(t *testing.T) { sp := createProvider() ret, err := sp.Retrieve(context.Background(), "yaml:processors: {batch/foo::timeout: 3s, batch::timeout: 2s}", nil) - assert.NoError(t, err) + require.NoError(t, err) retMap, err := ret.AsConf() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, map[string]any{ "processors": map[string]any{ "batch/foo": map[string]any{ @@ -90,9 +90,9 @@ func TestMapEntry(t *testing.T) { func TestArrayEntry(t *testing.T) { sp := createProvider() ret, err := sp.Retrieve(context.Background(), "yaml:service::extensions: [zpages, zpages/foo]", nil) - assert.NoError(t, err) + require.NoError(t, err) retMap, err := ret.AsConf() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, map[string]any{ "service": map[string]any{ "extensions": []any{ @@ -107,9 +107,9 @@ func TestArrayEntry(t *testing.T) { func TestNewLine(t *testing.T) { sp := createProvider() ret, err := sp.Retrieve(context.Background(), "yaml:processors::batch/foo::timeout: 3s\nprocessors::batch::timeout: 2s", nil) - assert.NoError(t, err) + require.NoError(t, err) retMap, err := ret.AsConf() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, map[string]any{ "processors": map[string]any{ "batch/foo": map[string]any{ @@ -126,9 +126,9 @@ func TestNewLine(t *testing.T) { func TestDotSeparator(t *testing.T) { sp := createProvider() ret, err := sp.Retrieve(context.Background(), "yaml:processors.batch.timeout: 4s", nil) - assert.NoError(t, err) + require.NoError(t, err) retMap, err := ret.AsConf() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, map[string]any{"processors.batch.timeout": "4s"}, retMap.ToStringMap()) assert.NoError(t, sp.Shutdown(context.Background())) } diff --git a/confmap/provider_test.go b/confmap/provider_test.go index 32554a52478..e82ddf90355 100644 --- a/confmap/provider_test.go +++ b/confmap/provider_test.go @@ -60,7 +60,7 @@ func TestNewRetrievedFromYAMLInvalidYAMLBytes(t *testing.T) { require.NoError(t, err) _, err = ret.AsConf() - assert.Error(t, err) + require.Error(t, err) str, err := ret.AsString() require.NoError(t, err) @@ -76,7 +76,7 @@ func TestNewRetrievedFromYAMLInvalidAsMap(t *testing.T) { require.NoError(t, err) _, err = ret.AsConf() - assert.Error(t, err) + require.Error(t, err) str, err := ret.AsString() require.NoError(t, err) diff --git a/confmap/resolver_test.go b/confmap/resolver_test.go index 8509ba4fdc1..bb93b4e2607 100644 --- a/confmap/resolver_test.go +++ b/confmap/resolver_test.go @@ -327,27 +327,27 @@ func TestResolver(t *testing.T) { ConverterFactories: nil}) require.NoError(t, err) _, errN := resolver.Resolve(context.Background()) - assert.NoError(t, errN) + require.NoError(t, errN) assert.Equal(t, int32(0), numCalls.Load()) errW := <-resolver.Watch() - assert.NoError(t, errW) + require.NoError(t, errW) // Repeat Resolve/Watch. _, errN = resolver.Resolve(context.Background()) - assert.NoError(t, errN) + require.NoError(t, errN) assert.Equal(t, int32(1), numCalls.Load()) errW = <-resolver.Watch() - assert.NoError(t, errW) + require.NoError(t, errW) _, errN = resolver.Resolve(context.Background()) - assert.NoError(t, errN) + require.NoError(t, errN) assert.Equal(t, int32(2), numCalls.Load()) errC := resolver.Shutdown(context.Background()) - assert.NoError(t, errC) + require.NoError(t, errC) assert.Equal(t, int32(3), numCalls.Load()) } @@ -382,7 +382,7 @@ func TestResolverShutdownClosesWatch(t *testing.T) { ConverterFactories: nil}) require.NoError(t, err) _, errN := resolver.Resolve(context.Background()) - assert.NoError(t, errN) + require.NoError(t, errN) var watcherWG sync.WaitGroup watcherWG.Add(1) @@ -394,7 +394,7 @@ func TestResolverShutdownClosesWatch(t *testing.T) { watcherWG.Done() }() - assert.NoError(t, resolver.Shutdown(context.Background())) + require.NoError(t, resolver.Shutdown(context.Background())) watcherWG.Wait() } diff --git a/connector/connector_test.go b/connector/connector_test.go index 23f253db320..9b94cee7636 100644 --- a/connector/connector_test.go +++ b/connector/connector_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/connector/internal" @@ -59,15 +60,15 @@ func TestNewFactoryWithSameTypes(t *testing.T) { assert.Equal(t, component.StabilityLevelAlpha, factory.TracesToTracesStability()) _, err := factory.CreateTracesToTraces(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelBeta, factory.MetricsToMetricsStability()) _, err = factory.CreateMetricsToMetrics(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelUnmaintained, factory.LogsToLogsStability()) _, err = factory.CreateLogsToLogs(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) _, err = factory.CreateTracesToMetrics(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop()) assert.Equal(t, err, internal.ErrDataTypes(testID, component.DataTypeTraces, component.DataTypeMetrics)) @@ -106,23 +107,23 @@ func TestNewFactoryWithTranslateTypes(t *testing.T) { assert.Equal(t, component.StabilityLevelDevelopment, factory.TracesToMetricsStability()) _, err = factory.CreateTracesToMetrics(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelAlpha, factory.TracesToLogsStability()) _, err = factory.CreateTracesToLogs(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelBeta, factory.MetricsToTracesStability()) _, err = factory.CreateMetricsToTraces(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelStable, factory.MetricsToLogsStability()) _, err = factory.CreateMetricsToLogs(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelDeprecated, factory.LogsToTracesStability()) _, err = factory.CreateLogsToTraces(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelUnmaintained, factory.LogsToMetricsStability()) _, err = factory.CreateLogsToMetrics(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop()) @@ -146,30 +147,30 @@ func TestNewFactoryWithAllTypes(t *testing.T) { assert.Equal(t, component.StabilityLevelAlpha, factory.TracesToTracesStability()) _, err := factory.CreateTracesToTraces(context.Background(), Settings{}, &defaultCfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelDevelopment, factory.TracesToMetricsStability()) _, err = factory.CreateTracesToMetrics(context.Background(), Settings{}, &defaultCfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelAlpha, factory.TracesToLogsStability()) _, err = factory.CreateTracesToLogs(context.Background(), Settings{}, &defaultCfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelBeta, factory.MetricsToTracesStability()) _, err = factory.CreateMetricsToTraces(context.Background(), Settings{}, &defaultCfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelBeta, factory.MetricsToMetricsStability()) _, err = factory.CreateMetricsToMetrics(context.Background(), Settings{}, &defaultCfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelStable, factory.MetricsToLogsStability()) _, err = factory.CreateMetricsToLogs(context.Background(), Settings{}, &defaultCfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelDeprecated, factory.LogsToTracesStability()) _, err = factory.CreateLogsToTraces(context.Background(), Settings{}, &defaultCfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelUnmaintained, factory.LogsToMetricsStability()) _, err = factory.CreateLogsToMetrics(context.Background(), Settings{}, &defaultCfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelUnmaintained, factory.LogsToLogsStability()) _, err = factory.CreateLogsToLogs(context.Background(), Settings{}, &defaultCfg, consumertest.NewNop()) assert.NoError(t, err) @@ -206,7 +207,7 @@ func TestMakeFactoryMap(t *testing.T) { assert.Error(t, err) return } - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tt.out, out) }) } diff --git a/connector/connectorprofiles/connector_test.go b/connector/connectorprofiles/connector_test.go index adb360be028..93493213c79 100644 --- a/connector/connectorprofiles/connector_test.go +++ b/connector/connectorprofiles/connector_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/component/componentprofiles" @@ -54,7 +55,7 @@ func TestNewFactoryWithSameTypes(t *testing.T) { assert.Equal(t, component.StabilityLevelAlpha, factory.ProfilesToProfilesStability()) _, err := factory.CreateProfilesToProfiles(context.Background(), connector.Settings{ID: testID}, &defaultCfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) _, err = factory.CreateProfilesToTraces(context.Background(), connector.Settings{ID: testID}, &defaultCfg, consumertest.NewNop()) assert.Equal(t, err, internal.ErrDataTypes(testID, componentprofiles.DataTypeProfiles, component.DataTypeTraces)) @@ -83,23 +84,23 @@ func TestNewFactoryWithTranslateTypes(t *testing.T) { assert.Equal(t, component.StabilityLevelBeta, factory.TracesToProfilesStability()) _, err = factory.CreateTracesToProfiles(context.Background(), connector.Settings{ID: testID}, &defaultCfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelDevelopment, factory.MetricsToProfilesStability()) _, err = factory.CreateMetricsToProfiles(context.Background(), connector.Settings{ID: testID}, &defaultCfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelAlpha, factory.LogsToProfilesStability()) _, err = factory.CreateLogsToProfiles(context.Background(), connector.Settings{ID: testID}, &defaultCfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelBeta, factory.ProfilesToTracesStability()) _, err = factory.CreateProfilesToTraces(context.Background(), connector.Settings{ID: testID}, &defaultCfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelDevelopment, factory.ProfilesToMetricsStability()) _, err = factory.CreateProfilesToMetrics(context.Background(), connector.Settings{ID: testID}, &defaultCfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelAlpha, factory.ProfilesToLogsStability()) _, err = factory.CreateProfilesToLogs(context.Background(), connector.Settings{ID: testID}, &defaultCfg, consumertest.NewNop()) diff --git a/connector/connectorprofiles/profiles_router_test.go b/connector/connectorprofiles/profiles_router_test.go index 08dc2490c11..0eb69a12be9 100644 --- a/connector/connectorprofiles/profiles_router_test.go +++ b/connector/connectorprofiles/profiles_router_test.go @@ -10,6 +10,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/consumer" @@ -149,7 +150,7 @@ func TestProfilessRouterConsumer(t *testing.T) { none, err := r.Consumer() assert.Nil(t, none) - assert.Error(t, err) + require.Error(t, err) fake, err := r.Consumer(component.MustNewID("fake")) assert.Nil(t, fake) diff --git a/connector/forwardconnector/forward_test.go b/connector/forwardconnector/forward_test.go index e3a9ef894b0..f936579670c 100644 --- a/connector/forwardconnector/forward_test.go +++ b/connector/forwardconnector/forward_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/component/componenttest" "go.opentelemetry.io/collector/connector/connectortest" @@ -27,17 +28,17 @@ func TestForward(t *testing.T) { tracesSink := new(consumertest.TracesSink) tracesToTraces, err := f.CreateTracesToTraces(ctx, set, cfg, tracesSink) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, tracesToTraces) metricsSink := new(consumertest.MetricsSink) metricsToMetrics, err := f.CreateMetricsToMetrics(ctx, set, cfg, metricsSink) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, metricsToMetrics) logsSink := new(consumertest.LogsSink) logsToLogs, err := f.CreateLogsToLogs(ctx, set, cfg, logsSink) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, logsToLogs) assert.NoError(t, tracesToTraces.Start(ctx, host)) diff --git a/connector/logs_router_test.go b/connector/logs_router_test.go index a8af2fc41ab..d4d70c3fec2 100644 --- a/connector/logs_router_test.go +++ b/connector/logs_router_test.go @@ -10,6 +10,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/consumer" @@ -148,7 +149,7 @@ func TestLogsRouterConsumers(t *testing.T) { none, err := r.Consumer() assert.Nil(t, none) - assert.Error(t, err) + require.Error(t, err) fake, err := r.Consumer(component.MustNewID("fake")) assert.Nil(t, fake) diff --git a/connector/metrics_router_test.go b/connector/metrics_router_test.go index 04072f05389..7fb12de9b1d 100644 --- a/connector/metrics_router_test.go +++ b/connector/metrics_router_test.go @@ -10,6 +10,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/consumer" @@ -148,7 +149,7 @@ func TestMetricsRouterConsumers(t *testing.T) { none, err := r.Consumer() assert.Nil(t, none) - assert.Error(t, err) + require.Error(t, err) fake, err := r.Consumer(component.MustNewID("fake")) assert.Nil(t, fake) diff --git a/connector/traces_router_test.go b/connector/traces_router_test.go index 42dc957c1a6..a54b1006012 100644 --- a/connector/traces_router_test.go +++ b/connector/traces_router_test.go @@ -10,6 +10,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/consumer" @@ -148,7 +149,7 @@ func TestTracesRouterConsumer(t *testing.T) { none, err := r.Consumer() assert.Nil(t, none) - assert.Error(t, err) + require.Error(t, err) fake, err := r.Consumer(component.MustNewID("fake")) assert.Nil(t, fake) diff --git a/consumer/consumererror/signalerrors_test.go b/consumer/consumererror/signalerrors_test.go index 6ec64710b8c..794532ec185 100644 --- a/consumer/consumererror/signalerrors_test.go +++ b/consumer/consumererror/signalerrors_test.go @@ -21,7 +21,7 @@ func TestTraces(t *testing.T) { var target Traces assert.False(t, errors.As(nil, &target)) assert.False(t, errors.As(err, &target)) - assert.ErrorAs(t, traceErr, &target) + require.ErrorAs(t, traceErr, &target) assert.Equal(t, td, target.Data()) } @@ -45,7 +45,7 @@ func TestLogs(t *testing.T) { var target Logs assert.False(t, errors.As(nil, &target)) assert.False(t, errors.As(err, &target)) - assert.ErrorAs(t, logsErr, &target) + require.ErrorAs(t, logsErr, &target) assert.Equal(t, td, target.Data()) } @@ -69,7 +69,7 @@ func TestMetrics(t *testing.T) { var target Metrics assert.False(t, errors.As(nil, &target)) assert.False(t, errors.As(err, &target)) - assert.ErrorAs(t, metricErr, &target) + require.ErrorAs(t, metricErr, &target) assert.Equal(t, td, target.Data()) } diff --git a/consumer/consumerprofiles/profiles_test.go b/consumer/consumerprofiles/profiles_test.go index e50866e74da..a9abead7bae 100644 --- a/consumer/consumerprofiles/profiles_test.go +++ b/consumer/consumerprofiles/profiles_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/consumer" "go.opentelemetry.io/collector/pdata/pprofile" @@ -46,6 +47,6 @@ func TestConsumeProfiles(t *testing.T) { func TestConsumeProfiles_ReturnError(t *testing.T) { want := errors.New("my_error") cp, err := NewProfiles(func(context.Context, pprofile.Profiles) error { return want }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, want, cp.ConsumeProfiles(context.Background(), pprofile.NewProfiles())) } diff --git a/consumer/logs_test.go b/consumer/logs_test.go index 9f3b4552a27..a6ca2eb6f95 100644 --- a/consumer/logs_test.go +++ b/consumer/logs_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/pdata/plog" ) @@ -45,6 +46,6 @@ func TestConsumeLogs(t *testing.T) { func TestConsumeLogs_ReturnError(t *testing.T) { want := errors.New("my_error") cp, err := NewLogs(func(context.Context, plog.Logs) error { return want }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, want, cp.ConsumeLogs(context.Background(), plog.NewLogs())) } diff --git a/consumer/metrics_test.go b/consumer/metrics_test.go index a7ce59de847..914e96a1529 100644 --- a/consumer/metrics_test.go +++ b/consumer/metrics_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/pdata/pmetric" ) @@ -45,6 +46,6 @@ func TestConsumeMetrics(t *testing.T) { func TestConsumeMetrics_ReturnError(t *testing.T) { want := errors.New("my_error") cp, err := NewMetrics(func(context.Context, pmetric.Metrics) error { return want }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, want, cp.ConsumeMetrics(context.Background(), pmetric.NewMetrics())) } diff --git a/consumer/traces_test.go b/consumer/traces_test.go index 114ae6525b5..168db58cef4 100644 --- a/consumer/traces_test.go +++ b/consumer/traces_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/pdata/ptrace" ) @@ -45,6 +46,6 @@ func TestConsumeTraces(t *testing.T) { func TestConsumeTraces_ReturnError(t *testing.T) { want := errors.New("my_error") cp, err := NewTraces(func(context.Context, ptrace.Traces) error { return want }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, want, cp.ConsumeTraces(context.Background(), ptrace.NewTraces())) } diff --git a/exporter/debugexporter/config_test.go b/exporter/debugexporter/config_test.go index a9fbf9f87e0..ef204196e61 100644 --- a/exporter/debugexporter/config_test.go +++ b/exporter/debugexporter/config_test.go @@ -18,7 +18,7 @@ import ( func TestUnmarshalDefaultConfig(t *testing.T) { factory := NewFactory() cfg := factory.CreateDefaultConfig() - assert.NoError(t, confmap.New().Unmarshal(&cfg)) + require.NoError(t, confmap.New().Unmarshal(&cfg)) assert.Equal(t, factory.CreateDefaultConfig(), cfg) } @@ -52,7 +52,7 @@ func TestUnmarshalConfig(t *testing.T) { if tt.expectedErr != "" { assert.ErrorContains(t, err, tt.expectedErr) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tt.cfg, cfg) } }) @@ -82,7 +82,7 @@ func Test_UnmarshalMarshalled(t *testing.T) { conf := confmap.New() err := conf.Marshal(tc.inCfg) - assert.NoError(t, err) + require.NoError(t, err) raw := conf.ToStringMap() @@ -93,11 +93,11 @@ func Test_UnmarshalMarshalled(t *testing.T) { err = conf.Unmarshal(outCfg) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tc.expectedConfig, outCfg) return } - assert.Error(t, err) + require.Error(t, err) assert.EqualError(t, err, tc.expectedErr) }) } diff --git a/exporter/debugexporter/factory_test.go b/exporter/debugexporter/factory_test.go index df16570e48e..a26fa1e6217 100644 --- a/exporter/debugexporter/factory_test.go +++ b/exporter/debugexporter/factory_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/component/componenttest" "go.opentelemetry.io/collector/exporter/exportertest" @@ -25,7 +26,7 @@ func TestCreateMetricsExporter(t *testing.T) { cfg := factory.CreateDefaultConfig() me, err := factory.CreateMetricsExporter(context.Background(), exportertest.NewNopSettings(), cfg) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, me) } @@ -34,7 +35,7 @@ func TestCreateTracesExporter(t *testing.T) { cfg := factory.CreateDefaultConfig() te, err := factory.CreateTracesExporter(context.Background(), exportertest.NewNopSettings(), cfg) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, te) } @@ -43,6 +44,6 @@ func TestCreateLogsExporter(t *testing.T) { cfg := factory.CreateDefaultConfig() te, err := factory.CreateLogsExporter(context.Background(), exportertest.NewNopSettings(), cfg) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, te) } diff --git a/exporter/debugexporter/internal/normal/logs_test.go b/exporter/debugexporter/internal/normal/logs_test.go index 8aafa49862a..57288e24083 100644 --- a/exporter/debugexporter/internal/normal/logs_test.go +++ b/exporter/debugexporter/internal/normal/logs_test.go @@ -8,6 +8,7 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/pdata/pcommon" "go.opentelemetry.io/collector/pdata/plog" @@ -111,7 +112,7 @@ log message mykey2=myvalue2 mykey1=myvalue1 for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { output, err := NewNormalLogsMarshaler().MarshalLogs(tt.input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tt.expected, string(output)) }) } diff --git a/exporter/debugexporter/internal/normal/metrics_test.go b/exporter/debugexporter/internal/normal/metrics_test.go index 8d941297cf6..38779d2fe82 100644 --- a/exporter/debugexporter/internal/normal/metrics_test.go +++ b/exporter/debugexporter/internal/normal/metrics_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/pdata/pmetric" ) @@ -113,7 +114,7 @@ func TestMarshalMetrics(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { output, err := NewNormalMetricsMarshaler().MarshalMetrics(tt.input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tt.expected, string(output)) }) } diff --git a/exporter/debugexporter/internal/normal/traces_test.go b/exporter/debugexporter/internal/normal/traces_test.go index 84f69d4a176..45c30ef0719 100644 --- a/exporter/debugexporter/internal/normal/traces_test.go +++ b/exporter/debugexporter/internal/normal/traces_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/pdata/ptrace" ) @@ -41,7 +42,7 @@ func TestMarshalTraces(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { output, err := NewNormalTracesMarshaler().MarshalTraces(tt.input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tt.expected, string(output)) }) } diff --git a/exporter/exporter_test.go b/exporter/exporter_test.go index 879933fdab9..54e23eb3d48 100644 --- a/exporter/exporter_test.go +++ b/exporter/exporter_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/consumer/consumertest" @@ -22,9 +23,9 @@ func TestNewFactory(t *testing.T) { assert.EqualValues(t, testType, factory.Type()) assert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig()) _, err := factory.CreateTracesExporter(context.Background(), Settings{}, &defaultCfg) - assert.Error(t, err) + require.Error(t, err) _, err = factory.CreateMetricsExporter(context.Background(), Settings{}, &defaultCfg) - assert.Error(t, err) + require.Error(t, err) _, err = factory.CreateLogsExporter(context.Background(), Settings{}, &defaultCfg) assert.Error(t, err) } @@ -43,11 +44,11 @@ func TestNewFactoryWithOptions(t *testing.T) { assert.Equal(t, component.StabilityLevelDevelopment, factory.TracesExporterStability()) _, err := factory.CreateTracesExporter(context.Background(), Settings{}, &defaultCfg) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelAlpha, factory.MetricsExporterStability()) _, err = factory.CreateMetricsExporter(context.Background(), Settings{}, &defaultCfg) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelDeprecated, factory.LogsExporterStability()) _, err = factory.CreateLogsExporter(context.Background(), Settings{}, &defaultCfg) @@ -85,7 +86,7 @@ func TestMakeFactoryMap(t *testing.T) { assert.Error(t, err) return } - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tt.out, out) }) } diff --git a/exporter/exporterbatcher/config_test.go b/exporter/exporterbatcher/config_test.go index 337f83ce318..6dfc1101f95 100644 --- a/exporter/exporterbatcher/config_test.go +++ b/exporter/exporterbatcher/config_test.go @@ -7,21 +7,22 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestConfig_Validate(t *testing.T) { cfg := NewDefaultConfig() - assert.NoError(t, cfg.Validate()) + require.NoError(t, cfg.Validate()) cfg.MinSizeItems = -1 - assert.EqualError(t, cfg.Validate(), "min_size_items must be greater than or equal to zero") + require.EqualError(t, cfg.Validate(), "min_size_items must be greater than or equal to zero") cfg = NewDefaultConfig() cfg.FlushTimeout = 0 - assert.EqualError(t, cfg.Validate(), "timeout must be greater than zero") + require.EqualError(t, cfg.Validate(), "timeout must be greater than zero") cfg.MaxSizeItems = -1 - assert.EqualError(t, cfg.Validate(), "max_size_items must be greater than or equal to zero") + require.EqualError(t, cfg.Validate(), "max_size_items must be greater than or equal to zero") cfg = NewDefaultConfig() cfg.MaxSizeItems = 20000 diff --git a/exporter/exporterhelper/batch_sender_test.go b/exporter/exporterhelper/batch_sender_test.go index a1c894102ca..0c4823c0e8b 100644 --- a/exporter/exporterhelper/batch_sender_test.go +++ b/exporter/exporterhelper/batch_sender_test.go @@ -341,7 +341,7 @@ func TestBatchSender_ConcurrencyLimitReached(t *testing.T) { }, 100*time.Millisecond, 10*time.Millisecond) // the 3rd request should be flushed by itself due to flush interval - assert.NoError(t, be.send(context.Background(), &fakeRequest{items: 2, sink: sink})) + require.NoError(t, be.send(context.Background(), &fakeRequest{items: 2, sink: sink})) assert.Eventually(t, func() bool { return sink.requestsCount.Load() == 2 && sink.itemsCount.Load() == 6 }, 100*time.Millisecond, 10*time.Millisecond) @@ -608,7 +608,7 @@ func TestBatchSenderWithTimeout(t *testing.T) { } wg.Wait() - assert.NoError(t, be.Shutdown(context.Background())) + require.NoError(t, be.Shutdown(context.Background())) // The sink should not change assert.EqualValues(t, 1, sink.requestsCount.Load()) diff --git a/exporter/exporterhelper/logs_batch_test.go b/exporter/exporterhelper/logs_batch_test.go index 2ed1f152aa3..f5e10b5bcc9 100644 --- a/exporter/exporterhelper/logs_batch_test.go +++ b/exporter/exporterhelper/logs_batch_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/exporter/exporterbatcher" "go.opentelemetry.io/collector/pdata/plog" @@ -18,7 +19,7 @@ func TestMergeLogs(t *testing.T) { lr1 := &logsRequest{ld: testdata.GenerateLogs(2)} lr2 := &logsRequest{ld: testdata.GenerateLogs(3)} res, err := mergeLogs(context.Background(), lr1, lr2) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 5, res.(*logsRequest).ld.LogRecordCount()) } @@ -132,7 +133,7 @@ func TestMergeSplitLogs(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { res, err := mergeSplitLogs(context.Background(), tt.cfg, tt.lr1, tt.lr2) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, len(tt.expected), len(res)) for i, r := range res { assert.Equal(t, tt.expected[i], r.(*logsRequest)) diff --git a/exporter/exporterhelper/logs_test.go b/exporter/exporterhelper/logs_test.go index e42a40159d0..1fb952d1486 100644 --- a/exporter/exporterhelper/logs_test.go +++ b/exporter/exporterhelper/logs_test.go @@ -86,7 +86,7 @@ func TestLogsExporter_Default(t *testing.T) { ld := plog.NewLogs() le, err := NewLogsExporter(context.Background(), exportertest.NewNopSettings(), &fakeLogsExporterConfig, newPushLogsData(nil)) assert.NotNil(t, le) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, consumer.Capabilities{MutatesData: false}, le.Capabilities()) assert.NoError(t, le.Start(context.Background(), componenttest.NewNopHost())) @@ -99,7 +99,7 @@ func TestLogsRequestExporter_Default(t *testing.T) { le, err := NewLogsRequestExporter(context.Background(), exportertest.NewNopSettings(), (&fakeRequestConverter{}).requestFromLogsFunc) assert.NotNil(t, le) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, consumer.Capabilities{MutatesData: false}, le.Capabilities()) assert.NoError(t, le.Start(context.Background(), componenttest.NewNopHost())) @@ -198,10 +198,10 @@ func TestLogsExporter_pLogModifiedDownStream_WithRecordMetrics(t *testing.T) { le, err := NewLogsExporter(context.Background(), exporter.Settings{ID: fakeLogsExporterName, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, &fakeLogsExporterConfig, newPushLogsDataModifiedDownstream(nil), WithCapabilities(consumer.Capabilities{MutatesData: true})) assert.NotNil(t, le) - assert.NoError(t, err) + require.NoError(t, err) ld := testdata.GenerateLogs(2) - assert.NoError(t, le.ConsumeLogs(context.Background(), ld)) + require.NoError(t, le.ConsumeLogs(context.Background(), ld)) assert.Equal(t, 0, ld.LogRecordCount()) require.NoError(t, tt.CheckExporterLogs(int64(2), 0)) } @@ -357,7 +357,7 @@ func TestLogsExporter_WithShutdown_ReturnError(t *testing.T) { le, err := NewLogsExporter(context.Background(), exportertest.NewNopSettings(), &fakeLogsExporterConfig, newPushLogsData(nil), WithShutdown(shutdownErr)) assert.NotNil(t, le) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, want, le.Shutdown(context.Background())) } @@ -369,7 +369,7 @@ func TestLogsRequestExporter_WithShutdown_ReturnError(t *testing.T) { le, err := NewLogsRequestExporter(context.Background(), exportertest.NewNopSettings(), (&fakeRequestConverter{}).requestFromLogsFunc, WithShutdown(shutdownErr)) assert.NotNil(t, le) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, want, le.Shutdown(context.Background())) } diff --git a/exporter/exporterhelper/metrics_batch_test.go b/exporter/exporterhelper/metrics_batch_test.go index 34aac146e22..860a1eee9c3 100644 --- a/exporter/exporterhelper/metrics_batch_test.go +++ b/exporter/exporterhelper/metrics_batch_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/exporter/exporterbatcher" "go.opentelemetry.io/collector/pdata/pmetric" @@ -18,7 +19,7 @@ func TestMergeMetrics(t *testing.T) { mr1 := &metricsRequest{md: testdata.GenerateMetrics(2)} mr2 := &metricsRequest{md: testdata.GenerateMetrics(3)} res, err := mergeMetrics(context.Background(), mr1, mr2) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 5, res.(*metricsRequest).md.MetricCount()) } @@ -133,7 +134,7 @@ func TestMergeSplitMetrics(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { res, err := mergeSplitMetrics(context.Background(), tt.cfg, tt.mr1, tt.mr2) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, len(tt.expected), len(res)) for i := range res { assert.Equal(t, tt.expected[i], res[i].(*metricsRequest)) diff --git a/exporter/exporterhelper/metrics_test.go b/exporter/exporterhelper/metrics_test.go index b97b2cdc650..02381396547 100644 --- a/exporter/exporterhelper/metrics_test.go +++ b/exporter/exporterhelper/metrics_test.go @@ -86,7 +86,7 @@ func TestMetricsRequestExporter_NilMetricsConverter(t *testing.T) { func TestMetricsExporter_Default(t *testing.T) { md := pmetric.NewMetrics() me, err := NewMetricsExporter(context.Background(), exportertest.NewNopSettings(), &fakeMetricsExporterConfig, newPushMetricsData(nil)) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, me) assert.Equal(t, consumer.Capabilities{MutatesData: false}, me.Capabilities()) @@ -99,7 +99,7 @@ func TestMetricsRequestExporter_Default(t *testing.T) { md := pmetric.NewMetrics() me, err := NewMetricsRequestExporter(context.Background(), exportertest.NewNopSettings(), (&fakeRequestConverter{}).requestFromMetricsFunc) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, me) assert.Equal(t, consumer.Capabilities{MutatesData: false}, me.Capabilities()) @@ -111,7 +111,7 @@ func TestMetricsRequestExporter_Default(t *testing.T) { func TestMetricsExporter_WithCapabilities(t *testing.T) { capabilities := consumer.Capabilities{MutatesData: true} me, err := NewMetricsExporter(context.Background(), exportertest.NewNopSettings(), &fakeMetricsExporterConfig, newPushMetricsData(nil), WithCapabilities(capabilities)) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, me) assert.Equal(t, capabilities, me.Capabilities()) @@ -121,7 +121,7 @@ func TestMetricsRequestExporter_WithCapabilities(t *testing.T) { capabilities := consumer.Capabilities{MutatesData: true} me, err := NewMetricsRequestExporter(context.Background(), exportertest.NewNopSettings(), (&fakeRequestConverter{}).requestFromMetricsFunc, WithCapabilities(capabilities)) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, me) assert.Equal(t, capabilities, me.Capabilities()) @@ -202,7 +202,7 @@ func TestMetricsExporter_pMetricModifiedDownStream_WithRecordMetrics(t *testing. require.NotNil(t, me) md := testdata.GenerateMetrics(2) - assert.NoError(t, me.ConsumeMetrics(context.Background(), md)) + require.NoError(t, me.ConsumeMetrics(context.Background(), md)) assert.Equal(t, 0, md.MetricCount()) require.NoError(t, tt.CheckExporterMetrics(int64(4), 0)) } diff --git a/exporter/exporterhelper/obsexporter_test.go b/exporter/exporterhelper/obsexporter_test.go index 802068983f0..ac939e21127 100644 --- a/exporter/exporterhelper/obsexporter_test.go +++ b/exporter/exporterhelper/obsexporter_test.go @@ -185,9 +185,9 @@ func TestCheckExporterTracesViews(t *testing.T) { require.NotNil(t, ctx) obsrep.endTracesOp(ctx, 7, nil) - assert.NoError(t, tt.CheckExporterTraces(7, 0)) - assert.Error(t, tt.CheckExporterTraces(7, 7)) - assert.Error(t, tt.CheckExporterTraces(0, 0)) + require.NoError(t, tt.CheckExporterTraces(7, 0)) + require.Error(t, tt.CheckExporterTraces(7, 7)) + require.Error(t, tt.CheckExporterTraces(0, 0)) assert.Error(t, tt.CheckExporterTraces(0, 7)) } @@ -205,9 +205,9 @@ func TestCheckExporterMetricsViews(t *testing.T) { require.NotNil(t, ctx) obsrep.endMetricsOp(ctx, 7, nil) - assert.NoError(t, tt.CheckExporterMetrics(7, 0)) - assert.Error(t, tt.CheckExporterMetrics(7, 7)) - assert.Error(t, tt.CheckExporterMetrics(0, 0)) + require.NoError(t, tt.CheckExporterMetrics(7, 0)) + require.Error(t, tt.CheckExporterMetrics(7, 7)) + require.Error(t, tt.CheckExporterMetrics(0, 0)) assert.Error(t, tt.CheckExporterMetrics(0, 7)) } @@ -225,9 +225,9 @@ func TestCheckExporterLogsViews(t *testing.T) { require.NotNil(t, ctx) obsrep.endLogsOp(ctx, 7, nil) - assert.NoError(t, tt.CheckExporterLogs(7, 0)) - assert.Error(t, tt.CheckExporterLogs(7, 7)) - assert.Error(t, tt.CheckExporterLogs(0, 0)) + require.NoError(t, tt.CheckExporterLogs(7, 0)) + require.Error(t, tt.CheckExporterLogs(7, 7)) + require.Error(t, tt.CheckExporterLogs(0, 0)) assert.Error(t, tt.CheckExporterLogs(0, 7)) } diff --git a/exporter/exporterhelper/queue_sender_test.go b/exporter/exporterhelper/queue_sender_test.go index 08484ad0496..f86b5d2aad1 100644 --- a/exporter/exporterhelper/queue_sender_test.go +++ b/exporter/exporterhelper/queue_sender_test.go @@ -51,7 +51,7 @@ func TestQueuedRetry_StopWhileWaiting(t *testing.T) { require.LessOrEqual(t, 1, be.queueSender.(*queueSender).queue.Size()) - assert.NoError(t, be.Shutdown(context.Background())) + require.NoError(t, be.Shutdown(context.Background())) secondMockR.checkNumRequests(t, 1) ocs.checkSendItemsCount(t, 3) @@ -242,7 +242,7 @@ func TestNoCancellationContext(t *testing.T) { require.Equal(t, deadline, d) nctx := context.WithoutCancel(ctx) - assert.NoError(t, nctx.Err()) + require.NoError(t, nctx.Err()) d, ok = nctx.Deadline() assert.False(t, ok) assert.True(t, d.IsZero()) @@ -250,15 +250,15 @@ func TestNoCancellationContext(t *testing.T) { func TestQueueConfig_Validate(t *testing.T) { qCfg := NewDefaultQueueConfig() - assert.NoError(t, qCfg.Validate()) + require.NoError(t, qCfg.Validate()) qCfg.QueueSize = 0 - assert.EqualError(t, qCfg.Validate(), "queue size must be positive") + require.EqualError(t, qCfg.Validate(), "queue size must be positive") qCfg = NewDefaultQueueConfig() qCfg.NumConsumers = 0 - assert.EqualError(t, qCfg.Validate(), "number of queue consumers must be positive") + require.EqualError(t, qCfg.Validate(), "number of queue consumers must be positive") // Confirm Validate doesn't return error with invalid config when feature is disabled qCfg.Enabled = false @@ -436,7 +436,7 @@ func TestQueueSenderNoStartShutdown(t *testing.T) { exporterID: exporterID, exporterCreateSettings: exportertest.NewNopSettings(), }) - assert.NoError(t, err) + require.NoError(t, err) qs := newQueueSender(queue, set, 1, "", obsrep) assert.NoError(t, qs.Shutdown(context.Background())) } diff --git a/exporter/exporterhelper/timeout_sender_test.go b/exporter/exporterhelper/timeout_sender_test.go index a0dac589821..f72cf565360 100644 --- a/exporter/exporterhelper/timeout_sender_test.go +++ b/exporter/exporterhelper/timeout_sender_test.go @@ -8,17 +8,18 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestNewDefaultTimeoutConfig(t *testing.T) { cfg := NewDefaultTimeoutConfig() - assert.NoError(t, cfg.Validate()) + require.NoError(t, cfg.Validate()) assert.Equal(t, TimeoutConfig{Timeout: 5 * time.Second}, cfg) } func TestInvalidTimeout(t *testing.T) { cfg := NewDefaultTimeoutConfig() - assert.NoError(t, cfg.Validate()) + require.NoError(t, cfg.Validate()) cfg.Timeout = -1 assert.Error(t, cfg.Validate()) } diff --git a/exporter/exporterhelper/traces_batch_test.go b/exporter/exporterhelper/traces_batch_test.go index 63bc73e94d0..d88591b3091 100644 --- a/exporter/exporterhelper/traces_batch_test.go +++ b/exporter/exporterhelper/traces_batch_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/exporter/exporterbatcher" "go.opentelemetry.io/collector/pdata/ptrace" @@ -18,7 +19,7 @@ func TestMergeTraces(t *testing.T) { tr1 := &tracesRequest{td: testdata.GenerateTraces(2)} tr2 := &tracesRequest{td: testdata.GenerateTraces(3)} res, err := mergeTraces(context.Background(), tr1, tr2) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 5, res.(*tracesRequest).td.SpanCount()) } @@ -133,7 +134,7 @@ func TestMergeSplitTraces(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { res, err := mergeSplitTraces(context.Background(), tt.cfg, tt.tr1, tt.tr2) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, len(tt.expected), len(res)) for i := range res { assert.Equal(t, tt.expected[i], res[i].(*tracesRequest)) diff --git a/exporter/exporterhelper/traces_test.go b/exporter/exporterhelper/traces_test.go index 103b9b76060..2d3d1cfdf8b 100644 --- a/exporter/exporterhelper/traces_test.go +++ b/exporter/exporterhelper/traces_test.go @@ -82,7 +82,7 @@ func TestTracesExporter_Default(t *testing.T) { td := ptrace.NewTraces() te, err := NewTracesExporter(context.Background(), exportertest.NewNopSettings(), &fakeTracesExporterConfig, newTraceDataPusher(nil)) assert.NotNil(t, te) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, consumer.Capabilities{MutatesData: false}, te.Capabilities()) assert.NoError(t, te.Start(context.Background(), componenttest.NewNopHost())) @@ -95,7 +95,7 @@ func TestTracesRequestExporter_Default(t *testing.T) { te, err := NewTracesRequestExporter(context.Background(), exportertest.NewNopSettings(), (&fakeRequestConverter{}).requestFromTracesFunc) assert.NotNil(t, te) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, consumer.Capabilities{MutatesData: false}, te.Capabilities()) assert.NoError(t, te.Start(context.Background(), componenttest.NewNopHost())) @@ -107,7 +107,7 @@ func TestTracesExporter_WithCapabilities(t *testing.T) { capabilities := consumer.Capabilities{MutatesData: true} te, err := NewTracesExporter(context.Background(), exportertest.NewNopSettings(), &fakeTracesExporterConfig, newTraceDataPusher(nil), WithCapabilities(capabilities)) assert.NotNil(t, te) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, capabilities, te.Capabilities()) } @@ -117,7 +117,7 @@ func TestTracesRequestExporter_WithCapabilities(t *testing.T) { te, err := NewTracesRequestExporter(context.Background(), exportertest.NewNopSettings(), (&fakeRequestConverter{}).requestFromTracesFunc, WithCapabilities(capabilities)) assert.NotNil(t, te) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, capabilities, te.Capabilities()) } @@ -196,10 +196,10 @@ func TestTracesExporter_pLogModifiedDownStream_WithRecordMetrics(t *testing.T) { te, err := NewTracesExporter(context.Background(), exporter.Settings{ID: fakeTracesExporterName, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, &fakeTracesExporterConfig, newTraceDataPusherModifiedDownstream(nil), WithCapabilities(consumer.Capabilities{MutatesData: true})) assert.NotNil(t, te) - assert.NoError(t, err) + require.NoError(t, err) td := testdata.GenerateTraces(2) - assert.NoError(t, te.ConsumeTraces(context.Background(), td)) + require.NoError(t, te.ConsumeTraces(context.Background(), td)) assert.Equal(t, 0, td.SpanCount()) require.NoError(t, tt.CheckExporterTraces(int64(2), 0)) } diff --git a/exporter/exporterqueue/config_test.go b/exporter/exporterqueue/config_test.go index c1b43ba5f8e..7679242631c 100644 --- a/exporter/exporterqueue/config_test.go +++ b/exporter/exporterqueue/config_test.go @@ -7,18 +7,19 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestQueueConfig_Validate(t *testing.T) { qCfg := NewDefaultConfig() - assert.NoError(t, qCfg.Validate()) + require.NoError(t, qCfg.Validate()) qCfg.NumConsumers = 0 - assert.EqualError(t, qCfg.Validate(), "number of consumers must be positive") + require.EqualError(t, qCfg.Validate(), "number of consumers must be positive") qCfg = NewDefaultConfig() qCfg.QueueSize = 0 - assert.EqualError(t, qCfg.Validate(), "queue size must be positive") + require.EqualError(t, qCfg.Validate(), "queue size must be positive") // Confirm Validate doesn't return error with invalid config when feature is disabled qCfg.Enabled = false diff --git a/exporter/exportertest/mock_consumer_test.go b/exporter/exportertest/mock_consumer_test.go index e853be14c6b..c71ac33898e 100644 --- a/exporter/exportertest/mock_consumer_test.go +++ b/exporter/exportertest/mock_consumer_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/consumer" "go.opentelemetry.io/collector/pdata/plog" @@ -46,13 +47,13 @@ func TestIDFromMetrics(t *testing.T) { validData := createMetric(id) metricID, err := idFromMetrics(validData) assert.Equal(t, metricID, id) - assert.NoError(t, err) + require.NoError(t, err) // Test case 2: Missing uniqueIDAttrName attribute invalidData := pmetric.NewMetrics() // Create an invalid pmetric.Metrics object with missing attribute invalidData.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptyHistogram().DataPoints().AppendEmpty().Attributes() _, err = idFromMetrics(invalidData) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, err.Error(), fmt.Sprintf("invalid data element, attribute %q is missing", uniqueIDAttrName)) // Test case 3: Wrong attribute type @@ -61,7 +62,7 @@ func TestIDFromMetrics(t *testing.T) { wrongAttribute.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty(). SetEmptyHistogram().DataPoints().AppendEmpty().Attributes().PutInt(uniqueIDAttrName, intID) _, err = idFromMetrics(wrongAttribute) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, err.Error(), fmt.Sprintf("invalid data element, attribute %q is wrong type Int", uniqueIDAttrName)) } @@ -71,13 +72,13 @@ func TestIDFromTraces(t *testing.T) { validData := createTrace(id) traceID, err := idFromTraces(validData) assert.Equal(t, traceID, id) - assert.NoError(t, err) + require.NoError(t, err) // Test case 2: Missing uniqueIDAttrName attribute invalidData := ptrace.NewTraces() invalidData.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans().AppendEmpty().Attributes() _, err = idFromTraces(invalidData) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, err.Error(), fmt.Sprintf("invalid data element, attribute %q is missing", uniqueIDAttrName)) // Test case 3: Wrong attribute type @@ -86,7 +87,7 @@ func TestIDFromTraces(t *testing.T) { wrongAttribute.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans().AppendEmpty().Attributes(). PutInt(uniqueIDAttrName, intID) _, err = idFromTraces(wrongAttribute) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, err.Error(), fmt.Sprintf("invalid data element, attribute %q is wrong type Int", uniqueIDAttrName)) } @@ -96,13 +97,13 @@ func TestIDFromLogs(t *testing.T) { validData := createLog(id) logID, err := idFromLogs(validData) assert.Equal(t, logID, id) - assert.NoError(t, err) + require.NoError(t, err) // Test case 2: Missing uniqueIDAttrName attribute invalidData := plog.NewLogs() invalidData.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty().Attributes() _, err = idFromLogs(invalidData) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, err.Error(), fmt.Sprintf("invalid data element, attribute %q is missing", uniqueIDAttrName)) // Test case 3: Wrong attribute type @@ -111,7 +112,7 @@ func TestIDFromLogs(t *testing.T) { wrongAttribute.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty().Attributes(). PutInt(uniqueIDAttrName, intID) _, err = idFromLogs(wrongAttribute) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, err.Error(), fmt.Sprintf("invalid data element, attribute %q is wrong type Int", uniqueIDAttrName)) } diff --git a/exporter/internal/common/factory_test.go b/exporter/internal/common/factory_test.go index 0509a4d91e3..4f59b26ebc3 100644 --- a/exporter/internal/common/factory_test.go +++ b/exporter/internal/common/factory_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/exporter/exportertest" @@ -19,18 +20,18 @@ func createDefaultConfig() component.Config { func TestCreateMetricsExporter(t *testing.T) { me, err := CreateMetricsExporter(context.Background(), exportertest.NewNopSettings(), createDefaultConfig(), &Common{}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, me) } func TestCreateTracesExporter(t *testing.T) { te, err := CreateTracesExporter(context.Background(), exportertest.NewNopSettings(), createDefaultConfig(), &Common{}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, te) } func TestCreateLogsExporter(t *testing.T) { te, err := CreateLogsExporter(context.Background(), exportertest.NewNopSettings(), createDefaultConfig(), &Common{}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, te) } diff --git a/exporter/internal/otlptext/logs_test.go b/exporter/internal/otlptext/logs_test.go index a1d15676d1a..e8e23709459 100644 --- a/exporter/internal/otlptext/logs_test.go +++ b/exporter/internal/otlptext/logs_test.go @@ -65,7 +65,7 @@ func TestLogsText(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := NewTextLogsMarshaler().MarshalLogs(tt.in) - assert.NoError(t, err) + require.NoError(t, err) out, err := os.ReadFile(filepath.Join("testdata", "logs", tt.out)) require.NoError(t, err) expected := strings.ReplaceAll(string(out), "\r", "") diff --git a/exporter/internal/otlptext/metrics_test.go b/exporter/internal/otlptext/metrics_test.go index b2772b17953..4e633756938 100644 --- a/exporter/internal/otlptext/metrics_test.go +++ b/exporter/internal/otlptext/metrics_test.go @@ -46,7 +46,7 @@ func TestMetricsText(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := NewTextMetricsMarshaler().MarshalMetrics(tt.in) - assert.NoError(t, err) + require.NoError(t, err) out, err := os.ReadFile(filepath.Join("testdata", "metrics", tt.out)) require.NoError(t, err) expected := strings.ReplaceAll(string(out), "\r", "") diff --git a/exporter/internal/otlptext/traces_test.go b/exporter/internal/otlptext/traces_test.go index 2c4b69280a1..454a2989f0f 100644 --- a/exporter/internal/otlptext/traces_test.go +++ b/exporter/internal/otlptext/traces_test.go @@ -37,7 +37,7 @@ func TestTracesText(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := NewTextTracesMarshaler().MarshalTraces(tt.in) - assert.NoError(t, err) + require.NoError(t, err) out, err := os.ReadFile(filepath.Join("testdata", "traces", tt.out)) require.NoError(t, err) expected := strings.ReplaceAll(string(out), "\r", "") diff --git a/exporter/internal/queue/bounded_memory_queue_test.go b/exporter/internal/queue/bounded_memory_queue_test.go index ae98dca41f1..3884a50cc84 100644 --- a/exporter/internal/queue/bounded_memory_queue_test.go +++ b/exporter/internal/queue/bounded_memory_queue_test.go @@ -23,7 +23,7 @@ import ( func TestBoundedQueue(t *testing.T) { q := NewBoundedMemoryQueue[string](MemoryQueueSettings[string]{Sizer: &RequestSizer[string]{}, Capacity: 1}) - assert.NoError(t, q.Offer(context.Background(), "a")) + require.NoError(t, q.Offer(context.Background(), "a")) numConsumed := 0 assert.True(t, q.Consume(func(_ context.Context, item string) error { @@ -35,11 +35,11 @@ func TestBoundedQueue(t *testing.T) { assert.Equal(t, 0, q.Size()) // produce two more items. The first one should be accepted, but not consumed. - assert.NoError(t, q.Offer(context.Background(), "b")) + require.NoError(t, q.Offer(context.Background(), "b")) assert.Equal(t, 1, q.Size()) // the second should be rejected since the queue is full - assert.ErrorIs(t, q.Offer(context.Background(), "c"), ErrQueueIsFull) + require.ErrorIs(t, q.Offer(context.Background(), "c"), ErrQueueIsFull) assert.Equal(t, 1, q.Size()) assert.True(t, q.Consume(func(_ context.Context, item string) error { @@ -50,7 +50,7 @@ func TestBoundedQueue(t *testing.T) { assert.Equal(t, 2, numConsumed) for _, toAddItem := range []string{"d", "e", "f"} { - assert.NoError(t, q.Offer(context.Background(), toAddItem)) + require.NoError(t, q.Offer(context.Background(), toAddItem)) assert.True(t, q.Consume(func(_ context.Context, item string) error { assert.Equal(t, toAddItem, item) numConsumed++ @@ -58,7 +58,7 @@ func TestBoundedQueue(t *testing.T) { })) } assert.Equal(t, 5, numConsumed) - assert.NoError(t, q.Shutdown(context.Background())) + require.NoError(t, q.Shutdown(context.Background())) assert.False(t, q.Consume(func(_ context.Context, item string) error { panic(item) })) @@ -75,7 +75,7 @@ func TestShutdownWhileNotEmpty(t *testing.T) { assert.NoError(t, q.Start(context.Background(), componenttest.NewNopHost())) for i := 0; i < 10; i++ { - assert.NoError(t, q.Offer(context.Background(), strconv.FormatInt(int64(i), 10))) + require.NoError(t, q.Offer(context.Background(), strconv.FormatInt(int64(i), 10))) } assert.NoError(t, q.Shutdown(context.Background())) @@ -150,9 +150,9 @@ func TestZeroSizeNoConsumers(t *testing.T) { q := NewBoundedMemoryQueue[string](MemoryQueueSettings[string]{Sizer: &RequestSizer[string]{}, Capacity: 0}) err := q.Start(context.Background(), componenttest.NewNopHost()) - assert.NoError(t, err) + require.NoError(t, err) - assert.ErrorIs(t, q.Offer(context.Background(), "a"), ErrQueueIsFull) // in process + require.ErrorIs(t, q.Offer(context.Background(), "a"), ErrQueueIsFull) // in process assert.NoError(t, q.Shutdown(context.Background())) } diff --git a/exporter/internal/queue/persistent_queue_test.go b/exporter/internal/queue/persistent_queue_test.go index 9742b464f3b..8c825e0d5cb 100644 --- a/exporter/internal/queue/persistent_queue_test.go +++ b/exporter/internal/queue/persistent_queue_test.go @@ -148,16 +148,16 @@ func TestPersistentQueue_FullCapacity(t *testing.T) { req := newTracesRequest(1, 10) // First request is picked by the consumer. Wait until the consumer is blocked on done. - assert.NoError(t, pq.Offer(context.Background(), req)) + require.NoError(t, pq.Offer(context.Background(), req)) start <- struct{}{} close(start) for i := 0; i < 10; i++ { result := pq.Offer(context.Background(), newTracesRequest(1, 10)) if i < 5 { - assert.NoError(t, result) + require.NoError(t, result) } else { - assert.ErrorIs(t, result, ErrQueueIsFull) + require.ErrorIs(t, result, ErrQueueIsFull) } } assert.Equal(t, 5*tt.sizeMultiplier, pq.Size()) @@ -219,7 +219,7 @@ func TestPersistentQueue_ConsumersProducers(t *testing.T) { }) for i := 0; i < c.numMessagesProduced; i++ { - assert.NoError(t, pq.Offer(context.Background(), req)) + require.NoError(t, pq.Offer(context.Background(), req)) } assert.Eventually(t, func() bool { @@ -309,10 +309,10 @@ func TestToStorageClient(t *testing.T) { // verify if tt.expectedError != nil { - assert.ErrorIs(t, err, tt.expectedError) + require.ErrorIs(t, err, tt.expectedError) assert.Nil(t, client) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, client) } }) @@ -327,7 +327,7 @@ func TestInvalidStorageExtensionType(t *testing.T) { extConfig := factory.CreateDefaultConfig() settings := extensiontest.NewNopSettings() extension, err := factory.CreateExtension(context.Background(), settings, extConfig) - assert.NoError(t, err) + require.NoError(t, err) var extensions = map[component.ID]component.Component{ storageID: extension, } @@ -338,7 +338,7 @@ func TestInvalidStorageExtensionType(t *testing.T) { client, err := toStorageClient(context.Background(), storageID, host, ownerID, component.DataTypeTraces) // we should get an error about the extension type - assert.ErrorIs(t, err, errWrongExtensionType) + require.ErrorIs(t, err, errWrongExtensionType) assert.Nil(t, client) } @@ -439,7 +439,7 @@ func TestPersistentQueue_CorruptedData(t *testing.T) { } // Cannot close until we corrupt the data because the - assert.NoError(t, ps.Shutdown(context.Background())) + require.NoError(t, ps.Shutdown(context.Background())) // Reload newPs := createTestPersistentQueueWithRequestsCapacity(t, ext, 1000) @@ -525,7 +525,7 @@ func TestPersistentQueueStartWithNonDispatched(t *testing.T) { require.Equal(t, 5, ps.Size()) return experr.NewShutdownErr(nil) })) - assert.NoError(t, ps.Shutdown(context.Background())) + require.NoError(t, ps.Shutdown(context.Background())) // Reload with extra capacity to make sure we re-enqueue in-progress items. newPs := createTestPersistentQueueWithRequestsCapacity(t, ext, 6) @@ -608,7 +608,7 @@ func TestPersistentQueue_PutCloseReadClose(t *testing.T) { assert.Equal(t, 2, ps.Size()) // TODO: Remove this, after the initialization writes the readIndex. _, _, _ = ps.getNextItem(context.Background()) - assert.NoError(t, ps.Shutdown(context.Background())) + require.NoError(t, ps.Shutdown(context.Background())) newPs := createTestPersistentQueueWithRequestsCapacity(t, ext, 1000) require.Equal(t, 2, newPs.Size()) @@ -733,12 +733,12 @@ func TestPersistentQueue_ShutdownWhileConsuming(t *testing.T) { assert.Equal(t, 0, ps.Size()) assert.False(t, ps.client.(*mockStorageClient).isClosed()) - assert.NoError(t, ps.Offer(context.Background(), newTracesRequest(5, 10))) + require.NoError(t, ps.Offer(context.Background(), newTracesRequest(5, 10))) _, onProcessingFinished, ok := ps.getNextItem(context.Background()) require.True(t, ok) assert.False(t, ps.client.(*mockStorageClient).isClosed()) - assert.NoError(t, ps.Shutdown(context.Background())) + require.NoError(t, ps.Shutdown(context.Background())) assert.False(t, ps.client.(*mockStorageClient).isClosed()) onProcessingFinished(nil) assert.True(t, ps.client.(*mockStorageClient).isClosed()) @@ -852,7 +852,7 @@ func TestPersistentQueue_ItemsCapacityUsageRestoredOnShutdown(t *testing.T) { assert.NoError(t, pq.Offer(context.Background(), newTracesRequest(2, 10))) assert.Equal(t, 100, pq.Size()) - assert.ErrorIs(t, pq.Offer(context.Background(), newTracesRequest(5, 5)), ErrQueueIsFull) + require.ErrorIs(t, pq.Offer(context.Background(), newTracesRequest(5, 5)), ErrQueueIsFull) assert.Equal(t, 100, pq.Size()) assert.True(t, pq.Consume(func(_ context.Context, traces tracesRequest) error { @@ -861,14 +861,14 @@ func TestPersistentQueue_ItemsCapacityUsageRestoredOnShutdown(t *testing.T) { })) assert.Equal(t, 60, pq.Size()) - assert.NoError(t, pq.Shutdown(context.Background())) + require.NoError(t, pq.Shutdown(context.Background())) newPQ := createTestPersistentQueueWithItemsCapacity(t, ext, 100) // The queue should be restored to the previous size. assert.Equal(t, 60, newPQ.Size()) - assert.NoError(t, newPQ.Offer(context.Background(), newTracesRequest(2, 5))) + require.NoError(t, newPQ.Offer(context.Background(), newTracesRequest(2, 5))) // Check the combined queue size. assert.Equal(t, 70, newPQ.Size()) @@ -906,14 +906,14 @@ func TestPersistentQueue_ItemsCapacityUsageIsNotPreserved(t *testing.T) { })) assert.Equal(t, 2, pq.Size()) - assert.NoError(t, pq.Shutdown(context.Background())) + require.NoError(t, pq.Shutdown(context.Background())) newPQ := createTestPersistentQueueWithItemsCapacity(t, ext, 100) // The queue items size cannot be restored, fall back to request-based size assert.Equal(t, 2, newPQ.Size()) - assert.NoError(t, newPQ.Offer(context.Background(), newTracesRequest(2, 5))) + require.NoError(t, newPQ.Offer(context.Background(), newTracesRequest(2, 5))) // Only new items are correctly reflected assert.Equal(t, 12, newPQ.Size()) @@ -933,7 +933,7 @@ func TestPersistentQueue_ItemsCapacityUsageIsNotPreserved(t *testing.T) { assert.Equal(t, 0, newPQ.Size()) // Adding another batch should update the size accordingly - assert.NoError(t, newPQ.Offer(context.Background(), newTracesRequest(5, 5))) + require.NoError(t, newPQ.Offer(context.Background(), newTracesRequest(5, 5))) assert.Equal(t, 25, newPQ.Size()) assert.True(t, newPQ.Consume(func(_ context.Context, traces tracesRequest) error { @@ -966,7 +966,7 @@ func TestPersistentQueue_RequestCapacityLessAfterRestart(t *testing.T) { })) assert.Equal(t, 3, pq.Size()) - assert.NoError(t, pq.Shutdown(context.Background())) + require.NoError(t, pq.Shutdown(context.Background())) // The queue is restarted with the less capacity than needed to restore the queued items, but with the same // underlying storage. No need to drop requests that are over capacity since they are already in the storage. @@ -976,7 +976,7 @@ func TestPersistentQueue_RequestCapacityLessAfterRestart(t *testing.T) { assert.Equal(t, 3, newPQ.Size()) // Queue is full - assert.Error(t, newPQ.Offer(context.Background(), newTracesRequest(2, 5))) + require.Error(t, newPQ.Offer(context.Background(), newTracesRequest(2, 5))) assert.True(t, newPQ.Consume(func(_ context.Context, traces tracesRequest) error { assert.Equal(t, 20, traces.traces.SpanCount()) @@ -985,7 +985,7 @@ func TestPersistentQueue_RequestCapacityLessAfterRestart(t *testing.T) { assert.Equal(t, 2, newPQ.Size()) // Still full - assert.Error(t, newPQ.Offer(context.Background(), newTracesRequest(2, 5))) + require.Error(t, newPQ.Offer(context.Background(), newTracesRequest(2, 5))) assert.True(t, newPQ.Consume(func(_ context.Context, traces tracesRequest) error { assert.Equal(t, 25, traces.traces.SpanCount()) @@ -1008,7 +1008,7 @@ func TestPersistentQueue_RestoredUsedSizeIsCorrectedOnDrain(t *testing.T) { assert.Equal(t, 0, pq.Size()) for i := 0; i < 6; i++ { - assert.NoError(t, pq.Offer(context.Background(), newTracesRequest(2, 5))) + require.NoError(t, pq.Offer(context.Background(), newTracesRequest(2, 5))) } assert.Equal(t, 60, pq.Size()) diff --git a/exporter/internal/queue/sized_channel_test.go b/exporter/internal/queue/sized_channel_test.go index 8d25510ff63..3aff98bff99 100644 --- a/exporter/internal/queue/sized_channel_test.go +++ b/exporter/internal/queue/sized_channel_test.go @@ -8,23 +8,24 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestSizedCapacityChannel(t *testing.T) { q := newSizedChannel[int](7, nil, 0) - assert.NoError(t, q.push(1, 1, nil)) + require.NoError(t, q.push(1, 1, nil)) assert.Equal(t, 1, q.Size()) assert.Equal(t, 7, q.Capacity()) // failed callback should not allow the element to be added - assert.Error(t, q.push(2, 2, func() error { return errors.New("failed") })) + require.Error(t, q.push(2, 2, func() error { return errors.New("failed") })) assert.Equal(t, 1, q.Size()) - assert.NoError(t, q.push(3, 3, nil)) + require.NoError(t, q.push(3, 3, nil)) assert.Equal(t, 4, q.Size()) // should not be able to send to the full queue - assert.Error(t, q.push(4, 4, nil)) + require.Error(t, q.push(4, 4, nil)) assert.Equal(t, 4, q.Size()) el, ok := q.pop(func(el int) int64 { return int64(el) }) @@ -45,10 +46,10 @@ func TestSizedCapacityChannel(t *testing.T) { func TestSizedCapacityChannel_Offer_sizedNotFullButChannelFull(t *testing.T) { q := newSizedChannel[int](1, nil, 0) - assert.NoError(t, q.push(1, 1, nil)) + require.NoError(t, q.push(1, 1, nil)) q.used.Store(0) err := q.push(1, 1, nil) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, ErrQueueIsFull, err) } diff --git a/exporter/loggingexporter/config_test.go b/exporter/loggingexporter/config_test.go index de9e769846e..6280113f981 100644 --- a/exporter/loggingexporter/config_test.go +++ b/exporter/loggingexporter/config_test.go @@ -19,7 +19,7 @@ import ( func TestUnmarshalDefaultConfig(t *testing.T) { factory := NewFactory() cfg := factory.CreateDefaultConfig() - assert.NoError(t, confmap.New().Unmarshal(&cfg)) + require.NoError(t, confmap.New().Unmarshal(&cfg)) assert.Equal(t, factory.CreateDefaultConfig(), cfg) } @@ -78,7 +78,7 @@ func TestUnmarshalConfig(t *testing.T) { if tt.expectedErr != "" { assert.ErrorContains(t, err, tt.expectedErr) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tt.cfg, cfg) } }) @@ -126,7 +126,7 @@ func Test_UnmarshalMarshalled(t *testing.T) { conf := confmap.New() err := conf.Marshal(tc.inCfg) - assert.NoError(t, err) + require.NoError(t, err) raw := conf.ToStringMap() @@ -137,11 +137,11 @@ func Test_UnmarshalMarshalled(t *testing.T) { err = conf.Unmarshal(outCfg) if tc.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tc.expectedConfig, outCfg) return } - assert.Error(t, err) + require.Error(t, err) assert.EqualError(t, err, tc.expectedErr) }) } diff --git a/exporter/loggingexporter/factory_test.go b/exporter/loggingexporter/factory_test.go index 173ee1ddd8c..2b35acddf3c 100644 --- a/exporter/loggingexporter/factory_test.go +++ b/exporter/loggingexporter/factory_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/component/componenttest" "go.opentelemetry.io/collector/exporter/exportertest" @@ -25,7 +26,7 @@ func TestCreateMetricsExporter(t *testing.T) { cfg := factory.CreateDefaultConfig() me, err := factory.CreateMetricsExporter(context.Background(), exportertest.NewNopSettings(), cfg) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, me) } @@ -34,7 +35,7 @@ func TestCreateTracesExporter(t *testing.T) { cfg := factory.CreateDefaultConfig() te, err := factory.CreateTracesExporter(context.Background(), exportertest.NewNopSettings(), cfg) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, te) } @@ -43,6 +44,6 @@ func TestCreateLogsExporter(t *testing.T) { cfg := factory.CreateDefaultConfig() te, err := factory.CreateLogsExporter(context.Background(), exportertest.NewNopSettings(), cfg) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, te) } diff --git a/exporter/otlpexporter/config_test.go b/exporter/otlpexporter/config_test.go index 32e3e9aa613..153f4215f5e 100644 --- a/exporter/otlpexporter/config_test.go +++ b/exporter/otlpexporter/config_test.go @@ -26,7 +26,7 @@ import ( func TestUnmarshalDefaultConfig(t *testing.T) { factory := NewFactory() cfg := factory.CreateDefaultConfig() - assert.NoError(t, confmap.New().Unmarshal(&cfg)) + require.NoError(t, confmap.New().Unmarshal(&cfg)) assert.Equal(t, factory.CreateDefaultConfig(), cfg) } @@ -35,7 +35,7 @@ func TestUnmarshalConfig(t *testing.T) { require.NoError(t, err) factory := NewFactory() cfg := factory.CreateDefaultConfig() - assert.NoError(t, cm.Unmarshal(&cfg)) + require.NoError(t, cm.Unmarshal(&cfg)) assert.Equal(t, &Config{ TimeoutConfig: exporterhelper.TimeoutConfig{ diff --git a/exporter/otlpexporter/factory_test.go b/exporter/otlpexporter/factory_test.go index 3c9722a27b0..921c9410131 100644 --- a/exporter/otlpexporter/factory_test.go +++ b/exporter/otlpexporter/factory_test.go @@ -27,7 +27,7 @@ func TestCreateDefaultConfig(t *testing.T) { factory := NewFactory() cfg := factory.CreateDefaultConfig() assert.NotNil(t, cfg, "failed to create default config") - assert.NoError(t, componenttest.CheckConfigStruct(cfg)) + require.NoError(t, componenttest.CheckConfigStruct(cfg)) ocfg, ok := factory.CreateDefaultConfig().(*Config) assert.True(t, ok) assert.Equal(t, configretry.NewDefaultBackOffConfig(), ocfg.RetryConfig) @@ -168,13 +168,13 @@ func TestCreateTracesExporter(t *testing.T) { factory := NewFactory() set := exportertest.NewNopSettings() consumer, err := factory.CreateTracesExporter(context.Background(), set, tt.config) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, consumer) err = consumer.Start(context.Background(), componenttest.NewNopHost()) if tt.mustFailOnStart { - assert.Error(t, err) + require.Error(t, err) } else { - assert.NoError(t, err) + require.NoError(t, err) } // Shutdown is called even when Start fails err = consumer.Shutdown(context.Background()) diff --git a/exporter/otlpexporter/otlp_test.go b/exporter/otlpexporter/otlp_test.go index 352720555a7..8953aee0e28 100644 --- a/exporter/otlpexporter/otlp_test.go +++ b/exporter/otlpexporter/otlp_test.go @@ -263,14 +263,14 @@ func TestSendTraces(t *testing.T) { }() host := componenttest.NewNopHost() - assert.NoError(t, exp.Start(context.Background(), host)) + require.NoError(t, exp.Start(context.Background(), host)) // Ensure that initially there is no data in the receiver. assert.EqualValues(t, 0, rcv.requestCount.Load()) // Send empty trace. td := ptrace.NewTraces() - assert.NoError(t, exp.ConsumeTraces(context.Background(), td)) + require.NoError(t, exp.ConsumeTraces(context.Background(), td)) // Wait until it is received. assert.Eventually(t, func() bool { @@ -284,7 +284,7 @@ func TestSendTraces(t *testing.T) { td = testdata.GenerateTraces(2) err = exp.ConsumeTraces(context.Background(), td) - assert.NoError(t, err) + require.NoError(t, err) // Wait until it is received. assert.Eventually(t, func() bool { @@ -317,7 +317,7 @@ func TestSendTraces(t *testing.T) { td = testdata.GenerateTraces(2) err = exp.ConsumeTraces(context.Background(), td) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, observed.FilterLevelExact(zap.WarnLevel).All(), 1) assert.Contains(t, observed.FilterLevelExact(zap.WarnLevel).All()[0].Message, "Partial success") } @@ -375,14 +375,14 @@ func TestSendTracesWhenEndpointHasHttpScheme(t *testing.T) { }() host := componenttest.NewNopHost() - assert.NoError(t, exp.Start(context.Background(), host)) + require.NoError(t, exp.Start(context.Background(), host)) // Ensure that initially there is no data in the receiver. assert.EqualValues(t, 0, rcv.requestCount.Load()) // Send empty trace. td := ptrace.NewTraces() - assert.NoError(t, exp.ConsumeTraces(context.Background(), td)) + require.NoError(t, exp.ConsumeTraces(context.Background(), td)) // Wait until it is received. assert.Eventually(t, func() bool { @@ -435,14 +435,14 @@ func TestSendMetrics(t *testing.T) { host := componenttest.NewNopHost() - assert.NoError(t, exp.Start(context.Background(), host)) + require.NoError(t, exp.Start(context.Background(), host)) // Ensure that initially there is no data in the receiver. assert.EqualValues(t, 0, rcv.requestCount.Load()) // Send empty metric. md := pmetric.NewMetrics() - assert.NoError(t, exp.ConsumeMetrics(context.Background(), md)) + require.NoError(t, exp.ConsumeMetrics(context.Background(), md)) // Wait until it is received. assert.Eventually(t, func() bool { @@ -456,7 +456,7 @@ func TestSendMetrics(t *testing.T) { md = testdata.GenerateMetrics(2) err = exp.ConsumeMetrics(context.Background(), md) - assert.NoError(t, err) + require.NoError(t, err) // Wait until it is received. assert.Eventually(t, func() bool { @@ -482,7 +482,7 @@ func TestSendMetrics(t *testing.T) { md = testdata.GenerateMetrics(2) err = exp.ConsumeMetrics(context.Background(), md) - assert.Error(t, err) + require.Error(t, err) rcv.setExportError(nil) @@ -498,7 +498,7 @@ func TestSendMetrics(t *testing.T) { // Send two metrics. md = testdata.GenerateMetrics(2) - assert.NoError(t, exp.ConsumeMetrics(context.Background(), md)) + require.NoError(t, exp.ConsumeMetrics(context.Background(), md)) assert.Len(t, observed.FilterLevelExact(zap.WarnLevel).All(), 1) assert.Contains(t, observed.FilterLevelExact(zap.WarnLevel).All()[0].Message, "Partial success") } @@ -533,24 +533,24 @@ func TestSendTraceDataServerDownAndUp(t *testing.T) { host := componenttest.NewNopHost() - assert.NoError(t, exp.Start(context.Background(), host)) + require.NoError(t, exp.Start(context.Background(), host)) // A trace with 2 spans. td := testdata.GenerateTraces(2) ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) - assert.Error(t, exp.ConsumeTraces(ctx, td)) + require.Error(t, exp.ConsumeTraces(ctx, td)) assert.EqualValues(t, context.DeadlineExceeded, ctx.Err()) cancel() ctx, cancel = context.WithTimeout(context.Background(), 1*time.Second) - assert.Error(t, exp.ConsumeTraces(ctx, td)) + require.Error(t, exp.ConsumeTraces(ctx, td)) assert.EqualValues(t, context.DeadlineExceeded, ctx.Err()) cancel() startServerAndMakeRequest(t, exp, td, ln) ctx, cancel = context.WithTimeout(context.Background(), 1*time.Second) - assert.Error(t, exp.ConsumeTraces(ctx, td)) + require.Error(t, exp.ConsumeTraces(ctx, td)) assert.EqualValues(t, context.DeadlineExceeded, ctx.Err()) cancel() @@ -561,7 +561,7 @@ func TestSendTraceDataServerDownAndUp(t *testing.T) { startServerAndMakeRequest(t, exp, td, ln) ctx, cancel = context.WithTimeout(context.Background(), 1*time.Second) - assert.Error(t, exp.ConsumeTraces(ctx, td)) + require.Error(t, exp.ConsumeTraces(ctx, td)) assert.EqualValues(t, context.DeadlineExceeded, ctx.Err()) cancel() } @@ -590,7 +590,7 @@ func TestSendTraceDataServerStartWhileRequest(t *testing.T) { host := componenttest.NewNopHost() - assert.NoError(t, exp.Start(context.Background(), host)) + require.NoError(t, exp.Start(context.Background(), host)) // A trace with 2 spans. td := testdata.GenerateTraces(2) @@ -610,7 +610,7 @@ func TestSendTraceDataServerStartWhileRequest(t *testing.T) { case <-ctx.Done(): t.Fail() case <-done: - assert.NoError(t, ctx.Err()) + require.NoError(t, ctx.Err()) } cancel() } @@ -641,12 +641,12 @@ func TestSendTracesOnResourceExhaustion(t *testing.T) { }() host := componenttest.NewNopHost() - assert.NoError(t, exp.Start(context.Background(), host)) + require.NoError(t, exp.Start(context.Background(), host)) assert.EqualValues(t, 0, rcv.requestCount.Load()) td := ptrace.NewTraces() - assert.NoError(t, exp.ConsumeTraces(context.Background(), td)) + require.NoError(t, exp.ConsumeTraces(context.Background(), td)) assert.Never(t, func() bool { return rcv.requestCount.Load() > 1 @@ -660,7 +660,7 @@ func TestSendTracesOnResourceExhaustion(t *testing.T) { }) rcv.setExportError(st.Err()) - assert.NoError(t, exp.ConsumeTraces(context.Background(), td)) + require.NoError(t, exp.ConsumeTraces(context.Background(), td)) assert.Eventually(t, func() bool { return rcv.requestCount.Load() > 1 @@ -679,7 +679,7 @@ func startServerAndMakeRequest(t *testing.T, exp exporter.Traces, td ptrace.Trac // Resend the request, this should succeed. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - assert.NoError(t, exp.ConsumeTraces(ctx, td)) + require.NoError(t, exp.ConsumeTraces(ctx, td)) cancel() // Wait until it is received. @@ -729,14 +729,14 @@ func TestSendLogData(t *testing.T) { host := componenttest.NewNopHost() - assert.NoError(t, exp.Start(context.Background(), host)) + require.NoError(t, exp.Start(context.Background(), host)) // Ensure that initially there is no data in the receiver. assert.EqualValues(t, 0, rcv.requestCount.Load()) // Send empty request. ld := plog.NewLogs() - assert.NoError(t, exp.ConsumeLogs(context.Background(), ld)) + require.NoError(t, exp.ConsumeLogs(context.Background(), ld)) // Wait until it is received. assert.Eventually(t, func() bool { @@ -750,7 +750,7 @@ func TestSendLogData(t *testing.T) { ld = testdata.GenerateLogs(2) err = exp.ConsumeLogs(context.Background(), ld) - assert.NoError(t, err) + require.NoError(t, err) // Wait until it is received. assert.Eventually(t, func() bool { @@ -773,7 +773,7 @@ func TestSendLogData(t *testing.T) { ld = testdata.GenerateLogs(2) err = exp.ConsumeLogs(context.Background(), ld) - assert.Error(t, err) + require.Error(t, err) rcv.setExportError(nil) @@ -791,7 +791,7 @@ func TestSendLogData(t *testing.T) { ld = testdata.GenerateLogs(2) err = exp.ConsumeLogs(context.Background(), ld) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, observed.FilterLevelExact(zap.WarnLevel).All(), 1) assert.Contains(t, observed.FilterLevelExact(zap.WarnLevel).All()[0].Message, "Partial success") } diff --git a/exporter/otlphttpexporter/config_test.go b/exporter/otlphttpexporter/config_test.go index 257f7e25389..a6a7e96ca8e 100644 --- a/exporter/otlphttpexporter/config_test.go +++ b/exporter/otlphttpexporter/config_test.go @@ -24,7 +24,7 @@ import ( func TestUnmarshalDefaultConfig(t *testing.T) { factory := NewFactory() cfg := factory.CreateDefaultConfig() - assert.NoError(t, confmap.New().Unmarshal(&cfg)) + require.NoError(t, confmap.New().Unmarshal(&cfg)) assert.Equal(t, factory.CreateDefaultConfig(), cfg) // Default/Empty config is invalid. assert.Error(t, component.ValidateConfig(cfg)) @@ -35,7 +35,7 @@ func TestUnmarshalConfig(t *testing.T) { require.NoError(t, err) factory := NewFactory() cfg := factory.CreateDefaultConfig() - assert.NoError(t, cm.Unmarshal(&cfg)) + require.NoError(t, cm.Unmarshal(&cfg)) assert.Equal(t, &Config{ RetryConfig: configretry.BackOffConfig{ @@ -122,7 +122,7 @@ func TestUnmarshalEncoding(t *testing.T) { if tt.shouldError { assert.Error(t, err) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tt.expected, encoding) } }) diff --git a/exporter/otlphttpexporter/factory_test.go b/exporter/otlphttpexporter/factory_test.go index 8964aeaf4b6..0aef54e96f6 100644 --- a/exporter/otlphttpexporter/factory_test.go +++ b/exporter/otlphttpexporter/factory_test.go @@ -25,7 +25,7 @@ func TestCreateDefaultConfig(t *testing.T) { factory := NewFactory() cfg := factory.CreateDefaultConfig() assert.NotNil(t, cfg, "failed to create default config") - assert.NoError(t, componenttest.CheckConfigStruct(cfg)) + require.NoError(t, componenttest.CheckConfigStruct(cfg)) ocfg, ok := factory.CreateDefaultConfig().(*Config) assert.True(t, ok) assert.Equal(t, "", ocfg.ClientConfig.Endpoint) @@ -181,11 +181,11 @@ func TestCreateTracesExporter(t *testing.T) { assert.Error(t, err) return } - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, consumer) err = consumer.Start(context.Background(), componenttest.NewNopHost()) if tt.mustFailOnStart { - assert.Error(t, err) + require.Error(t, err) } err = consumer.Shutdown(context.Background()) diff --git a/exporter/otlphttpexporter/otlp_test.go b/exporter/otlphttpexporter/otlp_test.go index 4d5099b9bbd..4d95f8f55c3 100644 --- a/exporter/otlphttpexporter/otlp_test.go +++ b/exporter/otlphttpexporter/otlp_test.go @@ -231,7 +231,7 @@ func TestErrorResponses(t *testing.T) { // generate traces traces := ptrace.NewTraces() err = exp.ConsumeTraces(context.Background(), traces) - assert.Error(t, err) + require.Error(t, err) if test.isPermErr { assert.True(t, consumererror.IsPermanent(err)) @@ -769,7 +769,7 @@ func TestPartialSuccess_longContentLengthHeader(t *testing.T) { // No real error happens for long content length, so the partial // success is handled as success with a warning. err = handlePartialSuccessResponse(resp, handler) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, observed.FilterLevelExact(zap.WarnLevel).All(), 1) assert.Contains(t, observed.FilterLevelExact(zap.WarnLevel).All()[0].Message, "Partial success") }) diff --git a/extension/auth/authtest/mock_clientauth_test.go b/extension/auth/authtest/mock_clientauth_test.go index 2797174095a..d844832269d 100644 --- a/extension/auth/authtest/mock_clientauth_test.go +++ b/extension/auth/authtest/mock_clientauth_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "google.golang.org/grpc/credentials" ) @@ -20,7 +21,7 @@ func TestNilStartAndShutdown(t *testing.T) { origCtx := context.Background() err := m.Start(origCtx, nil) - assert.NoError(t, err) + require.NoError(t, err) err = m.Shutdown(origCtx) assert.NoError(t, err) @@ -64,7 +65,7 @@ func TestMockRoundTripper(t *testing.T) { return } assert.NotNil(t, tripper) - assert.NoError(t, err) + require.NoError(t, err) // check if the resultant tripper is indeed the one provided _, ok := tripper.(*customRoundTripper) assert.True(t, ok) @@ -119,7 +120,7 @@ func TestMockPerRPCCredential(t *testing.T) { return } assert.NotNil(t, credential) - assert.NoError(t, err) + require.NoError(t, err) // check if the resultant tripper is indeed the one provided _, ok := credential.(*customPerRPCCredentials) assert.True(t, ok) diff --git a/extension/extension_test.go b/extension/extension_test.go index 2c6065cc60e..83932a1d054 100644 --- a/extension/extension_test.go +++ b/extension/extension_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/component" ) @@ -35,7 +36,7 @@ func TestNewFactory(t *testing.T) { assert.Equal(t, component.StabilityLevelDevelopment, factory.ExtensionStability()) ext, err := factory.CreateExtension(context.Background(), Settings{}, &defaultCfg) - assert.NoError(t, err) + require.NoError(t, err) assert.Same(t, nopExtensionInstance, ext) } @@ -69,7 +70,7 @@ func TestMakeFactoryMap(t *testing.T) { assert.Error(t, err) return } - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tt.out, out) }) } diff --git a/extension/memorylimiterextension/factory_test.go b/extension/memorylimiterextension/factory_test.go index 45bd06675aa..5c0acdc75a9 100644 --- a/extension/memorylimiterextension/factory_test.go +++ b/extension/memorylimiterextension/factory_test.go @@ -38,10 +38,10 @@ func TestCreateExtension(t *testing.T) { pCfg.CheckInterval = 100 * time.Millisecond tp, err := factory.CreateExtension(context.Background(), extensiontest.NewNopSettings(), cfg) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, tp) // test if we can shutdown a monitoring routine that has not started - assert.ErrorIs(t, tp.Shutdown(context.Background()), memorylimiter.ErrShutdownNotStarted) + require.ErrorIs(t, tp.Shutdown(context.Background()), memorylimiter.ErrShutdownNotStarted) assert.NoError(t, tp.Start(context.Background(), componenttest.NewNopHost())) assert.NoError(t, tp.Shutdown(context.Background())) diff --git a/extension/memorylimiterextension/memorylimiter_test.go b/extension/memorylimiterextension/memorylimiter_test.go index 2a63a497b08..96aa24e3ffe 100644 --- a/extension/memorylimiterextension/memorylimiter_test.go +++ b/extension/memorylimiterextension/memorylimiter_test.go @@ -10,6 +10,7 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.uber.org/zap" "go.opentelemetry.io/collector/component" @@ -82,7 +83,7 @@ func TestMemoryPressureResponse(t *testing.T) { if tt.expectError { assert.True(t, mustRefuse) } else { - assert.NoError(t, err) + require.NoError(t, err) } assert.NoError(t, ml.Shutdown(ctx)) }) diff --git a/extension/zpagesextension/config_test.go b/extension/zpagesextension/config_test.go index dd608aecbb3..cbbd324f008 100644 --- a/extension/zpagesextension/config_test.go +++ b/extension/zpagesextension/config_test.go @@ -18,7 +18,7 @@ import ( func TestUnmarshalDefaultConfig(t *testing.T) { factory := NewFactory() cfg := factory.CreateDefaultConfig() - assert.NoError(t, confmap.New().Unmarshal(&cfg)) + require.NoError(t, confmap.New().Unmarshal(&cfg)) assert.Equal(t, factory.CreateDefaultConfig(), cfg) } @@ -31,7 +31,7 @@ func TestUnmarshalConfig(t *testing.T) { require.NoError(t, err) factory := NewFactory() cfg := factory.CreateDefaultConfig() - assert.NoError(t, cm.Unmarshal(&cfg)) + require.NoError(t, cm.Unmarshal(&cfg)) assert.Equal(t, &Config{ ServerConfig: confighttp.ServerConfig{ diff --git a/extension/zpagesextension/factory_test.go b/extension/zpagesextension/factory_test.go index d4e66830ad1..0d851a98be6 100644 --- a/extension/zpagesextension/factory_test.go +++ b/extension/zpagesextension/factory_test.go @@ -25,7 +25,7 @@ func TestFactory_CreateDefaultConfig(t *testing.T) { }, cfg) - assert.NoError(t, componenttest.CheckConfigStruct(cfg)) + require.NoError(t, componenttest.CheckConfigStruct(cfg)) ext, err := createExtension(context.Background(), extensiontest.NewNopSettings(), cfg) require.NoError(t, err) require.NotNil(t, ext) diff --git a/featuregate/registry_test.go b/featuregate/registry_test.go index 47646721857..3dd0fb34f84 100644 --- a/featuregate/registry_test.go +++ b/featuregate/registry_test.go @@ -23,17 +23,17 @@ func TestRegistry(t *testing.T) { const id = "foo" g, err := r.Register(id, StageBeta, WithRegisterDescription("Test Gate")) - assert.NoError(t, err) + require.NoError(t, err) r.VisitAll(func(gate *Gate) { assert.Equal(t, id, gate.ID()) }) assert.True(t, g.IsEnabled()) - assert.NoError(t, r.Set(id, false)) + require.NoError(t, r.Set(id, false)) assert.False(t, g.IsEnabled()) _, err = r.Register(id, StageBeta) - assert.ErrorIs(t, err, ErrAlreadyRegistered) + require.ErrorIs(t, err, ErrAlreadyRegistered) assert.Panics(t, func() { r.MustRegister(id, StageBeta) }) @@ -41,20 +41,20 @@ func TestRegistry(t *testing.T) { func TestRegistryApplyError(t *testing.T) { r := NewRegistry() - assert.Error(t, r.Set("foo", true)) + require.Error(t, r.Set("foo", true)) r.MustRegister("bar", StageAlpha) - assert.Error(t, r.Set("foo", true)) + require.Error(t, r.Set("foo", true)) _, err := r.Register("foo", StageStable) - assert.Error(t, err) - assert.Error(t, r.Set("foo", true)) + require.Error(t, err) + require.Error(t, r.Set("foo", true)) r.MustRegister("foo", StageStable, WithRegisterToVersion("v1.0.0")) - assert.Error(t, r.Set("foo", false)) + require.Error(t, r.Set("foo", false)) - assert.Error(t, r.Set("deprecated", true)) + require.Error(t, r.Set("deprecated", true)) _, err = r.Register("deprecated", StageDeprecated) - assert.Error(t, err) - assert.Error(t, r.Set("deprecated", true)) + require.Error(t, err) + require.Error(t, r.Set("deprecated", true)) r.MustRegister("deprecated", StageDeprecated, WithRegisterToVersion("v1.0.0")) assert.Error(t, r.Set("deprecated", true)) } @@ -63,7 +63,7 @@ func TestRegistryApply(t *testing.T) { r := NewRegistry() fooGate := r.MustRegister("foo", StageAlpha, WithRegisterDescription("Test Gate")) assert.False(t, fooGate.IsEnabled()) - assert.NoError(t, r.Set(fooGate.ID(), true)) + require.NoError(t, r.Set(fooGate.ID(), true)) assert.True(t, fooGate.IsEnabled()) } @@ -195,7 +195,7 @@ func TestRegisterGateLifecycle(t *testing.T) { r.MustRegister("existing.gate", StageBeta) if tc.shouldErr { _, err := r.Register(tc.id, tc.stage, tc.opts...) - assert.Error(t, err) + require.Error(t, err) assert.Panics(t, func() { r.MustRegister(tc.id, tc.stage, tc.opts...) }) diff --git a/filter/config_test.go b/filter/config_test.go index c321580ed40..47269ccdd84 100644 --- a/filter/config_test.go +++ b/filter/config_test.go @@ -46,7 +46,7 @@ func TestConfig(t *testing.T) { assert.Equal(t, expCfg, actualCfg) for _, cfg := range actualCfg { - assert.NoError(t, cfg.Validate()) + require.NoError(t, cfg.Validate()) } fs := CreateFilter(actualCfg) assert.NotNil(t, fs) @@ -68,7 +68,7 @@ func TestMatches(t *testing.T) { } for _, c := range cfg { - assert.NoError(t, c.Validate()) + require.NoError(t, c.Validate()) } fs := CreateFilter(cfg) diff --git a/internal/cgroups/cgroups_test.go b/internal/cgroups/cgroups_test.go index b188a4d7ac4..1ead434f1d1 100644 --- a/internal/cgroups/cgroups_test.go +++ b/internal/cgroups/cgroups_test.go @@ -32,6 +32,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestNewCGroups(t *testing.T) { @@ -50,7 +51,7 @@ func TestNewCGroups(t *testing.T) { cgroups, err := NewCGroups(cgroupsProcMountInfoPath, cgroupsProcCGroupPath) assert.Equal(t, len(testTable), len(cgroups)) - assert.NoError(t, err) + require.NoError(t, err) for _, tt := range testTable { cgroup, exists := cgroups[tt.subsys] @@ -113,7 +114,7 @@ func TestCGroupsMemoryQuota(t *testing.T) { quota, defined, err := cgroups.MemoryQuota() assert.Equal(t, int64(-1), quota, "nonexistent") assert.False(t, defined, "nonexistent") - assert.NoError(t, err, "nonexistent") + require.NoError(t, err, "nonexistent") for _, tt := range testTable { cgroupPath := filepath.Join(testDataCGroupsPath, tt.name) @@ -209,7 +210,7 @@ func TestCGroupsMemoryQuotaV2(t *testing.T) { quota, defined, err := memoryQuotaV2("nonexistent", "nonexistent") assert.Equal(t, int64(-1), quota, "nonexistent") assert.False(t, defined, "nonexistent") - assert.NoError(t, err, "nonexistent") + require.NoError(t, err, "nonexistent") cgroupBasePath := filepath.Join(testDataCGroupsPath, "v2") for _, tt := range testTable { diff --git a/internal/cgroups/mountpoint_test.go b/internal/cgroups/mountpoint_test.go index 07f0d0ce3e6..d7c85c445e3 100644 --- a/internal/cgroups/mountpoint_test.go +++ b/internal/cgroups/mountpoint_test.go @@ -31,6 +31,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestNewMountPointFromLine(t *testing.T) { @@ -90,7 +91,7 @@ func TestNewMountPointFromLineErr(t *testing.T) { for i, line := range linesWithInvalidIDs { mountPoint, err := NewMountPointFromLine(line) assert.Nil(t, mountPoint, "[%d] %q", i, line) - assert.Error(t, err, line) + require.Error(t, err, line) } linesWithInvalidFields := []string{ @@ -115,7 +116,7 @@ func TestMountPointTranslate(t *testing.T) { cgroupMountPoint, err := NewMountPointFromLine(line) assert.NotNil(t, cgroupMountPoint) - assert.NoError(t, err) + require.NoError(t, err) testTable := []struct { name string @@ -151,7 +152,7 @@ func TestMountPointTranslateError(t *testing.T) { cgroupMountPoint, err := NewMountPointFromLine(line) assert.NotNil(t, cgroupMountPoint) - assert.NoError(t, err) + require.NoError(t, err) inaccessiblePaths := []string{ "/", diff --git a/internal/e2e/opaque_test.go b/internal/e2e/opaque_test.go index 550df79b17c..a2e62526f87 100644 --- a/internal/e2e/opaque_test.go +++ b/internal/e2e/opaque_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/config/configopaque" "go.opentelemetry.io/collector/confmap" @@ -24,7 +25,7 @@ var example = TestStruct{ func TestConfMapMarshalConfigOpaque(t *testing.T) { conf := confmap.New() - assert.NoError(t, conf.Marshal(example)) + require.NoError(t, conf.Marshal(example)) assert.Equal(t, "[REDACTED]", conf.Get("opaque")) assert.Equal(t, "plain", conf.Get("plain")) } diff --git a/internal/e2e/otlphttp_test.go b/internal/e2e/otlphttp_test.go index d7e0a6f6078..9a7e8ded972 100644 --- a/internal/e2e/otlphttp_test.go +++ b/internal/e2e/otlphttp_test.go @@ -62,7 +62,7 @@ func TestTraceNoBackend(t *testing.T) { func TestTraceInvalidUrl(t *testing.T) { exp := startTracesExporter(t, "http:/\\//this_is_an/*/invalid_url", "") td := testdata.GenerateTraces(1) - assert.Error(t, exp.ConsumeTraces(context.Background(), td)) + require.Error(t, exp.ConsumeTraces(context.Background(), td)) exp = startTracesExporter(t, "", "http:/\\//this_is_an/*/invalid_url") td = testdata.GenerateTraces(1) @@ -111,7 +111,7 @@ func TestTraceRoundTrip(t *testing.T) { exp := startTracesExporter(t, tt.baseURL, tt.overrideURL) td := testdata.GenerateTraces(1) - assert.NoError(t, exp.ConsumeTraces(context.Background(), td)) + require.NoError(t, exp.ConsumeTraces(context.Background(), td)) require.Eventually(t, func() bool { return sink.SpanCount() > 0 }, 1*time.Second, 10*time.Millisecond) @@ -164,7 +164,7 @@ func TestMetricsRoundTrip(t *testing.T) { exp := startMetricsExporter(t, tt.baseURL, tt.overrideURL) md := testdata.GenerateMetrics(1) - assert.NoError(t, exp.ConsumeMetrics(context.Background(), md)) + require.NoError(t, exp.ConsumeMetrics(context.Background(), md)) require.Eventually(t, func() bool { return sink.DataPointCount() > 0 }, 1*time.Second, 10*time.Millisecond) @@ -217,7 +217,7 @@ func TestLogsRoundTrip(t *testing.T) { exp := startLogsExporter(t, tt.baseURL, tt.overrideURL) md := testdata.GenerateLogs(1) - assert.NoError(t, exp.ConsumeLogs(context.Background(), md)) + require.NoError(t, exp.ConsumeLogs(context.Background(), md)) require.Eventually(t, func() bool { return sink.LogRecordCount() > 0 }, 1*time.Second, 10*time.Millisecond) diff --git a/internal/fanoutconsumer/logs_test.go b/internal/fanoutconsumer/logs_test.go index b7b4d510b4e..859250254b3 100644 --- a/internal/fanoutconsumer/logs_test.go +++ b/internal/fanoutconsumer/logs_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/consumer" "go.opentelemetry.io/collector/consumer/consumertest" @@ -221,7 +222,7 @@ func TestLogsWhenErrors(t *testing.T) { ld := testdata.GenerateLogs(1) for i := 0; i < 2; i++ { - assert.Error(t, lfc.ConsumeLogs(context.Background(), ld)) + require.Error(t, lfc.ConsumeLogs(context.Background(), ld)) } assert.Equal(t, ld, p3.AllLogs()[0]) diff --git a/internal/fanoutconsumer/metrics_test.go b/internal/fanoutconsumer/metrics_test.go index 2dad5e7ff26..a55882d087f 100644 --- a/internal/fanoutconsumer/metrics_test.go +++ b/internal/fanoutconsumer/metrics_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/consumer" "go.opentelemetry.io/collector/consumer/consumertest" @@ -221,7 +222,7 @@ func TestMetricsWhenErrors(t *testing.T) { md := testdata.GenerateMetrics(1) for i := 0; i < 2; i++ { - assert.Error(t, mfc.ConsumeMetrics(context.Background(), md)) + require.Error(t, mfc.ConsumeMetrics(context.Background(), md)) } assert.Equal(t, md, p3.AllMetrics()[0]) diff --git a/internal/fanoutconsumer/profiles_test.go b/internal/fanoutconsumer/profiles_test.go index 82915124194..58d01119f53 100644 --- a/internal/fanoutconsumer/profiles_test.go +++ b/internal/fanoutconsumer/profiles_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/consumer" "go.opentelemetry.io/collector/consumer/consumerprofiles" @@ -223,7 +224,7 @@ func TestProfilesWhenErrors(t *testing.T) { td := testdata.GenerateProfiles(1) for i := 0; i < 2; i++ { - assert.Error(t, tfc.ConsumeProfiles(context.Background(), td)) + require.Error(t, tfc.ConsumeProfiles(context.Background(), td)) } assert.Equal(t, td, p3.AllProfiles()[0]) diff --git a/internal/fanoutconsumer/traces_test.go b/internal/fanoutconsumer/traces_test.go index b17e674c46e..212a81a69bf 100644 --- a/internal/fanoutconsumer/traces_test.go +++ b/internal/fanoutconsumer/traces_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/consumer" "go.opentelemetry.io/collector/consumer/consumertest" @@ -222,7 +223,7 @@ func TestTracesWhenErrors(t *testing.T) { td := testdata.GenerateTraces(1) for i := 0; i < 2; i++ { - assert.Error(t, tfc.ConsumeTraces(context.Background(), td)) + require.Error(t, tfc.ConsumeTraces(context.Background(), td)) } assert.Equal(t, td, p3.AllTraces()[0]) diff --git a/internal/iruntime/mem_info_test.go b/internal/iruntime/mem_info_test.go index 57d0d857e66..05fc4bbcde8 100644 --- a/internal/iruntime/mem_info_test.go +++ b/internal/iruntime/mem_info_test.go @@ -7,10 +7,11 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestReadMemInfo(t *testing.T) { vmStat, err := readMemInfo() - assert.NoError(t, err) + require.NoError(t, err) assert.Positive(t, vmStat) } diff --git a/internal/sharedcomponent/sharedcomponent_test.go b/internal/sharedcomponent/sharedcomponent_test.go index 8b908f12586..4637b4a0d3a 100644 --- a/internal/sharedcomponent/sharedcomponent_test.go +++ b/internal/sharedcomponent/sharedcomponent_test.go @@ -38,7 +38,7 @@ func TestNewSharedComponentsCreateError(t *testing.T) { func() (*baseComponent, error) { return nil, myErr }, newNopTelemetrySettings(), ) - assert.ErrorIs(t, err, myErr) + require.ErrorIs(t, err, myErr) assert.Empty(t, comps.components) } @@ -64,7 +64,7 @@ func TestSharedComponentsLoadOrStore(t *testing.T) { assert.Same(t, got, gotSecond) // Shutdown nop will remove - assert.NoError(t, got.Shutdown(context.Background())) + require.NoError(t, got.Shutdown(context.Background())) assert.Empty(t, comps.components) gotThird, err := comps.LoadOrStore( id, @@ -99,13 +99,13 @@ func TestSharedComponent(t *testing.T) { assert.Equal(t, wantErr, got.Start(context.Background(), componenttest.NewNopHost())) assert.Equal(t, 1, calledStart) // Second time is not called anymore. - assert.NoError(t, got.Start(context.Background(), componenttest.NewNopHost())) + require.NoError(t, got.Start(context.Background(), componenttest.NewNopHost())) assert.Equal(t, 1, calledStart) // first time, shutdown is called. assert.Equal(t, wantErr, got.Shutdown(context.Background())) assert.Equal(t, 1, calledStop) // Second time is not called anymore. - assert.NoError(t, got.Shutdown(context.Background())) + require.NoError(t, got.Shutdown(context.Background())) assert.Equal(t, 1, calledStop) } diff --git a/otelcol/buffered_core_test.go b/otelcol/buffered_core_test.go index ee2d2c9133a..59977b22623 100644 --- a/otelcol/buffered_core_test.go +++ b/otelcol/buffered_core_test.go @@ -102,6 +102,6 @@ func Test_bufferedCore_TakeLogs(t *testing.T) { assert.Equal(t, expected, bc.TakeLogs()) assert.Nil(t, bc.logs) - assert.Error(t, bc.Write(e, fields)) + require.Error(t, bc.Write(e, fields)) assert.Nil(t, bc.TakeLogs()) } diff --git a/otelcol/collector_test.go b/otelcol/collector_test.go index 420db4ad414..7db8215eb39 100644 --- a/otelcol/collector_test.go +++ b/otelcol/collector_test.go @@ -165,7 +165,7 @@ func (e statusWatcherExtension) ComponentStatusChanged(source *componentstatus.I func TestComponentStatusWatcher(t *testing.T) { factories, err := nopFactories() - assert.NoError(t, err) + require.NoError(t, err) // Use a processor factory that creates "unhealthy" processor: one that // always reports StatusRecoverableError after successful Start. diff --git a/otelcol/internal/grpclog/logger_test.go b/otelcol/internal/grpclog/logger_test.go index 75d39d95368..bc9690a9ba5 100644 --- a/otelcol/internal/grpclog/logger_test.go +++ b/otelcol/internal/grpclog/logger_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.uber.org/zap" "go.uber.org/zap/zapcore" "google.golang.org/grpc/grpclog" @@ -65,7 +66,7 @@ func TestGRPCLogger(t *testing.T) { // create new collector zap logger logger, err := test.cfg.Build(hook) - assert.NoError(t, err) + require.NoError(t, err) // create GRPCLogger glogger := SetLogger(logger, test.cfg.Level.Level()) @@ -77,7 +78,7 @@ func TestGRPCLogger(t *testing.T) { assert.Equal(t, obsInfo, test.infoLogged) assert.Equal(t, obsWarn, test.warnLogged) // match the file name and line number of Warning() call above - assert.Contains(t, callerInfo, "internal/grpclog/logger_test.go:76") + assert.Contains(t, callerInfo, "internal/grpclog/logger_test.go:77") }) } } diff --git a/otelcol/otelcoltest/config_test.go b/otelcol/otelcoltest/config_test.go index 71502de536e..ba259ddc663 100644 --- a/otelcol/otelcoltest/config_test.go +++ b/otelcol/otelcoltest/config_test.go @@ -16,7 +16,7 @@ import ( func TestLoadConfig(t *testing.T) { factories, err := NopFactories() - assert.NoError(t, err) + require.NoError(t, err) cfg, err := LoadConfig(filepath.Join("testdata", "config.yaml"), factories) require.NoError(t, err) @@ -61,7 +61,7 @@ func TestLoadConfig(t *testing.T) { func TestLoadConfigAndValidate(t *testing.T) { factories, err := NopFactories() - assert.NoError(t, err) + require.NoError(t, err) cfgValidate, errValidate := LoadConfigAndValidate(filepath.Join("testdata", "config.yaml"), factories) require.NoError(t, errValidate) diff --git a/otelcol/unmarshaler_test.go b/otelcol/unmarshaler_test.go index 4810b5e5bb9..3885abc38dc 100644 --- a/otelcol/unmarshaler_test.go +++ b/otelcol/unmarshaler_test.go @@ -19,7 +19,7 @@ import ( func TestUnmarshalEmpty(t *testing.T) { factories, err := nopFactories() - assert.NoError(t, err) + require.NoError(t, err) _, err = unmarshal(confmap.New(), factories) assert.NoError(t, err) @@ -27,7 +27,7 @@ func TestUnmarshalEmpty(t *testing.T) { func TestUnmarshalEmptyAllSections(t *testing.T) { factories, err := nopFactories() - assert.NoError(t, err) + require.NoError(t, err) conf := confmap.NewFromStringMap(map[string]any{ "receivers": nil, @@ -38,7 +38,7 @@ func TestUnmarshalEmptyAllSections(t *testing.T) { "service": nil, }) cfg, err := unmarshal(conf, factories) - assert.NoError(t, err) + require.NoError(t, err) zapProdCfg := zap.NewProductionConfig() assert.Equal(t, telemetry.LogsConfig{ @@ -61,7 +61,7 @@ func TestUnmarshalEmptyAllSections(t *testing.T) { func TestUnmarshalUnknownTopLevel(t *testing.T) { factories, err := nopFactories() - assert.NoError(t, err) + require.NoError(t, err) conf := confmap.NewFromStringMap(map[string]any{ "unknown_section": nil, diff --git a/pdata/internal/data/profileid_test.go b/pdata/internal/data/profileid_test.go index c1107cfde46..1d09c6ac9b9 100644 --- a/pdata/internal/data/profileid_test.go +++ b/pdata/internal/data/profileid_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestProfileID(t *testing.T) { @@ -26,13 +27,13 @@ func TestProfileIDMarshal(t *testing.T) { tid := ProfileID([16]byte{}) n, err := tid.MarshalTo(buf) assert.EqualValues(t, 0, n) - assert.NoError(t, err) + require.NoError(t, err) tid = [16]byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78} n, err = tid.MarshalTo(buf) assert.EqualValues(t, 16, n) assert.EqualValues(t, []byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78}, buf[0:16]) - assert.NoError(t, err) + require.NoError(t, err) _, err = tid.MarshalTo(buf[0:1]) assert.Error(t, err) @@ -42,7 +43,7 @@ func TestProfileIDMarshalJSON(t *testing.T) { tid := ProfileID([16]byte{}) json, err := tid.MarshalJSON() assert.EqualValues(t, []byte(`""`), json) - assert.NoError(t, err) + require.NoError(t, err) tid = [16]byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78} json, err = tid.MarshalJSON() @@ -55,44 +56,44 @@ func TestProfileIDUnmarshal(t *testing.T) { tid := ProfileID{} err := tid.Unmarshal(buf[0:16]) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, buf, tid) err = tid.Unmarshal(buf[0:0]) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, [16]byte{}, tid) err = tid.Unmarshal(nil) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, [16]byte{}, tid) } func TestProfileIDUnmarshalJSON(t *testing.T) { tid := ProfileID([16]byte{}) err := tid.UnmarshalJSON([]byte(`""`)) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, [16]byte{}, tid) err = tid.UnmarshalJSON([]byte(`""""`)) - assert.Error(t, err) + require.Error(t, err) tidBytes := [16]byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78} err = tid.UnmarshalJSON([]byte(`"12345678123456781234567812345678"`)) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, tidBytes, tid) err = tid.UnmarshalJSON([]byte(`12345678123456781234567812345678`)) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, tidBytes, tid) err = tid.UnmarshalJSON([]byte(`"nothex"`)) - assert.Error(t, err) + require.Error(t, err) err = tid.UnmarshalJSON([]byte(`"1"`)) - assert.Error(t, err) + require.Error(t, err) err = tid.UnmarshalJSON([]byte(`"123"`)) - assert.Error(t, err) + require.Error(t, err) err = tid.UnmarshalJSON([]byte(`"`)) assert.Error(t, err) diff --git a/pdata/internal/data/spanid_test.go b/pdata/internal/data/spanid_test.go index a14287546d4..aa952097cb7 100644 --- a/pdata/internal/data/spanid_test.go +++ b/pdata/internal/data/spanid_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestSpanID(t *testing.T) { @@ -26,11 +27,11 @@ func TestSpanIDMarshal(t *testing.T) { sid := SpanID([8]byte{}) n, err := sid.MarshalTo(buf) assert.EqualValues(t, 0, n) - assert.NoError(t, err) + require.NoError(t, err) sid = [8]byte{1, 2, 3, 4, 5, 6, 7, 8} n, err = sid.MarshalTo(buf) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 8, n) assert.EqualValues(t, []byte{1, 2, 3, 4, 5, 6, 7, 8}, buf[0:8]) @@ -42,7 +43,7 @@ func TestSpanIDMarshalJSON(t *testing.T) { sid := SpanID([8]byte{}) json, err := sid.MarshalJSON() assert.EqualValues(t, []byte(`""`), json) - assert.NoError(t, err) + require.NoError(t, err) sid = [8]byte{0x12, 0x23, 0xAD, 0x12, 0x23, 0xAD, 0x12, 0x23} json, err = sid.MarshalJSON() @@ -55,15 +56,15 @@ func TestSpanIDUnmarshal(t *testing.T) { sid := SpanID{} err := sid.Unmarshal(buf[0:8]) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, [8]byte{0x12, 0x23, 0xAD, 0x12, 0x23, 0xAD, 0x12, 0x23}, sid) err = sid.Unmarshal(buf[0:0]) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, [8]byte{}, sid) err = sid.Unmarshal(nil) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, [8]byte{}, sid) err = sid.Unmarshal(buf[0:3]) @@ -73,25 +74,25 @@ func TestSpanIDUnmarshal(t *testing.T) { func TestSpanIDUnmarshalJSON(t *testing.T) { sid := SpanID{} err := sid.UnmarshalJSON([]byte(`""`)) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, [8]byte{}, sid) err = sid.UnmarshalJSON([]byte(`"1234567812345678"`)) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, [8]byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78}, sid) err = sid.UnmarshalJSON([]byte(`1234567812345678`)) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, [8]byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78}, sid) err = sid.UnmarshalJSON([]byte(`"nothex"`)) - assert.Error(t, err) + require.Error(t, err) err = sid.UnmarshalJSON([]byte(`"1"`)) - assert.Error(t, err) + require.Error(t, err) err = sid.UnmarshalJSON([]byte(`"123"`)) - assert.Error(t, err) + require.Error(t, err) err = sid.UnmarshalJSON([]byte(`"`)) assert.Error(t, err) diff --git a/pdata/internal/data/traceid_test.go b/pdata/internal/data/traceid_test.go index 467031d1cac..8a03d2f5271 100644 --- a/pdata/internal/data/traceid_test.go +++ b/pdata/internal/data/traceid_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestTraceID(t *testing.T) { @@ -26,13 +27,13 @@ func TestTraceIDMarshal(t *testing.T) { tid := TraceID([16]byte{}) n, err := tid.MarshalTo(buf) assert.EqualValues(t, 0, n) - assert.NoError(t, err) + require.NoError(t, err) tid = [16]byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78} n, err = tid.MarshalTo(buf) assert.EqualValues(t, 16, n) assert.EqualValues(t, []byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78}, buf[0:16]) - assert.NoError(t, err) + require.NoError(t, err) _, err = tid.MarshalTo(buf[0:1]) assert.Error(t, err) @@ -42,7 +43,7 @@ func TestTraceIDMarshalJSON(t *testing.T) { tid := TraceID([16]byte{}) json, err := tid.MarshalJSON() assert.EqualValues(t, []byte(`""`), json) - assert.NoError(t, err) + require.NoError(t, err) tid = [16]byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78} json, err = tid.MarshalJSON() @@ -55,44 +56,44 @@ func TestTraceIDUnmarshal(t *testing.T) { tid := TraceID{} err := tid.Unmarshal(buf[0:16]) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, buf, tid) err = tid.Unmarshal(buf[0:0]) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, [16]byte{}, tid) err = tid.Unmarshal(nil) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, [16]byte{}, tid) } func TestTraceIDUnmarshalJSON(t *testing.T) { tid := TraceID([16]byte{}) err := tid.UnmarshalJSON([]byte(`""`)) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, [16]byte{}, tid) err = tid.UnmarshalJSON([]byte(`""""`)) - assert.Error(t, err) + require.Error(t, err) tidBytes := [16]byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78} err = tid.UnmarshalJSON([]byte(`"12345678123456781234567812345678"`)) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, tidBytes, tid) err = tid.UnmarshalJSON([]byte(`12345678123456781234567812345678`)) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, tidBytes, tid) err = tid.UnmarshalJSON([]byte(`"nothex"`)) - assert.Error(t, err) + require.Error(t, err) err = tid.UnmarshalJSON([]byte(`"1"`)) - assert.Error(t, err) + require.Error(t, err) err = tid.UnmarshalJSON([]byte(`"123"`)) - assert.Error(t, err) + require.Error(t, err) err = tid.UnmarshalJSON([]byte(`"`)) assert.Error(t, err) diff --git a/pdata/internal/json/attribute_test.go b/pdata/internal/json/attribute_test.go index 8447534e888..fa355dbce38 100644 --- a/pdata/internal/json/attribute_test.go +++ b/pdata/internal/json/attribute_test.go @@ -8,6 +8,7 @@ import ( jsoniter "github.com/json-iterator/go" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" otlpcommon "go.opentelemetry.io/collector/pdata/internal/data/protogen/common/v1" ) @@ -151,7 +152,7 @@ func TestReadAttributeUnknownField(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) value := ReadAttribute(iter) // unknown fields should not be an error - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.EqualValues(t, otlpcommon.KeyValue{}, value) } @@ -162,7 +163,7 @@ func TestReadAttributeValueUnknownField(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) value := ReadAttribute(iter) // unknown fields should not be an error - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.EqualValues(t, otlpcommon.KeyValue{Key: "test"}, value) } @@ -172,7 +173,7 @@ func TestReadValueUnknownField(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) value := &otlpcommon.AnyValue{} ReadValue(iter, value) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.EqualValues(t, &otlpcommon.AnyValue{}, value) } @@ -192,7 +193,7 @@ func TestReadArrayUnknownField(t *testing.T) { iter := jsoniter.ConfigFastest.BorrowIterator([]byte(jsonStr)) defer jsoniter.ConfigFastest.ReturnIterator(iter) value := readArray(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.EqualValues(t, &otlpcommon.ArrayValue{}, value) } @@ -201,7 +202,7 @@ func TestReadKvlistValueUnknownField(t *testing.T) { iter := jsoniter.ConfigFastest.BorrowIterator([]byte(jsonStr)) defer jsoniter.ConfigFastest.ReturnIterator(iter) value := readKvlistValue(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.EqualValues(t, &otlpcommon.KeyValueList{}, value) } @@ -212,7 +213,7 @@ func TestReadArrayValueInvalidArrayValue(t *testing.T) { value := &otlpcommon.AnyValue{} ReadValue(iter, value) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.EqualValues(t, &otlpcommon.AnyValue{ Value: &otlpcommon.AnyValue_ArrayValue{ ArrayValue: &otlpcommon.ArrayValue{}, @@ -227,7 +228,7 @@ func TestReadKvlistValueInvalidArrayValue(t *testing.T) { value := &otlpcommon.AnyValue{} ReadValue(iter, value) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.EqualValues(t, &otlpcommon.AnyValue{ Value: &otlpcommon.AnyValue_KvlistValue{ KvlistValue: &otlpcommon.KeyValueList{}, diff --git a/pdata/internal/json/enum_test.go b/pdata/internal/json/enum_test.go index e2bbf99dd6a..138d7b221fe 100644 --- a/pdata/internal/json/enum_test.go +++ b/pdata/internal/json/enum_test.go @@ -8,6 +8,7 @@ import ( jsoniter "github.com/json-iterator/go" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestReadEnumValue(t *testing.T) { @@ -67,7 +68,7 @@ func TestReadEnumValue(t *testing.T) { assert.Error(t, iter.Error) return } - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, tt.want, val) }) } diff --git a/pdata/internal/json/number_test.go b/pdata/internal/json/number_test.go index d40df2d3db8..8d585263951 100644 --- a/pdata/internal/json/number_test.go +++ b/pdata/internal/json/number_test.go @@ -8,6 +8,7 @@ import ( jsoniter "github.com/json-iterator/go" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestReadInt32(t *testing.T) { @@ -57,7 +58,7 @@ func TestReadInt32(t *testing.T) { assert.Error(t, iter.Error) return } - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, tt.want, val) }) } @@ -110,7 +111,7 @@ func TestReadUint32(t *testing.T) { assert.Error(t, iter.Error) return } - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, tt.want, val) }) } @@ -163,7 +164,7 @@ func TestReadInt64(t *testing.T) { assert.Error(t, iter.Error) return } - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, tt.want, val) }) } @@ -216,7 +217,7 @@ func TestReadUint64(t *testing.T) { assert.Error(t, iter.Error) return } - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, tt.want, val) }) } @@ -269,7 +270,7 @@ func TestReadFloat64(t *testing.T) { assert.Error(t, iter.Error) return } - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.InDelta(t, tt.want, val, 0.01) }) } diff --git a/pdata/internal/json/resource_test.go b/pdata/internal/json/resource_test.go index 185696af2e9..71628a5cb45 100644 --- a/pdata/internal/json/resource_test.go +++ b/pdata/internal/json/resource_test.go @@ -8,6 +8,7 @@ import ( jsoniter "github.com/json-iterator/go" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" otlpcommon "go.opentelemetry.io/collector/pdata/internal/data/protogen/common/v1" otlpresource "go.opentelemetry.io/collector/pdata/internal/data/protogen/resource/v1" @@ -60,7 +61,7 @@ func TestReadResource(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) got := &otlpresource.Resource{} ReadResource(iter, got) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, tt.want, got) }) } diff --git a/pdata/internal/json/scope_test.go b/pdata/internal/json/scope_test.go index d872ce1bfa9..9b728501013 100644 --- a/pdata/internal/json/scope_test.go +++ b/pdata/internal/json/scope_test.go @@ -8,6 +8,7 @@ import ( jsoniter "github.com/json-iterator/go" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" otlpcommon "go.opentelemetry.io/collector/pdata/internal/data/protogen/common/v1" ) @@ -111,7 +112,7 @@ func TestReadScope(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) got := &otlpcommon.InstrumentationScope{} ReadScope(iter, got) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, tt.want, got) }) } diff --git a/pdata/pcommon/map_test.go b/pdata/pcommon/map_test.go index 5ea33b1d93a..eefef413b27 100644 --- a/pdata/pcommon/map_test.go +++ b/pdata/pcommon/map_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/pdata/internal" otlpcommon "go.opentelemetry.io/collector/pdata/internal/data/protogen/common/v1" @@ -305,7 +306,7 @@ func TestMap_Range(t *testing.T) { "k_empty": nil, } am := NewMap() - assert.NoError(t, am.FromRaw(rawMap)) + require.NoError(t, am.FromRaw(rawMap)) assert.Equal(t, 5, am.Len()) calls := 0 @@ -325,17 +326,17 @@ func TestMap_Range(t *testing.T) { func TestMap_FromRaw(t *testing.T) { am := NewMap() - assert.NoError(t, am.FromRaw(map[string]any{})) + require.NoError(t, am.FromRaw(map[string]any{})) assert.Equal(t, 0, am.Len()) am.PutEmpty("k") assert.Equal(t, 1, am.Len()) - assert.NoError(t, am.FromRaw(nil)) + require.NoError(t, am.FromRaw(nil)) assert.Equal(t, 0, am.Len()) am.PutEmpty("k") assert.Equal(t, 1, am.Len()) - assert.NoError(t, am.FromRaw(map[string]any{ + require.NoError(t, am.FromRaw(map[string]any{ "k_string": "123", "k_int": 123, "k_double": 1.23, diff --git a/pdata/pcommon/value_test.go b/pdata/pcommon/value_test.go index bc6b0b3e5fd..50e5dcce6c1 100644 --- a/pdata/pcommon/value_test.go +++ b/pdata/pcommon/value_test.go @@ -224,11 +224,11 @@ func TestNilOrigSetValue(t *testing.T) { assert.Equal(t, []byte{1, 2, 3}, av.Bytes().AsRaw()) av = NewValueEmpty() - assert.NoError(t, av.SetEmptyMap().FromRaw(map[string]any{"k": "v"})) + require.NoError(t, av.SetEmptyMap().FromRaw(map[string]any{"k": "v"})) assert.Equal(t, map[string]any{"k": "v"}, av.Map().AsRaw()) av = NewValueEmpty() - assert.NoError(t, av.SetEmptySlice().FromRaw([]any{int64(1), "val"})) + require.NoError(t, av.SetEmptySlice().FromRaw([]any{int64(1), "val"})) assert.Equal(t, []any{int64(1), "val"}, av.Slice().AsRaw()) } @@ -545,7 +545,7 @@ func TestNewValueFromRaw(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { actual := NewValueEmpty() - assert.NoError(t, actual.FromRaw(tt.input)) + require.NoError(t, actual.FromRaw(tt.input)) assert.Equal(t, tt.expected, actual) }) } diff --git a/pdata/plog/json_test.go b/pdata/plog/json_test.go index a69acf6a439..cf53853307a 100644 --- a/pdata/plog/json_test.go +++ b/pdata/plog/json_test.go @@ -48,10 +48,10 @@ var logsOTLP = func() Logs { func TestLogsJSON(t *testing.T) { encoder := &JSONMarshaler{} jsonBuf, err := encoder.MarshalLogs(logsOTLP) - assert.NoError(t, err) + require.NoError(t, err) decoder := &JSONUnmarshaler{} got, err := decoder.UnmarshalLogs(jsonBuf) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, logsOTLP, got) } @@ -60,14 +60,14 @@ var logsJSON = `{"resourceLogs":[{"resource":{"attributes":[{"key":"host.name"," func TestJSONUnmarshal(t *testing.T) { decoder := &JSONUnmarshaler{} got, err := decoder.UnmarshalLogs([]byte(logsJSON)) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, logsOTLP, got) } func TestJSONMarshal(t *testing.T) { encoder := &JSONMarshaler{} jsonBuf, err := encoder.MarshalLogs(logsOTLP) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, logsJSON, string(jsonBuf)) } @@ -84,7 +84,7 @@ func TestUnmarshalJsoniterLogsData(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewLogs() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewLogs(), val) } @@ -94,7 +94,7 @@ func TestUnmarshalJsoniterResourceLogs(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewResourceLogs() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewResourceLogs(), val) } @@ -104,7 +104,7 @@ func TestUnmarshalJsoniterScopeLogs(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewScopeLogs() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewScopeLogs(), val) } @@ -114,7 +114,7 @@ func TestUnmarshalJsoniterLogRecord(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewLogRecord() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewLogRecord(), val) } @@ -141,7 +141,7 @@ func BenchmarkJSONUnmarshal(b *testing.B) { encoder := &JSONMarshaler{} jsonBuf, err := encoder.MarshalLogs(logsOTLP) - assert.NoError(b, err) + require.NoError(b, err) decoder := &JSONUnmarshaler{} b.ResetTimer() diff --git a/pdata/plog/logs_test.go b/pdata/plog/logs_test.go index 9d3feef4d98..b47393a763b 100644 --- a/pdata/plog/logs_test.go +++ b/pdata/plog/logs_test.go @@ -9,6 +9,7 @@ import ( gogoproto "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" goproto "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/emptypb" @@ -84,23 +85,23 @@ func TestResourceLogsWireCompatibility(t *testing.T) { // Marshal its underlying ProtoBuf to wire. wire1, err := gogoproto.Marshal(logs.getOrig()) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, wire1) // Unmarshal from the wire to OTLP Protobuf in goproto's representation. var goprotoMessage emptypb.Empty err = goproto.Unmarshal(wire1, &goprotoMessage) - assert.NoError(t, err) + require.NoError(t, err) // Marshal to the wire again. wire2, err := goproto.Marshal(&goprotoMessage) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, wire2) // Unmarshal from the wire into gogoproto's representation. var gogoprotoRS2 otlpcollectorlog.ExportLogsServiceRequest err = gogoproto.Unmarshal(wire2, &gogoprotoRS2) - assert.NoError(t, err) + require.NoError(t, err) // Now compare that the original and final ProtoBuf messages are the same. // This proves that goproto and gogoproto marshaling/unmarshaling are wire compatible. diff --git a/pdata/plog/plogotlp/grpc_test.go b/pdata/plog/plogotlp/grpc_test.go index 95ce393db0e..7700888267c 100644 --- a/pdata/plog/plogotlp/grpc_test.go +++ b/pdata/plog/plogotlp/grpc_test.go @@ -43,7 +43,7 @@ func TestGrpc(t *testing.T) { return lis.Dial() }), grpc.WithTransportCredentials(insecure.NewCredentials())) - assert.NoError(t, err) + require.NoError(t, err) t.Cleanup(func() { assert.NoError(t, cc.Close()) }) @@ -51,7 +51,7 @@ func TestGrpc(t *testing.T) { logClient := NewGRPCClient(cc) resp, err := logClient.Export(context.Background(), generateLogsRequest()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, NewExportResponse(), resp) } @@ -75,7 +75,7 @@ func TestGrpcError(t *testing.T) { return lis.Dial() }), grpc.WithTransportCredentials(insecure.NewCredentials())) - assert.NoError(t, err) + require.NoError(t, err) t.Cleanup(func() { assert.NoError(t, cc.Close()) }) diff --git a/pdata/plog/plogotlp/request_test.go b/pdata/plog/plogotlp/request_test.go index 1a4acc62b97..5520d1ef021 100644 --- a/pdata/plog/plogotlp/request_test.go +++ b/pdata/plog/plogotlp/request_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var _ json.Unmarshaler = ExportRequest{} @@ -46,10 +47,10 @@ func TestRequestToPData(t *testing.T) { func TestRequestJSON(t *testing.T) { lr := NewExportRequest() - assert.NoError(t, lr.UnmarshalJSON(logsRequestJSON)) + require.NoError(t, lr.UnmarshalJSON(logsRequestJSON)) assert.Equal(t, "test_log_record", lr.Logs().ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().At(0).Body().AsString()) got, err := lr.MarshalJSON() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, strings.Join(strings.Fields(string(logsRequestJSON)), ""), string(got)) } diff --git a/pdata/plog/plogotlp/response_test.go b/pdata/plog/plogotlp/response_test.go index 1f3d343b251..9d26bf22192 100644 --- a/pdata/plog/plogotlp/response_test.go +++ b/pdata/plog/plogotlp/response_test.go @@ -9,6 +9,7 @@ import ( jsoniter "github.com/json-iterator/go" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var _ json.Unmarshaler = ExportResponse{} @@ -17,7 +18,7 @@ var _ json.Marshaler = ExportResponse{} func TestExportResponseJSON(t *testing.T) { jsonStr := `{"partialSuccess": {"rejectedLogRecords":1, "errorMessage":"nothing"}}` val := NewExportResponse() - assert.NoError(t, val.UnmarshalJSON([]byte(jsonStr))) + require.NoError(t, val.UnmarshalJSON([]byte(jsonStr))) expected := NewExportResponse() expected.PartialSuccess().SetRejectedLogRecords(1) expected.PartialSuccess().SetErrorMessage("nothing") @@ -27,7 +28,7 @@ func TestExportResponseJSON(t *testing.T) { func TestUnmarshalJSONExportResponse(t *testing.T) { jsonStr := `{"extra":"", "partialSuccess": {}}` val := NewExportResponse() - assert.NoError(t, val.UnmarshalJSON([]byte(jsonStr))) + require.NoError(t, val.UnmarshalJSON([]byte(jsonStr))) assert.Equal(t, NewExportResponse(), val) } @@ -37,6 +38,6 @@ func TestUnmarshalJsoniterExportPartialSuccess(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewExportPartialSuccess() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewExportPartialSuccess(), val) } diff --git a/pdata/pmetric/json_test.go b/pdata/pmetric/json_test.go index 552eee39edf..37934e68cfd 100644 --- a/pdata/pmetric/json_test.go +++ b/pdata/pmetric/json_test.go @@ -9,6 +9,7 @@ import ( jsoniter "github.com/json-iterator/go" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" otlpmetrics "go.opentelemetry.io/collector/pdata/internal/data/protogen/metrics/v1" "go.opentelemetry.io/collector/pdata/pcommon" @@ -32,11 +33,11 @@ var metricsJSON = `{"resourceMetrics":[{"resource":{"attributes":[{"key":"host.n func TestMetricsJSON(t *testing.T) { encoder := &JSONMarshaler{} jsonBuf, err := encoder.MarshalMetrics(metricsOTLP) - assert.NoError(t, err) + require.NoError(t, err) decoder := &JSONUnmarshaler{} got, err := decoder.UnmarshalMetrics(jsonBuf) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, metricsOTLP, got) } @@ -44,7 +45,7 @@ func TestMetricsJSON(t *testing.T) { func TestMetricsJSON_Marshal(t *testing.T) { encoder := &JSONMarshaler{} jsonBuf, err := encoder.MarshalMetrics(metricsOTLP) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, metricsJSON, string(jsonBuf)) } @@ -302,10 +303,10 @@ func Test_jsonUnmarshaler_UnmarshalMetrics(t *testing.T) { encoder := &JSONMarshaler{} m := tt.args.md() jsonBuf, err := encoder.MarshalMetrics(m) - assert.NoError(t, err) + require.NoError(t, err) decoder := JSONUnmarshaler{} got, err := decoder.UnmarshalMetrics(jsonBuf) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, m, got) }) } @@ -317,7 +318,7 @@ func TestUnmarshalJsoniterMetricsData(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewMetrics() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.EqualValues(t, NewMetrics(), val) } @@ -327,7 +328,7 @@ func TestUnmarshalJsoniterResourceMetrics(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewResourceMetrics() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.EqualValues(t, &otlpmetrics.ResourceMetrics{SchemaUrl: "schema"}, val.orig) } @@ -337,7 +338,7 @@ func TestUnmarshalJsoniterScopeMetrics(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewScopeMetrics() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.EqualValues(t, &otlpmetrics.ScopeMetrics{SchemaUrl: "schema"}, val.orig) } @@ -418,7 +419,7 @@ func TestUnmarshalJsoniterMetric(t *testing.T) { jsoniter.ConfigFastest.ReturnIterator(iter) val := NewMetric() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.EqualValues(t, tt.args.want, val.orig) } } @@ -429,7 +430,7 @@ func TestUnmarshalJsoniterNumberDataPoint(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewNumberDataPoint() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.EqualValues(t, NewNumberDataPoint(), val) } @@ -439,7 +440,7 @@ func TestUnmarshalJsoniterHistogramDataPoint(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewHistogramDataPoint() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.EqualValues(t, &otlpmetrics.HistogramDataPoint{Count: 3}, val.orig) } @@ -449,7 +450,7 @@ func TestUnmarshalJsoniterExponentialHistogramDataPoint(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewExponentialHistogramDataPoint() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.EqualValues(t, &otlpmetrics.ExponentialHistogramDataPoint{Count: 3}, val.orig) } @@ -459,7 +460,7 @@ func TestUnmarshalJsoniterExponentialHistogramDataPointBuckets(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewExponentialHistogramDataPointBuckets() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.EqualValues(t, &otlpmetrics.ExponentialHistogramDataPoint_Buckets{Offset: 3, BucketCounts: []uint64{1, 2}}, val.orig) } @@ -469,7 +470,7 @@ func TestUnmarshalJsoniterSummaryDataPoint(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewSummaryDataPoint() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.EqualValues(t, &otlpmetrics.SummaryDataPoint{ Count: 3, Sum: 3.14, @@ -482,7 +483,7 @@ func TestUnmarshalJsoniterQuantileValue(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewSummaryDataPointValueAtQuantile() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.EqualValues(t, &otlpmetrics.SummaryDataPoint_ValueAtQuantile{ Quantile: 0.314, Value: 3, @@ -551,6 +552,6 @@ func TestExemplar(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewExemplar() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.EqualValues(t, NewExemplar(), val) } diff --git a/pdata/pmetric/metrics_test.go b/pdata/pmetric/metrics_test.go index ad7977fb59c..6e4c5ff2c1d 100644 --- a/pdata/pmetric/metrics_test.go +++ b/pdata/pmetric/metrics_test.go @@ -9,6 +9,7 @@ import ( gogoproto "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" goproto "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/emptypb" @@ -35,23 +36,23 @@ func TestResourceMetricsWireCompatibility(t *testing.T) { // Marshal its underlying ProtoBuf to wire. wire1, err := gogoproto.Marshal(metrics.getOrig()) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, wire1) // Unmarshal from the wire to OTLP Protobuf in goproto's representation. var goprotoMessage emptypb.Empty err = goproto.Unmarshal(wire1, &goprotoMessage) - assert.NoError(t, err) + require.NoError(t, err) // Marshal to the wire again. wire2, err := goproto.Marshal(&goprotoMessage) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, wire2) // Unmarshal from the wire into gogoproto's representation. var gogoprotoRM otlpcollectormetrics.ExportMetricsServiceRequest err = gogoproto.Unmarshal(wire2, &gogoprotoRM) - assert.NoError(t, err) + require.NoError(t, err) // Now compare that the original and final ProtoBuf messages are the same. // This proves that goproto and gogoproto marshaling/unmarshaling are wire compatible. diff --git a/pdata/pmetric/pmetricotlp/grpc_test.go b/pdata/pmetric/pmetricotlp/grpc_test.go index e397f1d3e0c..f31c5b1cf89 100644 --- a/pdata/pmetric/pmetricotlp/grpc_test.go +++ b/pdata/pmetric/pmetricotlp/grpc_test.go @@ -43,7 +43,7 @@ func TestGrpc(t *testing.T) { return lis.Dial() }), grpc.WithTransportCredentials(insecure.NewCredentials())) - assert.NoError(t, err) + require.NoError(t, err) t.Cleanup(func() { assert.NoError(t, cc.Close()) }) @@ -51,7 +51,7 @@ func TestGrpc(t *testing.T) { logClient := NewGRPCClient(cc) resp, err := logClient.Export(context.Background(), generateMetricsRequest()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, NewExportResponse(), resp) } @@ -75,7 +75,7 @@ func TestGrpcError(t *testing.T) { return lis.Dial() }), grpc.WithTransportCredentials(insecure.NewCredentials())) - assert.NoError(t, err) + require.NoError(t, err) t.Cleanup(func() { assert.NoError(t, cc.Close()) }) diff --git a/pdata/pmetric/pmetricotlp/request_test.go b/pdata/pmetric/pmetricotlp/request_test.go index e125ef5fe61..d6fe9dbaa2f 100644 --- a/pdata/pmetric/pmetricotlp/request_test.go +++ b/pdata/pmetric/pmetricotlp/request_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var _ json.Unmarshaler = ExportRequest{} @@ -42,10 +43,10 @@ func TestRequestToPData(t *testing.T) { func TestRequestJSON(t *testing.T) { mr := NewExportRequest() - assert.NoError(t, mr.UnmarshalJSON(metricsRequestJSON)) + require.NoError(t, mr.UnmarshalJSON(metricsRequestJSON)) assert.Equal(t, "test_metric", mr.Metrics().ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0).Name()) got, err := mr.MarshalJSON() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, strings.Join(strings.Fields(string(metricsRequestJSON)), ""), string(got)) } diff --git a/pdata/pmetric/pmetricotlp/response_test.go b/pdata/pmetric/pmetricotlp/response_test.go index 04ccb438c5e..a8b689aacc9 100644 --- a/pdata/pmetric/pmetricotlp/response_test.go +++ b/pdata/pmetric/pmetricotlp/response_test.go @@ -9,6 +9,7 @@ import ( jsoniter "github.com/json-iterator/go" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var _ json.Unmarshaler = ExportResponse{} @@ -17,7 +18,7 @@ var _ json.Marshaler = ExportResponse{} func TestExportResponseJSON(t *testing.T) { jsonStr := `{"partialSuccess": {"rejectedDataPoints":1, "errorMessage":"nothing"}}` val := NewExportResponse() - assert.NoError(t, val.UnmarshalJSON([]byte(jsonStr))) + require.NoError(t, val.UnmarshalJSON([]byte(jsonStr))) expected := NewExportResponse() expected.PartialSuccess().SetRejectedDataPoints(1) expected.PartialSuccess().SetErrorMessage("nothing") @@ -27,7 +28,7 @@ func TestExportResponseJSON(t *testing.T) { func TestUnmarshalJSONExportResponse(t *testing.T) { jsonStr := `{"extra":"", "partialSuccess": {}}` val := NewExportResponse() - assert.NoError(t, val.UnmarshalJSON([]byte(jsonStr))) + require.NoError(t, val.UnmarshalJSON([]byte(jsonStr))) assert.Equal(t, NewExportResponse(), val) } @@ -37,6 +38,6 @@ func TestUnmarshalJsoniterExportPartialSuccess(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewExportPartialSuccess() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewExportPartialSuccess(), val) } diff --git a/pdata/pprofile/json_test.go b/pdata/pprofile/json_test.go index 08b59ea90d6..9978bb3a144 100644 --- a/pdata/pprofile/json_test.go +++ b/pdata/pprofile/json_test.go @@ -8,6 +8,7 @@ import ( jsoniter "github.com/json-iterator/go" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" otlpprofiles "go.opentelemetry.io/collector/pdata/internal/data/protogen/profiles/v1experimental" "go.opentelemetry.io/collector/pdata/pcommon" @@ -133,14 +134,14 @@ var profilesJSON = `{"resourceProfiles":[{"resource":{"attributes":[{"key":"host func TestJSONUnmarshal(t *testing.T) { decoder := &JSONUnmarshaler{} got, err := decoder.UnmarshalProfiles([]byte(profilesJSON)) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, profilesOTLP, got) } func TestJSONMarshal(t *testing.T) { encoder := &JSONMarshaler{} jsonBuf, err := encoder.MarshalProfiles(profilesOTLP) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, profilesJSON, string(jsonBuf)) } @@ -157,7 +158,7 @@ func TestUnmarshalJsoniterProfileData(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewProfiles() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, 1, val.ResourceProfiles().Len()) } @@ -177,7 +178,7 @@ func TestUnmarshalJsoniterResourceProfiles(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewResourceProfiles() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewResourceProfiles(), val) } @@ -187,7 +188,7 @@ func TestUnmarshalJsoniterScopeProfiles(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewScopeProfiles() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewScopeProfiles(), val) } @@ -197,7 +198,7 @@ func TestUnmarshalJsoniterProfile(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewProfile() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewProfile(), val) } @@ -207,7 +208,7 @@ func TestUnmarshalJsoniterValueType(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewValueType() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewValueType(), val) } @@ -217,7 +218,7 @@ func TestUnmarshalJsoniterSample(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewSample() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewSample(), val) } @@ -227,7 +228,7 @@ func TestUnmarshalJsoniterMapping(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewMapping() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewMapping(), val) } @@ -237,7 +238,7 @@ func TestUnmarshalJsoniterLocation(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewLocation() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewLocation(), val) } @@ -247,7 +248,7 @@ func TestUnmarshalJsoniterLine(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewLine() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewLine(), val) } @@ -257,7 +258,7 @@ func TestUnmarshalJsoniterFunction(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewFunction() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewFunction(), val) } @@ -267,7 +268,7 @@ func TestUnmarshalJsoniterAttributeUnit(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewAttributeUnit() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewAttributeUnit(), val) } @@ -277,7 +278,7 @@ func TestUnmarshalJsoniterLink(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewLink() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewLink(), val) } @@ -307,7 +308,7 @@ func TestUnmarshalJsoniterLabel(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewLabel() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewLabel(), val) } @@ -316,7 +317,7 @@ func BenchmarkJSONUnmarshal(b *testing.B) { encoder := &JSONMarshaler{} jsonBuf, err := encoder.MarshalProfiles(profilesOTLP) - assert.NoError(b, err) + require.NoError(b, err) decoder := &JSONUnmarshaler{} b.ResetTimer() diff --git a/pdata/pprofile/pprofileotlp/grpc_test.go b/pdata/pprofile/pprofileotlp/grpc_test.go index fb6bd922935..fb09ba2af7f 100644 --- a/pdata/pprofile/pprofileotlp/grpc_test.go +++ b/pdata/pprofile/pprofileotlp/grpc_test.go @@ -43,7 +43,7 @@ func TestGrpc(t *testing.T) { return lis.Dial() }), grpc.WithTransportCredentials(insecure.NewCredentials())) - assert.NoError(t, err) + require.NoError(t, err) t.Cleanup(func() { assert.NoError(t, cc.Close()) }) @@ -51,7 +51,7 @@ func TestGrpc(t *testing.T) { logClient := NewGRPCClient(cc) resp, err := logClient.Export(context.Background(), generateProfilesRequest()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, NewExportResponse(), resp) } @@ -75,7 +75,7 @@ func TestGrpcError(t *testing.T) { return lis.Dial() }), grpc.WithTransportCredentials(insecure.NewCredentials())) - assert.NoError(t, err) + require.NoError(t, err) t.Cleanup(func() { assert.NoError(t, cc.Close()) }) diff --git a/pdata/pprofile/pprofileotlp/request_test.go b/pdata/pprofile/pprofileotlp/request_test.go index c685346f5a7..49c19106c9e 100644 --- a/pdata/pprofile/pprofileotlp/request_test.go +++ b/pdata/pprofile/pprofileotlp/request_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var _ json.Unmarshaler = ExportRequest{} @@ -50,10 +51,10 @@ func TestRequestToPData(t *testing.T) { func TestRequestJSON(t *testing.T) { tr := NewExportRequest() - assert.NoError(t, tr.UnmarshalJSON(profilesRequestJSON)) + require.NoError(t, tr.UnmarshalJSON(profilesRequestJSON)) assert.Equal(t, uint64(42), tr.Profiles().ResourceProfiles().At(0).ScopeProfiles().At(0).Profiles().At(0).Profile().Sample().At(0).LocationsStartIndex()) got, err := tr.MarshalJSON() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, strings.Join(strings.Fields(string(profilesRequestJSON)), ""), string(got)) } diff --git a/pdata/pprofile/pprofileotlp/response_test.go b/pdata/pprofile/pprofileotlp/response_test.go index 485b3e33850..a7cede8fe9d 100644 --- a/pdata/pprofile/pprofileotlp/response_test.go +++ b/pdata/pprofile/pprofileotlp/response_test.go @@ -9,6 +9,7 @@ import ( jsoniter "github.com/json-iterator/go" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var _ json.Unmarshaler = ExportResponse{} @@ -17,7 +18,7 @@ var _ json.Marshaler = ExportResponse{} func TestExportResponseJSON(t *testing.T) { jsonStr := `{"partialSuccess": {"rejectedProfiles":1, "errorMessage":"nothing"}}` val := NewExportResponse() - assert.NoError(t, val.UnmarshalJSON([]byte(jsonStr))) + require.NoError(t, val.UnmarshalJSON([]byte(jsonStr))) expected := NewExportResponse() expected.PartialSuccess().SetRejectedProfiles(1) expected.PartialSuccess().SetErrorMessage("nothing") @@ -27,7 +28,7 @@ func TestExportResponseJSON(t *testing.T) { func TestUnmarshalJSONExportResponse(t *testing.T) { jsonStr := `{"extra":"", "partialSuccess": {}}` val := NewExportResponse() - assert.NoError(t, val.UnmarshalJSON([]byte(jsonStr))) + require.NoError(t, val.UnmarshalJSON([]byte(jsonStr))) assert.Equal(t, NewExportResponse(), val) } @@ -37,6 +38,6 @@ func TestUnmarshalJsoniterExportPartialSuccess(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewExportPartialSuccess() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewExportPartialSuccess(), val) } diff --git a/pdata/ptrace/json_test.go b/pdata/ptrace/json_test.go index 89eb8d3b17f..e0441760800 100644 --- a/pdata/ptrace/json_test.go +++ b/pdata/ptrace/json_test.go @@ -8,6 +8,7 @@ import ( jsoniter "github.com/json-iterator/go" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/pdata/pcommon" ) @@ -93,14 +94,14 @@ var tracesJSON = `{"resourceSpans":[{"resource":{"attributes":[{"key":"host.name func TestJSONUnmarshal(t *testing.T) { decoder := &JSONUnmarshaler{} got, err := decoder.UnmarshalTraces([]byte(tracesJSON)) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, tracesOTLP, got) } func TestJSONMarshal(t *testing.T) { encoder := &JSONMarshaler{} jsonBuf, err := encoder.MarshalTraces(tracesOTLP) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tracesJSON, string(jsonBuf)) } @@ -117,7 +118,7 @@ func TestUnmarshalJsoniterTraceData(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewTraces() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, 1, val.ResourceSpans().Len()) } @@ -127,7 +128,7 @@ func TestUnmarshalJsoniterResourceSpans(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewResourceSpans() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewResourceSpans(), val) } @@ -137,7 +138,7 @@ func TestUnmarshalJsoniterScopeSpans(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewScopeSpans() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewScopeSpans(), val) } @@ -147,7 +148,7 @@ func TestUnmarshalJsoniterSpan(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewSpan() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewSpan(), val) } @@ -187,7 +188,7 @@ func TestUnmarshalJsoniterSpanStatus(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewStatus() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewStatus(), val) } @@ -197,7 +198,7 @@ func TestUnmarshalJsoniterSpanLink(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewSpanLink() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewSpanLink(), val) } @@ -227,7 +228,7 @@ func TestUnmarshalJsoniterSpanEvent(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewSpanEvent() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewSpanEvent(), val) } @@ -236,7 +237,7 @@ func BenchmarkJSONUnmarshal(b *testing.B) { encoder := &JSONMarshaler{} jsonBuf, err := encoder.MarshalTraces(tracesOTLP) - assert.NoError(b, err) + require.NoError(b, err) decoder := &JSONUnmarshaler{} b.ResetTimer() diff --git a/pdata/ptrace/ptraceotlp/grpc_test.go b/pdata/ptrace/ptraceotlp/grpc_test.go index 2fee7aa5a05..2172245de61 100644 --- a/pdata/ptrace/ptraceotlp/grpc_test.go +++ b/pdata/ptrace/ptraceotlp/grpc_test.go @@ -43,7 +43,7 @@ func TestGrpc(t *testing.T) { return lis.Dial() }), grpc.WithTransportCredentials(insecure.NewCredentials())) - assert.NoError(t, err) + require.NoError(t, err) t.Cleanup(func() { assert.NoError(t, cc.Close()) }) @@ -51,7 +51,7 @@ func TestGrpc(t *testing.T) { logClient := NewGRPCClient(cc) resp, err := logClient.Export(context.Background(), generateTracesRequest()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, NewExportResponse(), resp) } @@ -75,7 +75,7 @@ func TestGrpcError(t *testing.T) { return lis.Dial() }), grpc.WithTransportCredentials(insecure.NewCredentials())) - assert.NoError(t, err) + require.NoError(t, err) t.Cleanup(func() { assert.NoError(t, cc.Close()) }) diff --git a/pdata/ptrace/ptraceotlp/request_test.go b/pdata/ptrace/ptraceotlp/request_test.go index be9530f5acd..444ae74b712 100644 --- a/pdata/ptrace/ptraceotlp/request_test.go +++ b/pdata/ptrace/ptraceotlp/request_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var _ json.Unmarshaler = ExportRequest{} @@ -46,10 +47,10 @@ func TestRequestToPData(t *testing.T) { func TestRequestJSON(t *testing.T) { tr := NewExportRequest() - assert.NoError(t, tr.UnmarshalJSON(tracesRequestJSON)) + require.NoError(t, tr.UnmarshalJSON(tracesRequestJSON)) assert.Equal(t, "test_span", tr.Traces().ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(0).Name()) got, err := tr.MarshalJSON() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, strings.Join(strings.Fields(string(tracesRequestJSON)), ""), string(got)) } diff --git a/pdata/ptrace/ptraceotlp/response_test.go b/pdata/ptrace/ptraceotlp/response_test.go index 9b2f4911ca3..c893557a075 100644 --- a/pdata/ptrace/ptraceotlp/response_test.go +++ b/pdata/ptrace/ptraceotlp/response_test.go @@ -9,6 +9,7 @@ import ( jsoniter "github.com/json-iterator/go" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var _ json.Unmarshaler = ExportResponse{} @@ -17,7 +18,7 @@ var _ json.Marshaler = ExportResponse{} func TestExportResponseJSON(t *testing.T) { jsonStr := `{"partialSuccess": {"rejectedSpans":1, "errorMessage":"nothing"}}` val := NewExportResponse() - assert.NoError(t, val.UnmarshalJSON([]byte(jsonStr))) + require.NoError(t, val.UnmarshalJSON([]byte(jsonStr))) expected := NewExportResponse() expected.PartialSuccess().SetRejectedSpans(1) expected.PartialSuccess().SetErrorMessage("nothing") @@ -27,7 +28,7 @@ func TestExportResponseJSON(t *testing.T) { func TestUnmarshalJSONExportResponse(t *testing.T) { jsonStr := `{"extra":"", "partialSuccess": {}}` val := NewExportResponse() - assert.NoError(t, val.UnmarshalJSON([]byte(jsonStr))) + require.NoError(t, val.UnmarshalJSON([]byte(jsonStr))) assert.Equal(t, NewExportResponse(), val) } @@ -37,6 +38,6 @@ func TestUnmarshalJsoniterExportPartialSuccess(t *testing.T) { defer jsoniter.ConfigFastest.ReturnIterator(iter) val := NewExportPartialSuccess() val.unmarshalJsoniter(iter) - assert.NoError(t, iter.Error) + require.NoError(t, iter.Error) assert.Equal(t, NewExportPartialSuccess(), val) } diff --git a/pdata/ptrace/traces_test.go b/pdata/ptrace/traces_test.go index 8884349485f..6ee1311dd7d 100644 --- a/pdata/ptrace/traces_test.go +++ b/pdata/ptrace/traces_test.go @@ -9,6 +9,7 @@ import ( gogoproto "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" goproto "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/emptypb" @@ -85,23 +86,23 @@ func TestResourceSpansWireCompatibility(t *testing.T) { // Marshal its underlying ProtoBuf to wire. wire1, err := gogoproto.Marshal(traces.getOrig()) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, wire1) // Unmarshal from the wire to OTLP Protobuf in goproto's representation. var goprotoMessage emptypb.Empty err = goproto.Unmarshal(wire1, &goprotoMessage) - assert.NoError(t, err) + require.NoError(t, err) // Marshal to the wire again. wire2, err := goproto.Marshal(&goprotoMessage) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, wire2) // Unmarshal from the wire into gogoproto's representation. var gogoprotoRS2 otlpcollectortrace.ExportTraceServiceRequest err = gogoproto.Unmarshal(wire2, &gogoprotoRS2) - assert.NoError(t, err) + require.NoError(t, err) // Now compare that the original and final ProtoBuf messages are the same. // This proves that goproto and gogoproto marshaling/unmarshaling are wire compatible. diff --git a/processor/batchprocessor/batch_processor_test.go b/processor/batchprocessor/batch_processor_test.go index 8647670a3c8..7f74df04332 100644 --- a/processor/batchprocessor/batch_processor_test.go +++ b/processor/batchprocessor/batch_processor_test.go @@ -100,7 +100,7 @@ func TestBatchProcessorSpansDelivered(t *testing.T) { spans.At(spanIndex).SetName(getTestSpanName(requestNum, spanIndex)) } td.ResourceSpans().At(0).CopyTo(sentResourceSpans.AppendEmpty()) - assert.NoError(t, batcher.ConsumeTraces(context.Background(), td)) + require.NoError(t, batcher.ConsumeTraces(context.Background(), td)) } // Added to test logic that check for empty resources. @@ -141,7 +141,7 @@ func TestBatchProcessorSpansDeliveredEnforceBatchSize(t *testing.T) { for spanIndex := 0; spanIndex < spansPerRequest; spanIndex++ { spans.At(spanIndex).SetName(getTestSpanName(requestNum, spanIndex)) } - assert.NoError(t, batcher.ConsumeTraces(context.Background(), td)) + require.NoError(t, batcher.ConsumeTraces(context.Background(), td)) } // Added to test logic that check for empty resources. @@ -188,7 +188,7 @@ func TestBatchProcessorSentBySize(t *testing.T) { for requestNum := 0; requestNum < requestCount; requestNum++ { td := testdata.GenerateTraces(spansPerRequest) - assert.NoError(t, batcher.ConsumeTraces(context.Background(), td)) + require.NoError(t, batcher.ConsumeTraces(context.Background(), td)) } require.NoError(t, batcher.Shutdown(context.Background())) @@ -310,7 +310,7 @@ func TestBatchProcessorSentBySizeWithMaxSize(t *testing.T) { sizeSum := 0 for requestNum := 0; requestNum < requestCount; requestNum++ { td := testdata.GenerateTraces(spansPerRequest) - assert.NoError(t, batcher.ConsumeTraces(context.Background(), td)) + require.NoError(t, batcher.ConsumeTraces(context.Background(), td)) } require.NoError(t, batcher.Shutdown(context.Background())) @@ -445,7 +445,7 @@ func TestBatchProcessorSentByTimeout(t *testing.T) { for requestNum := 0; requestNum < requestCount; requestNum++ { td := testdata.GenerateTraces(spansPerRequest) - assert.NoError(t, batcher.ConsumeTraces(context.Background(), td)) + require.NoError(t, batcher.ConsumeTraces(context.Background(), td)) } // Wait for at least one batch to be sent. @@ -494,7 +494,7 @@ func TestBatchProcessorTraceSendWhenClosing(t *testing.T) { spansPerRequest := 10 for requestNum := 0; requestNum < requestCount; requestNum++ { td := testdata.GenerateTraces(spansPerRequest) - assert.NoError(t, batcher.ConsumeTraces(context.Background(), td)) + require.NoError(t, batcher.ConsumeTraces(context.Background(), td)) } require.NoError(t, batcher.Shutdown(context.Background())) @@ -530,7 +530,7 @@ func TestBatchMetricProcessor_ReceivingData(t *testing.T) { metrics.At(metricIndex).SetName(getTestMetricName(requestNum, metricIndex)) } md.ResourceMetrics().At(0).CopyTo(sentResourceMetrics.AppendEmpty()) - assert.NoError(t, batcher.ConsumeMetrics(context.Background(), md)) + require.NoError(t, batcher.ConsumeMetrics(context.Background(), md)) } // Added to test case with empty resources sent. @@ -580,7 +580,7 @@ func TestBatchMetricProcessorBatchSize(t *testing.T) { for requestNum := 0; requestNum < requestCount; requestNum++ { md := testdata.GenerateMetrics(metricsPerRequest) size += sizer.MetricsSize(md) - assert.NoError(t, batcher.ConsumeMetrics(context.Background(), md)) + require.NoError(t, batcher.ConsumeMetrics(context.Background(), md)) } require.NoError(t, batcher.Shutdown(context.Background())) @@ -711,7 +711,7 @@ func TestBatchMetricsProcessor_Timeout(t *testing.T) { start := time.Now() for requestNum := 0; requestNum < requestCount; requestNum++ { md := testdata.GenerateMetrics(metricsPerRequest) - assert.NoError(t, batcher.ConsumeMetrics(context.Background(), md)) + require.NoError(t, batcher.ConsumeMetrics(context.Background(), md)) } // Wait for at least one batch to be sent. @@ -759,7 +759,7 @@ func TestBatchMetricProcessor_Shutdown(t *testing.T) { for requestNum := 0; requestNum < requestCount; requestNum++ { md := testdata.GenerateMetrics(metricsPerRequest) - assert.NoError(t, batcher.ConsumeMetrics(context.Background(), md)) + require.NoError(t, batcher.ConsumeMetrics(context.Background(), md)) } require.NoError(t, batcher.Shutdown(context.Background())) @@ -912,7 +912,7 @@ func TestBatchLogProcessor_ReceivingData(t *testing.T) { logs.At(logIndex).SetSeverityText(getTestLogSeverityText(requestNum, logIndex)) } ld.ResourceLogs().At(0).CopyTo(sentResourceLogs.AppendEmpty()) - assert.NoError(t, batcher.ConsumeLogs(context.Background(), ld)) + require.NoError(t, batcher.ConsumeLogs(context.Background(), ld)) } // Added to test case with empty resources sent. @@ -960,7 +960,7 @@ func TestBatchLogProcessor_BatchSize(t *testing.T) { for requestNum := 0; requestNum < requestCount; requestNum++ { ld := testdata.GenerateLogs(logsPerRequest) size += sizer.LogsSize(ld) - assert.NoError(t, batcher.ConsumeLogs(context.Background(), ld)) + require.NoError(t, batcher.ConsumeLogs(context.Background(), ld)) } require.NoError(t, batcher.Shutdown(context.Background())) @@ -1072,7 +1072,7 @@ func TestBatchLogsProcessor_Timeout(t *testing.T) { start := time.Now() for requestNum := 0; requestNum < requestCount; requestNum++ { ld := testdata.GenerateLogs(logsPerRequest) - assert.NoError(t, batcher.ConsumeLogs(context.Background(), ld)) + require.NoError(t, batcher.ConsumeLogs(context.Background(), ld)) } // Wait for at least one batch to be sent. @@ -1120,7 +1120,7 @@ func TestBatchLogProcessor_Shutdown(t *testing.T) { for requestNum := 0; requestNum < requestCount; requestNum++ { ld := testdata.GenerateLogs(logsPerRequest) - assert.NoError(t, batcher.ConsumeLogs(context.Background(), ld)) + require.NoError(t, batcher.ConsumeLogs(context.Background(), ld)) } require.NoError(t, batcher.Shutdown(context.Background())) @@ -1242,7 +1242,7 @@ func TestBatchProcessorSpansBatchedByMetadata(t *testing.T) { // use round-robin to assign context. num := requestNum % len(callCtxs) expectByContext[num] += spansPerRequest - assert.NoError(t, batcher.ConsumeTraces(callCtxs[num], td)) + require.NoError(t, batcher.ConsumeTraces(callCtxs[num], td)) } require.NoError(t, batcher.Shutdown(context.Background())) @@ -1299,7 +1299,7 @@ func TestBatchProcessorMetadataCardinalityLimit(t *testing.T) { }), }) - assert.NoError(t, batcher.ConsumeTraces(ctx, td)) + require.NoError(t, batcher.ConsumeTraces(ctx, td)) } td := testdata.GenerateTraces(1) @@ -1310,7 +1310,7 @@ func TestBatchProcessorMetadataCardinalityLimit(t *testing.T) { }) err = batcher.ConsumeTraces(ctx, td) - assert.Error(t, err) + require.Error(t, err) assert.True(t, consumererror.IsPermanent(err)) assert.Contains(t, err.Error(), "too many") @@ -1339,7 +1339,7 @@ func TestBatchZeroConfig(t *testing.T) { cnt := logsPerRequest + requestNum expect += cnt ld := testdata.GenerateLogs(cnt) - assert.NoError(t, batcher.ConsumeLogs(context.Background(), ld)) + require.NoError(t, batcher.ConsumeLogs(context.Background(), ld)) } // Wait for all batches. @@ -1377,7 +1377,7 @@ func TestBatchSplitOnly(t *testing.T) { for requestNum := 0; requestNum < requestCount; requestNum++ { ld := testdata.GenerateLogs(logsPerRequest) - assert.NoError(t, batcher.ConsumeLogs(context.Background(), ld)) + require.NoError(t, batcher.ConsumeLogs(context.Background(), ld)) } // Wait for all batches. diff --git a/processor/batchprocessor/config_test.go b/processor/batchprocessor/config_test.go index c5d3f693f92..38bb1e0c39b 100644 --- a/processor/batchprocessor/config_test.go +++ b/processor/batchprocessor/config_test.go @@ -18,7 +18,7 @@ import ( func TestUnmarshalDefaultConfig(t *testing.T) { factory := NewFactory() cfg := factory.CreateDefaultConfig() - assert.NoError(t, confmap.New().Unmarshal(&cfg)) + require.NoError(t, confmap.New().Unmarshal(&cfg)) assert.Equal(t, factory.CreateDefaultConfig(), cfg) } @@ -27,7 +27,7 @@ func TestUnmarshalConfig(t *testing.T) { require.NoError(t, err) factory := NewFactory() cfg := factory.CreateDefaultConfig() - assert.NoError(t, cm.Unmarshal(&cfg)) + require.NoError(t, cm.Unmarshal(&cfg)) assert.Equal(t, &Config{ SendBatchSize: uint32(10000), diff --git a/processor/memorylimiterprocessor/factory_test.go b/processor/memorylimiterprocessor/factory_test.go index f63d27a381e..2502fa5b1ef 100644 --- a/processor/memorylimiterprocessor/factory_test.go +++ b/processor/memorylimiterprocessor/factory_test.go @@ -39,19 +39,19 @@ func TestCreateProcessor(t *testing.T) { pCfg.CheckInterval = 100 * time.Millisecond tp, err := factory.CreateTracesProcessor(context.Background(), processortest.NewNopSettings(), cfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, tp) // test if we can shutdown a monitoring routine that has not started - assert.ErrorIs(t, tp.Shutdown(context.Background()), memorylimiter.ErrShutdownNotStarted) - assert.NoError(t, tp.Start(context.Background(), componenttest.NewNopHost())) + require.ErrorIs(t, tp.Shutdown(context.Background()), memorylimiter.ErrShutdownNotStarted) + require.NoError(t, tp.Start(context.Background(), componenttest.NewNopHost())) mp, err := factory.CreateMetricsProcessor(context.Background(), processortest.NewNopSettings(), cfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, mp) - assert.NoError(t, mp.Start(context.Background(), componenttest.NewNopHost())) + require.NoError(t, mp.Start(context.Background(), componenttest.NewNopHost())) lp, err := factory.CreateLogsProcessor(context.Background(), processortest.NewNopSettings(), cfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, lp) assert.NoError(t, lp.Start(context.Background(), componenttest.NewNopHost())) @@ -59,7 +59,7 @@ func TestCreateProcessor(t *testing.T) { assert.NoError(t, tp.Shutdown(context.Background())) assert.NoError(t, mp.Shutdown(context.Background())) // verify that no monitoring routine is running - assert.ErrorIs(t, tp.Shutdown(context.Background()), memorylimiter.ErrShutdownNotStarted) + require.ErrorIs(t, tp.Shutdown(context.Background()), memorylimiter.ErrShutdownNotStarted) // start and shutdown a new monitoring routine assert.NoError(t, lp.Start(context.Background(), componenttest.NewNopHost())) diff --git a/processor/memorylimiterprocessor/memorylimiter_test.go b/processor/memorylimiterprocessor/memorylimiter_test.go index a09c31e1ff0..9794b7dcd4b 100644 --- a/processor/memorylimiterprocessor/memorylimiter_test.go +++ b/processor/memorylimiterprocessor/memorylimiter_test.go @@ -193,7 +193,7 @@ func TestMetricsMemoryPressureResponse(t *testing.T) { if tt.expectError { assert.Equal(t, memorylimiter.ErrDataRefused, err) } else { - assert.NoError(t, err) + require.NoError(t, err) } assert.NoError(t, mp.Shutdown(ctx)) }) @@ -283,7 +283,7 @@ func TestTraceMemoryPressureResponse(t *testing.T) { if tt.expectError { assert.Equal(t, memorylimiter.ErrDataRefused, err) } else { - assert.NoError(t, err) + require.NoError(t, err) } assert.NoError(t, tp.Shutdown(ctx)) }) @@ -373,7 +373,7 @@ func TestLogMemoryPressureResponse(t *testing.T) { if tt.expectError { assert.Equal(t, memorylimiter.ErrDataRefused, err) } else { - assert.NoError(t, err) + require.NoError(t, err) } assert.NoError(t, tp.Shutdown(ctx)) }) diff --git a/processor/processor_test.go b/processor/processor_test.go index ea131f442b0..1d2c17c17e5 100644 --- a/processor/processor_test.go +++ b/processor/processor_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/consumer" @@ -23,9 +24,9 @@ func TestNewFactory(t *testing.T) { assert.EqualValues(t, testType, factory.Type()) assert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig()) _, err := factory.CreateTracesProcessor(context.Background(), Settings{}, &defaultCfg, consumertest.NewNop()) - assert.Error(t, err) + require.Error(t, err) _, err = factory.CreateMetricsProcessor(context.Background(), Settings{}, &defaultCfg, consumertest.NewNop()) - assert.Error(t, err) + require.Error(t, err) _, err = factory.CreateLogsProcessor(context.Background(), Settings{}, &defaultCfg, consumertest.NewNop()) assert.Error(t, err) } @@ -44,11 +45,11 @@ func TestNewFactoryWithOptions(t *testing.T) { assert.Equal(t, component.StabilityLevelAlpha, factory.TracesProcessorStability()) _, err := factory.CreateTracesProcessor(context.Background(), Settings{}, &defaultCfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelBeta, factory.MetricsProcessorStability()) _, err = factory.CreateMetricsProcessor(context.Background(), Settings{}, &defaultCfg, consumertest.NewNop()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelUnmaintained, factory.LogsProcessorStability()) _, err = factory.CreateLogsProcessor(context.Background(), Settings{}, &defaultCfg, consumertest.NewNop()) @@ -86,7 +87,7 @@ func TestMakeFactoryMap(t *testing.T) { assert.Error(t, err) return } - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tt.out, out) }) } diff --git a/processor/processorhelper/logs_test.go b/processor/processorhelper/logs_test.go index 0b65813ec79..1fe5bb7098d 100644 --- a/processor/processorhelper/logs_test.go +++ b/processor/processorhelper/logs_test.go @@ -39,7 +39,7 @@ func TestNewLogsProcessor_WithOptions(t *testing.T) { WithStart(func(context.Context, component.Host) error { return want }), WithShutdown(func(context.Context) error { return want }), WithCapabilities(consumer.Capabilities{MutatesData: false})) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, want, lp.Start(context.Background(), componenttest.NewNopHost())) assert.Equal(t, want, lp.Shutdown(context.Background())) diff --git a/processor/processorhelper/metrics_test.go b/processor/processorhelper/metrics_test.go index bdb077d54f6..90293dd0354 100644 --- a/processor/processorhelper/metrics_test.go +++ b/processor/processorhelper/metrics_test.go @@ -39,7 +39,7 @@ func TestNewMetricsProcessor_WithOptions(t *testing.T) { WithStart(func(context.Context, component.Host) error { return want }), WithShutdown(func(context.Context) error { return want }), WithCapabilities(consumer.Capabilities{MutatesData: false})) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, want, mp.Start(context.Background(), componenttest.NewNopHost())) assert.Equal(t, want, mp.Shutdown(context.Background())) diff --git a/processor/processorhelper/obsreport_test.go b/processor/processorhelper/obsreport_test.go index 6b8aa846e8c..4a3cb25507f 100644 --- a/processor/processorhelper/obsreport_test.go +++ b/processor/processorhelper/obsreport_test.go @@ -110,23 +110,23 @@ func TestCheckProcessorTracesViews(t *testing.T) { ProcessorID: processorID, ProcessorCreateSettings: processor.Settings{ID: processorID, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, }) - assert.NoError(t, err) + require.NoError(t, err) por.TracesAccepted(context.Background(), 7) por.TracesRefused(context.Background(), 8) por.TracesDropped(context.Background(), 9) - assert.NoError(t, tt.CheckProcessorTraces(7, 8, 9)) - assert.Error(t, tt.CheckProcessorTraces(0, 0, 0)) - assert.Error(t, tt.CheckProcessorTraces(7, 0, 0)) - assert.Error(t, tt.CheckProcessorTraces(0, 8, 0)) - assert.Error(t, tt.CheckProcessorTraces(0, 0, 9)) - assert.Error(t, tt.CheckProcessorTraces(0, 0, 0)) - assert.Error(t, tt.CheckProcessorTraces(7, 8, 0)) - assert.Error(t, tt.CheckProcessorTraces(7, 0, 9)) - assert.Error(t, tt.CheckProcessorTraces(7, 0, 0)) - assert.Error(t, tt.CheckProcessorTraces(0, 8, 9)) - assert.Error(t, tt.CheckProcessorTraces(0, 8, 0)) + require.NoError(t, tt.CheckProcessorTraces(7, 8, 9)) + require.Error(t, tt.CheckProcessorTraces(0, 0, 0)) + require.Error(t, tt.CheckProcessorTraces(7, 0, 0)) + require.Error(t, tt.CheckProcessorTraces(0, 8, 0)) + require.Error(t, tt.CheckProcessorTraces(0, 0, 9)) + require.Error(t, tt.CheckProcessorTraces(0, 0, 0)) + require.Error(t, tt.CheckProcessorTraces(7, 8, 0)) + require.Error(t, tt.CheckProcessorTraces(7, 0, 9)) + require.Error(t, tt.CheckProcessorTraces(7, 0, 0)) + require.Error(t, tt.CheckProcessorTraces(0, 8, 9)) + require.Error(t, tt.CheckProcessorTraces(0, 8, 0)) assert.Error(t, tt.CheckProcessorTraces(0, 0, 9)) } @@ -139,23 +139,23 @@ func TestCheckProcessorMetricsViews(t *testing.T) { ProcessorID: processorID, ProcessorCreateSettings: processor.Settings{ID: processorID, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, }) - assert.NoError(t, err) + require.NoError(t, err) por.MetricsAccepted(context.Background(), 7) por.MetricsRefused(context.Background(), 8) por.MetricsDropped(context.Background(), 9) - assert.NoError(t, tt.CheckProcessorMetrics(7, 8, 9)) - assert.Error(t, tt.CheckProcessorMetrics(0, 0, 0)) - assert.Error(t, tt.CheckProcessorMetrics(7, 0, 0)) - assert.Error(t, tt.CheckProcessorMetrics(0, 8, 0)) - assert.Error(t, tt.CheckProcessorMetrics(0, 0, 9)) - assert.Error(t, tt.CheckProcessorMetrics(0, 0, 0)) - assert.Error(t, tt.CheckProcessorMetrics(7, 8, 0)) - assert.Error(t, tt.CheckProcessorMetrics(7, 0, 9)) - assert.Error(t, tt.CheckProcessorMetrics(7, 0, 0)) - assert.Error(t, tt.CheckProcessorMetrics(0, 8, 9)) - assert.Error(t, tt.CheckProcessorMetrics(0, 8, 0)) + require.NoError(t, tt.CheckProcessorMetrics(7, 8, 9)) + require.Error(t, tt.CheckProcessorMetrics(0, 0, 0)) + require.Error(t, tt.CheckProcessorMetrics(7, 0, 0)) + require.Error(t, tt.CheckProcessorMetrics(0, 8, 0)) + require.Error(t, tt.CheckProcessorMetrics(0, 0, 9)) + require.Error(t, tt.CheckProcessorMetrics(0, 0, 0)) + require.Error(t, tt.CheckProcessorMetrics(7, 8, 0)) + require.Error(t, tt.CheckProcessorMetrics(7, 0, 9)) + require.Error(t, tt.CheckProcessorMetrics(7, 0, 0)) + require.Error(t, tt.CheckProcessorMetrics(0, 8, 9)) + require.Error(t, tt.CheckProcessorMetrics(0, 8, 0)) assert.Error(t, tt.CheckProcessorMetrics(0, 0, 9)) } @@ -168,23 +168,23 @@ func TestCheckProcessorLogViews(t *testing.T) { ProcessorID: processorID, ProcessorCreateSettings: processor.Settings{ID: processorID, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, }) - assert.NoError(t, err) + require.NoError(t, err) por.LogsAccepted(context.Background(), 7) por.LogsRefused(context.Background(), 8) por.LogsDropped(context.Background(), 9) - assert.NoError(t, tt.CheckProcessorLogs(7, 8, 9)) - assert.Error(t, tt.CheckProcessorLogs(0, 0, 0)) - assert.Error(t, tt.CheckProcessorLogs(7, 0, 0)) - assert.Error(t, tt.CheckProcessorLogs(0, 8, 0)) - assert.Error(t, tt.CheckProcessorLogs(0, 0, 9)) - assert.Error(t, tt.CheckProcessorLogs(0, 0, 0)) - assert.Error(t, tt.CheckProcessorLogs(7, 8, 0)) - assert.Error(t, tt.CheckProcessorLogs(7, 0, 9)) - assert.Error(t, tt.CheckProcessorLogs(7, 0, 0)) - assert.Error(t, tt.CheckProcessorLogs(0, 8, 9)) - assert.Error(t, tt.CheckProcessorLogs(0, 8, 0)) + require.NoError(t, tt.CheckProcessorLogs(7, 8, 9)) + require.Error(t, tt.CheckProcessorLogs(0, 0, 0)) + require.Error(t, tt.CheckProcessorLogs(7, 0, 0)) + require.Error(t, tt.CheckProcessorLogs(0, 8, 0)) + require.Error(t, tt.CheckProcessorLogs(0, 0, 9)) + require.Error(t, tt.CheckProcessorLogs(0, 0, 0)) + require.Error(t, tt.CheckProcessorLogs(7, 8, 0)) + require.Error(t, tt.CheckProcessorLogs(7, 0, 9)) + require.Error(t, tt.CheckProcessorLogs(7, 0, 0)) + require.Error(t, tt.CheckProcessorLogs(0, 8, 9)) + require.Error(t, tt.CheckProcessorLogs(0, 8, 0)) assert.Error(t, tt.CheckProcessorLogs(0, 0, 9)) } @@ -204,7 +204,7 @@ func TestNoMetrics(t *testing.T) { ProcessorID: processorID, ProcessorCreateSettings: processor.Settings{ID: processorID, TelemetrySettings: set, BuildInfo: component.NewDefaultBuildInfo()}, }) - assert.NoError(t, err) + require.NoError(t, err) por.TracesAccepted(context.Background(), accepted) por.TracesRefused(context.Background(), refused) @@ -226,7 +226,7 @@ func TestNoMetrics(t *testing.T) { ProcessorID: processorID, ProcessorCreateSettings: processor.Settings{ID: processorID, TelemetrySettings: set, BuildInfo: component.NewDefaultBuildInfo()}, }) - assert.NoError(t, err) + require.NoError(t, err) por.MetricsAccepted(context.Background(), accepted) por.MetricsRefused(context.Background(), refused) @@ -248,7 +248,7 @@ func TestNoMetrics(t *testing.T) { ProcessorID: processorID, ProcessorCreateSettings: processor.Settings{ID: processorID, TelemetrySettings: set, BuildInfo: component.NewDefaultBuildInfo()}, }) - assert.NoError(t, err) + require.NoError(t, err) por.LogsAccepted(context.Background(), accepted) por.LogsRefused(context.Background(), refused) diff --git a/processor/processorhelper/traces_test.go b/processor/processorhelper/traces_test.go index ab7c12ca9a0..74fbea2ed88 100644 --- a/processor/processorhelper/traces_test.go +++ b/processor/processorhelper/traces_test.go @@ -39,7 +39,7 @@ func TestNewTracesProcessor_WithOptions(t *testing.T) { WithStart(func(context.Context, component.Host) error { return want }), WithShutdown(func(context.Context) error { return want }), WithCapabilities(consumer.Capabilities{MutatesData: false})) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, want, tp.Start(context.Background(), componenttest.NewNopHost())) assert.Equal(t, want, tp.Shutdown(context.Background())) diff --git a/receiver/otlpreceiver/config_test.go b/receiver/otlpreceiver/config_test.go index b9c2349ae96..2b67125c15d 100644 --- a/receiver/otlpreceiver/config_test.go +++ b/receiver/otlpreceiver/config_test.go @@ -26,7 +26,7 @@ func TestUnmarshalDefaultConfig(t *testing.T) { require.NoError(t, err) factory := NewFactory() cfg := factory.CreateDefaultConfig() - assert.NoError(t, cm.Unmarshal(&cfg)) + require.NoError(t, cm.Unmarshal(&cfg)) assert.Equal(t, factory.CreateDefaultConfig(), cfg) } @@ -35,7 +35,7 @@ func TestUnmarshalConfigOnlyGRPC(t *testing.T) { require.NoError(t, err) factory := NewFactory() cfg := factory.CreateDefaultConfig() - assert.NoError(t, cm.Unmarshal(&cfg)) + require.NoError(t, cm.Unmarshal(&cfg)) defaultOnlyGRPC := factory.CreateDefaultConfig().(*Config) defaultOnlyGRPC.HTTP = nil @@ -47,7 +47,7 @@ func TestUnmarshalConfigOnlyHTTP(t *testing.T) { require.NoError(t, err) factory := NewFactory() cfg := factory.CreateDefaultConfig() - assert.NoError(t, cm.Unmarshal(&cfg)) + require.NoError(t, cm.Unmarshal(&cfg)) defaultOnlyHTTP := factory.CreateDefaultConfig().(*Config) defaultOnlyHTTP.GRPC = nil @@ -59,7 +59,7 @@ func TestUnmarshalConfigOnlyHTTPNull(t *testing.T) { require.NoError(t, err) factory := NewFactory() cfg := factory.CreateDefaultConfig() - assert.NoError(t, cm.Unmarshal(&cfg)) + require.NoError(t, cm.Unmarshal(&cfg)) defaultOnlyHTTP := factory.CreateDefaultConfig().(*Config) defaultOnlyHTTP.GRPC = nil @@ -71,7 +71,7 @@ func TestUnmarshalConfigOnlyHTTPEmptyMap(t *testing.T) { require.NoError(t, err) factory := NewFactory() cfg := factory.CreateDefaultConfig() - assert.NoError(t, cm.Unmarshal(&cfg)) + require.NoError(t, cm.Unmarshal(&cfg)) defaultOnlyHTTP := factory.CreateDefaultConfig().(*Config) defaultOnlyHTTP.GRPC = nil @@ -83,7 +83,7 @@ func TestUnmarshalConfig(t *testing.T) { require.NoError(t, err) factory := NewFactory() cfg := factory.CreateDefaultConfig() - assert.NoError(t, cm.Unmarshal(&cfg)) + require.NoError(t, cm.Unmarshal(&cfg)) assert.Equal(t, &Config{ Protocols: Protocols{ @@ -149,7 +149,7 @@ func TestUnmarshalConfigUnix(t *testing.T) { require.NoError(t, err) factory := NewFactory() cfg := factory.CreateDefaultConfig() - assert.NoError(t, cm.Unmarshal(&cfg)) + require.NoError(t, cm.Unmarshal(&cfg)) assert.Equal(t, &Config{ Protocols: Protocols{ @@ -193,7 +193,7 @@ func TestUnmarshalConfigEmptyProtocols(t *testing.T) { require.NoError(t, err) factory := NewFactory() cfg := factory.CreateDefaultConfig() - assert.NoError(t, cm.Unmarshal(&cfg)) + require.NoError(t, cm.Unmarshal(&cfg)) assert.EqualError(t, component.ValidateConfig(cfg), "must specify at least one protocol when using the OTLP receiver") } @@ -230,6 +230,6 @@ func TestUnmarshalConfigInvalidSignalPath(t *testing.T) { func TestUnmarshalConfigEmpty(t *testing.T) { factory := NewFactory() cfg := factory.CreateDefaultConfig() - assert.NoError(t, confmap.New().Unmarshal(&cfg)) + require.NoError(t, confmap.New().Unmarshal(&cfg)) assert.EqualError(t, component.ValidateConfig(cfg), "must specify at least one protocol when using the OTLP receiver") } diff --git a/receiver/otlpreceiver/factory_test.go b/receiver/otlpreceiver/factory_test.go index a4e2f6d999c..c77b19514b0 100644 --- a/receiver/otlpreceiver/factory_test.go +++ b/receiver/otlpreceiver/factory_test.go @@ -37,19 +37,19 @@ func TestCreateSameReceiver(t *testing.T) { creationSet := receivertest.NewNopSettings() tReceiver, err := factory.CreateTracesReceiver(context.Background(), creationSet, cfg, consumertest.NewNop()) assert.NotNil(t, tReceiver) - assert.NoError(t, err) + require.NoError(t, err) mReceiver, err := factory.CreateMetricsReceiver(context.Background(), creationSet, cfg, consumertest.NewNop()) assert.NotNil(t, mReceiver) - assert.NoError(t, err) + require.NoError(t, err) lReceiver, err := factory.CreateMetricsReceiver(context.Background(), creationSet, cfg, consumertest.NewNop()) assert.NotNil(t, lReceiver) - assert.NoError(t, err) + require.NoError(t, err) pReceiver, err := factory.CreateProfilesReceiver(context.Background(), creationSet, cfg, consumertest.NewNop()) assert.NotNil(t, pReceiver) - assert.NoError(t, err) + require.NoError(t, err) assert.Same(t, tReceiver, mReceiver) assert.Same(t, tReceiver, lReceiver) @@ -139,7 +139,7 @@ func TestCreateTracesReceiver(t *testing.T) { assert.Error(t, err) return } - assert.NoError(t, err) + require.NoError(t, err) if tt.wantStartErr { assert.Error(t, tr.Start(context.Background(), componenttest.NewNopHost())) } else { @@ -233,7 +233,7 @@ func TestCreateMetricReceiver(t *testing.T) { assert.Error(t, err) return } - assert.NoError(t, err) + require.NoError(t, err) if tt.wantStartErr { assert.Error(t, mr.Start(context.Background(), componenttest.NewNopHost())) } else { @@ -327,7 +327,7 @@ func TestCreateLogReceiver(t *testing.T) { assert.Error(t, err) return } - assert.NoError(t, err) + require.NoError(t, err) if tt.wantStartErr { assert.Error(t, mr.Start(context.Background(), componenttest.NewNopHost())) } else { @@ -420,7 +420,7 @@ func TestCreateProfilesReceiver(t *testing.T) { assert.Error(t, err) return } - assert.NoError(t, err) + require.NoError(t, err) if tt.wantStartErr { assert.Error(t, tr.Start(context.Background(), componenttest.NewNopHost())) } else { diff --git a/receiver/otlpreceiver/internal/logs/otlp_test.go b/receiver/otlpreceiver/internal/logs/otlp_test.go index 4523f6eb36a..0ee92098e53 100644 --- a/receiver/otlpreceiver/internal/logs/otlp_test.go +++ b/receiver/otlpreceiver/internal/logs/otlp_test.go @@ -46,7 +46,7 @@ func TestExport_EmptyRequest(t *testing.T) { logClient := makeLogsServiceClient(t, logSink) resp, err := logClient.Export(context.Background(), plogotlp.NewExportRequest()) - assert.NoError(t, err, "Failed to export trace: %v", err) + require.NoError(t, err, "Failed to export trace: %v", err) assert.NotNil(t, resp, "The response is missing") } @@ -56,7 +56,7 @@ func TestExport_NonPermanentErrorConsumer(t *testing.T) { logClient := makeLogsServiceClient(t, consumertest.NewErr(errors.New("my error"))) resp, err := logClient.Export(context.Background(), req) - assert.EqualError(t, err, "rpc error: code = Unavailable desc = my error") + require.EqualError(t, err, "rpc error: code = Unavailable desc = my error") assert.IsType(t, status.Error(codes.Unknown, ""), err) assert.Equal(t, plogotlp.ExportResponse{}, resp) } @@ -67,7 +67,7 @@ func TestExport_PermanentErrorConsumer(t *testing.T) { logClient := makeLogsServiceClient(t, consumertest.NewErr(consumererror.NewPermanent(errors.New("my error")))) resp, err := logClient.Export(context.Background(), req) - assert.EqualError(t, err, "rpc error: code = Internal desc = Permanent error: my error") + require.EqualError(t, err, "rpc error: code = Internal desc = Permanent error: my error") assert.IsType(t, status.Error(codes.Unknown, ""), err) assert.Equal(t, plogotlp.ExportResponse{}, resp) } diff --git a/receiver/otlpreceiver/internal/metrics/otlp_test.go b/receiver/otlpreceiver/internal/metrics/otlp_test.go index f71be5d17ab..7af686fd630 100644 --- a/receiver/otlpreceiver/internal/metrics/otlp_test.go +++ b/receiver/otlpreceiver/internal/metrics/otlp_test.go @@ -56,7 +56,7 @@ func TestExport_NonPermanentErrorConsumer(t *testing.T) { metricsClient := makeMetricsServiceClient(t, consumertest.NewErr(errors.New("my error"))) resp, err := metricsClient.Export(context.Background(), req) - assert.EqualError(t, err, "rpc error: code = Unavailable desc = my error") + require.EqualError(t, err, "rpc error: code = Unavailable desc = my error") assert.IsType(t, status.Error(codes.Unknown, ""), err) assert.Equal(t, pmetricotlp.ExportResponse{}, resp) } @@ -67,7 +67,7 @@ func TestExport_PermanentErrorConsumer(t *testing.T) { metricsClient := makeMetricsServiceClient(t, consumertest.NewErr(consumererror.NewPermanent(errors.New("my error")))) resp, err := metricsClient.Export(context.Background(), req) - assert.EqualError(t, err, "rpc error: code = Internal desc = Permanent error: my error") + require.EqualError(t, err, "rpc error: code = Internal desc = Permanent error: my error") assert.IsType(t, status.Error(codes.Unknown, ""), err) assert.Equal(t, pmetricotlp.ExportResponse{}, resp) } diff --git a/receiver/otlpreceiver/internal/profiles/otlp_test.go b/receiver/otlpreceiver/internal/profiles/otlp_test.go index 8d253c7f24b..cb4abc8ae39 100644 --- a/receiver/otlpreceiver/internal/profiles/otlp_test.go +++ b/receiver/otlpreceiver/internal/profiles/otlp_test.go @@ -41,7 +41,7 @@ func TestExport_EmptyRequest(t *testing.T) { profileSink := new(consumertest.ProfilesSink) profileClient := makeProfileServiceClient(t, profileSink) resp, err := profileClient.Export(context.Background(), pprofileotlp.NewExportRequest()) - assert.NoError(t, err, "Failed to export profile: %v", err) + require.NoError(t, err, "Failed to export profile: %v", err) assert.NotNil(t, resp, "The response is missing") } @@ -51,7 +51,7 @@ func TestExport_NonPermanentErrorConsumer(t *testing.T) { profileClient := makeProfileServiceClient(t, consumertest.NewErr(errors.New("my error"))) resp, err := profileClient.Export(context.Background(), req) - assert.EqualError(t, err, "rpc error: code = Unavailable desc = my error") + require.EqualError(t, err, "rpc error: code = Unavailable desc = my error") assert.IsType(t, status.Error(codes.Unknown, ""), err) assert.Equal(t, pprofileotlp.ExportResponse{}, resp) } @@ -61,7 +61,7 @@ func TestExport_PermanentErrorConsumer(t *testing.T) { profileClient := makeProfileServiceClient(t, consumertest.NewErr(consumererror.NewPermanent(errors.New("my error")))) resp, err := profileClient.Export(context.Background(), req) - assert.EqualError(t, err, "rpc error: code = Internal desc = Permanent error: my error") + require.EqualError(t, err, "rpc error: code = Internal desc = Permanent error: my error") assert.IsType(t, status.Error(codes.Unknown, ""), err) assert.Equal(t, pprofileotlp.ExportResponse{}, resp) } diff --git a/receiver/otlpreceiver/internal/trace/otlp_test.go b/receiver/otlpreceiver/internal/trace/otlp_test.go index c573471845d..3df87c317f0 100644 --- a/receiver/otlpreceiver/internal/trace/otlp_test.go +++ b/receiver/otlpreceiver/internal/trace/otlp_test.go @@ -44,7 +44,7 @@ func TestExport_EmptyRequest(t *testing.T) { traceSink := new(consumertest.TracesSink) traceClient := makeTraceServiceClient(t, traceSink) resp, err := traceClient.Export(context.Background(), ptraceotlp.NewExportRequest()) - assert.NoError(t, err, "Failed to export trace: %v", err) + require.NoError(t, err, "Failed to export trace: %v", err) assert.NotNil(t, resp, "The response is missing") } @@ -54,7 +54,7 @@ func TestExport_NonPermanentErrorConsumer(t *testing.T) { traceClient := makeTraceServiceClient(t, consumertest.NewErr(errors.New("my error"))) resp, err := traceClient.Export(context.Background(), req) - assert.EqualError(t, err, "rpc error: code = Unavailable desc = my error") + require.EqualError(t, err, "rpc error: code = Unavailable desc = my error") assert.IsType(t, status.Error(codes.Unknown, ""), err) assert.Equal(t, ptraceotlp.ExportResponse{}, resp) } @@ -64,7 +64,7 @@ func TestExport_PermanentErrorConsumer(t *testing.T) { traceClient := makeTraceServiceClient(t, consumertest.NewErr(consumererror.NewPermanent(errors.New("my error")))) resp, err := traceClient.Export(context.Background(), req) - assert.EqualError(t, err, "rpc error: code = Internal desc = Permanent error: my error") + require.EqualError(t, err, "rpc error: code = Internal desc = Permanent error: my error") assert.IsType(t, status.Error(codes.Unknown, ""), err) assert.Equal(t, ptraceotlp.ExportResponse{}, resp) } diff --git a/receiver/otlpreceiver/otlp_test.go b/receiver/otlpreceiver/otlp_test.go index 42f7ba71553..31b045771ca 100644 --- a/receiver/otlpreceiver/otlp_test.go +++ b/receiver/otlpreceiver/otlp_test.go @@ -134,11 +134,11 @@ func TestJsonHttp(t *testing.T) { respBytes := doHTTPRequest(t, url, tt.encoding, tt.contentType, dr.jsonBytes, tt.expectedStatusCode) if tt.err == nil { tr := ptraceotlp.NewExportResponse() - assert.NoError(t, tr.UnmarshalJSON(respBytes), "Unable to unmarshal response to Response") + require.NoError(t, tr.UnmarshalJSON(respBytes), "Unable to unmarshal response to Response") sink.checkData(t, dr.data, 1) } else { errStatus := &spb.Status{} - assert.NoError(t, json.Unmarshal(respBytes, errStatus)) + require.NoError(t, json.Unmarshal(respBytes, errStatus)) if s, ok := status.FromError(tt.err); ok { assert.True(t, proto.Equal(errStatus, s.Proto())) } else { @@ -391,11 +391,11 @@ func TestProtoHttp(t *testing.T) { respBytes := doHTTPRequest(t, url, tt.encoding, "application/x-protobuf", dr.protoBytes, tt.expectedStatusCode) if tt.err == nil { tr := ptraceotlp.NewExportResponse() - assert.NoError(t, tr.UnmarshalProto(respBytes)) + require.NoError(t, tr.UnmarshalProto(respBytes)) sink.checkData(t, dr.data, 1) } else { errStatus := &spb.Status{} - assert.NoError(t, proto.Unmarshal(respBytes, errStatus)) + require.NoError(t, proto.Unmarshal(respBytes, errStatus)) if s, ok := status.FromError(tt.err); ok { assert.True(t, proto.Equal(errStatus, s.Proto())) } else { @@ -669,10 +669,10 @@ func TestOTLPReceiverHTTPTracesIngestTest(t *testing.T) { if ingestionState.expectedCode == codes.OK { require.Equal(t, 200, resp.StatusCode) tr := ptraceotlp.NewExportResponse() - assert.NoError(t, tr.UnmarshalProto(respBytes)) + require.NoError(t, tr.UnmarshalProto(respBytes)) } else { errStatus := &spb.Status{} - assert.NoError(t, proto.Unmarshal(respBytes, errStatus)) + require.NoError(t, proto.Unmarshal(respBytes, errStatus)) assert.Equal(t, ingestionState.expectedStatusCode, resp.StatusCode) assert.Equal(t, ingestionState.expectedCode, codes.Code(errStatus.Code)) } @@ -1063,7 +1063,7 @@ func TestShutdown(t *testing.T) { // Now shutdown the receiver, while continuing sending traces to it. ctx, cancelFn := context.WithTimeout(context.Background(), 10*time.Second) defer cancelFn() - assert.NoError(t, r.Shutdown(ctx)) + require.NoError(t, r.Shutdown(ctx)) // Remember how many spans the sink received. This number should not change after this // point because after Shutdown() returns the component is not allowed to produce diff --git a/receiver/receiver_test.go b/receiver/receiver_test.go index cf0bf128a81..6eeadc50dca 100644 --- a/receiver/receiver_test.go +++ b/receiver/receiver_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/consumer" @@ -23,9 +24,9 @@ func TestNewFactory(t *testing.T) { assert.EqualValues(t, testType, factory.Type()) assert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig()) _, err := factory.CreateTracesReceiver(context.Background(), Settings{}, &defaultCfg, consumertest.NewNop()) - assert.Error(t, err) + require.Error(t, err) _, err = factory.CreateMetricsReceiver(context.Background(), Settings{}, &defaultCfg, consumertest.NewNop()) - assert.Error(t, err) + require.Error(t, err) _, err = factory.CreateLogsReceiver(context.Background(), Settings{}, &defaultCfg, consumertest.NewNop()) assert.Error(t, err) } @@ -44,11 +45,11 @@ func TestNewFactoryWithOptions(t *testing.T) { assert.Equal(t, component.StabilityLevelDeprecated, factory.TracesReceiverStability()) _, err := factory.CreateTracesReceiver(context.Background(), Settings{}, &defaultCfg, nil) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelAlpha, factory.MetricsReceiverStability()) _, err = factory.CreateMetricsReceiver(context.Background(), Settings{}, &defaultCfg, nil) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, component.StabilityLevelStable, factory.LogsReceiverStability()) _, err = factory.CreateLogsReceiver(context.Background(), Settings{}, &defaultCfg, nil) @@ -86,7 +87,7 @@ func TestMakeFactoryMap(t *testing.T) { assert.Error(t, err) return } - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tt.out, out) }) } diff --git a/receiver/receiverhelper/obsreport_test.go b/receiver/receiverhelper/obsreport_test.go index 105dcfe91c2..455fd16a8e9 100644 --- a/receiver/receiverhelper/obsreport_test.go +++ b/receiver/receiverhelper/obsreport_test.go @@ -248,9 +248,9 @@ func TestCheckReceiverTracesViews(t *testing.T) { require.NotNil(t, ctx) rec.EndTracesOp(ctx, format, 7, nil) - assert.NoError(t, tt.CheckReceiverTraces(transport, 7, 0)) - assert.Error(t, tt.CheckReceiverTraces(transport, 7, 7)) - assert.Error(t, tt.CheckReceiverTraces(transport, 0, 0)) + require.NoError(t, tt.CheckReceiverTraces(transport, 7, 0)) + require.Error(t, tt.CheckReceiverTraces(transport, 7, 7)) + require.Error(t, tt.CheckReceiverTraces(transport, 0, 0)) assert.Error(t, tt.CheckReceiverTraces(transport, 0, 7)) } @@ -269,9 +269,9 @@ func TestCheckReceiverMetricsViews(t *testing.T) { require.NotNil(t, ctx) rec.EndMetricsOp(ctx, format, 7, nil) - assert.NoError(t, tt.CheckReceiverMetrics(transport, 7, 0)) - assert.Error(t, tt.CheckReceiverMetrics(transport, 7, 7)) - assert.Error(t, tt.CheckReceiverMetrics(transport, 0, 0)) + require.NoError(t, tt.CheckReceiverMetrics(transport, 7, 0)) + require.Error(t, tt.CheckReceiverMetrics(transport, 7, 7)) + require.Error(t, tt.CheckReceiverMetrics(transport, 0, 0)) assert.Error(t, tt.CheckReceiverMetrics(transport, 0, 7)) } @@ -290,9 +290,9 @@ func TestCheckReceiverLogsViews(t *testing.T) { require.NotNil(t, ctx) rec.EndLogsOp(ctx, format, 7, nil) - assert.NoError(t, tt.CheckReceiverLogs(transport, 7, 0)) - assert.Error(t, tt.CheckReceiverLogs(transport, 7, 7)) - assert.Error(t, tt.CheckReceiverLogs(transport, 0, 0)) + require.NoError(t, tt.CheckReceiverLogs(transport, 7, 0)) + require.Error(t, tt.CheckReceiverLogs(transport, 7, 7)) + require.Error(t, tt.CheckReceiverLogs(transport, 0, 0)) assert.Error(t, tt.CheckReceiverLogs(transport, 0, 7)) } diff --git a/receiver/receivertest/contract_checker.go b/receiver/receivertest/contract_checker.go index c3378747b71..a8b95e06b03 100644 --- a/receiver/receivertest/contract_checker.go +++ b/receiver/receivertest/contract_checker.go @@ -193,7 +193,7 @@ func checkConsumeContractScenario(params CheckConsumeContractParams, decisionFun } err = receiver.Shutdown(ctx) - assert.NoError(params.T, err) + require.NoError(params.T, err) // Print some stats to help debug test failures. fmt.Printf( diff --git a/receiver/scrapererror/scrapeerror_test.go b/receiver/scrapererror/scrapeerror_test.go index 2568e4e28b5..7a47345013a 100644 --- a/receiver/scrapererror/scrapeerror_test.go +++ b/receiver/scrapererror/scrapeerror_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestScrapeErrorsAddPartial(t *testing.T) { @@ -89,10 +90,10 @@ func TestScrapeErrorsCombine(t *testing.T) { for _, tt := range testCases { scrapeErrs := tt.errs() if tt.expectNil { - assert.NoError(t, scrapeErrs.Combine()) + require.NoError(t, scrapeErrs.Combine()) continue } - assert.EqualError(t, scrapeErrs.Combine(), tt.expectedErr) + require.EqualError(t, scrapeErrs.Combine(), tt.expectedErr) if tt.expectedScrape { var partialScrapeErr PartialScrapeError if !errors.As(scrapeErrs.Combine(), &partialScrapeErr) { diff --git a/receiver/scraperhelper/obsreport_test.go b/receiver/scraperhelper/obsreport_test.go index e5927a1165e..2240ce2eff6 100644 --- a/receiver/scraperhelper/obsreport_test.go +++ b/receiver/scraperhelper/obsreport_test.go @@ -105,9 +105,9 @@ func TestCheckScraperMetricsViews(t *testing.T) { require.NotNil(t, ctx) s.EndMetricsOp(ctx, 7, nil) - assert.NoError(t, tt.CheckScraperMetrics(receiverID, scraperID, 7, 0)) - assert.Error(t, tt.CheckScraperMetrics(receiverID, scraperID, 7, 7)) - assert.Error(t, tt.CheckScraperMetrics(receiverID, scraperID, 0, 0)) + require.NoError(t, tt.CheckScraperMetrics(receiverID, scraperID, 7, 0)) + require.Error(t, tt.CheckScraperMetrics(receiverID, scraperID, 7, 7)) + require.Error(t, tt.CheckScraperMetrics(receiverID, scraperID, 0, 0)) assert.Error(t, tt.CheckScraperMetrics(receiverID, scraperID, 0, 7)) } diff --git a/receiver/scraperhelper/scrapercontroller_test.go b/receiver/scraperhelper/scrapercontroller_test.go index d611581b5e3..7d9fc8101e2 100644 --- a/receiver/scraperhelper/scrapercontroller_test.go +++ b/receiver/scraperhelper/scrapercontroller_test.go @@ -224,7 +224,7 @@ func configureMetricOptions(t *testing.T, test metricsTestCase, initializeChs [] scrapeMetricsChs[i] = make(chan int) tsm := &testScrapeMetrics{ch: scrapeMetricsChs[i], err: test.scrapeErr} scp, err := NewScraper(component.MustNewType("scraper"), tsm.scrape, scraperOptions...) - assert.NoError(t, err) + require.NoError(t, err) metricOptions = append(metricOptions, AddScraper(scp)) } @@ -326,7 +326,7 @@ func TestSingleScrapePerInterval(t *testing.T) { tickerCh := make(chan time.Time) scp, err := NewScraper(component.MustNewType("scaper"), tsm.scrape) - assert.NoError(t, err) + require.NoError(t, err) receiver, err := NewScraperControllerReceiver( cfg, @@ -383,7 +383,7 @@ func TestScrapeControllerStartsOnInit(t *testing.T) { assert.NoError(t, r.Start(context.Background(), componenttest.NewNopHost()), "Must not error on start") <-time.After(500 * time.Nanosecond) - assert.NoError(t, r.Shutdown(context.Background()), "Must not have errored on shutdown") + require.NoError(t, r.Shutdown(context.Background()), "Must not have errored on shutdown") assert.Equal(t, 1, tsm.timesScrapeCalled, "Must have been called as soon as the controller started") } diff --git a/semconv/semconv_test.go b/semconv/semconv_test.go index fcee8460f29..2d528bd23b4 100644 --- a/semconv/semconv_test.go +++ b/semconv/semconv_test.go @@ -10,6 +10,7 @@ import ( version "github.com/hashicorp/go-version" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAllSemConvFilesAreCrated(t *testing.T) { @@ -17,13 +18,13 @@ func TestAllSemConvFilesAreCrated(t *testing.T) { var expectedFiles = []string{"generated_resource.go", "generated_trace.go", "schema.go", "nonstandard.go"} files, err := os.ReadDir(".") - assert.NoError(t, err) + require.NoError(t, err) constraints, err := version.NewConstraint("> v1.16.0") - assert.NoError(t, err) + require.NoError(t, err) attrgroupconstraints, err := version.NewConstraint("> v1.22.0") - assert.NoError(t, err) + require.NoError(t, err) for _, f := range files { if !f.IsDir() { @@ -31,7 +32,7 @@ func TestAllSemConvFilesAreCrated(t *testing.T) { } ver, err := version.NewVersion(f.Name()) - assert.NoError(t, err) + require.NoError(t, err) expected := make([]string, len(expectedFiles)) copy(expected, expectedFiles) diff --git a/service/extensions/extensions_test.go b/service/extensions/extensions_test.go index f159533fd3f..351edddbc48 100644 --- a/service/extensions/extensions_test.go +++ b/service/extensions/extensions_test.go @@ -284,7 +284,7 @@ func TestNotifyConfig(t *testing.T) { BuildInfo: component.NewDefaultBuildInfo(), Extensions: builders.NewExtension(tt.extensionsConfigs, tt.factories), }, tt.serviceExtensions) - assert.NoError(t, err) + require.NoError(t, err) errs := extensions.NotifyConfig(context.Background(), confmap.NewFromStringMap(map[string]interface{}{})) assert.Equal(t, tt.want, errs) }) @@ -434,7 +434,7 @@ func TestStatusReportedOnStartupShutdown(t *testing.T) { []component.ID{compID}, WithReporter(rep), ) - assert.NoError(t, err) + require.NoError(t, err) rep.Ready() diff --git a/service/internal/builders/connector_test.go b/service/internal/builders/connector_test.go index 081ad3fe07e..9f2fe018ba8 100644 --- a/service/internal/builders/connector_test.go +++ b/service/internal/builders/connector_test.go @@ -290,67 +290,67 @@ func TestConnectorBuilderMissingConfig(t *testing.T) { missingID := component.MustNewIDWithName("all", "missing") t2t, err := bErr.CreateTracesToTraces(context.Background(), createConnectorSettings(missingID), consumertest.NewNop()) - assert.EqualError(t, err, "connector \"all/missing\" is not configured") + require.EqualError(t, err, "connector \"all/missing\" is not configured") assert.Nil(t, t2t) t2m, err := bErr.CreateTracesToMetrics(context.Background(), createConnectorSettings(missingID), consumertest.NewNop()) - assert.EqualError(t, err, "connector \"all/missing\" is not configured") + require.EqualError(t, err, "connector \"all/missing\" is not configured") assert.Nil(t, t2m) t2l, err := bErr.CreateTracesToLogs(context.Background(), createConnectorSettings(missingID), consumertest.NewNop()) - assert.EqualError(t, err, "connector \"all/missing\" is not configured") + require.EqualError(t, err, "connector \"all/missing\" is not configured") assert.Nil(t, t2l) t2p, err := bErr.CreateTracesToProfiles(context.Background(), createConnectorSettings(missingID), consumertest.NewNop()) - assert.EqualError(t, err, "connector \"all/missing\" is not configured") + require.EqualError(t, err, "connector \"all/missing\" is not configured") assert.Nil(t, t2p) m2t, err := bErr.CreateMetricsToTraces(context.Background(), createConnectorSettings(missingID), consumertest.NewNop()) - assert.EqualError(t, err, "connector \"all/missing\" is not configured") + require.EqualError(t, err, "connector \"all/missing\" is not configured") assert.Nil(t, m2t) m2m, err := bErr.CreateMetricsToMetrics(context.Background(), createConnectorSettings(missingID), consumertest.NewNop()) - assert.EqualError(t, err, "connector \"all/missing\" is not configured") + require.EqualError(t, err, "connector \"all/missing\" is not configured") assert.Nil(t, m2m) m2l, err := bErr.CreateMetricsToLogs(context.Background(), createConnectorSettings(missingID), consumertest.NewNop()) - assert.EqualError(t, err, "connector \"all/missing\" is not configured") + require.EqualError(t, err, "connector \"all/missing\" is not configured") assert.Nil(t, m2l) m2p, err := bErr.CreateMetricsToProfiles(context.Background(), createConnectorSettings(missingID), consumertest.NewNop()) - assert.EqualError(t, err, "connector \"all/missing\" is not configured") + require.EqualError(t, err, "connector \"all/missing\" is not configured") assert.Nil(t, m2p) l2t, err := bErr.CreateLogsToTraces(context.Background(), createConnectorSettings(missingID), consumertest.NewNop()) - assert.EqualError(t, err, "connector \"all/missing\" is not configured") + require.EqualError(t, err, "connector \"all/missing\" is not configured") assert.Nil(t, l2t) l2m, err := bErr.CreateLogsToMetrics(context.Background(), createConnectorSettings(missingID), consumertest.NewNop()) - assert.EqualError(t, err, "connector \"all/missing\" is not configured") + require.EqualError(t, err, "connector \"all/missing\" is not configured") assert.Nil(t, l2m) l2l, err := bErr.CreateLogsToLogs(context.Background(), createConnectorSettings(missingID), consumertest.NewNop()) - assert.EqualError(t, err, "connector \"all/missing\" is not configured") + require.EqualError(t, err, "connector \"all/missing\" is not configured") assert.Nil(t, l2l) l2p, err := bErr.CreateLogsToProfiles(context.Background(), createConnectorSettings(missingID), consumertest.NewNop()) - assert.EqualError(t, err, "connector \"all/missing\" is not configured") + require.EqualError(t, err, "connector \"all/missing\" is not configured") assert.Nil(t, l2p) p2t, err := bErr.CreateProfilesToTraces(context.Background(), createConnectorSettings(missingID), consumertest.NewNop()) - assert.EqualError(t, err, "connector \"all/missing\" is not configured") + require.EqualError(t, err, "connector \"all/missing\" is not configured") assert.Nil(t, p2t) p2m, err := bErr.CreateProfilesToMetrics(context.Background(), createConnectorSettings(missingID), consumertest.NewNop()) - assert.EqualError(t, err, "connector \"all/missing\" is not configured") + require.EqualError(t, err, "connector \"all/missing\" is not configured") assert.Nil(t, p2m) p2l, err := bErr.CreateProfilesToLogs(context.Background(), createConnectorSettings(missingID), consumertest.NewNop()) - assert.EqualError(t, err, "connector \"all/missing\" is not configured") + require.EqualError(t, err, "connector \"all/missing\" is not configured") assert.Nil(t, p2l) p2p, err := bErr.CreateProfilesToProfiles(context.Background(), createConnectorSettings(missingID), consumertest.NewNop()) - assert.EqualError(t, err, "connector \"all/missing\" is not configured") + require.EqualError(t, err, "connector \"all/missing\" is not configured") assert.Nil(t, p2p) } diff --git a/service/internal/builders/exporter_test.go b/service/internal/builders/exporter_test.go index e4a3cdd19ca..802a42f2a2c 100644 --- a/service/internal/builders/exporter_test.go +++ b/service/internal/builders/exporter_test.go @@ -65,37 +65,37 @@ func TestExporterBuilder(t *testing.T) { te, err := b.CreateTraces(context.Background(), createExporterSettings(tt.id)) if tt.err != "" { - assert.EqualError(t, err, tt.err) + require.EqualError(t, err, tt.err) assert.Nil(t, te) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, nopExporterInstance, te) } me, err := b.CreateMetrics(context.Background(), createExporterSettings(tt.id)) if tt.err != "" { - assert.EqualError(t, err, tt.err) + require.EqualError(t, err, tt.err) assert.Nil(t, me) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, nopExporterInstance, me) } le, err := b.CreateLogs(context.Background(), createExporterSettings(tt.id)) if tt.err != "" { - assert.EqualError(t, err, tt.err) + require.EqualError(t, err, tt.err) assert.Nil(t, le) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, nopExporterInstance, le) } pe, err := b.CreateProfiles(context.Background(), createExporterSettings(tt.id)) if tt.err != "" { - assert.EqualError(t, err, tt.err) + require.EqualError(t, err, tt.err) assert.Nil(t, pe) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, nopExporterInstance, pe) } }) @@ -121,19 +121,19 @@ func TestExporterBuilderMissingConfig(t *testing.T) { missingID := component.MustNewIDWithName("all", "missing") te, err := bErr.CreateTraces(context.Background(), createExporterSettings(missingID)) - assert.EqualError(t, err, "exporter \"all/missing\" is not configured") + require.EqualError(t, err, "exporter \"all/missing\" is not configured") assert.Nil(t, te) me, err := bErr.CreateMetrics(context.Background(), createExporterSettings(missingID)) - assert.EqualError(t, err, "exporter \"all/missing\" is not configured") + require.EqualError(t, err, "exporter \"all/missing\" is not configured") assert.Nil(t, me) le, err := bErr.CreateLogs(context.Background(), createExporterSettings(missingID)) - assert.EqualError(t, err, "exporter \"all/missing\" is not configured") + require.EqualError(t, err, "exporter \"all/missing\" is not configured") assert.Nil(t, le) pe, err := bErr.CreateProfiles(context.Background(), createExporterSettings(missingID)) - assert.EqualError(t, err, "exporter \"all/missing\" is not configured") + require.EqualError(t, err, "exporter \"all/missing\" is not configured") assert.Nil(t, pe) } diff --git a/service/internal/builders/extension_test.go b/service/internal/builders/extension_test.go index 153c094c29b..798b11c33ea 100644 --- a/service/internal/builders/extension_test.go +++ b/service/internal/builders/extension_test.go @@ -37,7 +37,7 @@ func TestExtensionBuilder(t *testing.T) { b := NewExtension(cfgs, factories) e, err := b.Create(context.Background(), createExtensionSettings(testID)) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, e) // Check that the extension has access to the resource attributes. @@ -46,11 +46,11 @@ func TestExtensionBuilder(t *testing.T) { assert.Equal(t, 0, nop.Settings.Resource.Attributes().Len()) missingType, err := b.Create(context.Background(), createExtensionSettings(unknownID)) - assert.EqualError(t, err, "extension factory not available for: \"unknown\"") + require.EqualError(t, err, "extension factory not available for: \"unknown\"") assert.Nil(t, missingType) missingCfg, err := b.Create(context.Background(), createExtensionSettings(component.NewIDWithName(testType, "foo"))) - assert.EqualError(t, err, "extension \"test/foo\" is not configured") + require.EqualError(t, err, "extension \"test/foo\" is not configured") assert.Nil(t, missingCfg) } diff --git a/service/internal/builders/processor_test.go b/service/internal/builders/processor_test.go index cc1ce0d5db2..09443387817 100644 --- a/service/internal/builders/processor_test.go +++ b/service/internal/builders/processor_test.go @@ -96,37 +96,37 @@ func TestProcessorBuilder(t *testing.T) { te, err := b.CreateTraces(context.Background(), createProcessorSettings(tt.id), tt.nextTraces) if tt.err != "" { - assert.EqualError(t, err, tt.err) + require.EqualError(t, err, tt.err) assert.Nil(t, te) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, nopProcessorInstance, te) } me, err := b.CreateMetrics(context.Background(), createProcessorSettings(tt.id), tt.nextMetrics) if tt.err != "" { - assert.EqualError(t, err, tt.err) + require.EqualError(t, err, tt.err) assert.Nil(t, me) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, nopProcessorInstance, me) } le, err := b.CreateLogs(context.Background(), createProcessorSettings(tt.id), tt.nextLogs) if tt.err != "" { - assert.EqualError(t, err, tt.err) + require.EqualError(t, err, tt.err) assert.Nil(t, le) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, nopProcessorInstance, le) } pe, err := b.CreateProfiles(context.Background(), createProcessorSettings(tt.id), tt.nextProfiles) if tt.err != "" { - assert.EqualError(t, err, tt.err) + require.EqualError(t, err, tt.err) assert.Nil(t, pe) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, nopProcessorInstance, pe) } }) @@ -152,19 +152,19 @@ func TestProcessorBuilderMissingConfig(t *testing.T) { missingID := component.MustNewIDWithName("all", "missing") te, err := bErr.CreateTraces(context.Background(), createProcessorSettings(missingID), consumertest.NewNop()) - assert.EqualError(t, err, "processor \"all/missing\" is not configured") + require.EqualError(t, err, "processor \"all/missing\" is not configured") assert.Nil(t, te) me, err := bErr.CreateMetrics(context.Background(), createProcessorSettings(missingID), consumertest.NewNop()) - assert.EqualError(t, err, "processor \"all/missing\" is not configured") + require.EqualError(t, err, "processor \"all/missing\" is not configured") assert.Nil(t, me) le, err := bErr.CreateLogs(context.Background(), createProcessorSettings(missingID), consumertest.NewNop()) - assert.EqualError(t, err, "processor \"all/missing\" is not configured") + require.EqualError(t, err, "processor \"all/missing\" is not configured") assert.Nil(t, le) pe, err := bErr.CreateProfiles(context.Background(), createProcessorSettings(missingID), consumertest.NewNop()) - assert.EqualError(t, err, "processor \"all/missing\" is not configured") + require.EqualError(t, err, "processor \"all/missing\" is not configured") assert.Nil(t, pe) } diff --git a/service/internal/builders/receiver_test.go b/service/internal/builders/receiver_test.go index 39f8e1595ae..488892a1310 100644 --- a/service/internal/builders/receiver_test.go +++ b/service/internal/builders/receiver_test.go @@ -96,37 +96,37 @@ func TestReceiverBuilder(t *testing.T) { te, err := b.CreateTraces(context.Background(), settings(tt.id), tt.nextTraces) if tt.err != "" { - assert.EqualError(t, err, tt.err) + require.EqualError(t, err, tt.err) assert.Nil(t, te) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, nopReceiverInstance, te) } me, err := b.CreateMetrics(context.Background(), settings(tt.id), tt.nextMetrics) if tt.err != "" { - assert.EqualError(t, err, tt.err) + require.EqualError(t, err, tt.err) assert.Nil(t, me) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, nopReceiverInstance, me) } le, err := b.CreateLogs(context.Background(), settings(tt.id), tt.nextLogs) if tt.err != "" { - assert.EqualError(t, err, tt.err) + require.EqualError(t, err, tt.err) assert.Nil(t, le) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, nopReceiverInstance, le) } pe, err := b.CreateProfiles(context.Background(), settings(tt.id), tt.nextProfiles) if tt.err != "" { - assert.EqualError(t, err, tt.err) + require.EqualError(t, err, tt.err) assert.Nil(t, pe) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, nopReceiverInstance, pe) } }) @@ -152,19 +152,19 @@ func TestReceiverBuilderMissingConfig(t *testing.T) { missingID := component.MustNewIDWithName("all", "missing") te, err := bErr.CreateTraces(context.Background(), settings(missingID), consumertest.NewNop()) - assert.EqualError(t, err, "receiver \"all/missing\" is not configured") + require.EqualError(t, err, "receiver \"all/missing\" is not configured") assert.Nil(t, te) me, err := bErr.CreateMetrics(context.Background(), settings(missingID), consumertest.NewNop()) - assert.EqualError(t, err, "receiver \"all/missing\" is not configured") + require.EqualError(t, err, "receiver \"all/missing\" is not configured") assert.Nil(t, me) le, err := bErr.CreateLogs(context.Background(), settings(missingID), consumertest.NewNop()) - assert.EqualError(t, err, "receiver \"all/missing\" is not configured") + require.EqualError(t, err, "receiver \"all/missing\" is not configured") assert.Nil(t, le) pe, err := bErr.CreateProfiles(context.Background(), settings(missingID), consumertest.NewNop()) - assert.EqualError(t, err, "receiver \"all/missing\" is not configured") + require.EqualError(t, err, "receiver \"all/missing\" is not configured") assert.Nil(t, pe) } diff --git a/service/internal/capabilityconsumer/capabilities_test.go b/service/internal/capabilityconsumer/capabilities_test.go index 83468f97000..746d8cda18c 100644 --- a/service/internal/capabilityconsumer/capabilities_test.go +++ b/service/internal/capabilityconsumer/capabilities_test.go @@ -25,7 +25,7 @@ func TestLogs(t *testing.T) { wrap := NewLogs(sink, consumer.Capabilities{MutatesData: true}) assert.Equal(t, consumer.Capabilities{MutatesData: true}, wrap.Capabilities()) - assert.NoError(t, wrap.ConsumeLogs(context.Background(), testdata.GenerateLogs(1))) + require.NoError(t, wrap.ConsumeLogs(context.Background(), testdata.GenerateLogs(1))) assert.Len(t, sink.AllLogs(), 1) assert.Equal(t, testdata.GenerateLogs(1), sink.AllLogs()[0]) } @@ -40,7 +40,7 @@ func TestMetrics(t *testing.T) { wrap := NewMetrics(sink, consumer.Capabilities{MutatesData: true}) assert.Equal(t, consumer.Capabilities{MutatesData: true}, wrap.Capabilities()) - assert.NoError(t, wrap.ConsumeMetrics(context.Background(), testdata.GenerateMetrics(1))) + require.NoError(t, wrap.ConsumeMetrics(context.Background(), testdata.GenerateMetrics(1))) assert.Len(t, sink.AllMetrics(), 1) assert.Equal(t, testdata.GenerateMetrics(1), sink.AllMetrics()[0]) } @@ -55,7 +55,7 @@ func TestTraces(t *testing.T) { wrap := NewTraces(sink, consumer.Capabilities{MutatesData: true}) assert.Equal(t, consumer.Capabilities{MutatesData: true}, wrap.Capabilities()) - assert.NoError(t, wrap.ConsumeTraces(context.Background(), testdata.GenerateTraces(1))) + require.NoError(t, wrap.ConsumeTraces(context.Background(), testdata.GenerateTraces(1))) assert.Len(t, sink.AllTraces(), 1) assert.Equal(t, testdata.GenerateTraces(1), sink.AllTraces()[0]) } @@ -70,7 +70,7 @@ func TestProfiles(t *testing.T) { wrap := NewProfiles(sink, consumer.Capabilities{MutatesData: true}) assert.Equal(t, consumer.Capabilities{MutatesData: true}, wrap.Capabilities()) - assert.NoError(t, wrap.ConsumeProfiles(context.Background(), testdata.GenerateProfiles(1))) + require.NoError(t, wrap.ConsumeProfiles(context.Background(), testdata.GenerateProfiles(1))) assert.Len(t, sink.AllProfiles(), 1) assert.Equal(t, testdata.GenerateProfiles(1), sink.AllProfiles()[0]) } diff --git a/service/internal/graph/graph_test.go b/service/internal/graph/graph_test.go index 71f4d2c3536..a6e636229fe 100644 --- a/service/internal/graph/graph_test.go +++ b/service/internal/graph/graph_test.go @@ -197,11 +197,11 @@ func TestGraphStartStopCycle(t *testing.T) { pg.componentGraph.SetEdge(simple.Edge{F: c1, T: p1}) // loop back err := pg.StartAll(context.Background(), &Host{Reporter: status.NewReporter(func(*componentstatus.InstanceID, *componentstatus.Event) {}, func(error) {})}) - assert.Error(t, err) + require.Error(t, err) assert.Contains(t, err.Error(), `topo: no topological ordering: cyclic components`) err = pg.ShutdownAll(context.Background(), statustest.NewNopStatusReporter()) - assert.Error(t, err) + require.Error(t, err) assert.Contains(t, err.Error(), `topo: no topological ordering: cyclic components`) } @@ -224,7 +224,7 @@ func TestGraphStartStopComponentError(t *testing.T) { F: r1, T: e1, }) - assert.EqualError(t, pg.StartAll(context.Background(), &Host{Reporter: status.NewReporter(func(*componentstatus.InstanceID, *componentstatus.Event) {}, func(error) {})}), "foo") + require.EqualError(t, pg.StartAll(context.Background(), &Host{Reporter: status.NewReporter(func(*componentstatus.InstanceID, *componentstatus.Event) {}, func(error) {})}), "foo") assert.EqualError(t, pg.ShutdownAll(context.Background(), statustest.NewNopStatusReporter()), "bar") } @@ -986,7 +986,7 @@ func TestConnectorPipelinesGraph(t *testing.T) { assert.Equal(t, len(tt.pipelineConfigs), len(pg.pipelines)) - assert.NoError(t, pg.StartAll(context.Background(), &Host{Reporter: status.NewReporter(func(*componentstatus.InstanceID, *componentstatus.Event) {}, func(error) {})})) + require.NoError(t, pg.StartAll(context.Background(), &Host{Reporter: status.NewReporter(func(*componentstatus.InstanceID, *componentstatus.Event) {}, func(error) {})})) mutatingPipelines := make(map[component.ID]bool, len(tt.pipelineConfigs)) @@ -1103,23 +1103,23 @@ func TestConnectorPipelinesGraph(t *testing.T) { allReceivers := pg.getReceivers() for _, c := range allReceivers[component.DataTypeTraces] { tracesReceiver := c.(*testcomponents.ExampleReceiver) - assert.NoError(t, tracesReceiver.ConsumeTraces(context.Background(), testdata.GenerateTraces(1))) + require.NoError(t, tracesReceiver.ConsumeTraces(context.Background(), testdata.GenerateTraces(1))) } for _, c := range allReceivers[component.DataTypeMetrics] { metricsReceiver := c.(*testcomponents.ExampleReceiver) - assert.NoError(t, metricsReceiver.ConsumeMetrics(context.Background(), testdata.GenerateMetrics(1))) + require.NoError(t, metricsReceiver.ConsumeMetrics(context.Background(), testdata.GenerateMetrics(1))) } for _, c := range allReceivers[component.DataTypeLogs] { logsReceiver := c.(*testcomponents.ExampleReceiver) - assert.NoError(t, logsReceiver.ConsumeLogs(context.Background(), testdata.GenerateLogs(1))) + require.NoError(t, logsReceiver.ConsumeLogs(context.Background(), testdata.GenerateLogs(1))) } for _, c := range allReceivers[componentprofiles.DataTypeProfiles] { profilesReceiver := c.(*testcomponents.ExampleReceiver) - assert.NoError(t, profilesReceiver.ConsumeProfiles(context.Background(), testdata.GenerateProfiles(1))) + require.NoError(t, profilesReceiver.ConsumeProfiles(context.Background(), testdata.GenerateProfiles(1))) } // Shut down the entire component graph - assert.NoError(t, pg.ShutdownAll(context.Background(), statustest.NewNopStatusReporter())) + require.NoError(t, pg.ShutdownAll(context.Background(), statustest.NewNopStatusReporter())) // Check each pipeline individually, ensuring that all components are stopped. for pipelineID := range tt.pipelineConfigs { @@ -1380,12 +1380,12 @@ func TestConnectorRouter(t *testing.T) { tracesLeft := allExporters[component.DataTypeTraces][expLeftID].(*testcomponents.ExampleExporter) // Consume 1, validate it went right - assert.NoError(t, tracesReceiver.ConsumeTraces(ctx, testdata.GenerateTraces(1))) + require.NoError(t, tracesReceiver.ConsumeTraces(ctx, testdata.GenerateTraces(1))) assert.Len(t, tracesRight.Traces, 1) assert.Empty(t, tracesLeft.Traces) // Consume 1, validate it went left - assert.NoError(t, tracesReceiver.ConsumeTraces(ctx, testdata.GenerateTraces(1))) + require.NoError(t, tracesReceiver.ConsumeTraces(ctx, testdata.GenerateTraces(1))) assert.Len(t, tracesRight.Traces, 1) assert.Len(t, tracesLeft.Traces, 1) @@ -1402,12 +1402,12 @@ func TestConnectorRouter(t *testing.T) { metricsLeft := allExporters[component.DataTypeMetrics][expLeftID].(*testcomponents.ExampleExporter) // Consume 1, validate it went right - assert.NoError(t, metricsReceiver.ConsumeMetrics(ctx, testdata.GenerateMetrics(1))) + require.NoError(t, metricsReceiver.ConsumeMetrics(ctx, testdata.GenerateMetrics(1))) assert.Len(t, metricsRight.Metrics, 1) assert.Empty(t, metricsLeft.Metrics) // Consume 1, validate it went left - assert.NoError(t, metricsReceiver.ConsumeMetrics(ctx, testdata.GenerateMetrics(1))) + require.NoError(t, metricsReceiver.ConsumeMetrics(ctx, testdata.GenerateMetrics(1))) assert.Len(t, metricsRight.Metrics, 1) assert.Len(t, metricsLeft.Metrics, 1) @@ -1424,12 +1424,12 @@ func TestConnectorRouter(t *testing.T) { logsLeft := allExporters[component.DataTypeLogs][expLeftID].(*testcomponents.ExampleExporter) // Consume 1, validate it went right - assert.NoError(t, logsReceiver.ConsumeLogs(ctx, testdata.GenerateLogs(1))) + require.NoError(t, logsReceiver.ConsumeLogs(ctx, testdata.GenerateLogs(1))) assert.Len(t, logsRight.Logs, 1) assert.Empty(t, logsLeft.Logs) // Consume 1, validate it went left - assert.NoError(t, logsReceiver.ConsumeLogs(ctx, testdata.GenerateLogs(1))) + require.NoError(t, logsReceiver.ConsumeLogs(ctx, testdata.GenerateLogs(1))) assert.Len(t, logsRight.Logs, 1) assert.Len(t, logsLeft.Logs, 1) @@ -1446,12 +1446,12 @@ func TestConnectorRouter(t *testing.T) { profilesLeft := allExporters[componentprofiles.DataTypeProfiles][expLeftID].(*testcomponents.ExampleExporter) // Consume 1, validate it went right - assert.NoError(t, profilesReceiver.ConsumeProfiles(ctx, testdata.GenerateProfiles(1))) + require.NoError(t, profilesReceiver.ConsumeProfiles(ctx, testdata.GenerateProfiles(1))) assert.Len(t, profilesRight.Profiles, 1) assert.Empty(t, profilesLeft.Profiles) // Consume 1, validate it went left - assert.NoError(t, profilesReceiver.ConsumeProfiles(ctx, testdata.GenerateProfiles(1))) + require.NoError(t, profilesReceiver.ConsumeProfiles(ctx, testdata.GenerateProfiles(1))) assert.Len(t, profilesRight.Profiles, 1) assert.Len(t, profilesLeft.Profiles, 1) @@ -2730,8 +2730,8 @@ func TestGraphFailToStartAndShutdown(t *testing.T) { }, } pipelines, err := Build(context.Background(), set) - assert.NoError(t, err) - assert.Error(t, pipelines.StartAll(context.Background(), &Host{Reporter: status.NewReporter(func(*componentstatus.InstanceID, *componentstatus.Event) {}, func(error) {})})) + require.NoError(t, err) + require.Error(t, pipelines.StartAll(context.Background(), &Host{Reporter: status.NewReporter(func(*componentstatus.InstanceID, *componentstatus.Event) {}, func(error) {})})) assert.Error(t, pipelines.ShutdownAll(context.Background(), statustest.NewNopStatusReporter())) }) @@ -2744,8 +2744,8 @@ func TestGraphFailToStartAndShutdown(t *testing.T) { }, } pipelines, err := Build(context.Background(), set) - assert.NoError(t, err) - assert.Error(t, pipelines.StartAll(context.Background(), &Host{Reporter: status.NewReporter(func(*componentstatus.InstanceID, *componentstatus.Event) {}, func(error) {})})) + require.NoError(t, err) + require.Error(t, pipelines.StartAll(context.Background(), &Host{Reporter: status.NewReporter(func(*componentstatus.InstanceID, *componentstatus.Event) {}, func(error) {})})) assert.Error(t, pipelines.ShutdownAll(context.Background(), statustest.NewNopStatusReporter())) }) @@ -2758,8 +2758,8 @@ func TestGraphFailToStartAndShutdown(t *testing.T) { }, } pipelines, err := Build(context.Background(), set) - assert.NoError(t, err) - assert.Error(t, pipelines.StartAll(context.Background(), &Host{Reporter: status.NewReporter(func(*componentstatus.InstanceID, *componentstatus.Event) {}, func(error) {})})) + require.NoError(t, err) + require.Error(t, pipelines.StartAll(context.Background(), &Host{Reporter: status.NewReporter(func(*componentstatus.InstanceID, *componentstatus.Event) {}, func(error) {})})) assert.Error(t, pipelines.ShutdownAll(context.Background(), statustest.NewNopStatusReporter())) }) @@ -2778,8 +2778,8 @@ func TestGraphFailToStartAndShutdown(t *testing.T) { }, } pipelines, err := Build(context.Background(), set) - assert.NoError(t, err) - assert.Error(t, pipelines.StartAll(context.Background(), &Host{Reporter: status.NewReporter(func(*componentstatus.InstanceID, *componentstatus.Event) {}, func(error) {})})) + require.NoError(t, err) + require.Error(t, pipelines.StartAll(context.Background(), &Host{Reporter: status.NewReporter(func(*componentstatus.InstanceID, *componentstatus.Event) {}, func(error) {})})) assert.Error(t, pipelines.ShutdownAll(context.Background(), statustest.NewNopStatusReporter())) }) } diff --git a/service/internal/resource/config_test.go b/service/internal/resource/config_test.go index 950054132fa..9ba74af936a 100644 --- a/service/internal/resource/config_test.go +++ b/service/internal/resource/config_test.go @@ -8,6 +8,7 @@ import ( "github.com/google/uuid" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" sdkresource "go.opentelemetry.io/otel/sdk/resource" "go.opentelemetry.io/collector/component" @@ -92,7 +93,7 @@ func TestNew(t *testing.T) { // Check that the value is a valid UUID. _, err := uuid.Parse(got["service.instance.id"]) - assert.NoError(t, err) + require.NoError(t, err) // Remove so that we can compare the rest of the map. delete(got, "service.instance.id") diff --git a/service/internal/testcomponents/example_connector_test.go b/service/internal/testcomponents/example_connector_test.go index e6ce1328153..9f95b5ae457 100644 --- a/service/internal/testcomponents/example_connector_test.go +++ b/service/internal/testcomponents/example_connector_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/component/componenttest" ) @@ -16,10 +17,10 @@ func TestExampleConnector(t *testing.T) { conn := &ExampleConnector{} host := componenttest.NewNopHost() assert.False(t, conn.Started()) - assert.NoError(t, conn.Start(context.Background(), host)) + require.NoError(t, conn.Start(context.Background(), host)) assert.True(t, conn.Started()) assert.False(t, conn.Stopped()) - assert.NoError(t, conn.Shutdown(context.Background())) + require.NoError(t, conn.Shutdown(context.Background())) assert.True(t, conn.Stopped()) } diff --git a/service/internal/testcomponents/example_exporter_test.go b/service/internal/testcomponents/example_exporter_test.go index cc911f2301f..a4792464415 100644 --- a/service/internal/testcomponents/example_exporter_test.go +++ b/service/internal/testcomponents/example_exporter_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/component/componenttest" "go.opentelemetry.io/collector/pdata/plog" @@ -20,26 +21,26 @@ func TestExampleExporter(t *testing.T) { exp := &ExampleExporter{} host := componenttest.NewNopHost() assert.False(t, exp.Started()) - assert.NoError(t, exp.Start(context.Background(), host)) + require.NoError(t, exp.Start(context.Background(), host)) assert.True(t, exp.Started()) assert.Empty(t, exp.Traces) - assert.NoError(t, exp.ConsumeTraces(context.Background(), ptrace.Traces{})) + require.NoError(t, exp.ConsumeTraces(context.Background(), ptrace.Traces{})) assert.Len(t, exp.Traces, 1) assert.Empty(t, exp.Metrics) - assert.NoError(t, exp.ConsumeMetrics(context.Background(), pmetric.Metrics{})) + require.NoError(t, exp.ConsumeMetrics(context.Background(), pmetric.Metrics{})) assert.Len(t, exp.Metrics, 1) assert.Empty(t, exp.Logs) - assert.NoError(t, exp.ConsumeLogs(context.Background(), plog.Logs{})) + require.NoError(t, exp.ConsumeLogs(context.Background(), plog.Logs{})) assert.Len(t, exp.Logs, 1) assert.Empty(t, exp.Profiles) - assert.NoError(t, exp.ConsumeProfiles(context.Background(), pprofile.Profiles{})) + require.NoError(t, exp.ConsumeProfiles(context.Background(), pprofile.Profiles{})) assert.Len(t, exp.Profiles, 1) assert.False(t, exp.Stopped()) - assert.NoError(t, exp.Shutdown(context.Background())) + require.NoError(t, exp.Shutdown(context.Background())) assert.True(t, exp.Stopped()) } diff --git a/service/internal/testcomponents/example_processor_test.go b/service/internal/testcomponents/example_processor_test.go index bd428375e8d..868c308b3d8 100644 --- a/service/internal/testcomponents/example_processor_test.go +++ b/service/internal/testcomponents/example_processor_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/component/componenttest" ) @@ -16,10 +17,10 @@ func TestExampleProcessor(t *testing.T) { prc := &ExampleProcessor{} host := componenttest.NewNopHost() assert.False(t, prc.Started()) - assert.NoError(t, prc.Start(context.Background(), host)) + require.NoError(t, prc.Start(context.Background(), host)) assert.True(t, prc.Started()) assert.False(t, prc.Stopped()) - assert.NoError(t, prc.Shutdown(context.Background())) + require.NoError(t, prc.Shutdown(context.Background())) assert.True(t, prc.Stopped()) } diff --git a/service/internal/testcomponents/example_receiver_test.go b/service/internal/testcomponents/example_receiver_test.go index 1e3bc73c656..4f31fc8f424 100644 --- a/service/internal/testcomponents/example_receiver_test.go +++ b/service/internal/testcomponents/example_receiver_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/component/componenttest" ) @@ -16,10 +17,10 @@ func TestExampleReceiver(t *testing.T) { rcv := &ExampleReceiver{} host := componenttest.NewNopHost() assert.False(t, rcv.Started()) - assert.NoError(t, rcv.Start(context.Background(), host)) + require.NoError(t, rcv.Start(context.Background(), host)) assert.True(t, rcv.Started()) assert.False(t, rcv.Stopped()) - assert.NoError(t, rcv.Shutdown(context.Background())) + require.NoError(t, rcv.Shutdown(context.Background())) assert.True(t, rcv.Stopped()) } diff --git a/service/internal/testcomponents/example_router_test.go b/service/internal/testcomponents/example_router_test.go index 8d89efff744..123799e9213 100644 --- a/service/internal/testcomponents/example_router_test.go +++ b/service/internal/testcomponents/example_router_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/component/componenttest" @@ -24,11 +25,11 @@ func TestExampleRouter(t *testing.T) { conn := &ExampleRouter{} host := componenttest.NewNopHost() assert.False(t, conn.Started()) - assert.NoError(t, conn.Start(context.Background(), host)) + require.NoError(t, conn.Start(context.Background(), host)) assert.True(t, conn.Started()) assert.False(t, conn.Stopped()) - assert.NoError(t, conn.Shutdown(context.Background())) + require.NoError(t, conn.Shutdown(context.Background())) assert.True(t, conn.Stopped()) } @@ -51,16 +52,16 @@ func TestTracesRouter(t *testing.T) { cfg := ExampleRouterConfig{Traces: &LeftRightConfig{Left: leftID, Right: rightID}} tr, err := ExampleRouterFactory.CreateTracesToTraces( context.Background(), connectortest.NewNopSettings(), cfg, router) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, tr.Capabilities().MutatesData) td := testdata.GenerateTraces(1) - assert.NoError(t, tr.ConsumeTraces(context.Background(), td)) + require.NoError(t, tr.ConsumeTraces(context.Background(), td)) assert.Len(t, sinkRight.AllTraces(), 1) assert.Empty(t, sinkLeft.AllTraces()) - assert.NoError(t, tr.ConsumeTraces(context.Background(), td)) + require.NoError(t, tr.ConsumeTraces(context.Background(), td)) assert.Len(t, sinkRight.AllTraces(), 1) assert.Len(t, sinkLeft.AllTraces(), 1) @@ -90,16 +91,16 @@ func TestMetricsRouter(t *testing.T) { cfg := ExampleRouterConfig{Metrics: &LeftRightConfig{Left: leftID, Right: rightID}} mr, err := ExampleRouterFactory.CreateMetricsToMetrics( context.Background(), connectortest.NewNopSettings(), cfg, router) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, mr.Capabilities().MutatesData) md := testdata.GenerateMetrics(1) - assert.NoError(t, mr.ConsumeMetrics(context.Background(), md)) + require.NoError(t, mr.ConsumeMetrics(context.Background(), md)) assert.Len(t, sinkRight.AllMetrics(), 1) assert.Empty(t, sinkLeft.AllMetrics()) - assert.NoError(t, mr.ConsumeMetrics(context.Background(), md)) + require.NoError(t, mr.ConsumeMetrics(context.Background(), md)) assert.Len(t, sinkRight.AllMetrics(), 1) assert.Len(t, sinkLeft.AllMetrics(), 1) @@ -129,16 +130,16 @@ func TestLogsRouter(t *testing.T) { cfg := ExampleRouterConfig{Logs: &LeftRightConfig{Left: leftID, Right: rightID}} lr, err := ExampleRouterFactory.CreateLogsToLogs( context.Background(), connectortest.NewNopSettings(), cfg, router) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, lr.Capabilities().MutatesData) ld := testdata.GenerateLogs(1) - assert.NoError(t, lr.ConsumeLogs(context.Background(), ld)) + require.NoError(t, lr.ConsumeLogs(context.Background(), ld)) assert.Len(t, sinkRight.AllLogs(), 1) assert.Empty(t, sinkLeft.AllLogs()) - assert.NoError(t, lr.ConsumeLogs(context.Background(), ld)) + require.NoError(t, lr.ConsumeLogs(context.Background(), ld)) assert.Len(t, sinkRight.AllLogs(), 1) assert.Len(t, sinkLeft.AllLogs(), 1) @@ -168,16 +169,16 @@ func TestProfilesRouter(t *testing.T) { cfg := ExampleRouterConfig{Profiles: &LeftRightConfig{Left: leftID, Right: rightID}} tr, err := ExampleRouterFactory.CreateProfilesToProfiles( context.Background(), connectortest.NewNopSettings(), cfg, router) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, tr.Capabilities().MutatesData) td := testdata.GenerateProfiles(1) - assert.NoError(t, tr.ConsumeProfiles(context.Background(), td)) + require.NoError(t, tr.ConsumeProfiles(context.Background(), td)) assert.Len(t, sinkRight.AllProfiles(), 1) assert.Empty(t, sinkLeft.AllProfiles()) - assert.NoError(t, tr.ConsumeProfiles(context.Background(), td)) + require.NoError(t, tr.ConsumeProfiles(context.Background(), td)) assert.Len(t, sinkRight.AllProfiles(), 1) assert.Len(t, sinkLeft.AllProfiles(), 1) diff --git a/service/internal/zpages/templates_test.go b/service/internal/zpages/templates_test.go index c3ea1ad2792..1c0f8f43da2 100644 --- a/service/internal/zpages/templates_test.go +++ b/service/internal/zpages/templates_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const tmplBody = ` @@ -36,7 +37,7 @@ func TestTemplateFuncs(t *testing.T) { Index: 32, Element: [2]string{"key", "value"}, } - assert.NoError(t, tmpl.Execute(buf, input)) + require.NoError(t, tmpl.Execute(buf, input)) assert.EqualValues(t, want, buf.String()) } diff --git a/service/service_test.go b/service/service_test.go index bff18959569..41e5e046b61 100644 --- a/service/service_test.go +++ b/service/service_test.go @@ -628,9 +628,7 @@ func assertZPages(t *testing.T, zpagesAddr string) { testZPagePathFn := func(t *testing.T, path string) { client := &http.Client{} resp, err := client.Get("http://" + zpagesAddr + path) - if !assert.NoError(t, err, "error retrieving zpage at %q", path) { - return - } + require.NoError(t, err, "error retrieving zpage at %q", path) assert.Equal(t, http.StatusOK, resp.StatusCode, "unsuccessful zpage %q GET", path) assert.NoError(t, resp.Body.Close()) } diff --git a/service/telemetry/internal/otelinit/config_test.go b/service/telemetry/internal/otelinit/config_test.go index c91e6f667e5..c1b7e105495 100644 --- a/service/telemetry/internal/otelinit/config_test.go +++ b/service/telemetry/internal/otelinit/config_test.go @@ -534,7 +534,7 @@ func TestMetricReader(t *testing.T) { defer func() { if gotReader != nil { - assert.NoError(t, gotReader.Shutdown(context.Background())) + require.NoError(t, gotReader.Shutdown(context.Background())) } if server != nil { assert.NoError(t, server.Shutdown(context.Background())) diff --git a/service/telemetry/telemetry_test.go b/service/telemetry/telemetry_test.go index 25c42d01830..f777f8dbbdc 100644 --- a/service/telemetry/telemetry_test.go +++ b/service/telemetry/telemetry_test.go @@ -9,6 +9,7 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.uber.org/zap" "go.uber.org/zap/zapcore" @@ -56,10 +57,10 @@ func TestTelemetryConfiguration(t *testing.T) { set := Settings{ZapOptions: []zap.Option{}} logger, err := f.CreateLogger(context.Background(), set, tt.cfg) if tt.success { - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, logger) } else { - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, logger) } }) @@ -114,7 +115,7 @@ func TestSampledLogger(t *testing.T) { ctx := context.Background() set := Settings{ZapOptions: []zap.Option{}} logger, err := f.CreateLogger(ctx, set, tt.cfg) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, logger) }) } From 6fab8ae7b840fc8edcf59341333dda5ee4a447a4 Mon Sep 17 00:00:00 2001 From: Sean Marciniak <30928402+MovieStoreGuy@users.noreply.github.com> Date: Thu, 19 Sep 2024 17:40:12 +0930 Subject: [PATCH 6/8] [chore] cleanup confighttp tests (#11176) #### Description Minor life improvements when reviewing the tests, - Using stdlib for error reading - Using the config client from test server - Moving examples into their own file for easy discovery/maintainability #### Link to tracking issue N/A --- config/confighttp/compression_test.go | 43 ++++++++------------ config/confighttp/confighttp_example_test.go | 33 +++++++++++++++ config/confighttp/confighttp_test.go | 22 ---------- 3 files changed, 50 insertions(+), 48 deletions(-) create mode 100644 config/confighttp/confighttp_example_test.go diff --git a/config/confighttp/compression_test.go b/config/confighttp/compression_test.go index 78fcc8cd555..9ebebfe4a7e 100644 --- a/config/confighttp/compression_test.go +++ b/config/confighttp/compression_test.go @@ -8,12 +8,14 @@ import ( "compress/gzip" "compress/zlib" "context" + "errors" "fmt" "io" "net/http" "net/http/httptest" "strings" "testing" + "testing/iotest" "github.com/golang/snappy" "github.com/klauspost/compress/zstd" @@ -142,7 +144,7 @@ func TestHTTPCustomDecompression(t *testing.T) { require.NoError(t, err, "failed to create request to test handler") req.Header.Set("Content-Encoding", "custom-encoding") - client := http.Client{} + client := srv.Client() res, err := client.Do(req) require.NoError(t, err) @@ -260,7 +262,7 @@ func TestHTTPContentDecompressionHandler(t *testing.T) { require.NoError(t, err, "failed to create request to test handler") req.Header.Set("Content-Encoding", tt.encoding) - client := http.Client{} + client := srv.Client() res, err := client.Do(req) require.NoError(t, err) @@ -276,18 +278,18 @@ func TestHTTPContentDecompressionHandler(t *testing.T) { func TestHTTPContentCompressionRequestWithNilBody(t *testing.T) { compressedGzipBody := compressGzip(t, []byte{}) - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) body, err := io.ReadAll(r.Body) assert.NoError(t, err, "failed to read request body: %v", err) assert.EqualValues(t, compressedGzipBody.Bytes(), body) })) - defer server.Close() + defer srv.Close() - req, err := http.NewRequest(http.MethodGet, server.URL, nil) + req, err := http.NewRequest(http.MethodGet, srv.URL, nil) require.NoError(t, err, "failed to create request to test handler") - client := http.Client{} + client := srv.Client() client.Transport, err = newCompressRoundTripper(http.DefaultTransport, configcompression.TypeGzip) require.NoError(t, err) res, err := client.Do(req) @@ -298,27 +300,16 @@ func TestHTTPContentCompressionRequestWithNilBody(t *testing.T) { require.NoError(t, res.Body.Close(), "failed to close request body: %v", err) } -type copyFailBody struct { -} - -func (*copyFailBody) Read([]byte) (n int, err error) { - return 0, fmt.Errorf("read failed") -} - -func (*copyFailBody) Close() error { - return nil -} - func TestHTTPContentCompressionCopyError(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })) - t.Cleanup(server.Close) + t.Cleanup(srv.Close) - req, err := http.NewRequest(http.MethodGet, server.URL, ©FailBody{}) + req, err := http.NewRequest(http.MethodGet, srv.URL, iotest.ErrReader(errors.New("read failed"))) require.NoError(t, err) - client := http.Client{} + client := srv.Client() client.Transport, err = newCompressRoundTripper(http.DefaultTransport, configcompression.TypeGzip) require.NoError(t, err) _, err = client.Do(req) @@ -334,15 +325,15 @@ func (*closeFailBody) Close() error { } func TestHTTPContentCompressionRequestBodyCloseError(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })) - t.Cleanup(server.Close) + t.Cleanup(srv.Close) - req, err := http.NewRequest(http.MethodGet, server.URL, &closeFailBody{Buffer: bytes.NewBuffer([]byte("blank"))}) + req, err := http.NewRequest(http.MethodGet, srv.URL, &closeFailBody{Buffer: bytes.NewBuffer([]byte("blank"))}) require.NoError(t, err) - client := http.Client{} + client := srv.Client() client.Transport, err = newCompressRoundTripper(http.DefaultTransport, configcompression.TypeGzip) require.NoError(t, err) _, err = client.Do(req) @@ -362,7 +353,7 @@ func TestOverrideCompressionList(t *testing.T) { require.NoError(t, err, "failed to create request to test handler") req.Header.Set("Content-Encoding", "snappy") - client := http.Client{} + client := srv.Client() // test res, err := client.Do(req) diff --git a/config/confighttp/confighttp_example_test.go b/config/confighttp/confighttp_example_test.go new file mode 100644 index 00000000000..73a287d9e36 --- /dev/null +++ b/config/confighttp/confighttp_example_test.go @@ -0,0 +1,33 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package confighttp + +import ( + "context" + "net/http" + + "go.opentelemetry.io/collector/component/componenttest" +) + +func ExampleServerConfig() { + settings := NewDefaultServerConfig() + settings.Endpoint = "localhost:443" + + s, err := settings.ToServer( + context.Background(), + componenttest.NewNopHost(), + componenttest.NewNopTelemetrySettings(), + http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + if err != nil { + panic(err) + } + + l, err := settings.ToListener(context.Background()) + if err != nil { + panic(err) + } + if err = s.Serve(l); err != nil { + panic(err) + } +} diff --git a/config/confighttp/confighttp_test.go b/config/confighttp/confighttp_test.go index 29ca8e6ef04..aaaef2bb501 100644 --- a/config/confighttp/confighttp_test.go +++ b/config/confighttp/confighttp_test.go @@ -1011,28 +1011,6 @@ func verifyHeadersResp(t *testing.T, url string, expected map[string]configopaqu } } -func ExampleServerConfig() { - settings := NewDefaultServerConfig() - settings.Endpoint = "localhost:443" - - s, err := settings.ToServer( - context.Background(), - componenttest.NewNopHost(), - componenttest.NewNopTelemetrySettings(), - http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) - if err != nil { - panic(err) - } - - l, err := settings.ToListener(context.Background()) - if err != nil { - panic(err) - } - if err = s.Serve(l); err != nil { - panic(err) - } -} - func TestHttpClientHeaders(t *testing.T) { tests := []struct { name string From 396ae85e9dedb8a671662f3d23310fb770e0e2f0 Mon Sep 17 00:00:00 2001 From: Peter Deng Date: Thu, 19 Sep 2024 16:10:43 +0800 Subject: [PATCH 7/8] Honor build_tags in config (#11156) #### Description #### Link to tracking issue Fixes # #### Testing #### Documentation --- .chloggen/fixbuildtags.yaml | 20 ++++++++++++++++++++ cmd/builder/internal/builder/config_test.go | 13 +++++++++++++ cmd/builder/internal/builder/main_test.go | 12 ++++++++++++ cmd/builder/internal/command.go | 1 + 4 files changed, 46 insertions(+) create mode 100644 .chloggen/fixbuildtags.yaml diff --git a/.chloggen/fixbuildtags.yaml b/.chloggen/fixbuildtags.yaml new file mode 100644 index 00000000000..a439eaea449 --- /dev/null +++ b/.chloggen/fixbuildtags.yaml @@ -0,0 +1,20 @@ +# Use this changelog template to create an entry for release notes. + +# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix' +change_type: 'bug_fix' + +# The name of the component, or a single word describing the area of concern, (e.g. otlpreceiver) +component: builder + +# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`). +note: Honor build_tags in config + +# One or more tracking issues or pull requests related to the change +issues: [11156] + +# Optional: The change log or logs in which this entry should be included. +# e.g. '[user]' or '[user, api]' +# Include 'user' if the change is relevant to end users. +# Include 'api' if there is a change to a library API. +# Default: '[user]' +change_logs: [user] diff --git a/cmd/builder/internal/builder/config_test.go b/cmd/builder/internal/builder/config_test.go index 856e60061e6..b37aa8ff085 100644 --- a/cmd/builder/internal/builder/config_test.go +++ b/cmd/builder/internal/builder/config_test.go @@ -153,6 +153,7 @@ func TestNewDefaultConfig(t *testing.T) { assert.NoError(t, cfg.SetGoPath()) require.NoError(t, cfg.Validate()) assert.False(t, cfg.Distribution.DebugCompilation) + assert.Empty(t, cfg.Distribution.BuildTags) } func TestNewBuiltinConfig(t *testing.T) { @@ -198,6 +199,18 @@ func TestSkipGoInitialization(t *testing.T) { assert.Zero(t, cfg.Distribution.Go) } +func TestBuildTagConfig(t *testing.T) { + cfg := Config{ + Distribution: Distribution{ + BuildTags: "customTag", + }, + SkipCompilation: true, + SkipGetModules: true, + } + require.NoError(t, cfg.Validate()) + assert.Equal(t, "customTag", cfg.Distribution.BuildTags) +} + func TestDebugOptionSetConfig(t *testing.T) { cfg := Config{ Distribution: Distribution{ diff --git a/cmd/builder/internal/builder/main_test.go b/cmd/builder/internal/builder/main_test.go index aa90c99ca4f..fe7bb1c09f8 100644 --- a/cmd/builder/internal/builder/main_test.go +++ b/cmd/builder/internal/builder/main_test.go @@ -289,6 +289,18 @@ func TestGenerateAndCompile(t *testing.T) { return cfg }, }, + { + name: "Build Tags Compilation", + cfgBuilder: func(t *testing.T) Config { + cfg := newTestConfig() + err := cfg.SetBackwardsCompatibility() + require.NoError(t, err) + cfg.Distribution.OutputPath = t.TempDir() + cfg.Replaces = append(cfg.Replaces, replaces...) + cfg.Distribution.BuildTags = "customTag" + return cfg + }, + }, { name: "Debug Compilation", cfgBuilder: func(t *testing.T) Config { diff --git a/cmd/builder/internal/command.go b/cmd/builder/internal/command.go index 3af77178727..124b51fdc91 100644 --- a/cmd/builder/internal/command.go +++ b/cmd/builder/internal/command.go @@ -209,5 +209,6 @@ func applyCfgFromFile(flags *flag.FlagSet, cfgFromFile builder.Config) { if !flags.Changed(distributionModuleFlag) && cfgFromFile.Distribution.Module != "" { cfg.Distribution.Module = cfgFromFile.Distribution.Module } + cfg.Distribution.BuildTags = cfgFromFile.Distribution.BuildTags cfg.Distribution.DebugCompilation = cfgFromFile.Distribution.DebugCompilation } From df3c9e38a80ccc3b14705462be2e2e51c628a3b3 Mon Sep 17 00:00:00 2001 From: Damien Mathieu <42@dmathieu.com> Date: Thu, 19 Sep 2024 13:17:38 +0200 Subject: [PATCH 8/8] [chore] split exporterhelper so a separate profiles module can use it (#11215) #### Description This is part of #11131, splitting the exporterhelper module with a new `internal` submodule that holds everything shared by the signals. This is so a new `exporterhelperprofiles` module can make use of the shared structs. --- exporter/exporterhelper/common.go | 328 +---------------- exporter/exporterhelper/exporterhelper.go | 6 - .../exporterhelper/internal/base_exporter.go | 341 ++++++++++++++++++ .../base_exporter_test.go} | 40 +- .../{ => internal}/batch_sender.go | 43 +-- .../{ => internal}/batch_sender_test.go | 137 +++---- .../{ => internal}/obsexporter.go | 97 +++-- .../{ => internal}/obsexporter_test.go | 87 +++-- .../exporterhelper/internal/queue_sender.go | 154 ++++++++ .../{ => internal}/queue_sender_test.go | 123 +++---- .../{request_test.go => internal/request.go} | 35 +- .../exporterhelper/internal/request_sender.go | 33 ++ .../exporterhelper/internal/retry_sender.go | 142 ++++++++ .../{ => internal}/retry_sender_test.go | 91 ++--- .../exporterhelper/internal/timeout_sender.go | 52 +++ .../{ => internal}/timeout_sender_test.go | 2 +- exporter/exporterhelper/logs.go | 31 +- exporter/exporterhelper/logs_test.go | 26 +- exporter/exporterhelper/metrics.go | 31 +- exporter/exporterhelper/metrics_test.go | 26 +- exporter/exporterhelper/obsreport_test.go | 15 +- exporter/exporterhelper/queue_sender.go | 133 +------ exporter/exporterhelper/retry_sender.go | 129 +------ exporter/exporterhelper/timeout_sender.go | 43 +-- exporter/exporterhelper/traces.go | 31 +- exporter/exporterhelper/traces_test.go | 26 +- 26 files changed, 1161 insertions(+), 1041 deletions(-) create mode 100644 exporter/exporterhelper/internal/base_exporter.go rename exporter/exporterhelper/{common_test.go => internal/base_exporter_test.go} (69%) rename exporter/exporterhelper/{ => internal}/batch_sender.go (81%) rename exporter/exporterhelper/{ => internal}/batch_sender_test.go (83%) rename exporter/exporterhelper/{ => internal}/obsexporter.go (52%) rename exporter/exporterhelper/{ => internal}/obsexporter_test.go (73%) create mode 100644 exporter/exporterhelper/internal/queue_sender.go rename exporter/exporterhelper/{ => internal}/queue_sender_test.go (77%) rename exporter/exporterhelper/{request_test.go => internal/request.go} (71%) create mode 100644 exporter/exporterhelper/internal/request_sender.go create mode 100644 exporter/exporterhelper/internal/retry_sender.go rename exporter/exporterhelper/{ => internal}/retry_sender_test.go (78%) create mode 100644 exporter/exporterhelper/internal/timeout_sender.go rename exporter/exporterhelper/{ => internal}/timeout_sender_test.go (95%) diff --git a/exporter/exporterhelper/common.go b/exporter/exporterhelper/common.go index 5b8a2a51767..f3e9f06b2ec 100644 --- a/exporter/exporterhelper/common.go +++ b/exporter/exporterhelper/common.go @@ -4,123 +4,46 @@ package exporterhelper // import "go.opentelemetry.io/collector/exporter/exporterhelper" import ( - "context" - "fmt" - - "go.uber.org/multierr" - "go.uber.org/zap" - "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/config/configretry" "go.opentelemetry.io/collector/consumer" - "go.opentelemetry.io/collector/exporter" "go.opentelemetry.io/collector/exporter/exporterbatcher" + "go.opentelemetry.io/collector/exporter/exporterhelper/internal" "go.opentelemetry.io/collector/exporter/exporterqueue" ) -// requestSender is an abstraction of a sender for a request independent of the type of the data (traces, metrics, logs). -type requestSender interface { - component.Component - send(context.Context, Request) error - setNextSender(nextSender requestSender) -} - -type baseRequestSender struct { - component.StartFunc - component.ShutdownFunc - nextSender requestSender -} - -var _ requestSender = (*baseRequestSender)(nil) - -func (b *baseRequestSender) send(ctx context.Context, req Request) error { - return b.nextSender.send(ctx, req) -} - -func (b *baseRequestSender) setNextSender(nextSender requestSender) { - b.nextSender = nextSender -} - -type obsrepSenderFactory func(obsrep *obsReport) requestSender - -// Option apply changes to baseExporter. -type Option interface { - apply(*baseExporter) error -} - -type optionFunc func(*baseExporter) error - -func (of optionFunc) apply(e *baseExporter) error { - return of(e) -} +// Option apply changes to BaseExporter. +type Option = internal.Option // WithStart overrides the default Start function for an exporter. // The default start function does nothing and always returns nil. func WithStart(start component.StartFunc) Option { - return optionFunc(func(o *baseExporter) error { - o.StartFunc = start - return nil - }) + return internal.WithStart(start) } // WithShutdown overrides the default Shutdown function for an exporter. // The default shutdown function does nothing and always returns nil. func WithShutdown(shutdown component.ShutdownFunc) Option { - return optionFunc(func(o *baseExporter) error { - o.ShutdownFunc = shutdown - return nil - }) + return internal.WithShutdown(shutdown) } // WithTimeout overrides the default TimeoutSettings for an exporter. // The default TimeoutSettings is 5 seconds. func WithTimeout(timeoutConfig TimeoutConfig) Option { - return optionFunc(func(o *baseExporter) error { - o.timeoutSender.cfg = timeoutConfig - return nil - }) + return internal.WithTimeout(timeoutConfig) } // WithRetry overrides the default configretry.BackOffConfig for an exporter. // The default configretry.BackOffConfig is to disable retries. func WithRetry(config configretry.BackOffConfig) Option { - return optionFunc(func(o *baseExporter) error { - if !config.Enabled { - o.exportFailureMessage += " Try enabling retry_on_failure config option to retry on retryable errors." - return nil - } - o.retrySender = newRetrySender(config, o.set) - return nil - }) + return internal.WithRetry(config) } // WithQueue overrides the default QueueConfig for an exporter. // The default QueueConfig is to disable queueing. // This option cannot be used with the new exporter helpers New[Traces|Metrics|Logs]RequestExporter. -func WithQueue(config QueueConfig) Option { - return optionFunc(func(o *baseExporter) error { - if o.marshaler == nil || o.unmarshaler == nil { - return fmt.Errorf("WithQueue option is not available for the new request exporters, use WithRequestQueue instead") - } - if !config.Enabled { - o.exportFailureMessage += " Try enabling sending_queue to survive temporary failures." - return nil - } - qf := exporterqueue.NewPersistentQueueFactory[Request](config.StorageID, exporterqueue.PersistentQueueSettings[Request]{ - Marshaler: o.marshaler, - Unmarshaler: o.unmarshaler, - }) - q := qf(context.Background(), exporterqueue.Settings{ - DataType: o.signal, - ExporterSettings: o.set, - }, exporterqueue.Config{ - Enabled: config.Enabled, - NumConsumers: config.NumConsumers, - QueueSize: config.QueueSize, - }) - o.queueSender = newQueueSender(q, o.set, config.NumConsumers, o.exportFailureMessage, o.obsrep) - return nil - }) +func WithQueue(config internal.QueueConfig) Option { + return internal.WithQueue(config) } // WithRequestQueue enables queueing for an exporter. @@ -128,54 +51,22 @@ func WithQueue(config QueueConfig) Option { // Experimental: This API is at the early stage of development and may change without backward compatibility // until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved. func WithRequestQueue(cfg exporterqueue.Config, queueFactory exporterqueue.Factory[Request]) Option { - return optionFunc(func(o *baseExporter) error { - if o.marshaler != nil || o.unmarshaler != nil { - return fmt.Errorf("WithRequestQueue option must be used with the new request exporters only, use WithQueue instead") - } - if !cfg.Enabled { - o.exportFailureMessage += " Try enabling sending_queue to survive temporary failures." - return nil - } - o.queueCfg = cfg - o.queueFactory = queueFactory - return nil - }) + return internal.WithRequestQueue(cfg, queueFactory) } // WithCapabilities overrides the default Capabilities() function for a Consumer. // The default is non-mutable data. // TODO: Verify if we can change the default to be mutable as we do for processors. func WithCapabilities(capabilities consumer.Capabilities) Option { - return optionFunc(func(o *baseExporter) error { - o.consumerOptions = append(o.consumerOptions, consumer.WithCapabilities(capabilities)) - return nil - }) + return internal.WithCapabilities(capabilities) } // BatcherOption apply changes to batcher sender. -type BatcherOption interface { - apply(*batchSender) error -} - -type batcherOptionFunc func(*batchSender) error - -func (of batcherOptionFunc) apply(e *batchSender) error { - return of(e) -} +type BatcherOption = internal.BatcherOption // WithRequestBatchFuncs sets the functions for merging and splitting batches for an exporter built for custom request types. func WithRequestBatchFuncs(mf exporterbatcher.BatchMergeFunc[Request], msf exporterbatcher.BatchMergeSplitFunc[Request]) BatcherOption { - return batcherOptionFunc(func(bs *batchSender) error { - if mf == nil || msf == nil { - return fmt.Errorf("WithRequestBatchFuncs must be provided with non-nil functions") - } - if bs.mergeFunc != nil || bs.mergeSplitFunc != nil { - return fmt.Errorf("WithRequestBatchFuncs can only be used once with request-based exporters") - } - bs.mergeFunc = mf - bs.mergeSplitFunc = msf - return nil - }) + return internal.WithRequestBatchFuncs(mf, msf) } // WithBatcher enables batching for an exporter based on custom request types. @@ -184,196 +75,5 @@ func WithRequestBatchFuncs(mf exporterbatcher.BatchMergeFunc[Request], msf expor // This API is at the early stage of development and may change without backward compatibility // until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved. func WithBatcher(cfg exporterbatcher.Config, opts ...BatcherOption) Option { - return optionFunc(func(o *baseExporter) error { - if !cfg.Enabled { - return nil - } - - bs := newBatchSender(cfg, o.set, o.batchMergeFunc, o.batchMergeSplitfunc) - for _, opt := range opts { - if err := opt.apply(bs); err != nil { - return err - } - } - if bs.mergeFunc == nil || bs.mergeSplitFunc == nil { - return fmt.Errorf("WithRequestBatchFuncs must be provided for the batcher applied to the request-based exporters") - } - o.batchSender = bs - return nil - }) -} - -// withMarshaler is used to set the request marshaler for the new exporter helper. -// It must be provided as the first option when creating a new exporter helper. -func withMarshaler(marshaler exporterqueue.Marshaler[Request]) Option { - return optionFunc(func(o *baseExporter) error { - o.marshaler = marshaler - return nil - }) -} - -// withUnmarshaler is used to set the request unmarshaler for the new exporter helper. -// It must be provided as the first option when creating a new exporter helper. -func withUnmarshaler(unmarshaler exporterqueue.Unmarshaler[Request]) Option { - return optionFunc(func(o *baseExporter) error { - o.unmarshaler = unmarshaler - return nil - }) -} - -// withBatchFuncs is used to set the functions for merging and splitting batches for OLTP-based exporters. -// It must be provided as the first option when creating a new exporter helper. -func withBatchFuncs(mf exporterbatcher.BatchMergeFunc[Request], msf exporterbatcher.BatchMergeSplitFunc[Request]) Option { - return optionFunc(func(o *baseExporter) error { - o.batchMergeFunc = mf - o.batchMergeSplitfunc = msf - return nil - }) -} - -// baseExporter contains common fields between different exporter types. -type baseExporter struct { - component.StartFunc - component.ShutdownFunc - - signal component.DataType - - batchMergeFunc exporterbatcher.BatchMergeFunc[Request] - batchMergeSplitfunc exporterbatcher.BatchMergeSplitFunc[Request] - - marshaler exporterqueue.Marshaler[Request] - unmarshaler exporterqueue.Unmarshaler[Request] - - set exporter.Settings - obsrep *obsReport - - // Message for the user to be added with an export failure message. - exportFailureMessage string - - // Chain of senders that the exporter helper applies before passing the data to the actual exporter. - // The data is handled by each sender in the respective order starting from the queueSender. - // Most of the senders are optional, and initialized with a no-op path-through sender. - batchSender requestSender - queueSender requestSender - obsrepSender requestSender - retrySender requestSender - timeoutSender *timeoutSender // timeoutSender is always initialized. - - consumerOptions []consumer.Option - - queueCfg exporterqueue.Config - queueFactory exporterqueue.Factory[Request] - batcherCfg exporterbatcher.Config - batcherOpts []BatcherOption -} - -func newBaseExporter(set exporter.Settings, signal component.DataType, osf obsrepSenderFactory, options ...Option) (*baseExporter, error) { - obsReport, err := newExporter(obsReportSettings{exporterID: set.ID, exporterCreateSettings: set, dataType: signal}) - if err != nil { - return nil, err - } - - be := &baseExporter{ - signal: signal, - - batchSender: &baseRequestSender{}, - queueSender: &baseRequestSender{}, - obsrepSender: osf(obsReport), - retrySender: &baseRequestSender{}, - timeoutSender: &timeoutSender{cfg: NewDefaultTimeoutConfig()}, - - set: set, - obsrep: obsReport, - } - - for _, op := range options { - err = multierr.Append(err, op.apply(be)) - } - if err != nil { - return nil, err - } - - if be.batcherCfg.Enabled { - bs := newBatchSender(be.batcherCfg, be.set, be.batchMergeFunc, be.batchMergeSplitfunc) - for _, opt := range be.batcherOpts { - err = multierr.Append(err, opt.apply(bs)) - } - if bs.mergeFunc == nil || bs.mergeSplitFunc == nil { - err = multierr.Append(err, fmt.Errorf("WithRequestBatchFuncs must be provided for the batcher applied to the request-based exporters")) - } - be.batchSender = bs - } - - if be.queueCfg.Enabled { - set := exporterqueue.Settings{ - DataType: be.signal, - ExporterSettings: be.set, - } - be.queueSender = newQueueSender(be.queueFactory(context.Background(), set, be.queueCfg), be.set, be.queueCfg.NumConsumers, be.exportFailureMessage, be.obsrep) - for _, op := range options { - err = multierr.Append(err, op.apply(be)) - } - } - - if err != nil { - return nil, err - } - - be.connectSenders() - - if bs, ok := be.batchSender.(*batchSender); ok { - // If queue sender is enabled assign to the batch sender the same number of workers. - if qs, ok := be.queueSender.(*queueSender); ok { - bs.concurrencyLimit = int64(qs.numConsumers) - } - // Batcher sender mutates the data. - be.consumerOptions = append(be.consumerOptions, consumer.WithCapabilities(consumer.Capabilities{MutatesData: true})) - } - - return be, nil -} - -// send sends the request using the first sender in the chain. -func (be *baseExporter) send(ctx context.Context, req Request) error { - err := be.queueSender.send(ctx, req) - if err != nil { - be.set.Logger.Error("Exporting failed. Rejecting data."+be.exportFailureMessage, - zap.Error(err), zap.Int("rejected_items", req.ItemsCount())) - } - return err -} - -// connectSenders connects the senders in the predefined order. -func (be *baseExporter) connectSenders() { - be.queueSender.setNextSender(be.batchSender) - be.batchSender.setNextSender(be.obsrepSender) - be.obsrepSender.setNextSender(be.retrySender) - be.retrySender.setNextSender(be.timeoutSender) -} - -func (be *baseExporter) Start(ctx context.Context, host component.Host) error { - // First start the wrapped exporter. - if err := be.StartFunc.Start(ctx, host); err != nil { - return err - } - - // If no error then start the batchSender. - if err := be.batchSender.Start(ctx, host); err != nil { - return err - } - - // Last start the queueSender. - return be.queueSender.Start(ctx, host) -} - -func (be *baseExporter) Shutdown(ctx context.Context) error { - return multierr.Combine( - // First shutdown the retry sender, so the queue sender can flush the queue without retries. - be.retrySender.Shutdown(ctx), - // Then shutdown the batch sender - be.batchSender.Shutdown(ctx), - // Then shutdown the queue sender. - be.queueSender.Shutdown(ctx), - // Last shutdown the wrapped exporter itself. - be.ShutdownFunc.Shutdown(ctx)) + return internal.WithBatcher(cfg, opts...) } diff --git a/exporter/exporterhelper/exporterhelper.go b/exporter/exporterhelper/exporterhelper.go index 0890ec71af1..d9e90d821d9 100644 --- a/exporter/exporterhelper/exporterhelper.go +++ b/exporter/exporterhelper/exporterhelper.go @@ -16,9 +16,3 @@ type Request = internal.Request // Experimental: This API is at the early stage of development and may change without backward compatibility // until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved. type RequestErrorHandler = internal.RequestErrorHandler - -// extractPartialRequest returns a new Request that may contain the items left to be sent -// if only some items failed to process and can be retried. Otherwise, it returns the original Request. -func extractPartialRequest(req Request, err error) Request { - return internal.ExtractPartialRequest(req, err) -} diff --git a/exporter/exporterhelper/internal/base_exporter.go b/exporter/exporterhelper/internal/base_exporter.go new file mode 100644 index 00000000000..922dbc9b34a --- /dev/null +++ b/exporter/exporterhelper/internal/base_exporter.go @@ -0,0 +1,341 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package internal // import "go.opentelemetry.io/collector/exporter/exporterhelper/internal" + +import ( + "context" + "fmt" + "testing" + + "github.com/stretchr/testify/require" + "go.opentelemetry.io/otel/codes" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + "go.uber.org/multierr" + "go.uber.org/zap" + + "go.opentelemetry.io/collector/component" + "go.opentelemetry.io/collector/config/configretry" + "go.opentelemetry.io/collector/consumer" + "go.opentelemetry.io/collector/exporter" + "go.opentelemetry.io/collector/exporter/exporterbatcher" + "go.opentelemetry.io/collector/exporter/exporterqueue" // BaseExporter contains common fields between different exporter types. + "go.opentelemetry.io/collector/exporter/internal" +) + +type ObsrepSenderFactory = func(obsrep *ObsReport) RequestSender + +// Option apply changes to BaseExporter. +type Option func(*BaseExporter) error + +// BatcherOption apply changes to batcher sender. +type BatcherOption func(*BatchSender) error + +type BaseExporter struct { + component.StartFunc + component.ShutdownFunc + + Signal component.DataType + + BatchMergeFunc exporterbatcher.BatchMergeFunc[internal.Request] + BatchMergeSplitfunc exporterbatcher.BatchMergeSplitFunc[internal.Request] + + Marshaler exporterqueue.Marshaler[internal.Request] + Unmarshaler exporterqueue.Unmarshaler[internal.Request] + + Set exporter.Settings + Obsrep *ObsReport + + // Message for the user to be added with an export failure message. + ExportFailureMessage string + + // Chain of senders that the exporter helper applies before passing the data to the actual exporter. + // The data is handled by each sender in the respective order starting from the queueSender. + // Most of the senders are optional, and initialized with a no-op path-through sender. + BatchSender RequestSender + QueueSender RequestSender + ObsrepSender RequestSender + RetrySender RequestSender + TimeoutSender *TimeoutSender // TimeoutSender is always initialized. + + ConsumerOptions []consumer.Option + + QueueCfg exporterqueue.Config + QueueFactory exporterqueue.Factory[internal.Request] + BatcherCfg exporterbatcher.Config + BatcherOpts []BatcherOption +} + +func NewBaseExporter(set exporter.Settings, signal component.DataType, osf ObsrepSenderFactory, options ...Option) (*BaseExporter, error) { + obsReport, err := NewExporter(ObsReportSettings{ExporterID: set.ID, ExporterCreateSettings: set, DataType: signal}) + if err != nil { + return nil, err + } + + be := &BaseExporter{ + Signal: signal, + + BatchSender: &BaseRequestSender{}, + QueueSender: &BaseRequestSender{}, + ObsrepSender: osf(obsReport), + RetrySender: &BaseRequestSender{}, + TimeoutSender: &TimeoutSender{cfg: NewDefaultTimeoutConfig()}, + + Set: set, + Obsrep: obsReport, + } + + for _, op := range options { + err = multierr.Append(err, op(be)) + } + if err != nil { + return nil, err + } + + if be.BatcherCfg.Enabled { + bs := NewBatchSender(be.BatcherCfg, be.Set, be.BatchMergeFunc, be.BatchMergeSplitfunc) + for _, opt := range be.BatcherOpts { + err = multierr.Append(err, opt(bs)) + } + if bs.mergeFunc == nil || bs.mergeSplitFunc == nil { + err = multierr.Append(err, fmt.Errorf("WithRequestBatchFuncs must be provided for the batcher applied to the request-based exporters")) + } + be.BatchSender = bs + } + + if be.QueueCfg.Enabled { + set := exporterqueue.Settings{ + DataType: be.Signal, + ExporterSettings: be.Set, + } + be.QueueSender = NewQueueSender(be.QueueFactory(context.Background(), set, be.QueueCfg), be.Set, be.QueueCfg.NumConsumers, be.ExportFailureMessage, be.Obsrep) + for _, op := range options { + err = multierr.Append(err, op(be)) + } + } + + if err != nil { + return nil, err + } + + be.connectSenders() + + if bs, ok := be.BatchSender.(*BatchSender); ok { + // If queue sender is enabled assign to the batch sender the same number of workers. + if qs, ok := be.QueueSender.(*QueueSender); ok { + bs.concurrencyLimit = int64(qs.numConsumers) + } + // Batcher sender mutates the data. + be.ConsumerOptions = append(be.ConsumerOptions, consumer.WithCapabilities(consumer.Capabilities{MutatesData: true})) + } + + return be, nil +} + +// send sends the request using the first sender in the chain. +func (be *BaseExporter) Send(ctx context.Context, req internal.Request) error { + err := be.QueueSender.Send(ctx, req) + if err != nil { + be.Set.Logger.Error("Exporting failed. Rejecting data."+be.ExportFailureMessage, + zap.Error(err), zap.Int("rejected_items", req.ItemsCount())) + } + return err +} + +// connectSenders connects the senders in the predefined order. +func (be *BaseExporter) connectSenders() { + be.QueueSender.SetNextSender(be.BatchSender) + be.BatchSender.SetNextSender(be.ObsrepSender) + be.ObsrepSender.SetNextSender(be.RetrySender) + be.RetrySender.SetNextSender(be.TimeoutSender) +} + +func (be *BaseExporter) Start(ctx context.Context, host component.Host) error { + // First start the wrapped exporter. + if err := be.StartFunc.Start(ctx, host); err != nil { + return err + } + + // If no error then start the BatchSender. + if err := be.BatchSender.Start(ctx, host); err != nil { + return err + } + + // Last start the queueSender. + return be.QueueSender.Start(ctx, host) +} + +func (be *BaseExporter) Shutdown(ctx context.Context) error { + return multierr.Combine( + // First shutdown the retry sender, so the queue sender can flush the queue without retries. + be.RetrySender.Shutdown(ctx), + // Then shutdown the batch sender + be.BatchSender.Shutdown(ctx), + // Then shutdown the queue sender. + be.QueueSender.Shutdown(ctx), + // Last shutdown the wrapped exporter itself. + be.ShutdownFunc.Shutdown(ctx)) +} + +// WithStart overrides the default Start function for an exporter. +// The default start function does nothing and always returns nil. +func WithStart(start component.StartFunc) Option { + return func(o *BaseExporter) error { + o.StartFunc = start + return nil + } +} + +// WithShutdown overrides the default Shutdown function for an exporter. +// The default shutdown function does nothing and always returns nil. +func WithShutdown(shutdown component.ShutdownFunc) Option { + return func(o *BaseExporter) error { + o.ShutdownFunc = shutdown + return nil + } +} + +// WithTimeout overrides the default TimeoutConfig for an exporter. +// The default TimeoutConfig is 5 seconds. +func WithTimeout(timeoutConfig TimeoutConfig) Option { + return func(o *BaseExporter) error { + o.TimeoutSender.cfg = timeoutConfig + return nil + } +} + +// WithRetry overrides the default configretry.BackOffConfig for an exporter. +// The default configretry.BackOffConfig is to disable retries. +func WithRetry(config configretry.BackOffConfig) Option { + return func(o *BaseExporter) error { + if !config.Enabled { + o.ExportFailureMessage += " Try enabling retry_on_failure config option to retry on retryable errors." + return nil + } + o.RetrySender = newRetrySender(config, o.Set) + return nil + } +} + +// WithQueue overrides the default QueueConfig for an exporter. +// The default QueueConfig is to disable queueing. +// This option cannot be used with the new exporter helpers New[Traces|Metrics|Logs]RequestExporter. +func WithQueue(config QueueConfig) Option { + return func(o *BaseExporter) error { + if o.Marshaler == nil || o.Unmarshaler == nil { + return fmt.Errorf("WithQueue option is not available for the new request exporters, use WithRequestQueue instead") + } + if !config.Enabled { + o.ExportFailureMessage += " Try enabling sending_queue to survive temporary failures." + return nil + } + qf := exporterqueue.NewPersistentQueueFactory[internal.Request](config.StorageID, exporterqueue.PersistentQueueSettings[internal.Request]{ + Marshaler: o.Marshaler, + Unmarshaler: o.Unmarshaler, + }) + q := qf(context.Background(), exporterqueue.Settings{ + DataType: o.Signal, + ExporterSettings: o.Set, + }, exporterqueue.Config{ + Enabled: config.Enabled, + NumConsumers: config.NumConsumers, + QueueSize: config.QueueSize, + }) + o.QueueSender = NewQueueSender(q, o.Set, config.NumConsumers, o.ExportFailureMessage, o.Obsrep) + return nil + } +} + +// WithRequestQueue enables queueing for an exporter. +// This option should be used with the new exporter helpers New[Traces|Metrics|Logs]RequestExporter. +// Experimental: This API is at the early stage of development and may change without backward compatibility +// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved. +func WithRequestQueue(cfg exporterqueue.Config, queueFactory exporterqueue.Factory[internal.Request]) Option { + return func(o *BaseExporter) error { + if o.Marshaler != nil || o.Unmarshaler != nil { + return fmt.Errorf("WithRequestQueue option must be used with the new request exporters only, use WithQueue instead") + } + if !cfg.Enabled { + o.ExportFailureMessage += " Try enabling sending_queue to survive temporary failures." + return nil + } + o.QueueCfg = cfg + o.QueueFactory = queueFactory + return nil + } +} + +// WithCapabilities overrides the default Capabilities() function for a Consumer. +// The default is non-mutable data. +// TODO: Verify if we can change the default to be mutable as we do for processors. +func WithCapabilities(capabilities consumer.Capabilities) Option { + return func(o *BaseExporter) error { + o.ConsumerOptions = append(o.ConsumerOptions, consumer.WithCapabilities(capabilities)) + return nil + } +} + +// WithRequestBatchFuncs sets the functions for merging and splitting batches for an exporter built for custom request types. +func WithRequestBatchFuncs(mf exporterbatcher.BatchMergeFunc[internal.Request], msf exporterbatcher.BatchMergeSplitFunc[internal.Request]) BatcherOption { + return func(bs *BatchSender) error { + if mf == nil || msf == nil { + return fmt.Errorf("WithRequestBatchFuncs must be provided with non-nil functions") + } + if bs.mergeFunc != nil || bs.mergeSplitFunc != nil { + return fmt.Errorf("WithRequestBatchFuncs can only be used once with request-based exporters") + } + bs.mergeFunc = mf + bs.mergeSplitFunc = msf + return nil + } +} + +// WithBatcher enables batching for an exporter based on custom request types. +// For now, it can be used only with the New[Traces|Metrics|Logs]RequestExporter exporter helpers and +// WithRequestBatchFuncs provided. +// This API is at the early stage of development and may change without backward compatibility +// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved. +func WithBatcher(cfg exporterbatcher.Config, opts ...BatcherOption) Option { + return func(o *BaseExporter) error { + o.BatcherCfg = cfg + o.BatcherOpts = opts + return nil + } +} + +// WithMarshaler is used to set the request marshaler for the new exporter helper. +// It must be provided as the first option when creating a new exporter helper. +func WithMarshaler(marshaler exporterqueue.Marshaler[internal.Request]) Option { + return func(o *BaseExporter) error { + o.Marshaler = marshaler + return nil + } +} + +// withUnmarshaler is used to set the request unmarshaler for the new exporter helper. +// It must be provided as the first option when creating a new exporter helper. +func WithUnmarshaler(unmarshaler exporterqueue.Unmarshaler[internal.Request]) Option { + return func(o *BaseExporter) error { + o.Unmarshaler = unmarshaler + return nil + } +} + +// withBatchFuncs is used to set the functions for merging and splitting batches for OLTP-based exporters. +// It must be provided as the first option when creating a new exporter helper. +func WithBatchFuncs(mf exporterbatcher.BatchMergeFunc[internal.Request], msf exporterbatcher.BatchMergeSplitFunc[internal.Request]) Option { + return func(o *BaseExporter) error { + o.BatchMergeFunc = mf + o.BatchMergeSplitfunc = msf + return nil + } +} + +func CheckStatus(t *testing.T, sd sdktrace.ReadOnlySpan, err error) { + if err != nil { + require.Equal(t, codes.Error, sd.Status().Code, "SpanData %v", sd) + require.Equal(t, err.Error(), sd.Status().Description, "SpanData %v", sd) + } else { + require.Equal(t, codes.Unset, sd.Status().Code, "SpanData %v", sd) + } +} diff --git a/exporter/exporterhelper/common_test.go b/exporter/exporterhelper/internal/base_exporter_test.go similarity index 69% rename from exporter/exporterhelper/common_test.go rename to exporter/exporterhelper/internal/base_exporter_test.go index 512233ae1c7..f9c5975a171 100644 --- a/exporter/exporterhelper/common_test.go +++ b/exporter/exporterhelper/internal/base_exporter_test.go @@ -1,7 +1,7 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -package exporterhelper +package internal import ( "context" @@ -9,8 +9,6 @@ import ( "testing" "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel/codes" - sdktrace "go.opentelemetry.io/otel/sdk/trace" "go.uber.org/zap" "go.uber.org/zap/zaptest/observer" @@ -20,6 +18,7 @@ import ( "go.opentelemetry.io/collector/exporter" "go.opentelemetry.io/collector/exporter/exporterqueue" "go.opentelemetry.io/collector/exporter/exportertest" + "go.opentelemetry.io/collector/exporter/internal" ) var ( @@ -33,12 +32,12 @@ var ( }() ) -func newNoopObsrepSender(*obsReport) requestSender { - return &baseRequestSender{} +func newNoopObsrepSender(*ObsReport) RequestSender { + return &BaseRequestSender{} } func TestBaseExporter(t *testing.T) { - be, err := newBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender) + be, err := NewBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender) require.NoError(t, err) require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost())) require.NoError(t, be.Shutdown(context.Background())) @@ -46,7 +45,7 @@ func TestBaseExporter(t *testing.T) { func TestBaseExporterWithOptions(t *testing.T) { want := errors.New("my error") - be, err := newBaseExporter( + be, err := NewBaseExporter( defaultSettings, defaultDataType, newNoopObsrepSender, WithStart(func(context.Context, component.Host) error { return want }), WithShutdown(func(context.Context) error { return want }), @@ -57,29 +56,20 @@ func TestBaseExporterWithOptions(t *testing.T) { require.Equal(t, want, be.Shutdown(context.Background())) } -func checkStatus(t *testing.T, sd sdktrace.ReadOnlySpan, err error) { - if err != nil { - require.Equal(t, codes.Error, sd.Status().Code, "SpanData %v", sd) - require.Equal(t, err.Error(), sd.Status().Description, "SpanData %v", sd) - } else { - require.Equal(t, codes.Unset, sd.Status().Code, "SpanData %v", sd) - } -} - func TestQueueOptionsWithRequestExporter(t *testing.T) { - bs, err := newBaseExporter(exportertest.NewNopSettings(), defaultDataType, newNoopObsrepSender, + bs, err := NewBaseExporter(exportertest.NewNopSettings(), defaultDataType, newNoopObsrepSender, WithRetry(configretry.NewDefaultBackOffConfig())) require.NoError(t, err) - require.Nil(t, bs.marshaler) - require.Nil(t, bs.unmarshaler) - _, err = newBaseExporter(exportertest.NewNopSettings(), defaultDataType, newNoopObsrepSender, + require.Nil(t, bs.Marshaler) + require.Nil(t, bs.Unmarshaler) + _, err = NewBaseExporter(exportertest.NewNopSettings(), defaultDataType, newNoopObsrepSender, WithRetry(configretry.NewDefaultBackOffConfig()), WithQueue(NewDefaultQueueConfig())) require.Error(t, err) - _, err = newBaseExporter(exportertest.NewNopSettings(), defaultDataType, newNoopObsrepSender, - withMarshaler(mockRequestMarshaler), withUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), + _, err = NewBaseExporter(exportertest.NewNopSettings(), defaultDataType, newNoopObsrepSender, + WithMarshaler(mockRequestMarshaler), WithUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), WithRetry(configretry.NewDefaultBackOffConfig()), - WithRequestQueue(exporterqueue.NewDefaultConfig(), exporterqueue.NewMemoryQueueFactory[Request]())) + WithRequestQueue(exporterqueue.NewDefaultConfig(), exporterqueue.NewMemoryQueueFactory[internal.Request]())) require.Error(t, err) } @@ -89,9 +79,9 @@ func TestBaseExporterLogging(t *testing.T) { set.Logger = zap.New(logger) rCfg := configretry.NewDefaultBackOffConfig() rCfg.Enabled = false - bs, err := newBaseExporter(set, defaultDataType, newNoopObsrepSender, WithRetry(rCfg)) + bs, err := NewBaseExporter(set, defaultDataType, newNoopObsrepSender, WithRetry(rCfg)) require.NoError(t, err) - sendErr := bs.send(context.Background(), newErrorRequest()) + sendErr := bs.Send(context.Background(), newErrorRequest()) require.Error(t, sendErr) require.Len(t, observed.FilterLevelExact(zap.ErrorLevel).All(), 1) diff --git a/exporter/exporterhelper/batch_sender.go b/exporter/exporterhelper/internal/batch_sender.go similarity index 81% rename from exporter/exporterhelper/batch_sender.go rename to exporter/exporterhelper/internal/batch_sender.go index 4d9635195e2..65d7e0965f7 100644 --- a/exporter/exporterhelper/batch_sender.go +++ b/exporter/exporterhelper/internal/batch_sender.go @@ -1,7 +1,7 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -package exporterhelper // import "go.opentelemetry.io/collector/exporter/exporterhelper" +package internal // import "go.opentelemetry.io/collector/exporter/exporterhelper/internal" import ( "context" @@ -14,18 +14,19 @@ import ( "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/exporter" "go.opentelemetry.io/collector/exporter/exporterbatcher" + "go.opentelemetry.io/collector/exporter/internal" ) -// batchSender is a component that places requests into batches before passing them to the downstream senders. +// BatchSender is a component that places requests into batches before passing them to the downstream senders. // Batches are sent out with any of the following conditions: // - batch size reaches cfg.MinSizeItems // - cfg.FlushTimeout is elapsed since the timestamp when the previous batch was sent out. // - concurrencyLimit is reached. -type batchSender struct { - baseRequestSender +type BatchSender struct { + BaseRequestSender cfg exporterbatcher.Config - mergeFunc exporterbatcher.BatchMergeFunc[Request] - mergeSplitFunc exporterbatcher.BatchMergeSplitFunc[Request] + mergeFunc exporterbatcher.BatchMergeFunc[internal.Request] + mergeSplitFunc exporterbatcher.BatchMergeSplitFunc[internal.Request] // concurrencyLimit is the maximum number of goroutines that can be blocked by the batcher. // If this number is reached and all the goroutines are busy, the batch will be sent right away. @@ -45,9 +46,9 @@ type batchSender struct { } // newBatchSender returns a new batch consumer component. -func newBatchSender(cfg exporterbatcher.Config, set exporter.Settings, - mf exporterbatcher.BatchMergeFunc[Request], msf exporterbatcher.BatchMergeSplitFunc[Request]) *batchSender { - bs := &batchSender{ +func NewBatchSender(cfg exporterbatcher.Config, set exporter.Settings, + mf exporterbatcher.BatchMergeFunc[internal.Request], msf exporterbatcher.BatchMergeSplitFunc[internal.Request]) *BatchSender { + bs := &BatchSender{ activeBatch: newEmptyBatch(), cfg: cfg, logger: set.Logger, @@ -60,7 +61,7 @@ func newBatchSender(cfg exporterbatcher.Config, set exporter.Settings, return bs } -func (bs *batchSender) Start(_ context.Context, _ component.Host) error { +func (bs *BatchSender) Start(_ context.Context, _ component.Host) error { bs.shutdownCh = make(chan struct{}) timer := time.NewTimer(bs.cfg.FlushTimeout) go func() { @@ -103,7 +104,7 @@ func (bs *batchSender) Start(_ context.Context, _ component.Host) error { type batch struct { ctx context.Context - request Request + request internal.Request done chan struct{} err error @@ -121,9 +122,9 @@ func newEmptyBatch() *batch { // exportActiveBatch exports the active batch asynchronously and replaces it with a new one. // Caller must hold the lock. -func (bs *batchSender) exportActiveBatch() { +func (bs *BatchSender) exportActiveBatch() { go func(b *batch) { - b.err = bs.nextSender.send(b.ctx, b.request) + b.err = bs.NextSender.Send(b.ctx, b.request) close(b.done) bs.activeRequests.Add(-b.requestsBlocked) }(bs.activeBatch) @@ -134,15 +135,15 @@ func (bs *batchSender) exportActiveBatch() { // isActiveBatchReady returns true if the active batch is ready to be exported. // The batch is ready if it has reached the minimum size or the concurrency limit is reached. // Caller must hold the lock. -func (bs *batchSender) isActiveBatchReady() bool { +func (bs *BatchSender) isActiveBatchReady() bool { return bs.activeBatch.request.ItemsCount() >= bs.cfg.MinSizeItems || (bs.concurrencyLimit > 0 && bs.activeRequests.Load() >= bs.concurrencyLimit) } -func (bs *batchSender) send(ctx context.Context, req Request) error { +func (bs *BatchSender) Send(ctx context.Context, req internal.Request) error { // Stopped batch sender should act as pass-through to allow the queue to be drained. if bs.stopped.Load() { - return bs.nextSender.send(ctx, req) + return bs.NextSender.Send(ctx, req) } if bs.cfg.MaxSizeItems > 0 { @@ -152,7 +153,7 @@ func (bs *batchSender) send(ctx context.Context, req Request) error { } // sendMergeSplitBatch sends the request to the batch which may be split into multiple requests. -func (bs *batchSender) sendMergeSplitBatch(ctx context.Context, req Request) error { +func (bs *BatchSender) sendMergeSplitBatch(ctx context.Context, req internal.Request) error { bs.mu.Lock() reqs, err := bs.mergeSplitFunc(ctx, bs.cfg.MaxSizeConfig, bs.activeBatch.request, req) @@ -187,7 +188,7 @@ func (bs *batchSender) sendMergeSplitBatch(ctx context.Context, req Request) err // Intentionally do not put the last request in the active batch to not block it. // TODO: Consider including the partial request in the error to avoid double publishing. for _, r := range reqs { - if err := bs.nextSender.send(ctx, r); err != nil { + if err := bs.NextSender.Send(ctx, r); err != nil { return err } } @@ -195,7 +196,7 @@ func (bs *batchSender) sendMergeSplitBatch(ctx context.Context, req Request) err } // sendMergeBatch sends the request to the batch and waits for the batch to be exported. -func (bs *batchSender) sendMergeBatch(ctx context.Context, req Request) error { +func (bs *BatchSender) sendMergeBatch(ctx context.Context, req internal.Request) error { bs.mu.Lock() if bs.activeBatch.request != nil { @@ -223,14 +224,14 @@ func (bs *batchSender) sendMergeBatch(ctx context.Context, req Request) error { // The context is only set once and is not updated after the first call. // Merging the context would be complex and require an additional goroutine to handle the context cancellation. // We take the approach of using the context from the first request since it's likely to have the shortest timeout. -func (bs *batchSender) updateActiveBatch(ctx context.Context, req Request) { +func (bs *BatchSender) updateActiveBatch(ctx context.Context, req internal.Request) { if bs.activeBatch.request == nil { bs.activeBatch.ctx = ctx } bs.activeBatch.request = req } -func (bs *batchSender) Shutdown(context.Context) error { +func (bs *BatchSender) Shutdown(context.Context) error { bs.stopped.Store(true) if bs.shutdownCh != nil { close(bs.shutdownCh) diff --git a/exporter/exporterhelper/batch_sender_test.go b/exporter/exporterhelper/internal/batch_sender_test.go similarity index 83% rename from exporter/exporterhelper/batch_sender_test.go rename to exporter/exporterhelper/internal/batch_sender_test.go index 0c4823c0e8b..53ef9451137 100644 --- a/exporter/exporterhelper/batch_sender_test.go +++ b/exporter/exporterhelper/internal/batch_sender_test.go @@ -1,7 +1,7 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -package exporterhelper // import "go.opentelemetry.io/collector/exporter/exporterhelper" +package internal import ( "context" @@ -17,6 +17,7 @@ import ( "go.opentelemetry.io/collector/component/componenttest" "go.opentelemetry.io/collector/exporter/exporterbatcher" "go.opentelemetry.io/collector/exporter/exporterqueue" + "go.opentelemetry.io/collector/exporter/internal" ) func TestBatchSender_Merge(t *testing.T) { @@ -55,23 +56,23 @@ func TestBatchSender_Merge(t *testing.T) { sink := newFakeRequestSink() - require.NoError(t, be.send(context.Background(), &fakeRequest{items: 8, sink: sink})) - require.NoError(t, be.send(context.Background(), &fakeRequest{items: 3, sink: sink})) + require.NoError(t, be.Send(context.Background(), &fakeRequest{items: 8, sink: sink})) + require.NoError(t, be.Send(context.Background(), &fakeRequest{items: 3, sink: sink})) // the first two requests should be merged into one and sent by reaching the minimum items size assert.Eventually(t, func() bool { return sink.requestsCount.Load() == 1 && sink.itemsCount.Load() == 11 }, 50*time.Millisecond, 10*time.Millisecond) - require.NoError(t, be.send(context.Background(), &fakeRequest{items: 3, sink: sink})) - require.NoError(t, be.send(context.Background(), &fakeRequest{items: 1, sink: sink})) + require.NoError(t, be.Send(context.Background(), &fakeRequest{items: 3, sink: sink})) + require.NoError(t, be.Send(context.Background(), &fakeRequest{items: 1, sink: sink})) // the third and fifth requests should be sent by reaching the timeout // the fourth request should be ignored because of the merge error. time.Sleep(50 * time.Millisecond) // should be ignored because of the merge error. - require.NoError(t, be.send(context.Background(), &fakeRequest{items: 3, sink: sink, + require.NoError(t, be.Send(context.Background(), &fakeRequest{items: 3, sink: sink, mergeErr: errors.New("merge error")})) assert.Equal(t, uint64(1), sink.requestsCount.Load()) @@ -125,8 +126,8 @@ func TestBatchSender_BatchExportError(t *testing.T) { sink := newFakeRequestSink() - require.NoError(t, be.send(context.Background(), &fakeRequest{items: 4, sink: sink})) - require.NoError(t, be.send(context.Background(), &fakeRequest{items: 4, sink: sink})) + require.NoError(t, be.Send(context.Background(), &fakeRequest{items: 4, sink: sink})) + require.NoError(t, be.Send(context.Background(), &fakeRequest{items: 4, sink: sink})) // the first two requests should be blocked by the batchSender. time.Sleep(50 * time.Millisecond) @@ -134,14 +135,14 @@ func TestBatchSender_BatchExportError(t *testing.T) { // the third request should trigger the export and cause an error. errReq := &fakeRequest{items: 20, exportErr: errors.New("transient error"), sink: sink} - require.NoError(t, be.send(context.Background(), errReq)) + require.NoError(t, be.Send(context.Background(), errReq)) // the batch should be dropped since the queue doesn't have requeuing enabled. assert.Eventually(t, func() bool { return sink.requestsCount.Load() == tt.expectedRequests && sink.itemsCount.Load() == tt.expectedItems && - be.batchSender.(*batchSender).activeRequests.Load() == 0 && - be.queueSender.(*queueSender).queue.Size() == 0 + be.BatchSender.(*BatchSender).activeRequests.Load() == 0 && + be.QueueSender.(*QueueSender).queue.Size() == 0 }, 100*time.Millisecond, 10*time.Millisecond) }) } @@ -162,24 +163,24 @@ func TestBatchSender_MergeOrSplit(t *testing.T) { sink := newFakeRequestSink() // should be sent right away by reaching the minimum items size. - require.NoError(t, be.send(context.Background(), &fakeRequest{items: 8, sink: sink})) + require.NoError(t, be.Send(context.Background(), &fakeRequest{items: 8, sink: sink})) assert.Eventually(t, func() bool { return sink.requestsCount.Load() == 1 && sink.itemsCount.Load() == 8 }, 50*time.Millisecond, 10*time.Millisecond) // big request should be broken down into two requests, both are sent right away. - require.NoError(t, be.send(context.Background(), &fakeRequest{items: 17, sink: sink})) + require.NoError(t, be.Send(context.Background(), &fakeRequest{items: 17, sink: sink})) assert.Eventually(t, func() bool { return sink.requestsCount.Load() == 3 && sink.itemsCount.Load() == 25 }, 50*time.Millisecond, 10*time.Millisecond) // request that cannot be split should be dropped. - require.NoError(t, be.send(context.Background(), &fakeRequest{items: 11, sink: sink, + require.NoError(t, be.Send(context.Background(), &fakeRequest{items: 11, sink: sink, mergeErr: errors.New("split error")})) // big request should be broken down into two requests, both are sent right away. - require.NoError(t, be.send(context.Background(), &fakeRequest{items: 13, sink: sink})) + require.NoError(t, be.Send(context.Background(), &fakeRequest{items: 13, sink: sink})) assert.Eventually(t, func() bool { return sink.requestsCount.Load() == 5 && sink.itemsCount.Load() == 38 @@ -194,7 +195,7 @@ func TestBatchSender_Shutdown(t *testing.T) { require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost())) sink := newFakeRequestSink() - require.NoError(t, be.send(context.Background(), &fakeRequest{items: 3, sink: sink})) + require.NoError(t, be.Send(context.Background(), &fakeRequest{items: 3, sink: sink})) // To make the request reached the batchSender before shutdown. time.Sleep(50 * time.Millisecond) @@ -210,7 +211,7 @@ func TestBatchSender_Disabled(t *testing.T) { cfg := exporterbatcher.NewDefaultConfig() cfg.Enabled = false cfg.MaxSizeItems = 5 - be, err := newBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, + be, err := NewBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, WithBatcher(cfg, WithRequestBatchFuncs(fakeBatchMergeFunc, fakeBatchMergeSplitFunc))) require.NotNil(t, be) require.NoError(t, err) @@ -222,20 +223,20 @@ func TestBatchSender_Disabled(t *testing.T) { sink := newFakeRequestSink() // should be sent right away without splitting because batching is disabled. - require.NoError(t, be.send(context.Background(), &fakeRequest{items: 8, sink: sink})) + require.NoError(t, be.Send(context.Background(), &fakeRequest{items: 8, sink: sink})) assert.Equal(t, uint64(1), sink.requestsCount.Load()) assert.Equal(t, uint64(8), sink.itemsCount.Load()) } func TestBatchSender_InvalidMergeSplitFunc(t *testing.T) { - invalidMergeSplitFunc := func(_ context.Context, _ exporterbatcher.MaxSizeConfig, _ Request, req2 Request) ([]Request, + invalidMergeSplitFunc := func(_ context.Context, _ exporterbatcher.MaxSizeConfig, _ internal.Request, req2 internal.Request) ([]internal.Request, error) { // reply with invalid 0 length slice if req2 is more than 20 items if req2.(*fakeRequest).items > 20 { - return []Request{}, nil + return []internal.Request{}, nil } // otherwise reply with a single request. - return []Request{req2}, nil + return []internal.Request{req2}, nil } cfg := exporterbatcher.NewDefaultConfig() cfg.FlushTimeout = 50 * time.Millisecond @@ -249,16 +250,16 @@ func TestBatchSender_InvalidMergeSplitFunc(t *testing.T) { sink := newFakeRequestSink() // first request should be ignored due to invalid merge/split function. - require.NoError(t, be.send(context.Background(), &fakeRequest{items: 30, sink: sink})) + require.NoError(t, be.Send(context.Background(), &fakeRequest{items: 30, sink: sink})) // second request should be sent after reaching the timeout. - require.NoError(t, be.send(context.Background(), &fakeRequest{items: 15, sink: sink})) + require.NoError(t, be.Send(context.Background(), &fakeRequest{items: 15, sink: sink})) assert.Eventually(t, func() bool { return sink.requestsCount.Load() == 1 && sink.itemsCount.Load() == 15 }, 100*time.Millisecond, 10*time.Millisecond) } func TestBatchSender_PostShutdown(t *testing.T) { - be, err := newBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, + be, err := NewBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, WithBatcher(exporterbatcher.NewDefaultConfig(), WithRequestBatchFuncs(fakeBatchMergeFunc, fakeBatchMergeSplitFunc))) require.NotNil(t, be) @@ -268,7 +269,7 @@ func TestBatchSender_PostShutdown(t *testing.T) { // Closed batch sender should act as a pass-through to not block queue draining. sink := newFakeRequestSink() - require.NoError(t, be.send(context.Background(), &fakeRequest{items: 8, sink: sink})) + require.NoError(t, be.Send(context.Background(), &fakeRequest{items: 8, sink: sink})) assert.Equal(t, uint64(1), sink.requestsCount.Load()) assert.Equal(t, uint64(8), sink.itemsCount.Load()) } @@ -321,9 +322,9 @@ func TestBatchSender_ConcurrencyLimitReached(t *testing.T) { t.Run(tt.name, func(t *testing.T) { qCfg := exporterqueue.NewDefaultConfig() qCfg.NumConsumers = 2 - be, err := newBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, + be, err := NewBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, WithBatcher(tt.batcherCfg, WithRequestBatchFuncs(fakeBatchMergeFunc, fakeBatchMergeSplitFunc)), - WithRequestQueue(qCfg, exporterqueue.NewMemoryQueueFactory[Request]())) + WithRequestQueue(qCfg, exporterqueue.NewMemoryQueueFactory[internal.Request]())) require.NotNil(t, be) require.NoError(t, err) assert.NoError(t, be.Start(context.Background(), componenttest.NewNopHost())) @@ -333,29 +334,29 @@ func TestBatchSender_ConcurrencyLimitReached(t *testing.T) { sink := newFakeRequestSink() // the 1st and 2nd request should be flushed in the same batched request by max concurrency limit. - assert.NoError(t, be.send(context.Background(), &fakeRequest{items: 2, sink: sink})) - assert.NoError(t, be.send(context.Background(), &fakeRequest{items: 2, sink: sink})) + assert.NoError(t, be.Send(context.Background(), &fakeRequest{items: 2, sink: sink})) + assert.NoError(t, be.Send(context.Background(), &fakeRequest{items: 2, sink: sink})) assert.Eventually(t, func() bool { return sink.requestsCount.Load() == 1 && sink.itemsCount.Load() == 4 }, 100*time.Millisecond, 10*time.Millisecond) // the 3rd request should be flushed by itself due to flush interval - require.NoError(t, be.send(context.Background(), &fakeRequest{items: 2, sink: sink})) + require.NoError(t, be.Send(context.Background(), &fakeRequest{items: 2, sink: sink})) assert.Eventually(t, func() bool { return sink.requestsCount.Load() == 2 && sink.itemsCount.Load() == 6 }, 100*time.Millisecond, 10*time.Millisecond) // the 4th and 5th request should be flushed in the same batched request by max concurrency limit. - assert.NoError(t, be.send(context.Background(), &fakeRequest{items: 2, sink: sink})) - assert.NoError(t, be.send(context.Background(), &fakeRequest{items: 2, sink: sink})) + assert.NoError(t, be.Send(context.Background(), &fakeRequest{items: 2, sink: sink})) + assert.NoError(t, be.Send(context.Background(), &fakeRequest{items: 2, sink: sink})) assert.Eventually(t, func() bool { return sink.requestsCount.Load() == 3 && sink.itemsCount.Load() == 10 }, 100*time.Millisecond, 10*time.Millisecond) // do it a few more times to ensure it produces the correct batch size regardless of goroutine scheduling. - assert.NoError(t, be.send(context.Background(), &fakeRequest{items: 5, sink: sink})) - assert.NoError(t, be.send(context.Background(), &fakeRequest{items: 6, sink: sink})) + assert.NoError(t, be.Send(context.Background(), &fakeRequest{items: 5, sink: sink})) + assert.NoError(t, be.Send(context.Background(), &fakeRequest{items: 6, sink: sink})) if tt.batcherCfg.MaxSizeItems == 10 { // in case of MaxSizeItems=10, wait for the leftover request to send assert.Eventually(t, func() bool { @@ -363,9 +364,9 @@ func TestBatchSender_ConcurrencyLimitReached(t *testing.T) { }, 50*time.Millisecond, 10*time.Millisecond) } - assert.NoError(t, be.send(context.Background(), &fakeRequest{items: 4, sink: sink})) - assert.NoError(t, be.send(context.Background(), &fakeRequest{items: 6, sink: sink})) - assert.NoError(t, be.send(context.Background(), &fakeRequest{items: 20, sink: sink})) + assert.NoError(t, be.Send(context.Background(), &fakeRequest{items: 4, sink: sink})) + assert.NoError(t, be.Send(context.Background(), &fakeRequest{items: 6, sink: sink})) + assert.NoError(t, be.Send(context.Background(), &fakeRequest{items: 20, sink: sink})) assert.Eventually(t, func() bool { return sink.requestsCount.Load() == tt.expectedRequests && sink.itemsCount.Load() == tt.expectedItems }, 100*time.Millisecond, 10*time.Millisecond) @@ -376,7 +377,7 @@ func TestBatchSender_ConcurrencyLimitReached(t *testing.T) { func TestBatchSender_BatchBlocking(t *testing.T) { bCfg := exporterbatcher.NewDefaultConfig() bCfg.MinSizeItems = 3 - be, err := newBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, + be, err := NewBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, WithBatcher(bCfg, WithRequestBatchFuncs(fakeBatchMergeFunc, fakeBatchMergeSplitFunc))) require.NotNil(t, be) require.NoError(t, err) @@ -389,7 +390,7 @@ func TestBatchSender_BatchBlocking(t *testing.T) { for i := 0; i < 6; i++ { wg.Add(1) go func() { - assert.NoError(t, be.send(context.Background(), &fakeRequest{items: 1, sink: sink, delay: 10 * time.Millisecond})) + assert.NoError(t, be.Send(context.Background(), &fakeRequest{items: 1, sink: sink, delay: 10 * time.Millisecond})) wg.Done() }() } @@ -406,7 +407,7 @@ func TestBatchSender_BatchBlocking(t *testing.T) { func TestBatchSender_BatchCancelled(t *testing.T) { bCfg := exporterbatcher.NewDefaultConfig() bCfg.MinSizeItems = 2 - be, err := newBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, + be, err := NewBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, WithBatcher(bCfg, WithRequestBatchFuncs(fakeBatchMergeFunc, fakeBatchMergeSplitFunc))) require.NotNil(t, be) require.NoError(t, err) @@ -419,13 +420,13 @@ func TestBatchSender_BatchCancelled(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) wg.Add(1) go func() { - assert.ErrorIs(t, be.send(ctx, &fakeRequest{items: 1, sink: sink, delay: 100 * time.Millisecond}), context.Canceled) + assert.ErrorIs(t, be.Send(ctx, &fakeRequest{items: 1, sink: sink, delay: 100 * time.Millisecond}), context.Canceled) wg.Done() }() wg.Add(1) go func() { time.Sleep(20 * time.Millisecond) // ensure this call is the second - assert.ErrorIs(t, be.send(context.Background(), &fakeRequest{items: 1, sink: sink, delay: 100 * time.Millisecond}), context.Canceled) + assert.ErrorIs(t, be.Send(context.Background(), &fakeRequest{items: 1, sink: sink, delay: 100 * time.Millisecond}), context.Canceled) wg.Done() }() cancel() // canceling the first request should cancel the whole batch @@ -441,7 +442,7 @@ func TestBatchSender_BatchCancelled(t *testing.T) { func TestBatchSender_DrainActiveRequests(t *testing.T) { bCfg := exporterbatcher.NewDefaultConfig() bCfg.MinSizeItems = 2 - be, err := newBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, + be, err := NewBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, WithBatcher(bCfg, WithRequestBatchFuncs(fakeBatchMergeFunc, fakeBatchMergeSplitFunc))) require.NotNil(t, be) require.NoError(t, err) @@ -451,13 +452,13 @@ func TestBatchSender_DrainActiveRequests(t *testing.T) { // send 3 blocking requests with a timeout go func() { - assert.NoError(t, be.send(context.Background(), &fakeRequest{items: 1, sink: sink, delay: 40 * time.Millisecond})) + assert.NoError(t, be.Send(context.Background(), &fakeRequest{items: 1, sink: sink, delay: 40 * time.Millisecond})) }() go func() { - assert.NoError(t, be.send(context.Background(), &fakeRequest{items: 1, sink: sink, delay: 40 * time.Millisecond})) + assert.NoError(t, be.Send(context.Background(), &fakeRequest{items: 1, sink: sink, delay: 40 * time.Millisecond})) }() go func() { - assert.NoError(t, be.send(context.Background(), &fakeRequest{items: 1, sink: sink, delay: 40 * time.Millisecond})) + assert.NoError(t, be.Send(context.Background(), &fakeRequest{items: 1, sink: sink, delay: 40 * time.Millisecond})) }() // give time for the first two requests to be batched @@ -484,13 +485,13 @@ func TestBatchSender_WithBatcherOption(t *testing.T) { }, { name: "funcs_set_internally", - opts: []Option{withBatchFuncs(fakeBatchMergeFunc, fakeBatchMergeSplitFunc), WithBatcher(exporterbatcher.NewDefaultConfig())}, + opts: []Option{WithBatchFuncs(fakeBatchMergeFunc, fakeBatchMergeSplitFunc), WithBatcher(exporterbatcher.NewDefaultConfig())}, expectedErr: false, }, { name: "funcs_set_twice", opts: []Option{ - withBatchFuncs(fakeBatchMergeFunc, fakeBatchMergeSplitFunc), + WithBatchFuncs(fakeBatchMergeFunc, fakeBatchMergeSplitFunc), WithBatcher(exporterbatcher.NewDefaultConfig(), WithRequestBatchFuncs(fakeBatchMergeFunc, fakeBatchMergeSplitFunc)), }, @@ -504,7 +505,7 @@ func TestBatchSender_WithBatcherOption(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - be, err := newBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, tt.opts...) + be, err := NewBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, tt.opts...) if tt.expectedErr { assert.Nil(t, be) assert.Error(t, err) @@ -517,7 +518,7 @@ func TestBatchSender_WithBatcherOption(t *testing.T) { } func TestBatchSender_UnstartedShutdown(t *testing.T) { - be, err := newBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, + be, err := NewBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, WithBatcher(exporterbatcher.NewDefaultConfig(), WithRequestBatchFuncs(fakeBatchMergeFunc, fakeBatchMergeSplitFunc))) require.NoError(t, err) @@ -532,7 +533,7 @@ func TestBatchSender_ShutdownDeadlock(t *testing.T) { waitMerge := make(chan struct{}, 10) // blockedBatchMergeFunc blocks until the blockMerge channel is closed - blockedBatchMergeFunc := func(_ context.Context, r1 Request, r2 Request) (Request, error) { + blockedBatchMergeFunc := func(_ context.Context, r1 internal.Request, r2 internal.Request) (internal.Request, error) { waitMerge <- struct{}{} <-blockMerge r1.(*fakeRequest).items += r2.(*fakeRequest).items @@ -541,7 +542,7 @@ func TestBatchSender_ShutdownDeadlock(t *testing.T) { bCfg := exporterbatcher.NewDefaultConfig() bCfg.FlushTimeout = 10 * time.Minute // high timeout to avoid the timeout to trigger - be, err := newBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, + be, err := NewBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, WithBatcher(bCfg, WithRequestBatchFuncs(blockedBatchMergeFunc, fakeBatchMergeSplitFunc))) require.NoError(t, err) require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost())) @@ -549,8 +550,8 @@ func TestBatchSender_ShutdownDeadlock(t *testing.T) { sink := newFakeRequestSink() // Send 2 concurrent requests - go func() { assert.NoError(t, be.send(context.Background(), &fakeRequest{items: 4, sink: sink})) }() - go func() { assert.NoError(t, be.send(context.Background(), &fakeRequest{items: 4, sink: sink})) }() + go func() { assert.NoError(t, be.Send(context.Background(), &fakeRequest{items: 4, sink: sink})) }() + go func() { assert.NoError(t, be.Send(context.Background(), &fakeRequest{items: 4, sink: sink})) }() // Wait for the requests to enter the merge function <-waitMerge @@ -577,7 +578,7 @@ func TestBatchSenderWithTimeout(t *testing.T) { bCfg.MinSizeItems = 10 tCfg := NewDefaultTimeoutConfig() tCfg.Timeout = 50 * time.Millisecond - be, err := newBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, + be, err := NewBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, WithBatcher(bCfg, WithRequestBatchFuncs(fakeBatchMergeFunc, fakeBatchMergeSplitFunc)), WithTimeout(tCfg)) require.NoError(t, err) @@ -590,7 +591,7 @@ func TestBatchSenderWithTimeout(t *testing.T) { for i := 0; i < 3; i++ { wg.Add(1) go func() { - assert.NoError(t, be.send(context.Background(), &fakeRequest{items: 4, sink: sink})) + assert.NoError(t, be.Send(context.Background(), &fakeRequest{items: 4, sink: sink})) wg.Done() }() } @@ -602,7 +603,7 @@ func TestBatchSenderWithTimeout(t *testing.T) { for i := 0; i < 3; i++ { wg.Add(1) go func() { - assert.Error(t, be.send(context.Background(), &fakeRequest{items: 4, sink: sink, delay: 30 * time.Millisecond})) + assert.Error(t, be.Send(context.Background(), &fakeRequest{items: 4, sink: sink, delay: 30 * time.Millisecond})) wg.Done() }() } @@ -616,7 +617,7 @@ func TestBatchSenderWithTimeout(t *testing.T) { } func TestBatchSenderTimerResetNoConflict(t *testing.T) { - delayBatchMergeFunc := func(_ context.Context, r1 Request, r2 Request) (Request, error) { + delayBatchMergeFunc := func(_ context.Context, r1 internal.Request, r2 internal.Request) (internal.Request, error) { time.Sleep(30 * time.Millisecond) if r1 == nil { return r2, nil @@ -636,7 +637,7 @@ func TestBatchSenderTimerResetNoConflict(t *testing.T) { bCfg := exporterbatcher.NewDefaultConfig() bCfg.MinSizeItems = 8 bCfg.FlushTimeout = 50 * time.Millisecond - be, err := newBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, + be, err := NewBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, WithBatcher(bCfg, WithRequestBatchFuncs(delayBatchMergeFunc, fakeBatchMergeSplitFunc))) require.NoError(t, err) require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost())) @@ -644,11 +645,11 @@ func TestBatchSenderTimerResetNoConflict(t *testing.T) { // Send 2 concurrent requests that should be merged in one batch in the same interval as the flush timer go func() { - assert.NoError(t, be.send(context.Background(), &fakeRequest{items: 4, sink: sink})) + assert.NoError(t, be.Send(context.Background(), &fakeRequest{items: 4, sink: sink})) }() time.Sleep(30 * time.Millisecond) go func() { - assert.NoError(t, be.send(context.Background(), &fakeRequest{items: 4, sink: sink})) + assert.NoError(t, be.Send(context.Background(), &fakeRequest{items: 4, sink: sink})) }() // The batch should be sent either with the flush interval or by reaching the minimum items size with no conflict @@ -667,7 +668,7 @@ func TestBatchSenderTimerFlush(t *testing.T) { bCfg := exporterbatcher.NewDefaultConfig() bCfg.MinSizeItems = 8 bCfg.FlushTimeout = 100 * time.Millisecond - be, err := newBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, + be, err := NewBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, WithBatcher(bCfg, WithRequestBatchFuncs(fakeBatchMergeFunc, fakeBatchMergeSplitFunc))) require.NoError(t, err) require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost())) @@ -676,10 +677,10 @@ func TestBatchSenderTimerFlush(t *testing.T) { // Send 2 concurrent requests that should be merged in one batch and sent immediately go func() { - assert.NoError(t, be.send(context.Background(), &fakeRequest{items: 4, sink: sink})) + assert.NoError(t, be.Send(context.Background(), &fakeRequest{items: 4, sink: sink})) }() go func() { - assert.NoError(t, be.send(context.Background(), &fakeRequest{items: 4, sink: sink})) + assert.NoError(t, be.Send(context.Background(), &fakeRequest{items: 4, sink: sink})) }() assert.EventuallyWithT(t, func(c *assert.CollectT) { assert.LessOrEqual(c, uint64(1), sink.requestsCount.Load()) @@ -688,7 +689,7 @@ func TestBatchSenderTimerFlush(t *testing.T) { // Send another request that should be flushed after 100ms instead of 50ms since last flush go func() { - assert.NoError(t, be.send(context.Background(), &fakeRequest{items: 4, sink: sink})) + assert.NoError(t, be.Send(context.Background(), &fakeRequest{items: 4, sink: sink})) }() // Confirm that it is not flushed in 50ms @@ -703,9 +704,9 @@ func TestBatchSenderTimerFlush(t *testing.T) { require.NoError(t, be.Shutdown(context.Background())) } -func queueBatchExporter(t *testing.T, batchOption Option) *baseExporter { - be, err := newBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, batchOption, - WithRequestQueue(exporterqueue.NewDefaultConfig(), exporterqueue.NewMemoryQueueFactory[Request]())) +func queueBatchExporter(t *testing.T, batchOption Option) *BaseExporter { + be, err := NewBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, batchOption, + WithRequestQueue(exporterqueue.NewDefaultConfig(), exporterqueue.NewMemoryQueueFactory[internal.Request]())) require.NotNil(t, be) require.NoError(t, err) return be diff --git a/exporter/exporterhelper/obsexporter.go b/exporter/exporterhelper/internal/obsexporter.go similarity index 52% rename from exporter/exporterhelper/obsexporter.go rename to exporter/exporterhelper/internal/obsexporter.go index 20821d9c779..2bb60f13544 100644 --- a/exporter/exporterhelper/obsexporter.go +++ b/exporter/exporterhelper/internal/obsexporter.go @@ -1,7 +1,7 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -package exporterhelper // import "go.opentelemetry.io/collector/exporter/exporterhelper" +package internal // import "go.opentelemetry.io/collector/exporter/exporterhelper/internal" import ( "context" @@ -13,109 +13,108 @@ import ( "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/exporter" - "go.opentelemetry.io/collector/exporter/exporterhelper/internal" "go.opentelemetry.io/collector/exporter/exporterhelper/internal/metadata" ) -// obsReport is a helper to add observability to an exporter. -type obsReport struct { +// ObsReport is a helper to add observability to an exporter. +type ObsReport struct { spanNamePrefix string tracer trace.Tracer - dataType component.DataType + DataType component.DataType otelAttrs []attribute.KeyValue - telemetryBuilder *metadata.TelemetryBuilder + TelemetryBuilder *metadata.TelemetryBuilder } -// obsReportSettings are settings for creating an obsReport. -type obsReportSettings struct { - exporterID component.ID - exporterCreateSettings exporter.Settings - dataType component.DataType +// ObsReportSettings are settings for creating an ObsReport. +type ObsReportSettings struct { + ExporterID component.ID + ExporterCreateSettings exporter.Settings + DataType component.DataType } -func newExporter(cfg obsReportSettings) (*obsReport, error) { - telemetryBuilder, err := metadata.NewTelemetryBuilder(cfg.exporterCreateSettings.TelemetrySettings) +func NewExporter(cfg ObsReportSettings) (*ObsReport, error) { + telemetryBuilder, err := metadata.NewTelemetryBuilder(cfg.ExporterCreateSettings.TelemetrySettings) if err != nil { return nil, err } - return &obsReport{ - spanNamePrefix: internal.ExporterPrefix + cfg.exporterID.String(), - tracer: cfg.exporterCreateSettings.TracerProvider.Tracer(cfg.exporterID.String()), - dataType: cfg.dataType, + return &ObsReport{ + spanNamePrefix: ExporterPrefix + cfg.ExporterID.String(), + tracer: cfg.ExporterCreateSettings.TracerProvider.Tracer(cfg.ExporterID.String()), + DataType: cfg.DataType, otelAttrs: []attribute.KeyValue{ - attribute.String(internal.ExporterKey, cfg.exporterID.String()), + attribute.String(ExporterKey, cfg.ExporterID.String()), }, - telemetryBuilder: telemetryBuilder, + TelemetryBuilder: telemetryBuilder, }, nil } -// startTracesOp is called at the start of an Export operation. +// StartTracesOp is called at the start of an Export operation. // The returned context should be used in other calls to the Exporter functions // dealing with the same export operation. -func (or *obsReport) startTracesOp(ctx context.Context) context.Context { - return or.startOp(ctx, internal.ExportTraceDataOperationSuffix) +func (or *ObsReport) StartTracesOp(ctx context.Context) context.Context { + return or.startOp(ctx, ExportTraceDataOperationSuffix) } -// endTracesOp completes the export operation that was started with startTracesOp. -func (or *obsReport) endTracesOp(ctx context.Context, numSpans int, err error) { +// EndTracesOp completes the export operation that was started with startTracesOp. +func (or *ObsReport) EndTracesOp(ctx context.Context, numSpans int, err error) { numSent, numFailedToSend := toNumItems(numSpans, err) or.recordMetrics(context.WithoutCancel(ctx), component.DataTypeTraces, numSent, numFailedToSend) - endSpan(ctx, err, numSent, numFailedToSend, internal.SentSpansKey, internal.FailedToSendSpansKey) + endSpan(ctx, err, numSent, numFailedToSend, SentSpansKey, FailedToSendSpansKey) } -// startMetricsOp is called at the start of an Export operation. +// StartMetricsOp is called at the start of an Export operation. // The returned context should be used in other calls to the Exporter functions // dealing with the same export operation. -func (or *obsReport) startMetricsOp(ctx context.Context) context.Context { - return or.startOp(ctx, internal.ExportMetricsOperationSuffix) +func (or *ObsReport) StartMetricsOp(ctx context.Context) context.Context { + return or.startOp(ctx, ExportMetricsOperationSuffix) } -// endMetricsOp completes the export operation that was started with +// EndMetricsOp completes the export operation that was started with // startMetricsOp. // // If needed, report your use case in https://github.com/open-telemetry/opentelemetry-collector/issues/10592. -func (or *obsReport) endMetricsOp(ctx context.Context, numMetricPoints int, err error) { +func (or *ObsReport) EndMetricsOp(ctx context.Context, numMetricPoints int, err error) { numSent, numFailedToSend := toNumItems(numMetricPoints, err) or.recordMetrics(context.WithoutCancel(ctx), component.DataTypeMetrics, numSent, numFailedToSend) - endSpan(ctx, err, numSent, numFailedToSend, internal.SentMetricPointsKey, internal.FailedToSendMetricPointsKey) + endSpan(ctx, err, numSent, numFailedToSend, SentMetricPointsKey, FailedToSendMetricPointsKey) } -// startLogsOp is called at the start of an Export operation. +// StartLogsOp is called at the start of an Export operation. // The returned context should be used in other calls to the Exporter functions // dealing with the same export operation. -func (or *obsReport) startLogsOp(ctx context.Context) context.Context { - return or.startOp(ctx, internal.ExportLogsOperationSuffix) +func (or *ObsReport) StartLogsOp(ctx context.Context) context.Context { + return or.startOp(ctx, ExportLogsOperationSuffix) } -// endLogsOp completes the export operation that was started with startLogsOp. -func (or *obsReport) endLogsOp(ctx context.Context, numLogRecords int, err error) { +// EndLogsOp completes the export operation that was started with startLogsOp. +func (or *ObsReport) EndLogsOp(ctx context.Context, numLogRecords int, err error) { numSent, numFailedToSend := toNumItems(numLogRecords, err) or.recordMetrics(context.WithoutCancel(ctx), component.DataTypeLogs, numSent, numFailedToSend) - endSpan(ctx, err, numSent, numFailedToSend, internal.SentLogRecordsKey, internal.FailedToSendLogRecordsKey) + endSpan(ctx, err, numSent, numFailedToSend, SentLogRecordsKey, FailedToSendLogRecordsKey) } // startOp creates the span used to trace the operation. Returning // the updated context and the created span. -func (or *obsReport) startOp(ctx context.Context, operationSuffix string) context.Context { +func (or *ObsReport) startOp(ctx context.Context, operationSuffix string) context.Context { spanName := or.spanNamePrefix + operationSuffix ctx, _ = or.tracer.Start(ctx, spanName) return ctx } -func (or *obsReport) recordMetrics(ctx context.Context, dataType component.DataType, sent, failed int64) { +func (or *ObsReport) recordMetrics(ctx context.Context, dataType component.DataType, sent, failed int64) { var sentMeasure, failedMeasure metric.Int64Counter switch dataType { case component.DataTypeTraces: - sentMeasure = or.telemetryBuilder.ExporterSentSpans - failedMeasure = or.telemetryBuilder.ExporterSendFailedSpans + sentMeasure = or.TelemetryBuilder.ExporterSentSpans + failedMeasure = or.TelemetryBuilder.ExporterSendFailedSpans case component.DataTypeMetrics: - sentMeasure = or.telemetryBuilder.ExporterSentMetricPoints - failedMeasure = or.telemetryBuilder.ExporterSendFailedMetricPoints + sentMeasure = or.TelemetryBuilder.ExporterSentMetricPoints + failedMeasure = or.TelemetryBuilder.ExporterSendFailedMetricPoints case component.DataTypeLogs: - sentMeasure = or.telemetryBuilder.ExporterSentLogRecords - failedMeasure = or.telemetryBuilder.ExporterSendFailedLogRecords + sentMeasure = or.TelemetryBuilder.ExporterSentLogRecords + failedMeasure = or.TelemetryBuilder.ExporterSendFailedLogRecords } sentMeasure.Add(ctx, sent, metric.WithAttributes(or.otelAttrs...)) @@ -144,15 +143,15 @@ func toNumItems(numExportedItems int, err error) (int64, int64) { return int64(numExportedItems), 0 } -func (or *obsReport) recordEnqueueFailure(ctx context.Context, dataType component.DataType, failed int64) { +func (or *ObsReport) RecordEnqueueFailure(ctx context.Context, dataType component.DataType, failed int64) { var enqueueFailedMeasure metric.Int64Counter switch dataType { case component.DataTypeTraces: - enqueueFailedMeasure = or.telemetryBuilder.ExporterEnqueueFailedSpans + enqueueFailedMeasure = or.TelemetryBuilder.ExporterEnqueueFailedSpans case component.DataTypeMetrics: - enqueueFailedMeasure = or.telemetryBuilder.ExporterEnqueueFailedMetricPoints + enqueueFailedMeasure = or.TelemetryBuilder.ExporterEnqueueFailedMetricPoints case component.DataTypeLogs: - enqueueFailedMeasure = or.telemetryBuilder.ExporterEnqueueFailedLogRecords + enqueueFailedMeasure = or.TelemetryBuilder.ExporterEnqueueFailedLogRecords } enqueueFailedMeasure.Add(ctx, failed, metric.WithAttributes(or.otelAttrs...)) diff --git a/exporter/exporterhelper/obsexporter_test.go b/exporter/exporterhelper/internal/obsexporter_test.go similarity index 73% rename from exporter/exporterhelper/obsexporter_test.go rename to exporter/exporterhelper/internal/obsexporter_test.go index ac939e21127..cafe163581c 100644 --- a/exporter/exporterhelper/obsexporter_test.go +++ b/exporter/exporterhelper/internal/obsexporter_test.go @@ -1,7 +1,7 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -package exporterhelper // import "go.opentelemetry.io/collector/exporter/exporterhelper" +package internal import ( "context" @@ -16,7 +16,6 @@ import ( "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/component/componenttest" "go.opentelemetry.io/collector/exporter" - "go.opentelemetry.io/collector/exporter/exporterhelper/internal" ) var ( @@ -30,9 +29,9 @@ func TestExportTraceDataOp(t *testing.T) { parentCtx, parentSpan := tt.TelemetrySettings().TracerProvider.Tracer("test").Start(context.Background(), t.Name()) defer parentSpan.End() - obsrep, err := newExporter(obsReportSettings{ - exporterID: exporterID, - exporterCreateSettings: exporter.Settings{ID: exporterID, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, + obsrep, err := NewExporter(ObsReportSettings{ + ExporterID: exporterID, + ExporterCreateSettings: exporter.Settings{ID: exporterID, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, }) require.NoError(t, err) @@ -41,9 +40,9 @@ func TestExportTraceDataOp(t *testing.T) { {items: 14, err: errFake}, } for i := range params { - ctx := obsrep.startTracesOp(parentCtx) + ctx := obsrep.StartTracesOp(parentCtx) assert.NotNil(t, ctx) - obsrep.endTracesOp(ctx, params[i].items, params[i].err) + obsrep.EndTracesOp(ctx, params[i].items, params[i].err) } spans := tt.SpanRecorder.Ended() @@ -55,13 +54,13 @@ func TestExportTraceDataOp(t *testing.T) { switch { case params[i].err == nil: sentSpans += params[i].items - require.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.SentSpansKey, Value: attribute.Int64Value(int64(params[i].items))}) - require.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.FailedToSendSpansKey, Value: attribute.Int64Value(0)}) + require.Contains(t, span.Attributes(), attribute.KeyValue{Key: SentSpansKey, Value: attribute.Int64Value(int64(params[i].items))}) + require.Contains(t, span.Attributes(), attribute.KeyValue{Key: FailedToSendSpansKey, Value: attribute.Int64Value(0)}) assert.Equal(t, codes.Unset, span.Status().Code) case errors.Is(params[i].err, errFake): failedToSendSpans += params[i].items - require.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.SentSpansKey, Value: attribute.Int64Value(0)}) - require.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.FailedToSendSpansKey, Value: attribute.Int64Value(int64(params[i].items))}) + require.Contains(t, span.Attributes(), attribute.KeyValue{Key: SentSpansKey, Value: attribute.Int64Value(0)}) + require.Contains(t, span.Attributes(), attribute.KeyValue{Key: FailedToSendSpansKey, Value: attribute.Int64Value(int64(params[i].items))}) assert.Equal(t, codes.Error, span.Status().Code) assert.Equal(t, params[i].err.Error(), span.Status().Description) default: @@ -78,9 +77,9 @@ func TestExportMetricsOp(t *testing.T) { parentCtx, parentSpan := tt.TelemetrySettings().TracerProvider.Tracer("test").Start(context.Background(), t.Name()) defer parentSpan.End() - obsrep, err := newExporter(obsReportSettings{ - exporterID: exporterID, - exporterCreateSettings: exporter.Settings{ID: exporterID, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, + obsrep, err := NewExporter(ObsReportSettings{ + ExporterID: exporterID, + ExporterCreateSettings: exporter.Settings{ID: exporterID, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, }) require.NoError(t, err) @@ -89,10 +88,10 @@ func TestExportMetricsOp(t *testing.T) { {items: 23, err: errFake}, } for i := range params { - ctx := obsrep.startMetricsOp(parentCtx) + ctx := obsrep.StartMetricsOp(parentCtx) assert.NotNil(t, ctx) - obsrep.endMetricsOp(ctx, params[i].items, params[i].err) + obsrep.EndMetricsOp(ctx, params[i].items, params[i].err) } spans := tt.SpanRecorder.Ended() @@ -104,13 +103,13 @@ func TestExportMetricsOp(t *testing.T) { switch { case params[i].err == nil: sentMetricPoints += params[i].items - require.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.SentMetricPointsKey, Value: attribute.Int64Value(int64(params[i].items))}) - require.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.FailedToSendMetricPointsKey, Value: attribute.Int64Value(0)}) + require.Contains(t, span.Attributes(), attribute.KeyValue{Key: SentMetricPointsKey, Value: attribute.Int64Value(int64(params[i].items))}) + require.Contains(t, span.Attributes(), attribute.KeyValue{Key: FailedToSendMetricPointsKey, Value: attribute.Int64Value(0)}) assert.Equal(t, codes.Unset, span.Status().Code) case errors.Is(params[i].err, errFake): failedToSendMetricPoints += params[i].items - require.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.SentMetricPointsKey, Value: attribute.Int64Value(0)}) - require.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.FailedToSendMetricPointsKey, Value: attribute.Int64Value(int64(params[i].items))}) + require.Contains(t, span.Attributes(), attribute.KeyValue{Key: SentMetricPointsKey, Value: attribute.Int64Value(0)}) + require.Contains(t, span.Attributes(), attribute.KeyValue{Key: FailedToSendMetricPointsKey, Value: attribute.Int64Value(int64(params[i].items))}) assert.Equal(t, codes.Error, span.Status().Code) assert.Equal(t, params[i].err.Error(), span.Status().Description) default: @@ -127,9 +126,9 @@ func TestExportLogsOp(t *testing.T) { parentCtx, parentSpan := tt.TelemetrySettings().TracerProvider.Tracer("test").Start(context.Background(), t.Name()) defer parentSpan.End() - obsrep, err := newExporter(obsReportSettings{ - exporterID: exporterID, - exporterCreateSettings: exporter.Settings{ID: exporterID, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, + obsrep, err := NewExporter(ObsReportSettings{ + ExporterID: exporterID, + ExporterCreateSettings: exporter.Settings{ID: exporterID, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, }) require.NoError(t, err) @@ -138,10 +137,10 @@ func TestExportLogsOp(t *testing.T) { {items: 23, err: errFake}, } for i := range params { - ctx := obsrep.startLogsOp(parentCtx) + ctx := obsrep.StartLogsOp(parentCtx) assert.NotNil(t, ctx) - obsrep.endLogsOp(ctx, params[i].items, params[i].err) + obsrep.EndLogsOp(ctx, params[i].items, params[i].err) } spans := tt.SpanRecorder.Ended() @@ -153,13 +152,13 @@ func TestExportLogsOp(t *testing.T) { switch { case params[i].err == nil: sentLogRecords += params[i].items - require.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.SentLogRecordsKey, Value: attribute.Int64Value(int64(params[i].items))}) - require.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.FailedToSendLogRecordsKey, Value: attribute.Int64Value(0)}) + require.Contains(t, span.Attributes(), attribute.KeyValue{Key: SentLogRecordsKey, Value: attribute.Int64Value(int64(params[i].items))}) + require.Contains(t, span.Attributes(), attribute.KeyValue{Key: FailedToSendLogRecordsKey, Value: attribute.Int64Value(0)}) assert.Equal(t, codes.Unset, span.Status().Code) case errors.Is(params[i].err, errFake): failedToSendLogRecords += params[i].items - require.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.SentLogRecordsKey, Value: attribute.Int64Value(0)}) - require.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.FailedToSendLogRecordsKey, Value: attribute.Int64Value(int64(params[i].items))}) + require.Contains(t, span.Attributes(), attribute.KeyValue{Key: SentLogRecordsKey, Value: attribute.Int64Value(0)}) + require.Contains(t, span.Attributes(), attribute.KeyValue{Key: FailedToSendLogRecordsKey, Value: attribute.Int64Value(int64(params[i].items))}) assert.Equal(t, codes.Error, span.Status().Code) assert.Equal(t, params[i].err.Error(), span.Status().Description) default: @@ -176,14 +175,14 @@ func TestCheckExporterTracesViews(t *testing.T) { require.NoError(t, err) t.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) }) - obsrep, err := newExporter(obsReportSettings{ - exporterID: exporterID, - exporterCreateSettings: exporter.Settings{ID: exporterID, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, + obsrep, err := NewExporter(ObsReportSettings{ + ExporterID: exporterID, + ExporterCreateSettings: exporter.Settings{ID: exporterID, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, }) require.NoError(t, err) - ctx := obsrep.startTracesOp(context.Background()) + ctx := obsrep.StartTracesOp(context.Background()) require.NotNil(t, ctx) - obsrep.endTracesOp(ctx, 7, nil) + obsrep.EndTracesOp(ctx, 7, nil) require.NoError(t, tt.CheckExporterTraces(7, 0)) require.Error(t, tt.CheckExporterTraces(7, 7)) @@ -196,14 +195,14 @@ func TestCheckExporterMetricsViews(t *testing.T) { require.NoError(t, err) t.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) }) - obsrep, err := newExporter(obsReportSettings{ - exporterID: exporterID, - exporterCreateSettings: exporter.Settings{ID: exporterID, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, + obsrep, err := NewExporter(ObsReportSettings{ + ExporterID: exporterID, + ExporterCreateSettings: exporter.Settings{ID: exporterID, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, }) require.NoError(t, err) - ctx := obsrep.startMetricsOp(context.Background()) + ctx := obsrep.StartMetricsOp(context.Background()) require.NotNil(t, ctx) - obsrep.endMetricsOp(ctx, 7, nil) + obsrep.EndMetricsOp(ctx, 7, nil) require.NoError(t, tt.CheckExporterMetrics(7, 0)) require.Error(t, tt.CheckExporterMetrics(7, 7)) @@ -216,14 +215,14 @@ func TestCheckExporterLogsViews(t *testing.T) { require.NoError(t, err) t.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) }) - obsrep, err := newExporter(obsReportSettings{ - exporterID: exporterID, - exporterCreateSettings: exporter.Settings{ID: exporterID, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, + obsrep, err := NewExporter(ObsReportSettings{ + ExporterID: exporterID, + ExporterCreateSettings: exporter.Settings{ID: exporterID, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, }) require.NoError(t, err) - ctx := obsrep.startLogsOp(context.Background()) + ctx := obsrep.StartLogsOp(context.Background()) require.NotNil(t, ctx) - obsrep.endLogsOp(ctx, 7, nil) + obsrep.EndLogsOp(ctx, 7, nil) require.NoError(t, tt.CheckExporterLogs(7, 0)) require.Error(t, tt.CheckExporterLogs(7, 7)) diff --git a/exporter/exporterhelper/internal/queue_sender.go b/exporter/exporterhelper/internal/queue_sender.go new file mode 100644 index 00000000000..60a94966336 --- /dev/null +++ b/exporter/exporterhelper/internal/queue_sender.go @@ -0,0 +1,154 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package internal // import "go.opentelemetry.io/collector/exporter/exporterhelper/internal" + +import ( + "context" + "errors" + + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/trace" + "go.uber.org/multierr" + "go.uber.org/zap" + + "go.opentelemetry.io/collector/component" + "go.opentelemetry.io/collector/exporter" + "go.opentelemetry.io/collector/exporter/exporterqueue" + "go.opentelemetry.io/collector/exporter/internal" + "go.opentelemetry.io/collector/exporter/internal/queue" +) + +const defaultQueueSize = 1000 + +// Deprecated: [v0.110.0] Use QueueConfig instead. +type QueueSettings = QueueConfig + +// QueueConfig defines configuration for queueing batches before sending to the consumerSender. +type QueueConfig struct { + // Enabled indicates whether to not enqueue batches before sending to the consumerSender. + Enabled bool `mapstructure:"enabled"` + // NumConsumers is the number of consumers from the queue. Defaults to 10. + // If batching is enabled, a combined batch cannot contain more requests than the number of consumers. + // So it's recommended to set higher number of consumers if batching is enabled. + NumConsumers int `mapstructure:"num_consumers"` + // QueueSize is the maximum number of batches allowed in queue at a given time. + QueueSize int `mapstructure:"queue_size"` + // StorageID if not empty, enables the persistent storage and uses the component specified + // as a storage extension for the persistent queue + StorageID *component.ID `mapstructure:"storage"` +} + +// Deprecated: [v0.110.0] Use NewDefaultQueueConfig instead. +func NewDefaultQueueSettings() QueueSettings { + return NewDefaultQueueConfig() +} + +// NewDefaultQueueConfig returns the default config for QueueConfig. +func NewDefaultQueueConfig() QueueConfig { + return QueueConfig{ + Enabled: true, + NumConsumers: 10, + // By default, batches are 8192 spans, for a total of up to 8 million spans in the queue + // This can be estimated at 1-4 GB worth of maximum memory usage + // This default is probably still too high, and may be adjusted further down in a future release + QueueSize: defaultQueueSize, + } +} + +// Validate checks if the QueueConfig configuration is valid +func (qCfg *QueueConfig) Validate() error { + if !qCfg.Enabled { + return nil + } + + if qCfg.QueueSize <= 0 { + return errors.New("queue size must be positive") + } + + if qCfg.NumConsumers <= 0 { + return errors.New("number of queue consumers must be positive") + } + + return nil +} + +type QueueSender struct { + BaseRequestSender + queue exporterqueue.Queue[internal.Request] + numConsumers int + traceAttribute attribute.KeyValue + consumers *queue.Consumers[internal.Request] + + obsrep *ObsReport + exporterID component.ID +} + +func NewQueueSender(q exporterqueue.Queue[internal.Request], set exporter.Settings, numConsumers int, + exportFailureMessage string, obsrep *ObsReport) *QueueSender { + qs := &QueueSender{ + queue: q, + numConsumers: numConsumers, + traceAttribute: attribute.String(ExporterKey, set.ID.String()), + obsrep: obsrep, + exporterID: set.ID, + } + consumeFunc := func(ctx context.Context, req internal.Request) error { + err := qs.NextSender.Send(ctx, req) + if err != nil { + set.Logger.Error("Exporting failed. Dropping data."+exportFailureMessage, + zap.Error(err), zap.Int("dropped_items", req.ItemsCount())) + } + return err + } + qs.consumers = queue.NewQueueConsumers[internal.Request](q, numConsumers, consumeFunc) + return qs +} + +// Start is invoked during service startup. +func (qs *QueueSender) Start(ctx context.Context, host component.Host) error { + if err := qs.consumers.Start(ctx, host); err != nil { + return err + } + + dataTypeAttr := attribute.String(DataTypeKey, qs.obsrep.DataType.String()) + return multierr.Append( + qs.obsrep.TelemetryBuilder.InitExporterQueueSize(func() int64 { return int64(qs.queue.Size()) }, + metric.WithAttributeSet(attribute.NewSet(qs.traceAttribute, dataTypeAttr))), + qs.obsrep.TelemetryBuilder.InitExporterQueueCapacity(func() int64 { return int64(qs.queue.Capacity()) }, + metric.WithAttributeSet(attribute.NewSet(qs.traceAttribute))), + ) +} + +// Shutdown is invoked during service shutdown. +func (qs *QueueSender) Shutdown(ctx context.Context) error { + // Stop the queue and consumers, this will drain the queue and will call the retry (which is stopped) that will only + // try once every request. + return qs.consumers.Shutdown(ctx) +} + +// send implements the requestSender interface. It puts the request in the queue. +func (qs *QueueSender) Send(ctx context.Context, req internal.Request) error { + // Prevent cancellation and deadline to propagate to the context stored in the queue. + // The grpc/http based receivers will cancel the request context after this function returns. + c := context.WithoutCancel(ctx) + + span := trace.SpanFromContext(c) + if err := qs.queue.Offer(c, req); err != nil { + span.AddEvent("Failed to enqueue item.", trace.WithAttributes(qs.traceAttribute)) + return err + } + + span.AddEvent("Enqueued item.", trace.WithAttributes(qs.traceAttribute)) + return nil +} + +type MockHost struct { + component.Host + Ext map[component.ID]component.Component +} + +func (nh *MockHost) GetExtensions() map[component.ID]component.Component { + return nh.Ext +} diff --git a/exporter/exporterhelper/queue_sender_test.go b/exporter/exporterhelper/internal/queue_sender_test.go similarity index 77% rename from exporter/exporterhelper/queue_sender_test.go rename to exporter/exporterhelper/internal/queue_sender_test.go index f86b5d2aad1..a9dd5ab7cea 100644 --- a/exporter/exporterhelper/queue_sender_test.go +++ b/exporter/exporterhelper/internal/queue_sender_test.go @@ -1,7 +1,7 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -package exporterhelper +package internal import ( "context" @@ -19,9 +19,9 @@ import ( "go.opentelemetry.io/collector/component/componenttest" "go.opentelemetry.io/collector/config/configretry" "go.opentelemetry.io/collector/exporter" - "go.opentelemetry.io/collector/exporter/exporterhelper/internal" "go.opentelemetry.io/collector/exporter/exporterqueue" "go.opentelemetry.io/collector/exporter/exportertest" + "go.opentelemetry.io/collector/exporter/internal" "go.opentelemetry.io/collector/exporter/internal/queue" ) @@ -29,45 +29,45 @@ func TestQueuedRetry_StopWhileWaiting(t *testing.T) { qCfg := NewDefaultQueueConfig() qCfg.NumConsumers = 1 rCfg := configretry.NewDefaultBackOffConfig() - be, err := newBaseExporter(defaultSettings, defaultDataType, newObservabilityConsumerSender, - withMarshaler(mockRequestMarshaler), withUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), + be, err := NewBaseExporter(defaultSettings, defaultDataType, newObservabilityConsumerSender, + WithMarshaler(mockRequestMarshaler), WithUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), WithRetry(rCfg), WithQueue(qCfg)) require.NoError(t, err) - ocs := be.obsrepSender.(*observabilityConsumerSender) + ocs := be.ObsrepSender.(*observabilityConsumerSender) require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost())) firstMockR := newErrorRequest() ocs.run(func() { // This is asynchronous so it should just enqueue, no errors expected. - require.NoError(t, be.send(context.Background(), firstMockR)) + require.NoError(t, be.Send(context.Background(), firstMockR)) }) // Enqueue another request to ensure when calling shutdown we drain the queue. secondMockR := newMockRequest(3, nil) ocs.run(func() { // This is asynchronous so it should just enqueue, no errors expected. - require.NoError(t, be.send(context.Background(), secondMockR)) + require.NoError(t, be.Send(context.Background(), secondMockR)) }) - require.LessOrEqual(t, 1, be.queueSender.(*queueSender).queue.Size()) + require.LessOrEqual(t, 1, be.QueueSender.(*QueueSender).queue.Size()) require.NoError(t, be.Shutdown(context.Background())) secondMockR.checkNumRequests(t, 1) ocs.checkSendItemsCount(t, 3) ocs.checkDroppedItemsCount(t, 7) - require.Zero(t, be.queueSender.(*queueSender).queue.Size()) + require.Zero(t, be.QueueSender.(*QueueSender).queue.Size()) } func TestQueuedRetry_DoNotPreserveCancellation(t *testing.T) { qCfg := NewDefaultQueueConfig() qCfg.NumConsumers = 1 rCfg := configretry.NewDefaultBackOffConfig() - be, err := newBaseExporter(defaultSettings, defaultDataType, newObservabilityConsumerSender, - withMarshaler(mockRequestMarshaler), withUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), + be, err := NewBaseExporter(defaultSettings, defaultDataType, newObservabilityConsumerSender, + WithMarshaler(mockRequestMarshaler), WithUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), WithRetry(rCfg), WithQueue(qCfg)) require.NoError(t, err) - ocs := be.obsrepSender.(*observabilityConsumerSender) + ocs := be.ObsrepSender.(*observabilityConsumerSender) require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost())) t.Cleanup(func() { assert.NoError(t, be.Shutdown(context.Background())) @@ -78,14 +78,14 @@ func TestQueuedRetry_DoNotPreserveCancellation(t *testing.T) { mockR := newMockRequest(2, nil) ocs.run(func() { // This is asynchronous so it should just enqueue, no errors expected. - require.NoError(t, be.send(ctx, mockR)) + require.NoError(t, be.Send(ctx, mockR)) }) ocs.awaitAsyncProcessing() mockR.checkNumRequests(t, 1) ocs.checkSendItemsCount(t, 2) ocs.checkDroppedItemsCount(t, 0) - require.Zero(t, be.queueSender.(*queueSender).queue.Size()) + require.Zero(t, be.QueueSender.(*QueueSender).queue.Size()) } func TestQueuedRetry_RejectOnFull(t *testing.T) { @@ -95,15 +95,15 @@ func TestQueuedRetry_RejectOnFull(t *testing.T) { set := exportertest.NewNopSettings() logger, observed := observer.New(zap.ErrorLevel) set.Logger = zap.New(logger) - be, err := newBaseExporter(set, defaultDataType, newNoopObsrepSender, - withMarshaler(mockRequestMarshaler), withUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), + be, err := NewBaseExporter(set, defaultDataType, newNoopObsrepSender, + WithMarshaler(mockRequestMarshaler), WithUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), WithQueue(qCfg)) require.NoError(t, err) require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost())) t.Cleanup(func() { assert.NoError(t, be.Shutdown(context.Background())) }) - require.Error(t, be.send(context.Background(), newMockRequest(2, nil))) + require.Error(t, be.Send(context.Background(), newMockRequest(2, nil))) assert.Len(t, observed.All(), 1) assert.Equal(t, "Exporting failed. Rejecting data.", observed.All()[0].Message) assert.Equal(t, "sending queue is full", observed.All()[0].ContextMap()["error"]) @@ -117,8 +117,8 @@ func TestQueuedRetryHappyPath(t *testing.T) { { name: "WithQueue", queueOptions: []Option{ - withMarshaler(mockRequestMarshaler), - withUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), + WithMarshaler(mockRequestMarshaler), + WithUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), WithQueue(QueueConfig{ Enabled: true, QueueSize: 10, @@ -134,7 +134,7 @@ func TestQueuedRetryHappyPath(t *testing.T) { Enabled: true, QueueSize: 10, NumConsumers: 1, - }, exporterqueue.NewMemoryQueueFactory[Request]()), + }, exporterqueue.NewMemoryQueueFactory[internal.Request]()), WithRetry(configretry.NewDefaultBackOffConfig()), }, }, @@ -145,7 +145,7 @@ func TestQueuedRetryHappyPath(t *testing.T) { Enabled: true, QueueSize: 10, NumConsumers: 1, - }, exporterqueue.NewPersistentQueueFactory[Request](nil, exporterqueue.PersistentQueueSettings[Request]{})), + }, exporterqueue.NewPersistentQueueFactory[internal.Request](nil, exporterqueue.PersistentQueueSettings[internal.Request]{})), WithRetry(configretry.NewDefaultBackOffConfig()), }, }, @@ -156,7 +156,7 @@ func TestQueuedRetryHappyPath(t *testing.T) { Enabled: true, QueueSize: 10, NumConsumers: 1, - }, exporterqueue.NewPersistentQueueFactory[Request](nil, exporterqueue.PersistentQueueSettings[Request]{})), + }, exporterqueue.NewPersistentQueueFactory[internal.Request](nil, exporterqueue.PersistentQueueSettings[internal.Request]{})), WithRetry(configretry.NewDefaultBackOffConfig()), }, }, @@ -168,9 +168,9 @@ func TestQueuedRetryHappyPath(t *testing.T) { t.Cleanup(func() { require.NoError(t, tel.Shutdown(context.Background())) }) set := exporter.Settings{ID: defaultID, TelemetrySettings: tel.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()} - be, err := newBaseExporter(set, defaultDataType, newObservabilityConsumerSender, tt.queueOptions...) + be, err := NewBaseExporter(set, defaultDataType, newObservabilityConsumerSender, tt.queueOptions...) require.NoError(t, err) - ocs := be.obsrepSender.(*observabilityConsumerSender) + ocs := be.ObsrepSender.(*observabilityConsumerSender) wantRequests := 10 reqs := make([]*mockRequest, 0, 10) @@ -178,12 +178,12 @@ func TestQueuedRetryHappyPath(t *testing.T) { ocs.run(func() { req := newMockRequest(2, nil) reqs = append(reqs, req) - require.NoError(t, be.send(context.Background(), req)) + require.NoError(t, be.Send(context.Background(), req)) }) } // expect queue to be full - require.Error(t, be.send(context.Background(), newMockRequest(2, nil))) + require.Error(t, be.Send(context.Background(), newMockRequest(2, nil))) require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost())) t.Cleanup(func() { @@ -214,8 +214,8 @@ func TestQueuedRetry_QueueMetricsReported(t *testing.T) { qCfg.NumConsumers = 0 // to make every request go straight to the queue rCfg := configretry.NewDefaultBackOffConfig() set := exporter.Settings{ID: defaultID, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()} - be, err := newBaseExporter(set, dataType, newObservabilityConsumerSender, - withMarshaler(mockRequestMarshaler), withUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), + be, err := NewBaseExporter(set, dataType, newObservabilityConsumerSender, + WithMarshaler(mockRequestMarshaler), WithUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), WithRetry(rCfg), WithQueue(qCfg)) require.NoError(t, err) require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost())) @@ -223,10 +223,10 @@ func TestQueuedRetry_QueueMetricsReported(t *testing.T) { require.NoError(t, tt.CheckExporterMetricGauge("otelcol_exporter_queue_capacity", int64(defaultQueueSize))) for i := 0; i < 7; i++ { - require.NoError(t, be.send(context.Background(), newErrorRequest())) + require.NoError(t, be.Send(context.Background(), newErrorRequest())) } require.NoError(t, tt.CheckExporterMetricGauge("otelcol_exporter_queue_size", int64(7), - attribute.String(internal.DataTypeKey, dataType.String()))) + attribute.String(DataTypeKey, dataType.String()))) assert.NoError(t, be.Shutdown(context.Background())) } @@ -273,8 +273,8 @@ func TestQueueRetryWithDisabledQueue(t *testing.T) { { name: "WithQueue", queueOptions: []Option{ - withMarshaler(mockRequestMarshaler), - withUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), + WithMarshaler(mockRequestMarshaler), + WithUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), func() Option { qs := NewDefaultQueueConfig() qs.Enabled = false @@ -288,7 +288,7 @@ func TestQueueRetryWithDisabledQueue(t *testing.T) { func() Option { qs := exporterqueue.NewDefaultConfig() qs.Enabled = false - return WithRequestQueue(qs, exporterqueue.NewMemoryQueueFactory[Request]()) + return WithRequestQueue(qs, exporterqueue.NewMemoryQueueFactory[internal.Request]()) }(), }, }, @@ -299,13 +299,13 @@ func TestQueueRetryWithDisabledQueue(t *testing.T) { set := exportertest.NewNopSettings() logger, observed := observer.New(zap.ErrorLevel) set.Logger = zap.New(logger) - be, err := newBaseExporter(set, component.DataTypeLogs, newObservabilityConsumerSender, tt.queueOptions...) + be, err := NewBaseExporter(set, component.DataTypeLogs, newObservabilityConsumerSender, tt.queueOptions...) require.NoError(t, err) require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost())) - ocs := be.obsrepSender.(*observabilityConsumerSender) + ocs := be.ObsrepSender.(*observabilityConsumerSender) mockR := newMockRequest(2, errors.New("some error")) ocs.run(func() { - require.Error(t, be.send(context.Background(), mockR)) + require.Error(t, be.Send(context.Background(), mockR)) }) assert.Len(t, observed.All(), 1) assert.Equal(t, "Exporting failed. Rejecting data. Try enabling sending_queue to survive temporary failures.", observed.All()[0].Message) @@ -323,12 +323,12 @@ func TestQueueFailedRequestDropped(t *testing.T) { set := exportertest.NewNopSettings() logger, observed := observer.New(zap.ErrorLevel) set.Logger = zap.New(logger) - be, err := newBaseExporter(set, component.DataTypeLogs, newNoopObsrepSender, - WithRequestQueue(exporterqueue.NewDefaultConfig(), exporterqueue.NewMemoryQueueFactory[Request]())) + be, err := NewBaseExporter(set, component.DataTypeLogs, newNoopObsrepSender, + WithRequestQueue(exporterqueue.NewDefaultConfig(), exporterqueue.NewMemoryQueueFactory[internal.Request]())) require.NoError(t, err) require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost())) mockR := newMockRequest(2, errors.New("some error")) - require.NoError(t, be.send(context.Background(), mockR)) + require.NoError(t, be.Send(context.Background(), mockR)) require.NoError(t, be.Shutdown(context.Background())) mockR.checkNumRequests(t, 1) assert.Len(t, observed.All(), 1) @@ -345,15 +345,15 @@ func TestQueuedRetryPersistenceEnabled(t *testing.T) { qCfg.StorageID = &storageID // enable persistence rCfg := configretry.NewDefaultBackOffConfig() set := exporter.Settings{ID: defaultID, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()} - be, err := newBaseExporter(set, defaultDataType, newObservabilityConsumerSender, - withMarshaler(mockRequestMarshaler), withUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), + be, err := NewBaseExporter(set, defaultDataType, newObservabilityConsumerSender, + WithMarshaler(mockRequestMarshaler), WithUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), WithRetry(rCfg), WithQueue(qCfg)) require.NoError(t, err) var extensions = map[component.ID]component.Component{ storageID: queue.NewMockStorageExtension(nil), } - host := &mockHost{ext: extensions} + host := &MockHost{Ext: extensions} // we start correctly with a file storage extension require.NoError(t, be.Start(context.Background(), host)) @@ -371,14 +371,14 @@ func TestQueuedRetryPersistenceEnabledStorageError(t *testing.T) { qCfg.StorageID = &storageID // enable persistence rCfg := configretry.NewDefaultBackOffConfig() set := exporter.Settings{ID: defaultID, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()} - be, err := newBaseExporter(set, defaultDataType, newObservabilityConsumerSender, withMarshaler(mockRequestMarshaler), - withUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), WithRetry(rCfg), WithQueue(qCfg)) + be, err := NewBaseExporter(set, defaultDataType, newObservabilityConsumerSender, WithMarshaler(mockRequestMarshaler), + WithUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), WithRetry(rCfg), WithQueue(qCfg)) require.NoError(t, err) var extensions = map[component.ID]component.Component{ storageID: queue.NewMockStorageExtension(storageError), } - host := &mockHost{ext: extensions} + host := &MockHost{Ext: extensions} // we fail to start if we get an error creating the storage client require.Error(t, be.Start(context.Background(), host), "could not get storage client") @@ -395,23 +395,23 @@ func TestQueuedRetryPersistentEnabled_NoDataLossOnShutdown(t *testing.T) { rCfg.MaxElapsedTime = 0 // retry infinitely so shutdown can be triggered mockReq := newErrorRequest() - be, err := newBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, withMarshaler(mockRequestMarshaler), - withUnmarshaler(mockRequestUnmarshaler(mockReq)), WithRetry(rCfg), WithQueue(qCfg)) + be, err := NewBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, WithMarshaler(mockRequestMarshaler), + WithUnmarshaler(mockRequestUnmarshaler(mockReq)), WithRetry(rCfg), WithQueue(qCfg)) require.NoError(t, err) var extensions = map[component.ID]component.Component{ storageID: queue.NewMockStorageExtension(nil), } - host := &mockHost{ext: extensions} + host := &MockHost{Ext: extensions} require.NoError(t, be.Start(context.Background(), host)) // Invoke queuedRetrySender so the producer will put the item for consumer to poll - require.NoError(t, be.send(context.Background(), mockReq)) + require.NoError(t, be.Send(context.Background(), mockReq)) // first wait for the item to be consumed from the queue assert.Eventually(t, func() bool { - return be.queueSender.(*queueSender).queue.Size() == 0 + return be.QueueSender.(*QueueSender).queue.Size() == 0 }, time.Second, 1*time.Millisecond) // shuts down the exporter, unsent data should be preserved as in-flight data in the persistent queue. @@ -419,8 +419,8 @@ func TestQueuedRetryPersistentEnabled_NoDataLossOnShutdown(t *testing.T) { // start the exporter again replacing the preserved mockRequest in the unmarshaler with a new one that doesn't fail. replacedReq := newMockRequest(1, nil) - be, err = newBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, withMarshaler(mockRequestMarshaler), - withUnmarshaler(mockRequestUnmarshaler(replacedReq)), WithRetry(rCfg), WithQueue(qCfg)) + be, err = NewBaseExporter(defaultSettings, defaultDataType, newNoopObsrepSender, WithMarshaler(mockRequestMarshaler), + WithUnmarshaler(mockRequestUnmarshaler(replacedReq)), WithRetry(rCfg), WithQueue(qCfg)) require.NoError(t, err) require.NoError(t, be.Start(context.Background(), host)) t.Cleanup(func() { require.NoError(t, be.Shutdown(context.Background())) }) @@ -430,22 +430,13 @@ func TestQueuedRetryPersistentEnabled_NoDataLossOnShutdown(t *testing.T) { } func TestQueueSenderNoStartShutdown(t *testing.T) { - queue := queue.NewBoundedMemoryQueue[Request](queue.MemoryQueueSettings[Request]{}) + queue := queue.NewBoundedMemoryQueue[internal.Request](queue.MemoryQueueSettings[internal.Request]{}) set := exportertest.NewNopSettings() - obsrep, err := newExporter(obsReportSettings{ - exporterID: exporterID, - exporterCreateSettings: exportertest.NewNopSettings(), + obsrep, err := NewExporter(ObsReportSettings{ + ExporterID: exporterID, + ExporterCreateSettings: exportertest.NewNopSettings(), }) require.NoError(t, err) - qs := newQueueSender(queue, set, 1, "", obsrep) + qs := NewQueueSender(queue, set, 1, "", obsrep) assert.NoError(t, qs.Shutdown(context.Background())) } - -type mockHost struct { - component.Host - ext map[component.ID]component.Component -} - -func (nh *mockHost) GetExtensions() map[component.ID]component.Component { - return nh.ext -} diff --git a/exporter/exporterhelper/request_test.go b/exporter/exporterhelper/internal/request.go similarity index 71% rename from exporter/exporterhelper/request_test.go rename to exporter/exporterhelper/internal/request.go index fe373c67e12..79f58a82608 100644 --- a/exporter/exporterhelper/request_test.go +++ b/exporter/exporterhelper/internal/request.go @@ -1,7 +1,7 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -package exporterhelper +package internal // import "go.opentelemetry.io/collector/exporter/exporterhelper/internal" import ( "context" @@ -9,6 +9,7 @@ import ( "time" "go.opentelemetry.io/collector/exporter/exporterbatcher" + "go.opentelemetry.io/collector/exporter/internal" "go.opentelemetry.io/collector/pdata/plog" "go.opentelemetry.io/collector/pdata/pmetric" "go.opentelemetry.io/collector/pdata/ptrace" @@ -54,7 +55,7 @@ func (r *fakeRequest) ItemsCount() int { return r.items } -func fakeBatchMergeFunc(_ context.Context, r1 Request, r2 Request) (Request, error) { +func fakeBatchMergeFunc(_ context.Context, r1 internal.Request, r2 internal.Request) (internal.Request, error) { if r1 == nil { return r2, nil } @@ -71,11 +72,11 @@ func fakeBatchMergeFunc(_ context.Context, r1 Request, r2 Request) (Request, err }, nil } -func fakeBatchMergeSplitFunc(ctx context.Context, cfg exporterbatcher.MaxSizeConfig, r1 Request, r2 Request) ([]Request, error) { +func fakeBatchMergeSplitFunc(ctx context.Context, cfg exporterbatcher.MaxSizeConfig, r1 internal.Request, r2 internal.Request) ([]internal.Request, error) { maxItems := cfg.MaxSizeItems if maxItems == 0 { r, err := fakeBatchMergeFunc(ctx, r1, r2) - return []Request{r}, err + return []internal.Request{r}, err } if r2.(*fakeRequest).mergeErr != nil { @@ -84,7 +85,7 @@ func fakeBatchMergeSplitFunc(ctx context.Context, cfg exporterbatcher.MaxSizeCon fr2 := r2.(*fakeRequest) fr2 = &fakeRequest{items: fr2.items, sink: fr2.sink, exportErr: fr2.exportErr, delay: fr2.delay} - var res []Request + var res []internal.Request // fill fr1 to maxItems if it's not nil if r1 != nil { @@ -95,7 +96,7 @@ func fakeBatchMergeSplitFunc(ctx context.Context, cfg exporterbatcher.MaxSizeCon if fr2.exportErr != nil { fr1.exportErr = fr2.exportErr } - return []Request{fr1}, nil + return []internal.Request{fr1}, nil } // if split is needed, we don't propagate exportErr from fr2 to fr1 to test more cases fr2.items -= maxItems - fr1.items @@ -116,21 +117,21 @@ func fakeBatchMergeSplitFunc(ctx context.Context, cfg exporterbatcher.MaxSizeCon return res, nil } -type fakeRequestConverter struct { - metricsError error - tracesError error - logsError error - requestError error +type FakeRequestConverter struct { + MetricsError error + TracesError error + LogsError error + RequestError error } -func (frc *fakeRequestConverter) requestFromMetricsFunc(_ context.Context, md pmetric.Metrics) (Request, error) { - return &fakeRequest{items: md.DataPointCount(), exportErr: frc.requestError}, frc.metricsError +func (frc *FakeRequestConverter) RequestFromMetricsFunc(_ context.Context, md pmetric.Metrics) (internal.Request, error) { + return &fakeRequest{items: md.DataPointCount(), exportErr: frc.RequestError}, frc.MetricsError } -func (frc *fakeRequestConverter) requestFromTracesFunc(_ context.Context, md ptrace.Traces) (Request, error) { - return &fakeRequest{items: md.SpanCount(), exportErr: frc.requestError}, frc.tracesError +func (frc *FakeRequestConverter) RequestFromTracesFunc(_ context.Context, md ptrace.Traces) (internal.Request, error) { + return &fakeRequest{items: md.SpanCount(), exportErr: frc.RequestError}, frc.TracesError } -func (frc *fakeRequestConverter) requestFromLogsFunc(_ context.Context, md plog.Logs) (Request, error) { - return &fakeRequest{items: md.LogRecordCount(), exportErr: frc.requestError}, frc.logsError +func (frc *FakeRequestConverter) RequestFromLogsFunc(_ context.Context, md plog.Logs) (internal.Request, error) { + return &fakeRequest{items: md.LogRecordCount(), exportErr: frc.RequestError}, frc.LogsError } diff --git a/exporter/exporterhelper/internal/request_sender.go b/exporter/exporterhelper/internal/request_sender.go new file mode 100644 index 00000000000..683aca40d79 --- /dev/null +++ b/exporter/exporterhelper/internal/request_sender.go @@ -0,0 +1,33 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package internal // import "go.opentelemetry.io/collector/exporter/exporterhelper/internal" + +import ( + "context" // RequestSender is an abstraction of a sender for a request independent of the type of the data (traces, metrics, logs). + + "go.opentelemetry.io/collector/component" + "go.opentelemetry.io/collector/exporter/internal" +) + +type RequestSender interface { + component.Component + Send(context.Context, internal.Request) error + SetNextSender(nextSender RequestSender) +} + +type BaseRequestSender struct { + component.StartFunc + component.ShutdownFunc + NextSender RequestSender +} + +var _ RequestSender = (*BaseRequestSender)(nil) + +func (b *BaseRequestSender) Send(ctx context.Context, req internal.Request) error { + return b.NextSender.Send(ctx, req) +} + +func (b *BaseRequestSender) SetNextSender(nextSender RequestSender) { + b.NextSender = nextSender +} diff --git a/exporter/exporterhelper/internal/retry_sender.go b/exporter/exporterhelper/internal/retry_sender.go new file mode 100644 index 00000000000..c6648785183 --- /dev/null +++ b/exporter/exporterhelper/internal/retry_sender.go @@ -0,0 +1,142 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package internal // import "go.opentelemetry.io/collector/exporter/exporterhelper/internal" + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/cenkalti/backoff/v4" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/trace" + "go.uber.org/zap" + + "go.opentelemetry.io/collector/config/configretry" + "go.opentelemetry.io/collector/consumer/consumererror" + "go.opentelemetry.io/collector/exporter" + "go.opentelemetry.io/collector/exporter/internal" + "go.opentelemetry.io/collector/exporter/internal/experr" +) + +// TODO: Clean this by forcing all exporters to return an internal error type that always include the information about retries. +type throttleRetry struct { + err error + delay time.Duration +} + +func (t throttleRetry) Error() string { + return "Throttle (" + t.delay.String() + "), error: " + t.err.Error() +} + +func (t throttleRetry) Unwrap() error { + return t.err +} + +// NewThrottleRetry creates a new throttle retry error. +func NewThrottleRetry(err error, delay time.Duration) error { + return throttleRetry{ + err: err, + delay: delay, + } +} + +type retrySender struct { + BaseRequestSender + traceAttribute attribute.KeyValue + cfg configretry.BackOffConfig + stopCh chan struct{} + logger *zap.Logger +} + +func newRetrySender(config configretry.BackOffConfig, set exporter.Settings) *retrySender { + return &retrySender{ + traceAttribute: attribute.String(ExporterKey, set.ID.String()), + cfg: config, + stopCh: make(chan struct{}), + logger: set.Logger, + } +} + +func (rs *retrySender) Shutdown(context.Context) error { + close(rs.stopCh) + return nil +} + +// send implements the requestSender interface +func (rs *retrySender) Send(ctx context.Context, req internal.Request) error { + // Do not use NewExponentialBackOff since it calls Reset and the code here must + // call Reset after changing the InitialInterval (this saves an unnecessary call to Now). + expBackoff := backoff.ExponentialBackOff{ + InitialInterval: rs.cfg.InitialInterval, + RandomizationFactor: rs.cfg.RandomizationFactor, + Multiplier: rs.cfg.Multiplier, + MaxInterval: rs.cfg.MaxInterval, + MaxElapsedTime: rs.cfg.MaxElapsedTime, + Stop: backoff.Stop, + Clock: backoff.SystemClock, + } + expBackoff.Reset() + span := trace.SpanFromContext(ctx) + retryNum := int64(0) + for { + span.AddEvent( + "Sending request.", + trace.WithAttributes(rs.traceAttribute, attribute.Int64("retry_num", retryNum))) + + err := rs.NextSender.Send(ctx, req) + if err == nil { + return nil + } + + // Immediately drop data on permanent errors. + if consumererror.IsPermanent(err) { + return fmt.Errorf("not retryable error: %w", err) + } + + req = internal.ExtractPartialRequest(req, err) + + backoffDelay := expBackoff.NextBackOff() + if backoffDelay == backoff.Stop { + return fmt.Errorf("no more retries left: %w", err) + } + + throttleErr := throttleRetry{} + if errors.As(err, &throttleErr) { + backoffDelay = max(backoffDelay, throttleErr.delay) + } + + backoffDelayStr := backoffDelay.String() + span.AddEvent( + "Exporting failed. Will retry the request after interval.", + trace.WithAttributes( + rs.traceAttribute, + attribute.String("interval", backoffDelayStr), + attribute.String("error", err.Error()))) + rs.logger.Info( + "Exporting failed. Will retry the request after interval.", + zap.Error(err), + zap.String("interval", backoffDelayStr), + ) + retryNum++ + + // back-off, but get interrupted when shutting down or request is cancelled or timed out. + select { + case <-ctx.Done(): + return fmt.Errorf("request is cancelled or timed out %w", err) + case <-rs.stopCh: + return experr.NewShutdownErr(err) + case <-time.After(backoffDelay): + } + } +} + +// max returns the larger of x or y. +func max(x, y time.Duration) time.Duration { + if x < y { + return y + } + return x +} diff --git a/exporter/exporterhelper/retry_sender_test.go b/exporter/exporterhelper/internal/retry_sender_test.go similarity index 78% rename from exporter/exporterhelper/retry_sender_test.go rename to exporter/exporterhelper/internal/retry_sender_test.go index a0dab1f8782..f4cc0f5ee0b 100644 --- a/exporter/exporterhelper/retry_sender_test.go +++ b/exporter/exporterhelper/internal/retry_sender_test.go @@ -1,7 +1,7 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -package exporterhelper +package internal import ( "context" @@ -22,16 +22,17 @@ import ( "go.opentelemetry.io/collector/consumer/consumererror" "go.opentelemetry.io/collector/exporter/exporterqueue" "go.opentelemetry.io/collector/exporter/exportertest" + "go.opentelemetry.io/collector/exporter/internal" "go.opentelemetry.io/collector/pdata/testdata" ) -func mockRequestUnmarshaler(mr Request) exporterqueue.Unmarshaler[Request] { - return func([]byte) (Request, error) { +func mockRequestUnmarshaler(mr internal.Request) exporterqueue.Unmarshaler[internal.Request] { + return func([]byte) (internal.Request, error) { return mr, nil } } -func mockRequestMarshaler(Request) ([]byte, error) { +func mockRequestMarshaler(internal.Request) ([]byte, error) { return []byte("mockRequest"), nil } @@ -39,10 +40,10 @@ func TestQueuedRetry_DropOnPermanentError(t *testing.T) { qCfg := NewDefaultQueueConfig() rCfg := configretry.NewDefaultBackOffConfig() mockR := newMockRequest(2, consumererror.NewPermanent(errors.New("bad data"))) - be, err := newBaseExporter(defaultSettings, defaultDataType, newObservabilityConsumerSender, - withMarshaler(mockRequestMarshaler), withUnmarshaler(mockRequestUnmarshaler(mockR)), WithRetry(rCfg), WithQueue(qCfg)) + be, err := NewBaseExporter(defaultSettings, defaultDataType, newObservabilityConsumerSender, + WithMarshaler(mockRequestMarshaler), WithUnmarshaler(mockRequestUnmarshaler(mockR)), WithRetry(rCfg), WithQueue(qCfg)) require.NoError(t, err) - ocs := be.obsrepSender.(*observabilityConsumerSender) + ocs := be.ObsrepSender.(*observabilityConsumerSender) require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost())) t.Cleanup(func() { assert.NoError(t, be.Shutdown(context.Background())) @@ -50,7 +51,7 @@ func TestQueuedRetry_DropOnPermanentError(t *testing.T) { ocs.run(func() { // This is asynchronous so it should just enqueue, no errors expected. - require.NoError(t, be.send(context.Background(), mockR)) + require.NoError(t, be.Send(context.Background(), mockR)) }) ocs.awaitAsyncProcessing() // In the newMockConcurrentExporter we count requests and items even for failed requests @@ -63,11 +64,11 @@ func TestQueuedRetry_DropOnNoRetry(t *testing.T) { qCfg := NewDefaultQueueConfig() rCfg := configretry.NewDefaultBackOffConfig() rCfg.Enabled = false - be, err := newBaseExporter(defaultSettings, defaultDataType, newObservabilityConsumerSender, withMarshaler(mockRequestMarshaler), - withUnmarshaler(mockRequestUnmarshaler(newMockRequest(2, errors.New("transient error")))), + be, err := NewBaseExporter(defaultSettings, defaultDataType, newObservabilityConsumerSender, WithMarshaler(mockRequestMarshaler), + WithUnmarshaler(mockRequestUnmarshaler(newMockRequest(2, errors.New("transient error")))), WithQueue(qCfg), WithRetry(rCfg)) require.NoError(t, err) - ocs := be.obsrepSender.(*observabilityConsumerSender) + ocs := be.ObsrepSender.(*observabilityConsumerSender) require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost())) t.Cleanup(func() { assert.NoError(t, be.Shutdown(context.Background())) @@ -76,7 +77,7 @@ func TestQueuedRetry_DropOnNoRetry(t *testing.T) { mockR := newMockRequest(2, errors.New("transient error")) ocs.run(func() { // This is asynchronous so it should just enqueue, no errors expected. - require.NoError(t, be.send(context.Background(), mockR)) + require.NoError(t, be.Send(context.Background(), mockR)) }) ocs.awaitAsyncProcessing() // In the newMockConcurrentExporter we count requests and items even for failed requests @@ -90,8 +91,8 @@ func TestQueuedRetry_OnError(t *testing.T) { qCfg.NumConsumers = 1 rCfg := configretry.NewDefaultBackOffConfig() rCfg.InitialInterval = 0 - be, err := newBaseExporter(defaultSettings, defaultDataType, newObservabilityConsumerSender, - withMarshaler(mockRequestMarshaler), withUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), + be, err := NewBaseExporter(defaultSettings, defaultDataType, newObservabilityConsumerSender, + WithMarshaler(mockRequestMarshaler), WithUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), WithRetry(rCfg), WithQueue(qCfg)) require.NoError(t, err) require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost())) @@ -101,10 +102,10 @@ func TestQueuedRetry_OnError(t *testing.T) { traceErr := consumererror.NewTraces(errors.New("some error"), testdata.GenerateTraces(1)) mockR := newMockRequest(2, traceErr) - ocs := be.obsrepSender.(*observabilityConsumerSender) + ocs := be.ObsrepSender.(*observabilityConsumerSender) ocs.run(func() { // This is asynchronous so it should just enqueue, no errors expected. - require.NoError(t, be.send(context.Background(), mockR)) + require.NoError(t, be.Send(context.Background(), mockR)) }) ocs.awaitAsyncProcessing() @@ -120,11 +121,11 @@ func TestQueuedRetry_MaxElapsedTime(t *testing.T) { rCfg := configretry.NewDefaultBackOffConfig() rCfg.InitialInterval = time.Millisecond rCfg.MaxElapsedTime = 100 * time.Millisecond - be, err := newBaseExporter(defaultSettings, defaultDataType, newObservabilityConsumerSender, - withMarshaler(mockRequestMarshaler), withUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), + be, err := NewBaseExporter(defaultSettings, defaultDataType, newObservabilityConsumerSender, + WithMarshaler(mockRequestMarshaler), WithUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), WithRetry(rCfg), WithQueue(qCfg)) require.NoError(t, err) - ocs := be.obsrepSender.(*observabilityConsumerSender) + ocs := be.ObsrepSender.(*observabilityConsumerSender) require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost())) t.Cleanup(func() { assert.NoError(t, be.Shutdown(context.Background())) @@ -132,14 +133,14 @@ func TestQueuedRetry_MaxElapsedTime(t *testing.T) { ocs.run(func() { // Add an item that will always fail. - require.NoError(t, be.send(context.Background(), newErrorRequest())) + require.NoError(t, be.Send(context.Background(), newErrorRequest())) }) mockR := newMockRequest(2, nil) start := time.Now() ocs.run(func() { // This is asynchronous so it should just enqueue, no errors expected. - require.NoError(t, be.send(context.Background(), mockR)) + require.NoError(t, be.Send(context.Background(), mockR)) }) ocs.awaitAsyncProcessing() @@ -152,7 +153,7 @@ func TestQueuedRetry_MaxElapsedTime(t *testing.T) { mockR.checkNumRequests(t, 1) ocs.checkSendItemsCount(t, 2) ocs.checkDroppedItemsCount(t, 7) - require.Zero(t, be.queueSender.(*queueSender).queue.Size()) + require.Zero(t, be.QueueSender.(*QueueSender).queue.Size()) } type wrappedError struct { @@ -168,11 +169,11 @@ func TestQueuedRetry_ThrottleError(t *testing.T) { qCfg.NumConsumers = 1 rCfg := configretry.NewDefaultBackOffConfig() rCfg.InitialInterval = 10 * time.Millisecond - be, err := newBaseExporter(defaultSettings, defaultDataType, newObservabilityConsumerSender, - withMarshaler(mockRequestMarshaler), withUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), + be, err := NewBaseExporter(defaultSettings, defaultDataType, newObservabilityConsumerSender, + WithMarshaler(mockRequestMarshaler), WithUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), WithRetry(rCfg), WithQueue(qCfg)) require.NoError(t, err) - ocs := be.obsrepSender.(*observabilityConsumerSender) + ocs := be.ObsrepSender.(*observabilityConsumerSender) require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost())) t.Cleanup(func() { assert.NoError(t, be.Shutdown(context.Background())) @@ -183,7 +184,7 @@ func TestQueuedRetry_ThrottleError(t *testing.T) { start := time.Now() ocs.run(func() { // This is asynchronous so it should just enqueue, no errors expected. - require.NoError(t, be.send(context.Background(), mockR)) + require.NoError(t, be.Send(context.Background(), mockR)) }) ocs.awaitAsyncProcessing() @@ -193,7 +194,7 @@ func TestQueuedRetry_ThrottleError(t *testing.T) { mockR.checkNumRequests(t, 2) ocs.checkSendItemsCount(t, 2) ocs.checkDroppedItemsCount(t, 0) - require.Zero(t, be.queueSender.(*queueSender).queue.Size()) + require.Zero(t, be.QueueSender.(*QueueSender).queue.Size()) } func TestQueuedRetry_RetryOnError(t *testing.T) { @@ -202,11 +203,11 @@ func TestQueuedRetry_RetryOnError(t *testing.T) { qCfg.QueueSize = 1 rCfg := configretry.NewDefaultBackOffConfig() rCfg.InitialInterval = 0 - be, err := newBaseExporter(defaultSettings, defaultDataType, newObservabilityConsumerSender, - withMarshaler(mockRequestMarshaler), withUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), + be, err := NewBaseExporter(defaultSettings, defaultDataType, newObservabilityConsumerSender, + WithMarshaler(mockRequestMarshaler), WithUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), WithRetry(rCfg), WithQueue(qCfg)) require.NoError(t, err) - ocs := be.obsrepSender.(*observabilityConsumerSender) + ocs := be.ObsrepSender.(*observabilityConsumerSender) require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost())) t.Cleanup(func() { assert.NoError(t, be.Shutdown(context.Background())) @@ -215,7 +216,7 @@ func TestQueuedRetry_RetryOnError(t *testing.T) { mockR := newMockRequest(2, errors.New("transient error")) ocs.run(func() { // This is asynchronous so it should just enqueue, no errors expected. - require.NoError(t, be.send(context.Background(), mockR)) + require.NoError(t, be.Send(context.Background(), mockR)) }) ocs.awaitAsyncProcessing() @@ -223,19 +224,19 @@ func TestQueuedRetry_RetryOnError(t *testing.T) { mockR.checkNumRequests(t, 2) ocs.checkSendItemsCount(t, 2) ocs.checkDroppedItemsCount(t, 0) - require.Zero(t, be.queueSender.(*queueSender).queue.Size()) + require.Zero(t, be.QueueSender.(*QueueSender).queue.Size()) } func TestQueueRetryWithNoQueue(t *testing.T) { rCfg := configretry.NewDefaultBackOffConfig() rCfg.MaxElapsedTime = time.Nanosecond // fail fast - be, err := newBaseExporter(exportertest.NewNopSettings(), component.DataTypeLogs, newObservabilityConsumerSender, WithRetry(rCfg)) + be, err := NewBaseExporter(exportertest.NewNopSettings(), component.DataTypeLogs, newObservabilityConsumerSender, WithRetry(rCfg)) require.NoError(t, err) require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost())) - ocs := be.obsrepSender.(*observabilityConsumerSender) + ocs := be.ObsrepSender.(*observabilityConsumerSender) mockR := newMockRequest(2, errors.New("some error")) ocs.run(func() { - require.Error(t, be.send(context.Background(), mockR)) + require.Error(t, be.Send(context.Background(), mockR)) }) ocs.awaitAsyncProcessing() mockR.checkNumRequests(t, 1) @@ -250,13 +251,13 @@ func TestQueueRetryWithDisabledRetires(t *testing.T) { set := exportertest.NewNopSettings() logger, observed := observer.New(zap.ErrorLevel) set.Logger = zap.New(logger) - be, err := newBaseExporter(set, component.DataTypeLogs, newObservabilityConsumerSender, WithRetry(rCfg)) + be, err := NewBaseExporter(set, component.DataTypeLogs, newObservabilityConsumerSender, WithRetry(rCfg)) require.NoError(t, err) require.NoError(t, be.Start(context.Background(), componenttest.NewNopHost())) - ocs := be.obsrepSender.(*observabilityConsumerSender) + ocs := be.ObsrepSender.(*observabilityConsumerSender) mockR := newMockRequest(2, errors.New("some error")) ocs.run(func() { - require.Error(t, be.send(context.Background(), mockR)) + require.Error(t, be.Send(context.Background(), mockR)) }) assert.Len(t, observed.All(), 1) assert.Equal(t, "Exporting failed. Rejecting data. "+ @@ -274,7 +275,7 @@ func (mer *mockErrorRequest) Export(context.Context) error { return errors.New("transient error") } -func (mer *mockErrorRequest) OnError(error) Request { +func (mer *mockErrorRequest) OnError(error) internal.Request { return mer } @@ -282,7 +283,7 @@ func (mer *mockErrorRequest) ItemsCount() int { return 7 } -func newErrorRequest() Request { +func newErrorRequest() internal.Request { return &mockErrorRequest{} } @@ -306,7 +307,7 @@ func (m *mockRequest) Export(ctx context.Context) error { return ctx.Err() } -func (m *mockRequest) OnError(error) Request { +func (m *mockRequest) OnError(error) internal.Request { return &mockRequest{ cnt: 1, consumeError: nil, @@ -333,13 +334,13 @@ func newMockRequest(cnt int, consumeError error) *mockRequest { } type observabilityConsumerSender struct { - baseRequestSender + BaseRequestSender waitGroup *sync.WaitGroup sentItemsCount *atomic.Int64 droppedItemsCount *atomic.Int64 } -func newObservabilityConsumerSender(*obsReport) requestSender { +func newObservabilityConsumerSender(*ObsReport) RequestSender { return &observabilityConsumerSender{ waitGroup: new(sync.WaitGroup), droppedItemsCount: &atomic.Int64{}, @@ -347,8 +348,8 @@ func newObservabilityConsumerSender(*obsReport) requestSender { } } -func (ocs *observabilityConsumerSender) send(ctx context.Context, req Request) error { - err := ocs.nextSender.send(ctx, req) +func (ocs *observabilityConsumerSender) Send(ctx context.Context, req internal.Request) error { + err := ocs.NextSender.Send(ctx, req) if err != nil { ocs.droppedItemsCount.Add(int64(req.ItemsCount())) } else { diff --git a/exporter/exporterhelper/internal/timeout_sender.go b/exporter/exporterhelper/internal/timeout_sender.go new file mode 100644 index 00000000000..5abae1b6746 --- /dev/null +++ b/exporter/exporterhelper/internal/timeout_sender.go @@ -0,0 +1,52 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package internal // import "go.opentelemetry.io/collector/exporter/exporterhelper/internal" + +import ( + "context" + "errors" + "time" + + "go.opentelemetry.io/collector/exporter/internal" +) + +// TimeoutConfig for timeout. The timeout applies to individual attempts to send data to the backend. +type TimeoutConfig struct { + // Timeout is the timeout for every attempt to send data to the backend. + // A zero timeout means no timeout. + Timeout time.Duration `mapstructure:"timeout"` +} + +func (ts *TimeoutConfig) Validate() error { + // Negative timeouts are not acceptable, since all sends will fail. + if ts.Timeout < 0 { + return errors.New("'timeout' must be non-negative") + } + return nil +} + +// NewDefaultTimeoutConfig returns the default config for TimeoutConfig. +func NewDefaultTimeoutConfig() TimeoutConfig { + return TimeoutConfig{ + Timeout: 5 * time.Second, + } +} + +// TimeoutSender is a requestSender that adds a `timeout` to every request that passes this sender. +type TimeoutSender struct { + BaseRequestSender + cfg TimeoutConfig +} + +func (ts *TimeoutSender) Send(ctx context.Context, req internal.Request) error { + // TODO: Remove this by avoiding to create the timeout sender if timeout is 0. + if ts.cfg.Timeout == 0 { + return req.Export(ctx) + } + // Intentionally don't overwrite the context inside the request, because in case of retries deadline will not be + // updated because this deadline most likely is before the next one. + tCtx, cancelFunc := context.WithTimeout(ctx, ts.cfg.Timeout) + defer cancelFunc() + return req.Export(tCtx) +} diff --git a/exporter/exporterhelper/timeout_sender_test.go b/exporter/exporterhelper/internal/timeout_sender_test.go similarity index 95% rename from exporter/exporterhelper/timeout_sender_test.go rename to exporter/exporterhelper/internal/timeout_sender_test.go index f72cf565360..8da16b24e18 100644 --- a/exporter/exporterhelper/timeout_sender_test.go +++ b/exporter/exporterhelper/internal/timeout_sender_test.go @@ -1,7 +1,7 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -package exporterhelper +package internal import ( "testing" diff --git a/exporter/exporterhelper/logs.go b/exporter/exporterhelper/logs.go index 790ba188657..795bf91408e 100644 --- a/exporter/exporterhelper/logs.go +++ b/exporter/exporterhelper/logs.go @@ -13,6 +13,7 @@ import ( "go.opentelemetry.io/collector/consumer" "go.opentelemetry.io/collector/consumer/consumererror" "go.opentelemetry.io/collector/exporter" + "go.opentelemetry.io/collector/exporter/exporterhelper/internal" "go.opentelemetry.io/collector/exporter/exporterqueue" "go.opentelemetry.io/collector/exporter/internal/queue" "go.opentelemetry.io/collector/pdata/plog" @@ -64,7 +65,7 @@ func (req *logsRequest) ItemsCount() int { } type logsExporter struct { - *baseExporter + *internal.BaseExporter consumer.Logs } @@ -83,8 +84,8 @@ func NewLogsExporter( return nil, errNilPushLogsData } logsOpts := []Option{ - withMarshaler(logsRequestMarshaler), withUnmarshaler(newLogsRequestUnmarshalerFunc(pusher)), - withBatchFuncs(mergeLogs, mergeSplitLogs), + internal.WithMarshaler(logsRequestMarshaler), internal.WithUnmarshaler(newLogsRequestUnmarshalerFunc(pusher)), + internal.WithBatchFuncs(mergeLogs, mergeSplitLogs), } return NewLogsRequestExporter(ctx, set, requestFromLogs(pusher), append(logsOpts, options...)...) } @@ -118,7 +119,7 @@ func NewLogsRequestExporter( return nil, errNilLogsConverter } - be, err := newBaseExporter(set, component.DataTypeLogs, newLogsExporterWithObservability, options...) + be, err := internal.NewBaseExporter(set, component.DataTypeLogs, newLogsExporterWithObservability, options...) if err != nil { return nil, err } @@ -131,32 +132,32 @@ func NewLogsRequestExporter( zap.Error(err)) return consumererror.NewPermanent(cErr) } - sErr := be.send(ctx, req) + sErr := be.Send(ctx, req) if errors.Is(sErr, queue.ErrQueueIsFull) { - be.obsrep.recordEnqueueFailure(ctx, component.DataTypeLogs, int64(req.ItemsCount())) + be.Obsrep.RecordEnqueueFailure(ctx, component.DataTypeLogs, int64(req.ItemsCount())) } return sErr - }, be.consumerOptions...) + }, be.ConsumerOptions...) return &logsExporter{ - baseExporter: be, + BaseExporter: be, Logs: lc, }, err } type logsExporterWithObservability struct { - baseRequestSender - obsrep *obsReport + internal.BaseRequestSender + obsrep *internal.ObsReport } -func newLogsExporterWithObservability(obsrep *obsReport) requestSender { +func newLogsExporterWithObservability(obsrep *internal.ObsReport) internal.RequestSender { return &logsExporterWithObservability{obsrep: obsrep} } -func (lewo *logsExporterWithObservability) send(ctx context.Context, req Request) error { - c := lewo.obsrep.startLogsOp(ctx) +func (lewo *logsExporterWithObservability) Send(ctx context.Context, req Request) error { + c := lewo.obsrep.StartLogsOp(ctx) numLogRecords := req.ItemsCount() - err := lewo.nextSender.send(c, req) - lewo.obsrep.endLogsOp(c, numLogRecords, err) + err := lewo.NextSender.Send(c, req) + lewo.obsrep.EndLogsOp(c, numLogRecords, err) return err } diff --git a/exporter/exporterhelper/logs_test.go b/exporter/exporterhelper/logs_test.go index 1fb952d1486..32a50b5e063 100644 --- a/exporter/exporterhelper/logs_test.go +++ b/exporter/exporterhelper/logs_test.go @@ -65,7 +65,7 @@ func TestLogsExporter_NilLogger(t *testing.T) { } func TestLogsRequestExporter_NilLogger(t *testing.T) { - le, err := NewLogsRequestExporter(context.Background(), exporter.Settings{}, (&fakeRequestConverter{}).requestFromLogsFunc) + le, err := NewLogsRequestExporter(context.Background(), exporter.Settings{}, (&internal.FakeRequestConverter{}).RequestFromLogsFunc) require.Nil(t, le) require.Equal(t, errNilLogger, err) } @@ -97,7 +97,7 @@ func TestLogsExporter_Default(t *testing.T) { func TestLogsRequestExporter_Default(t *testing.T) { ld := plog.NewLogs() le, err := NewLogsRequestExporter(context.Background(), exportertest.NewNopSettings(), - (&fakeRequestConverter{}).requestFromLogsFunc) + (&internal.FakeRequestConverter{}).RequestFromLogsFunc) assert.NotNil(t, le) require.NoError(t, err) @@ -119,7 +119,7 @@ func TestLogsExporter_WithCapabilities(t *testing.T) { func TestLogsRequestExporter_WithCapabilities(t *testing.T) { capabilities := consumer.Capabilities{MutatesData: true} le, err := NewLogsRequestExporter(context.Background(), exportertest.NewNopSettings(), - (&fakeRequestConverter{}).requestFromLogsFunc, WithCapabilities(capabilities)) + (&internal.FakeRequestConverter{}).RequestFromLogsFunc, WithCapabilities(capabilities)) require.NoError(t, err) require.NotNil(t, le) @@ -139,7 +139,7 @@ func TestLogsRequestExporter_Default_ConvertError(t *testing.T) { ld := plog.NewLogs() want := errors.New("convert_error") le, err := NewLogsRequestExporter(context.Background(), exportertest.NewNopSettings(), - (&fakeRequestConverter{logsError: want}).requestFromLogsFunc) + (&internal.FakeRequestConverter{LogsError: want}).RequestFromLogsFunc) require.NoError(t, err) require.NotNil(t, le) require.Equal(t, consumererror.NewPermanent(want), le.ConsumeLogs(context.Background(), ld)) @@ -149,7 +149,7 @@ func TestLogsRequestExporter_Default_ExportError(t *testing.T) { ld := plog.NewLogs() want := errors.New("export_error") le, err := NewLogsRequestExporter(context.Background(), exportertest.NewNopSettings(), - (&fakeRequestConverter{requestError: want}).requestFromLogsFunc) + (&internal.FakeRequestConverter{RequestError: want}).RequestFromLogsFunc) require.NoError(t, err) require.NotNil(t, le) require.Equal(t, want, le.ConsumeLogs(context.Background(), ld)) @@ -166,7 +166,7 @@ func TestLogsExporter_WithPersistentQueue(t *testing.T) { te, err := NewLogsExporter(context.Background(), set, &fakeLogsExporterConfig, ts.ConsumeLogs, WithRetry(rCfg), WithQueue(qCfg)) require.NoError(t, err) - host := &mockHost{ext: map[component.ID]component.Component{ + host := &internal.MockHost{Ext: map[component.ID]component.Component{ storageID: queue.NewMockStorageExtension(nil), }} require.NoError(t, te.Start(context.Background(), host)) @@ -213,7 +213,7 @@ func TestLogsRequestExporter_WithRecordMetrics(t *testing.T) { le, err := NewLogsRequestExporter(context.Background(), exporter.Settings{ID: fakeLogsExporterName, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, - (&fakeRequestConverter{}).requestFromLogsFunc) + (&internal.FakeRequestConverter{}).RequestFromLogsFunc) require.NoError(t, err) require.NotNil(t, le) @@ -240,7 +240,7 @@ func TestLogsRequestExporter_WithRecordMetrics_ExportError(t *testing.T) { t.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) }) le, err := NewLogsRequestExporter(context.Background(), exporter.Settings{ID: fakeLogsExporterName, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, - (&fakeRequestConverter{requestError: want}).requestFromLogsFunc) + (&internal.FakeRequestConverter{RequestError: want}).RequestFromLogsFunc) require.NoError(t, err) require.NotNil(t, le) @@ -292,7 +292,7 @@ func TestLogsRequestExporter_WithSpan(t *testing.T) { otel.SetTracerProvider(set.TracerProvider) defer otel.SetTracerProvider(nooptrace.NewTracerProvider()) - le, err := NewLogsRequestExporter(context.Background(), set, (&fakeRequestConverter{}).requestFromLogsFunc) + le, err := NewLogsRequestExporter(context.Background(), set, (&internal.FakeRequestConverter{}).RequestFromLogsFunc) require.NoError(t, err) require.NotNil(t, le) checkWrapSpanForLogsExporter(t, sr, set.TracerProvider.Tracer("test"), le, nil, 1) @@ -320,7 +320,7 @@ func TestLogsRequestExporter_WithSpan_ReturnError(t *testing.T) { defer otel.SetTracerProvider(nooptrace.NewTracerProvider()) want := errors.New("my_error") - le, err := NewLogsRequestExporter(context.Background(), set, (&fakeRequestConverter{requestError: want}).requestFromLogsFunc) + le, err := NewLogsRequestExporter(context.Background(), set, (&internal.FakeRequestConverter{RequestError: want}).RequestFromLogsFunc) require.NoError(t, err) require.NotNil(t, le) checkWrapSpanForLogsExporter(t, sr, set.TracerProvider.Tracer("test"), le, want, 1) @@ -343,7 +343,7 @@ func TestLogsRequestExporter_WithShutdown(t *testing.T) { shutdown := func(context.Context) error { shutdownCalled = true; return nil } le, err := NewLogsRequestExporter(context.Background(), exportertest.NewNopSettings(), - (&fakeRequestConverter{}).requestFromLogsFunc, WithShutdown(shutdown)) + (&internal.FakeRequestConverter{}).RequestFromLogsFunc, WithShutdown(shutdown)) assert.NotNil(t, le) assert.NoError(t, err) @@ -367,7 +367,7 @@ func TestLogsRequestExporter_WithShutdown_ReturnError(t *testing.T) { shutdownErr := func(context.Context) error { return want } le, err := NewLogsRequestExporter(context.Background(), exportertest.NewNopSettings(), - (&fakeRequestConverter{}).requestFromLogsFunc, WithShutdown(shutdownErr)) + (&internal.FakeRequestConverter{}).RequestFromLogsFunc, WithShutdown(shutdownErr)) assert.NotNil(t, le) require.NoError(t, err) @@ -424,7 +424,7 @@ func checkWrapSpanForLogsExporter(t *testing.T, sr *tracetest.SpanRecorder, trac require.Equalf(t, fakeLogsParentSpanName, parentSpan.Name(), "SpanData %v", parentSpan) for _, sd := range gotSpanData[:numRequests] { require.Equalf(t, parentSpan.SpanContext(), sd.Parent(), "Exporter span not a child\nSpanData %v", sd) - checkStatus(t, sd, wantError) + internal.CheckStatus(t, sd, wantError) sentLogRecords := numLogRecords var failedToSendLogRecords int64 diff --git a/exporter/exporterhelper/metrics.go b/exporter/exporterhelper/metrics.go index 382c9b9ce8a..f78fc2fc972 100644 --- a/exporter/exporterhelper/metrics.go +++ b/exporter/exporterhelper/metrics.go @@ -13,6 +13,7 @@ import ( "go.opentelemetry.io/collector/consumer" "go.opentelemetry.io/collector/consumer/consumererror" "go.opentelemetry.io/collector/exporter" + "go.opentelemetry.io/collector/exporter/exporterhelper/internal" "go.opentelemetry.io/collector/exporter/exporterqueue" "go.opentelemetry.io/collector/exporter/internal/queue" "go.opentelemetry.io/collector/pdata/pmetric" @@ -64,7 +65,7 @@ func (req *metricsRequest) ItemsCount() int { } type metricsExporter struct { - *baseExporter + *internal.BaseExporter consumer.Metrics } @@ -83,8 +84,8 @@ func NewMetricsExporter( return nil, errNilPushMetricsData } metricsOpts := []Option{ - withMarshaler(metricsRequestMarshaler), withUnmarshaler(newMetricsRequestUnmarshalerFunc(pusher)), - withBatchFuncs(mergeMetrics, mergeSplitMetrics), + internal.WithMarshaler(metricsRequestMarshaler), internal.WithUnmarshaler(newMetricsRequestUnmarshalerFunc(pusher)), + internal.WithBatchFuncs(mergeMetrics, mergeSplitMetrics), } return NewMetricsRequestExporter(ctx, set, requestFromMetrics(pusher), append(metricsOpts, options...)...) } @@ -118,7 +119,7 @@ func NewMetricsRequestExporter( return nil, errNilMetricsConverter } - be, err := newBaseExporter(set, component.DataTypeMetrics, newMetricsSenderWithObservability, options...) + be, err := internal.NewBaseExporter(set, component.DataTypeMetrics, newMetricsSenderWithObservability, options...) if err != nil { return nil, err } @@ -131,32 +132,32 @@ func NewMetricsRequestExporter( zap.Error(err)) return consumererror.NewPermanent(cErr) } - sErr := be.send(ctx, req) + sErr := be.Send(ctx, req) if errors.Is(sErr, queue.ErrQueueIsFull) { - be.obsrep.recordEnqueueFailure(ctx, component.DataTypeMetrics, int64(req.ItemsCount())) + be.Obsrep.RecordEnqueueFailure(ctx, component.DataTypeMetrics, int64(req.ItemsCount())) } return sErr - }, be.consumerOptions...) + }, be.ConsumerOptions...) return &metricsExporter{ - baseExporter: be, + BaseExporter: be, Metrics: mc, }, err } type metricsSenderWithObservability struct { - baseRequestSender - obsrep *obsReport + internal.BaseRequestSender + obsrep *internal.ObsReport } -func newMetricsSenderWithObservability(obsrep *obsReport) requestSender { +func newMetricsSenderWithObservability(obsrep *internal.ObsReport) internal.RequestSender { return &metricsSenderWithObservability{obsrep: obsrep} } -func (mewo *metricsSenderWithObservability) send(ctx context.Context, req Request) error { - c := mewo.obsrep.startMetricsOp(ctx) +func (mewo *metricsSenderWithObservability) Send(ctx context.Context, req Request) error { + c := mewo.obsrep.StartMetricsOp(ctx) numMetricDataPoints := req.ItemsCount() - err := mewo.nextSender.send(c, req) - mewo.obsrep.endMetricsOp(c, numMetricDataPoints, err) + err := mewo.NextSender.Send(c, req) + mewo.obsrep.EndMetricsOp(c, numMetricDataPoints, err) return err } diff --git a/exporter/exporterhelper/metrics_test.go b/exporter/exporterhelper/metrics_test.go index 02381396547..ef3bbc4f6e2 100644 --- a/exporter/exporterhelper/metrics_test.go +++ b/exporter/exporterhelper/metrics_test.go @@ -66,7 +66,7 @@ func TestMetricsExporter_NilLogger(t *testing.T) { func TestMetricsRequestExporter_NilLogger(t *testing.T) { me, err := NewMetricsRequestExporter(context.Background(), exporter.Settings{}, - (&fakeRequestConverter{}).requestFromMetricsFunc) + (&internal.FakeRequestConverter{}).RequestFromMetricsFunc) require.Nil(t, me) require.Equal(t, errNilLogger, err) } @@ -98,7 +98,7 @@ func TestMetricsExporter_Default(t *testing.T) { func TestMetricsRequestExporter_Default(t *testing.T) { md := pmetric.NewMetrics() me, err := NewMetricsRequestExporter(context.Background(), exportertest.NewNopSettings(), - (&fakeRequestConverter{}).requestFromMetricsFunc) + (&internal.FakeRequestConverter{}).RequestFromMetricsFunc) require.NoError(t, err) assert.NotNil(t, me) @@ -120,7 +120,7 @@ func TestMetricsExporter_WithCapabilities(t *testing.T) { func TestMetricsRequestExporter_WithCapabilities(t *testing.T) { capabilities := consumer.Capabilities{MutatesData: true} me, err := NewMetricsRequestExporter(context.Background(), exportertest.NewNopSettings(), - (&fakeRequestConverter{}).requestFromMetricsFunc, WithCapabilities(capabilities)) + (&internal.FakeRequestConverter{}).RequestFromMetricsFunc, WithCapabilities(capabilities)) require.NoError(t, err) assert.NotNil(t, me) @@ -140,7 +140,7 @@ func TestMetricsRequestExporter_Default_ConvertError(t *testing.T) { md := pmetric.NewMetrics() want := errors.New("convert_error") me, err := NewMetricsRequestExporter(context.Background(), exportertest.NewNopSettings(), - (&fakeRequestConverter{metricsError: want}).requestFromMetricsFunc) + (&internal.FakeRequestConverter{MetricsError: want}).RequestFromMetricsFunc) require.NoError(t, err) require.NotNil(t, me) require.Equal(t, consumererror.NewPermanent(want), me.ConsumeMetrics(context.Background(), md)) @@ -150,7 +150,7 @@ func TestMetricsRequestExporter_Default_ExportError(t *testing.T) { md := pmetric.NewMetrics() want := errors.New("export_error") me, err := NewMetricsRequestExporter(context.Background(), exportertest.NewNopSettings(), - (&fakeRequestConverter{requestError: want}).requestFromMetricsFunc) + (&internal.FakeRequestConverter{RequestError: want}).RequestFromMetricsFunc) require.NoError(t, err) require.NotNil(t, me) require.Equal(t, want, me.ConsumeMetrics(context.Background(), md)) @@ -167,7 +167,7 @@ func TestMetricsExporter_WithPersistentQueue(t *testing.T) { te, err := NewMetricsExporter(context.Background(), set, &fakeTracesExporterConfig, ms.ConsumeMetrics, WithRetry(rCfg), WithQueue(qCfg)) require.NoError(t, err) - host := &mockHost{ext: map[component.ID]component.Component{ + host := &internal.MockHost{Ext: map[component.ID]component.Component{ storageID: queue.NewMockStorageExtension(nil), }} require.NoError(t, te.Start(context.Background(), host)) @@ -214,7 +214,7 @@ func TestMetricsRequestExporter_WithRecordMetrics(t *testing.T) { me, err := NewMetricsRequestExporter(context.Background(), exporter.Settings{ID: fakeMetricsExporterName, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, - (&fakeRequestConverter{}).requestFromMetricsFunc) + (&internal.FakeRequestConverter{}).RequestFromMetricsFunc) require.NoError(t, err) require.NotNil(t, me) @@ -242,7 +242,7 @@ func TestMetricsRequestExporter_WithRecordMetrics_ExportError(t *testing.T) { me, err := NewMetricsRequestExporter(context.Background(), exporter.Settings{ID: fakeMetricsExporterName, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, - (&fakeRequestConverter{requestError: want}).requestFromMetricsFunc) + (&internal.FakeRequestConverter{RequestError: want}).RequestFromMetricsFunc) require.NoError(t, err) require.NotNil(t, me) @@ -294,7 +294,7 @@ func TestMetricsRequestExporter_WithSpan(t *testing.T) { otel.SetTracerProvider(set.TracerProvider) defer otel.SetTracerProvider(nooptrace.NewTracerProvider()) - me, err := NewMetricsRequestExporter(context.Background(), set, (&fakeRequestConverter{}).requestFromMetricsFunc) + me, err := NewMetricsRequestExporter(context.Background(), set, (&internal.FakeRequestConverter{}).RequestFromMetricsFunc) require.NoError(t, err) require.NotNil(t, me) checkWrapSpanForMetricsExporter(t, sr, set.TracerProvider.Tracer("test"), me, nil, 2) @@ -322,7 +322,7 @@ func TestMetricsRequestExporter_WithSpan_ExportError(t *testing.T) { defer otel.SetTracerProvider(nooptrace.NewTracerProvider()) want := errors.New("my_error") - me, err := NewMetricsRequestExporter(context.Background(), set, (&fakeRequestConverter{requestError: want}).requestFromMetricsFunc) + me, err := NewMetricsRequestExporter(context.Background(), set, (&internal.FakeRequestConverter{RequestError: want}).RequestFromMetricsFunc) require.NoError(t, err) require.NotNil(t, me) checkWrapSpanForMetricsExporter(t, sr, set.TracerProvider.Tracer("test"), me, want, 2) @@ -346,7 +346,7 @@ func TestMetricsRequestExporter_WithShutdown(t *testing.T) { shutdown := func(context.Context) error { shutdownCalled = true; return nil } me, err := NewMetricsRequestExporter(context.Background(), exportertest.NewNopSettings(), - (&fakeRequestConverter{}).requestFromMetricsFunc, WithShutdown(shutdown)) + (&internal.FakeRequestConverter{}).RequestFromMetricsFunc, WithShutdown(shutdown)) assert.NotNil(t, me) assert.NoError(t, err) @@ -372,7 +372,7 @@ func TestMetricsRequestExporter_WithShutdown_ReturnError(t *testing.T) { shutdownErr := func(context.Context) error { return want } me, err := NewMetricsRequestExporter(context.Background(), exportertest.NewNopSettings(), - (&fakeRequestConverter{}).requestFromMetricsFunc, WithShutdown(shutdownErr)) + (&internal.FakeRequestConverter{}).RequestFromMetricsFunc, WithShutdown(shutdownErr)) assert.NotNil(t, me) assert.NoError(t, err) @@ -430,7 +430,7 @@ func checkWrapSpanForMetricsExporter(t *testing.T, sr *tracetest.SpanRecorder, t require.Equalf(t, fakeMetricsParentSpanName, parentSpan.Name(), "SpanData %v", parentSpan) for _, sd := range gotSpanData[:numRequests] { require.Equalf(t, parentSpan.SpanContext(), sd.Parent(), "Exporter span not a child\nSpanData %v", sd) - checkStatus(t, sd, wantError) + internal.CheckStatus(t, sd, wantError) sentMetricPoints := numMetricPoints var failedToSendMetricPoints int64 diff --git a/exporter/exporterhelper/obsreport_test.go b/exporter/exporterhelper/obsreport_test.go index f8ab9aed1c8..80134bc8a62 100644 --- a/exporter/exporterhelper/obsreport_test.go +++ b/exporter/exporterhelper/obsreport_test.go @@ -12,28 +12,31 @@ import ( "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/component/componenttest" "go.opentelemetry.io/collector/exporter" + "go.opentelemetry.io/collector/exporter/exporterhelper/internal" ) +var exporterID = component.MustNewID("fakeExporter") + func TestExportEnqueueFailure(t *testing.T) { tt, err := componenttest.SetupTelemetry(exporterID) require.NoError(t, err) t.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) }) - obsrep, err := newExporter(obsReportSettings{ - exporterID: exporterID, - exporterCreateSettings: exporter.Settings{ID: exporterID, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, + obsrep, err := internal.NewExporter(internal.ObsReportSettings{ + ExporterID: exporterID, + ExporterCreateSettings: exporter.Settings{ID: exporterID, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, }) require.NoError(t, err) logRecords := int64(7) - obsrep.recordEnqueueFailure(context.Background(), component.DataTypeLogs, logRecords) + obsrep.RecordEnqueueFailure(context.Background(), component.DataTypeLogs, logRecords) require.NoError(t, tt.CheckExporterEnqueueFailedLogs(logRecords)) spans := int64(12) - obsrep.recordEnqueueFailure(context.Background(), component.DataTypeTraces, spans) + obsrep.RecordEnqueueFailure(context.Background(), component.DataTypeTraces, spans) require.NoError(t, tt.CheckExporterEnqueueFailedTraces(spans)) metricPoints := int64(21) - obsrep.recordEnqueueFailure(context.Background(), component.DataTypeMetrics, metricPoints) + obsrep.RecordEnqueueFailure(context.Background(), component.DataTypeMetrics, metricPoints) require.NoError(t, tt.CheckExporterEnqueueFailedMetrics(metricPoints)) } diff --git a/exporter/exporterhelper/queue_sender.go b/exporter/exporterhelper/queue_sender.go index 58edbcc8732..b81e2036fab 100644 --- a/exporter/exporterhelper/queue_sender.go +++ b/exporter/exporterhelper/queue_sender.go @@ -3,143 +3,20 @@ package exporterhelper // import "go.opentelemetry.io/collector/exporter/exporterhelper" -import ( - "context" - "errors" - - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/metric" - "go.opentelemetry.io/otel/trace" - "go.uber.org/multierr" - "go.uber.org/zap" - - "go.opentelemetry.io/collector/component" - "go.opentelemetry.io/collector/exporter" - "go.opentelemetry.io/collector/exporter/exporterhelper/internal" - "go.opentelemetry.io/collector/exporter/exporterqueue" - "go.opentelemetry.io/collector/exporter/internal/queue" -) - -const defaultQueueSize = 1000 +import "go.opentelemetry.io/collector/exporter/exporterhelper/internal" // Deprecated: [v0.110.0] Use QueueConfig instead. -type QueueSettings = QueueConfig +type QueueSettings = internal.QueueConfig // QueueConfig defines configuration for queueing batches before sending to the consumerSender. -type QueueConfig struct { - // Enabled indicates whether to not enqueue batches before sending to the consumerSender. - Enabled bool `mapstructure:"enabled"` - // NumConsumers is the number of consumers from the queue. Defaults to 10. - // If batching is enabled, a combined batch cannot contain more requests than the number of consumers. - // So it's recommended to set higher number of consumers if batching is enabled. - NumConsumers int `mapstructure:"num_consumers"` - // QueueSize is the maximum number of batches allowed in queue at a given time. - QueueSize int `mapstructure:"queue_size"` - // StorageID if not empty, enables the persistent storage and uses the component specified - // as a storage extension for the persistent queue - StorageID *component.ID `mapstructure:"storage"` -} +type QueueConfig = internal.QueueConfig // Deprecated: [v0.110.0] Use NewDefaultQueueConfig instead. func NewDefaultQueueSettings() QueueSettings { - return NewDefaultQueueConfig() + return internal.NewDefaultQueueConfig() } // NewDefaultQueueConfig returns the default config for QueueConfig. func NewDefaultQueueConfig() QueueConfig { - return QueueConfig{ - Enabled: true, - NumConsumers: 10, - // By default, batches are 8192 spans, for a total of up to 8 million spans in the queue - // This can be estimated at 1-4 GB worth of maximum memory usage - // This default is probably still too high, and may be adjusted further down in a future release - QueueSize: defaultQueueSize, - } -} - -// Validate checks if the QueueConfig configuration is valid -func (qCfg *QueueConfig) Validate() error { - if !qCfg.Enabled { - return nil - } - - if qCfg.QueueSize <= 0 { - return errors.New("queue size must be positive") - } - - if qCfg.NumConsumers <= 0 { - return errors.New("number of queue consumers must be positive") - } - - return nil -} - -type queueSender struct { - baseRequestSender - queue exporterqueue.Queue[Request] - numConsumers int - traceAttribute attribute.KeyValue - consumers *queue.Consumers[Request] - - obsrep *obsReport - exporterID component.ID -} - -func newQueueSender(q exporterqueue.Queue[Request], set exporter.Settings, numConsumers int, - exportFailureMessage string, obsrep *obsReport) *queueSender { - qs := &queueSender{ - queue: q, - numConsumers: numConsumers, - traceAttribute: attribute.String(internal.ExporterKey, set.ID.String()), - obsrep: obsrep, - exporterID: set.ID, - } - consumeFunc := func(ctx context.Context, req Request) error { - err := qs.nextSender.send(ctx, req) - if err != nil { - set.Logger.Error("Exporting failed. Dropping data."+exportFailureMessage, - zap.Error(err), zap.Int("dropped_items", req.ItemsCount())) - } - return err - } - qs.consumers = queue.NewQueueConsumers[Request](q, numConsumers, consumeFunc) - return qs -} - -// Start is invoked during service startup. -func (qs *queueSender) Start(ctx context.Context, host component.Host) error { - if err := qs.consumers.Start(ctx, host); err != nil { - return err - } - - dataTypeAttr := attribute.String(internal.DataTypeKey, qs.obsrep.dataType.String()) - return multierr.Append( - qs.obsrep.telemetryBuilder.InitExporterQueueSize(func() int64 { return int64(qs.queue.Size()) }, - metric.WithAttributeSet(attribute.NewSet(qs.traceAttribute, dataTypeAttr))), - qs.obsrep.telemetryBuilder.InitExporterQueueCapacity(func() int64 { return int64(qs.queue.Capacity()) }, - metric.WithAttributeSet(attribute.NewSet(qs.traceAttribute))), - ) -} - -// Shutdown is invoked during service shutdown. -func (qs *queueSender) Shutdown(ctx context.Context) error { - // Stop the queue and consumers, this will drain the queue and will call the retry (which is stopped) that will only - // try once every request. - return qs.consumers.Shutdown(ctx) -} - -// send implements the requestSender interface. It puts the request in the queue. -func (qs *queueSender) send(ctx context.Context, req Request) error { - // Prevent cancellation and deadline to propagate to the context stored in the queue. - // The grpc/http based receivers will cancel the request context after this function returns. - c := context.WithoutCancel(ctx) - - span := trace.SpanFromContext(c) - if err := qs.queue.Offer(c, req); err != nil { - span.AddEvent("Failed to enqueue item.", trace.WithAttributes(qs.traceAttribute)) - return err - } - - span.AddEvent("Enqueued item.", trace.WithAttributes(qs.traceAttribute)) - return nil + return internal.NewDefaultQueueConfig() } diff --git a/exporter/exporterhelper/retry_sender.go b/exporter/exporterhelper/retry_sender.go index 0caa10ad72f..5b4476bb1f6 100644 --- a/exporter/exporterhelper/retry_sender.go +++ b/exporter/exporterhelper/retry_sender.go @@ -4,139 +4,12 @@ package exporterhelper // import "go.opentelemetry.io/collector/exporter/exporterhelper" import ( - "context" - "errors" - "fmt" "time" - "github.com/cenkalti/backoff/v4" - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/trace" - "go.uber.org/zap" - - "go.opentelemetry.io/collector/config/configretry" - "go.opentelemetry.io/collector/consumer/consumererror" - "go.opentelemetry.io/collector/exporter" "go.opentelemetry.io/collector/exporter/exporterhelper/internal" - "go.opentelemetry.io/collector/exporter/internal/experr" ) -// TODO: Clean this by forcing all exporters to return an internal error type that always include the information about retries. -type throttleRetry struct { - err error - delay time.Duration -} - -func (t throttleRetry) Error() string { - return "Throttle (" + t.delay.String() + "), error: " + t.err.Error() -} - -func (t throttleRetry) Unwrap() error { - return t.err -} - // NewThrottleRetry creates a new throttle retry error. func NewThrottleRetry(err error, delay time.Duration) error { - return throttleRetry{ - err: err, - delay: delay, - } -} - -type retrySender struct { - baseRequestSender - traceAttribute attribute.KeyValue - cfg configretry.BackOffConfig - stopCh chan struct{} - logger *zap.Logger -} - -func newRetrySender(config configretry.BackOffConfig, set exporter.Settings) *retrySender { - return &retrySender{ - traceAttribute: attribute.String(internal.ExporterKey, set.ID.String()), - cfg: config, - stopCh: make(chan struct{}), - logger: set.Logger, - } -} - -func (rs *retrySender) Shutdown(context.Context) error { - close(rs.stopCh) - return nil -} - -// send implements the requestSender interface -func (rs *retrySender) send(ctx context.Context, req Request) error { - // Do not use NewExponentialBackOff since it calls Reset and the code here must - // call Reset after changing the InitialInterval (this saves an unnecessary call to Now). - expBackoff := backoff.ExponentialBackOff{ - InitialInterval: rs.cfg.InitialInterval, - RandomizationFactor: rs.cfg.RandomizationFactor, - Multiplier: rs.cfg.Multiplier, - MaxInterval: rs.cfg.MaxInterval, - MaxElapsedTime: rs.cfg.MaxElapsedTime, - Stop: backoff.Stop, - Clock: backoff.SystemClock, - } - expBackoff.Reset() - span := trace.SpanFromContext(ctx) - retryNum := int64(0) - for { - span.AddEvent( - "Sending request.", - trace.WithAttributes(rs.traceAttribute, attribute.Int64("retry_num", retryNum))) - - err := rs.nextSender.send(ctx, req) - if err == nil { - return nil - } - - // Immediately drop data on permanent errors. - if consumererror.IsPermanent(err) { - return fmt.Errorf("not retryable error: %w", err) - } - - req = extractPartialRequest(req, err) - - backoffDelay := expBackoff.NextBackOff() - if backoffDelay == backoff.Stop { - return fmt.Errorf("no more retries left: %w", err) - } - - throttleErr := throttleRetry{} - if errors.As(err, &throttleErr) { - backoffDelay = max(backoffDelay, throttleErr.delay) - } - - backoffDelayStr := backoffDelay.String() - span.AddEvent( - "Exporting failed. Will retry the request after interval.", - trace.WithAttributes( - rs.traceAttribute, - attribute.String("interval", backoffDelayStr), - attribute.String("error", err.Error()))) - rs.logger.Info( - "Exporting failed. Will retry the request after interval.", - zap.Error(err), - zap.String("interval", backoffDelayStr), - ) - retryNum++ - - // back-off, but get interrupted when shutting down or request is cancelled or timed out. - select { - case <-ctx.Done(): - return fmt.Errorf("request is cancelled or timed out %w", err) - case <-rs.stopCh: - return experr.NewShutdownErr(err) - case <-time.After(backoffDelay): - } - } -} - -// max returns the larger of x or y. -func max(x, y time.Duration) time.Duration { - if x < y { - return y - } - return x + return internal.NewThrottleRetry(err, delay) } diff --git a/exporter/exporterhelper/timeout_sender.go b/exporter/exporterhelper/timeout_sender.go index 9e489f54ded..9788397b7d2 100644 --- a/exporter/exporterhelper/timeout_sender.go +++ b/exporter/exporterhelper/timeout_sender.go @@ -4,55 +4,20 @@ package exporterhelper // import "go.opentelemetry.io/collector/exporter/exporterhelper" import ( - "context" - "errors" - "time" + "go.opentelemetry.io/collector/exporter/exporterhelper/internal" ) // Deprecated: [v0.110.0] Use TimeoutConfig instead. type TimeoutSettings = TimeoutConfig -// TimeoutConfig for timeout. The timeout applies to individual attempts to send data to the backend. -type TimeoutConfig struct { - // Timeout is the timeout for every attempt to send data to the backend. - // A zero timeout means no timeout. - Timeout time.Duration `mapstructure:"timeout"` -} - -func (ts *TimeoutConfig) Validate() error { - // Negative timeouts are not acceptable, since all sends will fail. - if ts.Timeout < 0 { - return errors.New("'timeout' must be non-negative") - } - return nil -} +type TimeoutConfig = internal.TimeoutConfig // Deprecated: [v0.110.0] Use NewDefaultTimeoutConfig instead. func NewDefaultTimeoutSettings() TimeoutSettings { - return NewDefaultTimeoutConfig() + return internal.NewDefaultTimeoutConfig() } // NewDefaultTimeoutConfig returns the default config for TimeoutConfig. func NewDefaultTimeoutConfig() TimeoutConfig { - return TimeoutConfig{ - Timeout: 5 * time.Second, - } -} - -// timeoutSender is a requestSender that adds a `timeout` to every request that passes this sender. -type timeoutSender struct { - baseRequestSender - cfg TimeoutConfig -} - -func (ts *timeoutSender) send(ctx context.Context, req Request) error { - // TODO: Remove this by avoiding to create the timeout sender if timeout is 0. - if ts.cfg.Timeout == 0 { - return req.Export(ctx) - } - // Intentionally don't overwrite the context inside the request, because in case of retries deadline will not be - // updated because this deadline most likely is before the next one. - tCtx, cancelFunc := context.WithTimeout(ctx, ts.cfg.Timeout) - defer cancelFunc() - return req.Export(tCtx) + return internal.NewDefaultTimeoutConfig() } diff --git a/exporter/exporterhelper/traces.go b/exporter/exporterhelper/traces.go index 075db219d6a..da057a861bf 100644 --- a/exporter/exporterhelper/traces.go +++ b/exporter/exporterhelper/traces.go @@ -13,6 +13,7 @@ import ( "go.opentelemetry.io/collector/consumer" "go.opentelemetry.io/collector/consumer/consumererror" "go.opentelemetry.io/collector/exporter" + "go.opentelemetry.io/collector/exporter/exporterhelper/internal" "go.opentelemetry.io/collector/exporter/exporterqueue" "go.opentelemetry.io/collector/exporter/internal/queue" "go.opentelemetry.io/collector/pdata/ptrace" @@ -64,7 +65,7 @@ func (req *tracesRequest) ItemsCount() int { } type traceExporter struct { - *baseExporter + *internal.BaseExporter consumer.Traces } @@ -83,8 +84,8 @@ func NewTracesExporter( return nil, errNilPushTraceData } tracesOpts := []Option{ - withMarshaler(tracesRequestMarshaler), withUnmarshaler(newTraceRequestUnmarshalerFunc(pusher)), - withBatchFuncs(mergeTraces, mergeSplitTraces), + internal.WithMarshaler(tracesRequestMarshaler), internal.WithUnmarshaler(newTraceRequestUnmarshalerFunc(pusher)), + internal.WithBatchFuncs(mergeTraces, mergeSplitTraces), } return NewTracesRequestExporter(ctx, set, requestFromTraces(pusher), append(tracesOpts, options...)...) } @@ -118,7 +119,7 @@ func NewTracesRequestExporter( return nil, errNilTracesConverter } - be, err := newBaseExporter(set, component.DataTypeTraces, newTracesExporterWithObservability, options...) + be, err := internal.NewBaseExporter(set, component.DataTypeTraces, newTracesExporterWithObservability, options...) if err != nil { return nil, err } @@ -131,33 +132,33 @@ func NewTracesRequestExporter( zap.Error(err)) return consumererror.NewPermanent(cErr) } - sErr := be.send(ctx, req) + sErr := be.Send(ctx, req) if errors.Is(sErr, queue.ErrQueueIsFull) { - be.obsrep.recordEnqueueFailure(ctx, component.DataTypeTraces, int64(req.ItemsCount())) + be.Obsrep.RecordEnqueueFailure(ctx, component.DataTypeTraces, int64(req.ItemsCount())) } return sErr - }, be.consumerOptions...) + }, be.ConsumerOptions...) return &traceExporter{ - baseExporter: be, + BaseExporter: be, Traces: tc, }, err } type tracesExporterWithObservability struct { - baseRequestSender - obsrep *obsReport + internal.BaseRequestSender + obsrep *internal.ObsReport } -func newTracesExporterWithObservability(obsrep *obsReport) requestSender { +func newTracesExporterWithObservability(obsrep *internal.ObsReport) internal.RequestSender { return &tracesExporterWithObservability{obsrep: obsrep} } -func (tewo *tracesExporterWithObservability) send(ctx context.Context, req Request) error { - c := tewo.obsrep.startTracesOp(ctx) +func (tewo *tracesExporterWithObservability) Send(ctx context.Context, req Request) error { + c := tewo.obsrep.StartTracesOp(ctx) numTraceSpans := req.ItemsCount() // Forward the data to the next consumer (this pusher is the next). - err := tewo.nextSender.send(c, req) - tewo.obsrep.endTracesOp(c, numTraceSpans, err) + err := tewo.NextSender.Send(c, req) + tewo.obsrep.EndTracesOp(c, numTraceSpans, err) return err } diff --git a/exporter/exporterhelper/traces_test.go b/exporter/exporterhelper/traces_test.go index 2d3d1cfdf8b..d6feaedc1e4 100644 --- a/exporter/exporterhelper/traces_test.go +++ b/exporter/exporterhelper/traces_test.go @@ -61,7 +61,7 @@ func TestTracesExporter_NilLogger(t *testing.T) { } func TestTracesRequestExporter_NilLogger(t *testing.T) { - te, err := NewTracesRequestExporter(context.Background(), exporter.Settings{}, (&fakeRequestConverter{}).requestFromTracesFunc) + te, err := NewTracesRequestExporter(context.Background(), exporter.Settings{}, (&internal.FakeRequestConverter{}).RequestFromTracesFunc) require.Nil(t, te) require.Equal(t, errNilLogger, err) } @@ -93,7 +93,7 @@ func TestTracesExporter_Default(t *testing.T) { func TestTracesRequestExporter_Default(t *testing.T) { td := ptrace.NewTraces() te, err := NewTracesRequestExporter(context.Background(), exportertest.NewNopSettings(), - (&fakeRequestConverter{}).requestFromTracesFunc) + (&internal.FakeRequestConverter{}).RequestFromTracesFunc) assert.NotNil(t, te) require.NoError(t, err) @@ -115,7 +115,7 @@ func TestTracesExporter_WithCapabilities(t *testing.T) { func TestTracesRequestExporter_WithCapabilities(t *testing.T) { capabilities := consumer.Capabilities{MutatesData: true} te, err := NewTracesRequestExporter(context.Background(), exportertest.NewNopSettings(), - (&fakeRequestConverter{}).requestFromTracesFunc, WithCapabilities(capabilities)) + (&internal.FakeRequestConverter{}).RequestFromTracesFunc, WithCapabilities(capabilities)) assert.NotNil(t, te) require.NoError(t, err) @@ -137,7 +137,7 @@ func TestTracesRequestExporter_Default_ConvertError(t *testing.T) { td := ptrace.NewTraces() want := errors.New("convert_error") te, err := NewTracesRequestExporter(context.Background(), exportertest.NewNopSettings(), - (&fakeRequestConverter{tracesError: want}).requestFromTracesFunc) + (&internal.FakeRequestConverter{TracesError: want}).RequestFromTracesFunc) require.NoError(t, err) require.NotNil(t, te) require.Equal(t, consumererror.NewPermanent(want), te.ConsumeTraces(context.Background(), td)) @@ -147,7 +147,7 @@ func TestTracesRequestExporter_Default_ExportError(t *testing.T) { td := ptrace.NewTraces() want := errors.New("export_error") te, err := NewTracesRequestExporter(context.Background(), exportertest.NewNopSettings(), - (&fakeRequestConverter{requestError: want}).requestFromTracesFunc) + (&internal.FakeRequestConverter{RequestError: want}).RequestFromTracesFunc) require.NoError(t, err) require.NotNil(t, te) require.Equal(t, want, te.ConsumeTraces(context.Background(), td)) @@ -164,7 +164,7 @@ func TestTracesExporter_WithPersistentQueue(t *testing.T) { te, err := NewTracesExporter(context.Background(), set, &fakeTracesExporterConfig, ts.ConsumeTraces, WithRetry(rCfg), WithQueue(qCfg)) require.NoError(t, err) - host := &mockHost{ext: map[component.ID]component.Component{ + host := &internal.MockHost{Ext: map[component.ID]component.Component{ storageID: queue.NewMockStorageExtension(nil), }} require.NoError(t, te.Start(context.Background(), host)) @@ -211,7 +211,7 @@ func TestTracesRequestExporter_WithRecordMetrics(t *testing.T) { te, err := NewTracesRequestExporter(context.Background(), exporter.Settings{ID: fakeTracesExporterName, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, - (&fakeRequestConverter{}).requestFromTracesFunc) + (&internal.FakeRequestConverter{}).RequestFromTracesFunc) require.NoError(t, err) require.NotNil(t, te) @@ -239,7 +239,7 @@ func TestTracesRequestExporter_WithRecordMetrics_RequestSenderError(t *testing.T te, err := NewTracesRequestExporter(context.Background(), exporter.Settings{ID: fakeTracesExporterName, TelemetrySettings: tt.TelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, - (&fakeRequestConverter{requestError: want}).requestFromTracesFunc) + (&internal.FakeRequestConverter{RequestError: want}).RequestFromTracesFunc) require.NoError(t, err) require.NotNil(t, te) @@ -292,7 +292,7 @@ func TestTracesRequestExporter_WithSpan(t *testing.T) { otel.SetTracerProvider(set.TracerProvider) defer otel.SetTracerProvider(nooptrace.NewTracerProvider()) - te, err := NewTracesRequestExporter(context.Background(), set, (&fakeRequestConverter{}).requestFromTracesFunc) + te, err := NewTracesRequestExporter(context.Background(), set, (&internal.FakeRequestConverter{}).RequestFromTracesFunc) require.NoError(t, err) require.NotNil(t, te) @@ -322,7 +322,7 @@ func TestTracesRequestExporter_WithSpan_ExportError(t *testing.T) { defer otel.SetTracerProvider(nooptrace.NewTracerProvider()) want := errors.New("export_error") - te, err := NewTracesRequestExporter(context.Background(), set, (&fakeRequestConverter{requestError: want}).requestFromTracesFunc) + te, err := NewTracesRequestExporter(context.Background(), set, (&internal.FakeRequestConverter{RequestError: want}).RequestFromTracesFunc) require.NoError(t, err) require.NotNil(t, te) @@ -347,7 +347,7 @@ func TestTracesRequestExporter_WithShutdown(t *testing.T) { shutdown := func(context.Context) error { shutdownCalled = true; return nil } te, err := NewTracesRequestExporter(context.Background(), exportertest.NewNopSettings(), - (&fakeRequestConverter{}).requestFromTracesFunc, WithShutdown(shutdown)) + (&internal.FakeRequestConverter{}).RequestFromTracesFunc, WithShutdown(shutdown)) assert.NotNil(t, te) assert.NoError(t, err) @@ -373,7 +373,7 @@ func TestTracesRequestExporter_WithShutdown_ReturnError(t *testing.T) { shutdownErr := func(context.Context) error { return want } te, err := NewTracesRequestExporter(context.Background(), exportertest.NewNopSettings(), - (&fakeRequestConverter{}).requestFromTracesFunc, WithShutdown(shutdownErr)) + (&internal.FakeRequestConverter{}).RequestFromTracesFunc, WithShutdown(shutdownErr)) assert.NotNil(t, te) assert.NoError(t, err) @@ -433,7 +433,7 @@ func checkWrapSpanForTracesExporter(t *testing.T, sr *tracetest.SpanRecorder, tr for _, sd := range gotSpanData[:numRequests] { require.Equalf(t, parentSpan.SpanContext(), sd.Parent(), "Exporter span not a child\nSpanData %v", sd) - checkStatus(t, sd, wantError) + internal.CheckStatus(t, sd, wantError) sentSpans := numSpans var failedToSendSpans int64