Debian Codegraph @

otelconf/config_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package otelconf
5
6 import (
7 "encoding/json"
8 "fmt"
9 "os"
10 "path/filepath"
11 "testing"
12
13 "github.com/stretchr/testify/assert"
14 "github.com/stretchr/testify/require"
15 lognoop "go.opentelemetry.io/otel/log/noop"
16 metricnoop "go.opentelemetry.io/otel/metric/noop"
17 "go.opentelemetry.io/otel/propagation"
18 sdklog "go.opentelemetry.io/otel/sdk/log"
19 sdkmetric "go.opentelemetry.io/otel/sdk/metric"
20 sdktrace "go.opentelemetry.io/otel/sdk/trace"
21 tracenoop "go.opentelemetry.io/otel/trace/noop"
22 "go.yaml.in/yaml/v3"
23 )
24
25 func TestUnmarshalPushMetricExporterInvalidData(t *testing.T) {
26 cl := PushMetricExporter{}
27 err := cl.UnmarshalJSON([]byte(`{:2000}`))
28 assert.ErrorIs(t, err, newErrUnmarshal(&PushMetricExporter{}))
29
30 cl = PushMetricExporter{}
31 err = yaml.Unmarshal([]byte("console: !!str str"), &cl)
32 assert.ErrorIs(t, err, newErrUnmarshal(&PushMetricExporter{}))
33 }
34
35 func TestUnmarshalLogRecordExporterInvalidData(t *testing.T) {
36 cl := LogRecordExporter{}
37 err := cl.UnmarshalJSON([]byte(`{:2000}`))
38 assert.ErrorIs(t, err, newErrUnmarshal(&LogRecordExporter{}))
39
40 cl = LogRecordExporter{}
41 err = cl.UnmarshalJSON([]byte(`{"console":2000}`))
42 assert.ErrorIs(t, err, newErrUnmarshal(&ConsoleExporter{}))
43
44 cl = LogRecordExporter{}
45 err = yaml.Unmarshal([]byte("console: !!str str"), &cl)
46 assert.ErrorIs(t, err, newErrUnmarshal(&LogRecordExporter{}))
47 }
48
49 func TestUnmarshalSpanExporterInvalidData(t *testing.T) {
50 cl := SpanExporter{}
51 err := cl.UnmarshalJSON([]byte(`{:2000}`))
52 assert.ErrorIs(t, err, newErrUnmarshal(&SpanExporter{}))
53
54 cl = SpanExporter{}
55 err = cl.UnmarshalJSON([]byte(`{"console":2000}`))
56 assert.ErrorIs(t, err, newErrUnmarshal(&ConsoleExporter{}))
57
58 cl = SpanExporter{}
59 err = yaml.Unmarshal([]byte("console: !!str str"), &cl)
60 assert.ErrorIs(t, err, newErrUnmarshal(&SpanExporter{}))
61 }
62
63 func TestUnmarshalTextMapPropagator(t *testing.T) {
64 for _, tt := range []struct {
65 name string
66 yamlConfig []byte
67 jsonConfig []byte
68 wantErrT error
69 wantTextMapPropagator TextMapPropagator
70 }{
71 {
72 name: "valid with b3 propagator",
73 jsonConfig: []byte(`{"b3":{}}`),
74 yamlConfig: []byte("b3: {}\n"),
75 wantTextMapPropagator: TextMapPropagator{B3: B3Propagator{}},
76 },
77 {
78 name: "valid with all propagators",
79 jsonConfig: []byte(`{"b3":{},"b3multi":{},"baggage":{},"jaeger":{},"ottrace":{},"tracecontext":{}}`),
80 yamlConfig: []byte("b3: {}\nb3multi: {}\nbaggage: {}\njaeger: {}\nottrace: {}\ntracecontext: {}\n"),
81 wantTextMapPropagator: TextMapPropagator{
82 B3: B3Propagator{},
83 B3Multi: B3MultiPropagator{},
84 Baggage: BaggagePropagator{},
85 Jaeger: JaegerPropagator{},
86 Ottrace: OpenTracingPropagator{},
87 Tracecontext: TraceContextPropagator{},
88 },
89 },
90 {
91 name: "valid with all propagators nil",
92 jsonConfig: []byte(`{"b3":null,"b3multi":null,"baggage":null,"jaeger":null,"ottrace":null,"tracecontext":null}`),
93 yamlConfig: []byte("b3:\nb3multi:\nbaggage:\njaeger:\nottrace:\ntracecontext:\n"),
94 wantTextMapPropagator: TextMapPropagator{
95 B3: B3Propagator{},
96 B3Multi: B3MultiPropagator{},
97 Baggage: BaggagePropagator{},
98 Jaeger: JaegerPropagator{},
99 Ottrace: OpenTracingPropagator{},
100 Tracecontext: TraceContextPropagator{},
101 },
102 },
103 {
104 name: "invalid b3 data",
105 jsonConfig: []byte(`{"b3":2000}`),
106 yamlConfig: []byte("b3: !!str str"),
107 wantErrT: newErrUnmarshal(&TextMapPropagator{}),
108 },
109 {
110 name: "invalid b3multi data",
111 jsonConfig: []byte(`{"b3multi":2000}`),
112 yamlConfig: []byte("b3multi: !!str str"),
113 wantErrT: newErrUnmarshal(&TextMapPropagator{}),
114 },
115 {
116 name: "invalid baggage data",
117 jsonConfig: []byte(`{"baggage":2000}`),
118 yamlConfig: []byte("baggage: !!str str"),
119 wantErrT: newErrUnmarshal(&TextMapPropagator{}),
120 },
121 {
122 name: "invalid jaeger data",
123 jsonConfig: []byte(`{"jaeger":2000}`),
124 yamlConfig: []byte("jaeger: !!str str"),
125 wantErrT: newErrUnmarshal(&TextMapPropagator{}),
126 },
127 {
128 name: "invalid ottrace data",
129 jsonConfig: []byte(`{"ottrace":2000}`),
130 yamlConfig: []byte("ottrace: !!str str"),
131 wantErrT: newErrUnmarshal(&TextMapPropagator{}),
132 },
133 {
134 name: "invalid tracecontext data",
135 jsonConfig: []byte(`{"tracecontext":2000}`),
136 yamlConfig: []byte("tracecontext: !!str str"),
137 wantErrT: newErrUnmarshal(&TextMapPropagator{}),
138 },
139 } {
140 t.Run(tt.name, func(t *testing.T) {
141 cl := TextMapPropagator{}
142 err := cl.UnmarshalJSON(tt.jsonConfig)
143 assert.ErrorIs(t, err, tt.wantErrT)
144 assert.Equal(t, tt.wantTextMapPropagator, cl)
145
146 cl = TextMapPropagator{}
147 err = yaml.Unmarshal(tt.yamlConfig, &cl)
148 assert.ErrorIs(t, err, tt.wantErrT)
149 assert.Equal(t, tt.wantTextMapPropagator, cl)
150 })
151 }
152 }
153
154 func TestUnmarshalSimpleLogRecordProcessor(t *testing.T) {
155 for _, tt := range []struct {
156 name string
157 yamlConfig []byte
158 jsonConfig []byte
159 wantErrT error
160 wantExporter LogRecordExporter
161 }{
162 {
163 name: "valid with console exporter",
164 jsonConfig: []byte(`{"exporter":{"console":{}}}`),
165 yamlConfig: []byte("exporter:\n console: {}"),
166 wantExporter: LogRecordExporter{Console: ConsoleExporter{}},
167 },
168 {
169 name: "valid with null console exporter",
170 jsonConfig: []byte(`{"exporter":{"console":null}}`),
171 yamlConfig: []byte("exporter:\n console:\n"),
172 wantExporter: LogRecordExporter{Console: ConsoleExporter{}},
173 },
174 {
175 name: "missing required exporter field",
176 jsonConfig: []byte(`{}`),
177 yamlConfig: []byte("{}"),
178 wantErrT: newErrRequired(&SimpleLogRecordProcessor{}, "exporter"),
179 },
180 {
181 name: "invalid data",
182 jsonConfig: []byte(`{:2000}`),
183 yamlConfig: []byte("exporter:\n console: []"),
184 wantErrT: newErrUnmarshal(&SimpleLogRecordProcessor{}),
185 },
186 } {
187 t.Run(tt.name, func(t *testing.T) {
188 cl := SimpleLogRecordProcessor{}
189 err := cl.UnmarshalJSON(tt.jsonConfig)
190 assert.ErrorIs(t, err, tt.wantErrT)
191 assert.Equal(t, tt.wantExporter, cl.Exporter)
192
193 cl = SimpleLogRecordProcessor{}
194 err = yaml.Unmarshal(tt.yamlConfig, &cl)
195 assert.ErrorIs(t, err, tt.wantErrT)
196 assert.Equal(t, tt.wantExporter, cl.Exporter)
197 })
198 }
199 }
200
201 func TestUnmarshalSimpleSpanProcessor(t *testing.T) {
202 for _, tt := range []struct {
203 name string
204 yamlConfig []byte
205 jsonConfig []byte
206 wantErrT error
207 wantExporter SpanExporter
208 }{
209 {
210 name: "valid with null console exporter",
211 jsonConfig: []byte(`{"exporter":{"console":null}}`),
212 yamlConfig: []byte("exporter:\n console:\n"),
213 wantExporter: SpanExporter{Console: ConsoleExporter{}},
214 },
215 {
216 name: "valid with console exporter",
217 jsonConfig: []byte(`{"exporter":{"console":{}}}`),
218 yamlConfig: []byte("exporter:\n console: {}"),
219 wantExporter: SpanExporter{Console: ConsoleExporter{}},
220 },
221 {
222 name: "missing required exporter field",
223 jsonConfig: []byte(`{}`),
224 yamlConfig: []byte("{}"),
225 wantErrT: newErrRequired(&SimpleSpanProcessor{}, "exporter"),
226 },
227 {
228 name: "invalid data",
229 jsonConfig: []byte(`{:2000}`),
230 yamlConfig: []byte("exporter:\n console: []"),
231 wantErrT: newErrUnmarshal(&SimpleSpanProcessor{}),
232 },
233 } {
234 t.Run(tt.name, func(t *testing.T) {
235 cl := SimpleSpanProcessor{}
236 err := cl.UnmarshalJSON(tt.jsonConfig)
237 assert.ErrorIs(t, err, tt.wantErrT)
238 assert.Equal(t, tt.wantExporter, cl.Exporter)
239
240 cl = SimpleSpanProcessor{}
241 err = yaml.Unmarshal(tt.yamlConfig, &cl)
242 assert.ErrorIs(t, err, tt.wantErrT)
243 assert.Equal(t, tt.wantExporter, cl.Exporter)
244 })
245 }
246 }
247
248 func TestUnmarshalBatchLogRecordProcessor(t *testing.T) {
249 for _, tt := range []struct {
250 name string
251 yamlConfig []byte
252 jsonConfig []byte
253 wantErrT error
254 wantExporter LogRecordExporter
255 }{
256 {
257 name: "valid with console exporter",
258 jsonConfig: []byte(`{"exporter":{"console":{}}}`),
259 yamlConfig: []byte("exporter:\n console: {}"),
260 wantExporter: LogRecordExporter{Console: ConsoleExporter{}},
261 },
262 {
263 name: "valid with null console exporter",
264 jsonConfig: []byte(`{"exporter":{"console":null}}`),
265 yamlConfig: []byte("exporter:\n console:\n"),
266 wantExporter: LogRecordExporter{Console: ConsoleExporter{}},
267 },
268 {
269 name: "valid with all fields positive",
270 jsonConfig: []byte(`{"exporter":{"console":{}},"export_timeout":5000,"max_export_batch_size":512,"max_queue_size":2048,"schedule_delay":1000}`),
271 yamlConfig: []byte("exporter:\n console: {}\nexport_timeout: 5000\nmax_export_batch_size: 512\nmax_queue_size: 2048\nschedule_delay: 1000"),
272 wantExporter: LogRecordExporter{Console: ConsoleExporter{}},
273 },
274 {
275 name: "valid with zero export_timeout",
276 jsonConfig: []byte(`{"exporter":{"console":{}},"export_timeout":0}`),
277 yamlConfig: []byte("exporter:\n console: {}\nexport_timeout: 0"),
278 wantExporter: LogRecordExporter{Console: ConsoleExporter{}},
279 },
280 {
281 name: "valid with zero schedule_delay",
282 jsonConfig: []byte(`{"exporter":{"console":{}},"schedule_delay":0}`),
283 yamlConfig: []byte("exporter:\n console: {}\nschedule_delay: 0"),
284 wantExporter: LogRecordExporter{Console: ConsoleExporter{}},
285 },
286 {
287 name: "missing required exporter field",
288 jsonConfig: []byte(`{}`),
289 yamlConfig: []byte("{}"),
290 wantErrT: newErrRequired(&BatchLogRecordProcessor{}, "exporter"),
291 },
292 {
293 name: "invalid data",
294 jsonConfig: []byte(`{:2000}`),
295 yamlConfig: []byte("exporter:\n console: {}\nexport_timeout: !!str str"),
296 wantErrT: newErrUnmarshal(&BatchLogRecordProcessor{}),
297 },
298 {
299 name: "invalid export_timeout negative",
300 jsonConfig: []byte(`{"exporter":{"console":{}},"export_timeout":-1}`),
301 yamlConfig: []byte("exporter:\n console: {}\nexport_timeout: -1"),
302 wantErrT: newErrGreaterOrEqualZero("export_timeout"),
303 },
304 {
305 name: "invalid max_export_batch_size zero",
306 jsonConfig: []byte(`{"exporter":{"console":{}},"max_export_batch_size":0}`),
307 yamlConfig: []byte("exporter:\n console: {}\nmax_export_batch_size: 0"),
308 wantErrT: newErrGreaterThanZero("max_export_batch_size"),
309 },
310 {
311 name: "invalid max_export_batch_size negative",
312 jsonConfig: []byte(`{"exporter":{"console":{}},"max_export_batch_size":-1}`),
313 yamlConfig: []byte("exporter:\n console: {}\nmax_export_batch_size: -1"),
314 wantErrT: newErrGreaterThanZero("max_export_batch_size"),
315 },
316 {
317 name: "invalid max_queue_size zero",
318 jsonConfig: []byte(`{"exporter":{"console":{}},"max_queue_size":0}`),
319 yamlConfig: []byte("exporter:\n console: {}\nmax_queue_size: 0"),
320 wantErrT: newErrGreaterThanZero("max_queue_size"),
321 },
322 {
323 name: "invalid max_queue_size negative",
324 jsonConfig: []byte(`{"exporter":{"console":{}},"max_queue_size":-1}`),
325 yamlConfig: []byte("exporter:\n console: {}\nmax_queue_size: -1"),
326 wantErrT: newErrGreaterThanZero("max_queue_size"),
327 },
328 {
329 name: "invalid schedule_delay negative",
330 jsonConfig: []byte(`{"exporter":{"console":{}},"schedule_delay":-1}`),
331 yamlConfig: []byte("exporter:\n console: {}\nschedule_delay: -1"),
332 wantErrT: newErrGreaterOrEqualZero("schedule_delay"),
333 },
334 } {
335 t.Run(tt.name, func(t *testing.T) {
336 cl := BatchLogRecordProcessor{}
337 err := cl.UnmarshalJSON(tt.jsonConfig)
338 assert.ErrorIs(t, err, tt.wantErrT)
339 assert.Equal(t, tt.wantExporter, cl.Exporter)
340
341 cl = BatchLogRecordProcessor{}
342 err = yaml.Unmarshal(tt.yamlConfig, &cl)
343 assert.ErrorIs(t, err, tt.wantErrT)
344 assert.Equal(t, tt.wantExporter, cl.Exporter)
345 })
346 }
347 }
348
349 func TestNewSDK(t *testing.T) {
350 tests := []struct {
351 name string
352 cfg []ConfigurationOption
353 wantTracerProvider any
354 wantMeterProvider any
355 wantLoggerProvider any
356 wantPropagator any
357 wantErr error
358 wantShutdownErr error
359 }{
360 {
361 name: "no-configuration",
362 wantTracerProvider: tracenoop.NewTracerProvider(),
363 wantMeterProvider: metricnoop.NewMeterProvider(),
364 wantLoggerProvider: lognoop.NewLoggerProvider(),
365 wantPropagator: propagation.NewCompositeTextMapPropagator(),
366 },
367 {
368 name: "with-configuration",
369 cfg: []ConfigurationOption{
370 WithContext(t.Context()),
371 WithOpenTelemetryConfiguration(OpenTelemetryConfiguration{
372 TracerProvider: &TracerProvider{},
373 MeterProvider: &MeterProvider{},
374 LoggerProvider: &LoggerProvider{},
375 Propagator: &Propagator{},
376 }),
377 },
378 wantTracerProvider: &sdktrace.TracerProvider{},
379 wantMeterProvider: &sdkmetric.MeterProvider{},
380 wantLoggerProvider: &sdklog.LoggerProvider{},
381 wantPropagator: propagation.NewCompositeTextMapPropagator(),
382 },
383 {
384 name: "with-sdk-disabled",
385 cfg: []ConfigurationOption{
386 WithContext(t.Context()),
387 WithOpenTelemetryConfiguration(OpenTelemetryConfiguration{
388 Disabled: ptr(true),
389 TracerProvider: &TracerProvider{},
390 MeterProvider: &MeterProvider{},
391 LoggerProvider: &LoggerProvider{},
392 }),
393 },
394 wantTracerProvider: tracenoop.NewTracerProvider(),
395 wantMeterProvider: metricnoop.NewMeterProvider(),
396 wantLoggerProvider: lognoop.NewLoggerProvider(),
397 wantPropagator: propagation.NewCompositeTextMapPropagator(),
398 },
399 }
400 for _, tt := range tests {
401 sdk, err := NewSDK(tt.cfg...)
402 require.Equal(t, tt.wantErr, err)
403 assert.IsType(t, tt.wantTracerProvider, sdk.TracerProvider())
404 assert.IsType(t, tt.wantMeterProvider, sdk.MeterProvider())
405 assert.IsType(t, tt.wantLoggerProvider, sdk.LoggerProvider())
406 assert.IsType(t, tt.wantPropagator, sdk.Propagator())
407 require.Equal(t, tt.wantShutdownErr, sdk.Shutdown(t.Context()))
408 }
409 }
410
411 func TestNewSDKWithEnvVar(t *testing.T) {
412 cfg := []ConfigurationOption{
413 WithContext(t.Context()),
414 WithOpenTelemetryConfiguration(OpenTelemetryConfiguration{
415 TracerProvider: nil,
416 }),
417 }
418 // test a non existent file
419 t.Setenv(envVarConfigFile, filepath.Join("testdata", "file_missing.yaml"))
420 _, err := NewSDK(cfg...)
421 require.Error(t, err)
422 // test a file that causes a parse error
423 t.Setenv(envVarConfigFile, filepath.Join("testdata", "v1.0.0_invalid_nil_name.yaml"))
424 _, err = NewSDK(cfg...)
425 require.Error(t, err)
426 require.ErrorIs(t, err, newErrRequired(&NameStringValuePair{}, "name"))
427 // test a valid file, error is returned from the SDK instantiation
428 t.Setenv(envVarConfigFile, filepath.Join("testdata", "v1.0.0.yaml"))
429 _, err = NewSDK(cfg...)
430 require.ErrorIs(t, err, newErrInvalid("otlp_file/development"))
431 // validate that use of deprecated env var returns an error
432 t.Setenv(envVarConfigFileDeprecated, filepath.Join("testdata", "v1.0.0.yaml"))
433 _, err = NewSDK(cfg...)
434 require.ErrorIs(t, err, errDeprecatedEnvVarUsed)
435 }
436
437 var v10OpenTelemetryConfig = OpenTelemetryConfiguration{
438 Disabled: ptr(false),
439 FileFormat: "1.0-rc.2",
440 AttributeLimits: &AttributeLimits{
441 AttributeCountLimit: ptr(128),
442 AttributeValueLengthLimit: ptr(4096),
443 },
444
445 LogLevel: ptr(SeverityNumberInfo),
446 LoggerProvider: &LoggerProvider{
447 Limits: &LogRecordLimits{
448 AttributeCountLimit: ptr(128),
449 AttributeValueLengthLimit: ptr(4096),
450 },
451 Processors: []LogRecordProcessor{
452 {
453 Batch: &BatchLogRecordProcessor{
454 ExportTimeout: ptr(30000),
455 Exporter: LogRecordExporter{
456 OTLPHttp: &OTLPHttpExporter{
457 Tls: &HttpTls{
458 CaFile: ptr("testdata/ca.crt"),
459 CertFile: ptr("testdata/client.crt"),
460 KeyFile: ptr("testdata/client.key"),
461 },
462 Compression: ptr("gzip"),
463 Encoding: ptr(OTLPHttpEncodingProtobuf),
464 Endpoint: ptr("http://localhost:4318/v1/logs"),
465 Headers: []NameStringValuePair{
466 {Name: "api-key", Value: ptr("1234")},
467 },
468 HeadersList: ptr("api-key=1234"),
469 Timeout: ptr(10000),
470 },
471 },
472 MaxExportBatchSize: ptr(512),
473 MaxQueueSize: ptr(2048),
474 ScheduleDelay: ptr(5000),
475 },
476 },
477 {
478 Batch: &BatchLogRecordProcessor{
479 Exporter: LogRecordExporter{
480 OTLPGrpc: &OTLPGrpcExporter{
481 Tls: &GrpcTls{
482 CaFile: ptr("testdata/ca.crt"),
483 CertFile: ptr("testdata/client.crt"),
484 KeyFile: ptr("testdata/client.key"),
485 Insecure: ptr(false),
486 },
487 Compression: ptr("gzip"),
488 Endpoint: ptr("http://localhost:4317"),
489 Headers: []NameStringValuePair{
490 {Name: "api-key", Value: ptr("1234")},
491 },
492 HeadersList: ptr("api-key=1234"),
493 Timeout: ptr(10000),
494 },
495 },
496 },
497 },
498 {
499 Batch: &BatchLogRecordProcessor{
500 Exporter: LogRecordExporter{},
501 },
502 },
503 {
504 Batch: &BatchLogRecordProcessor{
505 Exporter: LogRecordExporter{},
506 },
507 },
508 {
509 Simple: &SimpleLogRecordProcessor{
510 Exporter: LogRecordExporter{
511 Console: ConsoleExporter{},
512 },
513 },
514 },
515 },
516 },
517 MeterProvider: &MeterProvider{
518 ExemplarFilter: ptr(ExemplarFilter("trace_based")),
519 Readers: []MetricReader{
520 {
521 Pull: &PullMetricReader{
522 Producers: []MetricProducer{
523 {
524 Opencensus: OpenCensusMetricProducer{},
525 },
526 },
527 CardinalityLimits: &CardinalityLimits{
528 Default: ptr(2000),
529 Counter: ptr(2000),
530 Gauge: ptr(2000),
531 Histogram: ptr(2000),
532 ObservableCounter: ptr(2000),
533 ObservableGauge: ptr(2000),
534 ObservableUpDownCounter: ptr(2000),
535 UpDownCounter: ptr(2000),
536 },
537 Exporter: PullMetricExporter{},
538 },
539 },
540 {
541 Periodic: &PeriodicMetricReader{
542 Producers: []MetricProducer{
543 {
544 AdditionalProperties: map[string]any{
545 "prometheus": nil,
546 },
547 },
548 },
549 CardinalityLimits: &CardinalityLimits{
550 Default: ptr(2000),
551 Counter: ptr(2000),
552 Gauge: ptr(2000),
553 Histogram: ptr(2000),
554 ObservableCounter: ptr(2000),
555 ObservableGauge: ptr(2000),
556 ObservableUpDownCounter: ptr(2000),
557 UpDownCounter: ptr(2000),
558 },
559 Exporter: PushMetricExporter{
560 OTLPHttp: &OTLPHttpMetricExporter{
561 Tls: &HttpTls{
562 CaFile: ptr("testdata/ca.crt"),
563 CertFile: ptr("testdata/client.crt"),
564 KeyFile: ptr("testdata/client.key"),
565 },
566 Compression: ptr("gzip"),
567 DefaultHistogramAggregation: ptr(ExporterDefaultHistogramAggregationBase2ExponentialBucketHistogram),
568 Endpoint: ptr("http://localhost:4318/v1/metrics"),
569 Encoding: ptr(OTLPHttpEncodingProtobuf),
570 Headers: []NameStringValuePair{
571 {Name: "api-key", Value: ptr("1234")},
572 },
573 HeadersList: ptr("api-key=1234"),
574 TemporalityPreference: ptr(ExporterTemporalityPreferenceDelta),
575 Timeout: ptr(10000),
576 },
577 },
578 Interval: ptr(60000),
579 Timeout: ptr(30000),
580 },
581 },
582 {
583 Periodic: &PeriodicMetricReader{
584 Exporter: PushMetricExporter{
585 OTLPGrpc: &OTLPGrpcMetricExporter{
586 Tls: &GrpcTls{
587 CaFile: ptr("testdata/ca.crt"),
588 CertFile: ptr("testdata/client.crt"),
589 KeyFile: ptr("testdata/client.key"),
590 Insecure: ptr(false),
591 },
592 Compression: ptr("gzip"),
593 DefaultHistogramAggregation: ptr(ExporterDefaultHistogramAggregationBase2ExponentialBucketHistogram),
594 Endpoint: ptr("http://localhost:4317"),
595 Headers: []NameStringValuePair{
596 {Name: "api-key", Value: ptr("1234")},
597 },
598 HeadersList: ptr("api-key=1234"),
599 TemporalityPreference: ptr(ExporterTemporalityPreferenceDelta),
600 Timeout: ptr(10000),
601 },
602 },
603 },
604 },
605 {
606 Periodic: &PeriodicMetricReader{
607 Exporter: PushMetricExporter{},
608 },
609 },
610 {
611 Periodic: &PeriodicMetricReader{
612 Exporter: PushMetricExporter{},
613 },
614 },
615 {
616 Periodic: &PeriodicMetricReader{
617 Exporter: PushMetricExporter{
618 Console: &ConsoleMetricExporter{},
619 },
620 },
621 },
622 },
623 Views: []View{
624 {
625 Selector: ViewSelector{
626 InstrumentName: ptr("my-instrument"),
627 InstrumentType: ptr(InstrumentTypeHistogram),
628 MeterName: ptr("my-meter"),
629 MeterSchemaUrl: ptr("https://opentelemetry.io/schemas/1.16.0"),
630 MeterVersion: ptr("1.0.0"),
631 Unit: ptr("ms"),
632 },
633 Stream: ViewStream{
634 Aggregation: &Aggregation{
635 ExplicitBucketHistogram: &ExplicitBucketHistogramAggregation{
636 Boundaries: []float64{0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000},
637 RecordMinMax: ptr(true),
638 },
639 },
640 AggregationCardinalityLimit: ptr(2000),
641 AttributeKeys: &IncludeExclude{
642 Included: []string{"key1", "key2"},
643 Excluded: []string{"key3"},
644 },
645 Description: ptr("new_description"),
646 Name: ptr("new_instrument_name"),
647 },
648 },
649 },
650 },
651 Propagator: &Propagator{
652 Composite: []TextMapPropagator{
653 {
654 Tracecontext: TraceContextPropagator{},
655 },
656 {
657 Baggage: BaggagePropagator{},
658 },
659 {
660 B3: B3Propagator{},
661 },
662 {
663 B3Multi: B3MultiPropagator{},
664 },
665 {
666 Jaeger: JaegerPropagator{},
667 },
668 {
669 Ottrace: OpenTracingPropagator{},
670 },
671 },
672 CompositeList: ptr("tracecontext,baggage,b3,b3multi,jaeger,ottrace,xray"),
673 },
674 Resource: &Resource{
675 Attributes: []AttributeNameValue{
676 {Name: "service.name", Value: "unknown_service"},
677 {Name: "string_key", Type: ptr(AttributeTypeString), Value: "value"},
678 {Name: "bool_key", Type: ptr(AttributeTypeBool), Value: true},
679 {Name: "int_key", Type: ptr(AttributeTypeInt), Value: 1},
680 {Name: "double_key", Type: ptr(AttributeTypeDouble), Value: 1.1},
681 {Name: "string_array_key", Type: ptr(AttributeTypeStringArray), Value: []any{"value1", "value2"}},
682 {Name: "bool_array_key", Type: ptr(AttributeTypeBoolArray), Value: []any{true, false}},
683 {Name: "int_array_key", Type: ptr(AttributeTypeIntArray), Value: []any{1, 2}},
684 {Name: "double_array_key", Type: ptr(AttributeTypeDoubleArray), Value: []any{1.1, 2.2}},
685 },
686 AttributesList: ptr("service.namespace=my-namespace,service.version=1.0.0"),
687 },
688 TracerProvider: &TracerProvider{
689 Limits: &SpanLimits{
690 AttributeCountLimit: ptr(128),
691 AttributeValueLengthLimit: ptr(4096),
692 EventCountLimit: ptr(128),
693 EventAttributeCountLimit: ptr(128),
694 LinkCountLimit: ptr(128),
695 LinkAttributeCountLimit: ptr(128),
696 },
697 Processors: []SpanProcessor{
698 {
699 Batch: &BatchSpanProcessor{
700 ExportTimeout: ptr(30000),
701 Exporter: SpanExporter{
702 OTLPHttp: &OTLPHttpExporter{
703 Tls: &HttpTls{
704 CaFile: ptr("testdata/ca.crt"),
705 CertFile: ptr("testdata/client.crt"),
706 KeyFile: ptr("testdata/client.key"),
707 },
708 Compression: ptr("gzip"),
709 Encoding: ptr(OTLPHttpEncodingProtobuf),
710 Endpoint: ptr("http://localhost:4318/v1/traces"),
711 Headers: []NameStringValuePair{
712 {Name: "api-key", Value: ptr("1234")},
713 },
714 HeadersList: ptr("api-key=1234"),
715 Timeout: ptr(10000),
716 },
717 },
718 MaxExportBatchSize: ptr(512),
719 MaxQueueSize: ptr(2048),
720 ScheduleDelay: ptr(5000),
721 },
722 },
723 {
724 Batch: &BatchSpanProcessor{
725 Exporter: SpanExporter{
726 OTLPGrpc: &OTLPGrpcExporter{
727 Tls: &GrpcTls{
728 CaFile: ptr("testdata/ca.crt"),
729 CertFile: ptr("testdata/client.crt"),
730 KeyFile: ptr("testdata/client.key"),
731 Insecure: ptr(false),
732 },
733 Compression: ptr("gzip"),
734 Endpoint: ptr("http://localhost:4317"),
735 Headers: []NameStringValuePair{
736 {Name: "api-key", Value: ptr("1234")},
737 },
738 HeadersList: ptr("api-key=1234"),
739 Timeout: ptr(10000),
740 },
741 },
742 },
743 },
744 {
745 Batch: &BatchSpanProcessor{
746 Exporter: SpanExporter{},
747 },
748 },
749 {
750 Batch: &BatchSpanProcessor{
751 Exporter: SpanExporter{},
752 },
753 },
754 {
755 Simple: &SimpleSpanProcessor{
756 Exporter: SpanExporter{
757 Console: ConsoleExporter{},
758 },
759 },
760 },
761 },
762 Sampler: &Sampler{
763 ParentBased: &ParentBasedSampler{
764 LocalParentNotSampled: &Sampler{
765 AlwaysOff: AlwaysOffSampler{},
766 },
767 LocalParentSampled: &Sampler{
768 AlwaysOn: AlwaysOnSampler{},
769 },
770 RemoteParentNotSampled: &Sampler{
771 AlwaysOff: AlwaysOffSampler{},
772 },
773 RemoteParentSampled: &Sampler{
774 AlwaysOn: AlwaysOnSampler{},
775 },
776 Root: &Sampler{
777 TraceIDRatioBased: &TraceIDRatioBasedSampler{
778 Ratio: ptr(0.0001),
779 },
780 },
781 },
782 },
783 },
784 }
785
786 var v100OpenTelemetryConfigEnvParsing = OpenTelemetryConfiguration{
787 Disabled: ptr(false),
788 FileFormat: "1.0",
789 LogLevel: ptr(SeverityNumberInfo),
790 AttributeLimits: &AttributeLimits{
791 AttributeCountLimit: ptr(128),
792 AttributeValueLengthLimit: ptr(4096),
793 },
794 Resource: &Resource{
795 Attributes: []AttributeNameValue{
796 {Name: "service.name", Value: "unknown_service"},
797 {Name: "string_key", Type: ptr(AttributeTypeString), Value: "value"},
798 {Name: "bool_key", Type: ptr(AttributeTypeBool), Value: true},
799 {Name: "int_key", Type: ptr(AttributeTypeInt), Value: 1},
800 {Name: "double_key", Type: ptr(AttributeTypeDouble), Value: 1.1},
801 {Name: "string_array_key", Type: ptr(AttributeTypeStringArray), Value: []any{"value1", "value2"}},
802 {Name: "bool_array_key", Type: ptr(AttributeTypeBoolArray), Value: []any{true, false}},
803 {Name: "int_array_key", Type: ptr(AttributeTypeIntArray), Value: []any{1, 2}},
804 {Name: "double_array_key", Type: ptr(AttributeTypeDoubleArray), Value: []any{1.1, 2.2}},
805 {Name: "string_value", Type: ptr(AttributeTypeString), Value: "value"},
806 {Name: "bool_value", Type: ptr(AttributeTypeBool), Value: true},
807 {Name: "int_value", Type: ptr(AttributeTypeInt), Value: 1},
808 {Name: "float_value", Type: ptr(AttributeTypeDouble), Value: 1.1},
809 {Name: "hex_value", Type: ptr(AttributeTypeInt), Value: int(48879)},
810 {Name: "quoted_string_value", Type: ptr(AttributeTypeString), Value: "value"},
811 {Name: "quoted_bool_value", Type: ptr(AttributeTypeString), Value: "true"},
812 {Name: "quoted_int_value", Type: ptr(AttributeTypeString), Value: "1"},
813 {Name: "quoted_float_value", Type: ptr(AttributeTypeString), Value: "1.1"},
814 {Name: "quoted_hex_value", Type: ptr(AttributeTypeString), Value: "0xbeef"},
815 {Name: "alternative_env_syntax", Type: ptr(AttributeTypeString), Value: "value"},
816 {Name: "invalid_map_value", Type: ptr(AttributeTypeString), Value: "value\nkey:value"},
817 {Name: "multiple_references_inject", Type: ptr(AttributeTypeString), Value: "foo value 1.1"},
818 {Name: "undefined_key", Type: ptr(AttributeTypeString), Value: nil},
819 {Name: "undefined_key_fallback", Type: ptr(AttributeTypeString), Value: "fallback"},
820 {Name: "env_var_in_key", Type: ptr(AttributeTypeString), Value: "value"},
821 {Name: "replace_me", Type: ptr(AttributeTypeString), Value: "${DO_NOT_REPLACE_ME}"},
822 {Name: "undefined_defaults_to_var", Type: ptr(AttributeTypeString), Value: "${STRING_VALUE}"},
823 {Name: "escaped_does_not_substitute", Type: ptr(AttributeTypeString), Value: "${STRING_VALUE}"},
824 {Name: "escaped_does_not_substitute_fallback", Type: ptr(AttributeTypeString), Value: "${STRING_VALUE:-fallback}"},
825 {Name: "escaped_and_substituted_fallback", Type: ptr(AttributeTypeString), Value: "${STRING_VALUE:-value}"},
826 {Name: "escaped_and_substituted", Type: ptr(AttributeTypeString), Value: "$value"},
827 {Name: "multiple_escaped_and_not_substituted", Type: ptr(AttributeTypeString), Value: "$${STRING_VALUE}"},
828 {Name: "undefined_key_with_escape_sequence_in_fallback", Type: ptr(AttributeTypeString), Value: "${UNDEFINED_KEY}"},
829 {Name: "value_with_escape", Type: ptr(AttributeTypeString), Value: "value$$"},
830 {Name: "escape_sequence", Type: ptr(AttributeTypeString), Value: "a $ b"},
831 {Name: "no_escape_sequence", Type: ptr(AttributeTypeString), Value: "a $ b"},
832 },
833 AttributesList: ptr("service.namespace=my-namespace,service.version=1.0.0"),
834 // Detectors: &Detectors{
835 // Attributes: &DetectorsAttributes{
836 // Excluded: []string{"process.command_args"},
837 // Included: []string{"process.*"},
838 // },
839 // },
840 SchemaUrl: ptr("https://opentelemetry.io/schemas/1.16.0"),
841 },
842 }
843
844 func TestParseFiles(t *testing.T) {
845 tests := []struct {
846 name string
847 input string
848 wantErr error
849 wantType *OpenTelemetryConfiguration
850 }{
851 {
852 name: "invalid nil name",
853 input: "v1.0.0_invalid_nil_name",
854 wantErr: newErrRequired(&NameStringValuePair{}, "name"),
855 wantType: &OpenTelemetryConfiguration{},
856 },
857 {
858 name: "invalid nil value",
859 input: "v1.0.0_invalid_nil_value",
860 wantErr: newErrRequired(&NameStringValuePair{}, "value"),
861 wantType: &OpenTelemetryConfiguration{},
862 },
863 {
864 name: "valid v0.2 config",
865 input: "v0.2",
866 wantErr: newErrUnmarshal(&OpenTelemetryConfiguration{}),
867 wantType: &OpenTelemetryConfiguration{},
868 },
869 {
870 name: "valid v0.3 config",
871 input: "v0.3",
872 wantErr: newErrUnmarshal(&TextMapPropagator{}),
873 wantType: &OpenTelemetryConfiguration{},
874 },
875 {
876 name: "valid v1.0.0 config",
877 input: "v1.0.0",
878 wantType: &v10OpenTelemetryConfig,
879 },
880 }
881
882 for _, tt := range tests {
883 t.Run("yaml:"+tt.name, func(t *testing.T) {
884 b, err := os.ReadFile(filepath.Join("testdata", fmt.Sprintf("%s.yaml", tt.input)))
885 require.NoError(t, err)
886
887 got, err := ParseYAML(b)
888 require.ErrorIs(t, err, tt.wantErr)
889 if tt.wantErr == nil {
890 assert.Equal(t, tt.wantType, got)
891 }
892 })
893 t.Run("json: "+tt.name, func(t *testing.T) {
894 b, err := os.ReadFile(filepath.Join("testdata", fmt.Sprintf("%s.json", tt.input)))
895 require.NoError(t, err)
896
897 var got OpenTelemetryConfiguration
898 err = json.Unmarshal(b, &got)
899 require.ErrorIs(t, err, tt.wantErr)
900 assert.Equal(t, tt.wantType, &got)
901 })
902 }
903 }
904
905 func TestUnmarshalOpenTelemetryConfiguration(t *testing.T) {
906 tests := []struct {
907 name string
908 jsonConfig []byte
909 yamlConfig []byte
910 wantErr error
911 wantType OpenTelemetryConfiguration
912 }{
913 {
914 name: "valid defaults config",
915 jsonConfig: []byte(`{"file_format": "1.0"}`),
916 yamlConfig: []byte("file_format: 1.0"),
917 wantType: OpenTelemetryConfiguration{
918 Disabled: ptr(false),
919 FileFormat: "1.0",
920 LogLevel: ptr(SeverityNumberInfo),
921 },
922 },
923 {
924 name: "invalid config missing required file_format",
925 jsonConfig: []byte(`{"disabled": false}`),
926 yamlConfig: []byte("disabled: false"),
927 wantErr: newErrRequired(&OpenTelemetryConfiguration{}, "file_format"),
928 },
929 {
930 name: "file_format invalid",
931 jsonConfig: []byte(`{"file_format":[], "disabled": false}`),
932 yamlConfig: []byte("file_format: []\ndisabled: false"),
933 wantErr: newErrUnmarshal(&OpenTelemetryConfiguration{}),
934 },
935 {
936 name: "invalid config",
937 jsonConfig: []byte(`{"file_format": "yaml", "disabled": "notabool"}`),
938 yamlConfig: []byte("file_format: []\ndisabled: notabool"),
939 wantErr: newErrUnmarshal(&OpenTelemetryConfiguration{}),
940 },
941 {
942 name: "invalid data",
943 jsonConfig: []byte(`{:2000}`),
944 yamlConfig: []byte("disabled: []\nconsole: {}\nfile_format: str"),
945 wantErr: newErrUnmarshal(&OpenTelemetryConfiguration{}),
946 },
947 {
948 name: "resource invalid",
949 jsonConfig: []byte(`{"resource":[], "file_format": "1.0"}`),
950 yamlConfig: []byte("resource: []\nfile_format: 1.0"),
951 wantErr: newErrUnmarshal(&OpenTelemetryConfiguration{}),
952 },
953 {
954 name: "attribute_limits invalid",
955 jsonConfig: []byte(`{"attribute_limits":[], "file_format": "1.0"}`),
956 yamlConfig: []byte("attribute_limits: []\nfile_format: 1.0"),
957 wantErr: newErrUnmarshal(&OpenTelemetryConfiguration{}),
958 },
959 {
960 name: "log_level invalid",
961 jsonConfig: []byte(`{"log_level":[], "file_format": "1.0"}`),
962 yamlConfig: []byte("log_level: []\nfile_format: 1.0"),
963 wantErr: newErrUnmarshal(&OpenTelemetryConfiguration{}),
964 },
965 }
966
967 for _, tt := range tests {
968 t.Run(tt.name, func(t *testing.T) {
969 got := OpenTelemetryConfiguration{}
970 err := got.UnmarshalJSON(tt.jsonConfig)
971 assert.ErrorIs(t, err, tt.wantErr)
972 assert.Equal(t, tt.wantType, got)
973
974 got = OpenTelemetryConfiguration{}
975 err = yaml.Unmarshal(tt.yamlConfig, &got)
976 assert.ErrorIs(t, err, tt.wantErr)
977 assert.Equal(t, tt.wantType, got)
978 })
979 }
980 }
981
982 func TestUnmarshalBatchSpanProcessor(t *testing.T) {
983 for _, tt := range []struct {
984 name string
985 yamlConfig []byte
986 jsonConfig []byte
987 wantErrT error
988 wantExporter SpanExporter
989 }{
990 {
991 name: "valid with null console exporter",
992 jsonConfig: []byte(`{"exporter":{"console":null}}`),
993 yamlConfig: []byte("exporter:\n console:\n"),
994 wantExporter: SpanExporter{Console: ConsoleExporter{}},
995 },
996 {
997 name: "valid with console exporter",
998 jsonConfig: []byte(`{"exporter":{"console":{}}}`),
999 yamlConfig: []byte("exporter:\n console: {}"),
1000 wantExporter: SpanExporter{Console: ConsoleExporter{}},
1001 },
1002 {
1003 name: "valid with all fields positive",
1004 jsonConfig: []byte(`{"exporter":{"console":{}},"export_timeout":5000,"max_export_batch_size":512,"max_queue_size":2048,"schedule_delay":1000}`),
1005 yamlConfig: []byte("exporter:\n console: {}\nexport_timeout: 5000\nmax_export_batch_size: 512\nmax_queue_size: 2048\nschedule_delay: 1000"),
1006 wantExporter: SpanExporter{Console: ConsoleExporter{}},
1007 },
1008 {
1009 name: "valid with zero export_timeout",
1010 jsonConfig: []byte(`{"exporter":{"console":{}},"export_timeout":0}`),
1011 yamlConfig: []byte("exporter:\n console: {}\nexport_timeout: 0"),
1012 wantExporter: SpanExporter{Console: ConsoleExporter{}},
1013 },
1014 {
1015 name: "valid with zero schedule_delay",
1016 jsonConfig: []byte(`{"exporter":{"console":{}},"schedule_delay":0}`),
1017 yamlConfig: []byte("exporter:\n console: {}\nschedule_delay: 0"),
1018 wantExporter: SpanExporter{Console: ConsoleExporter{}},
1019 },
1020 {
1021 name: "missing required exporter field",
1022 jsonConfig: []byte(`{}`),
1023 yamlConfig: []byte("{}"),
1024 wantErrT: newErrRequired(&BatchSpanProcessor{}, "exporter"),
1025 },
1026 {
1027 name: "invalid data",
1028 jsonConfig: []byte(`{:2000}`),
1029 yamlConfig: []byte("exporter:\n console: {}\nexport_timeout: !!str str"),
1030 wantErrT: newErrUnmarshal(&BatchSpanProcessor{}),
1031 },
1032 {
1033 name: "invalid export_timeout negative",
1034 jsonConfig: []byte(`{"exporter":{"console":{}},"export_timeout":-1}`),
1035 yamlConfig: []byte("exporter:\n console: {}\nexport_timeout: -1"),
1036 wantErrT: newErrGreaterOrEqualZero("export_timeout"),
1037 },
1038 {
1039 name: "invalid max_export_batch_size zero",
1040 jsonConfig: []byte(`{"exporter":{"console":{}},"max_export_batch_size":0}`),
1041 yamlConfig: []byte("exporter:\n console: {}\nmax_export_batch_size: 0"),
1042 wantErrT: newErrGreaterThanZero("max_export_batch_size"),
1043 },
1044 {
1045 name: "invalid max_export_batch_size negative",
1046 jsonConfig: []byte(`{"exporter":{"console":{}},"max_export_batch_size":-1}`),
1047 yamlConfig: []byte("exporter:\n console: {}\nmax_export_batch_size: -1"),
1048 wantErrT: newErrGreaterThanZero("max_export_batch_size"),
1049 },
1050 {
1051 name: "invalid max_queue_size zero",
1052 jsonConfig: []byte(`{"exporter":{"console":{}},"max_queue_size":0}`),
1053 yamlConfig: []byte("exporter:\n console: {}\nmax_queue_size: 0"),
1054 wantErrT: newErrGreaterThanZero("max_queue_size"),
1055 },
1056 {
1057 name: "invalid max_queue_size negative",
1058 jsonConfig: []byte(`{"exporter":{"console":{}},"max_queue_size":-1}`),
1059 yamlConfig: []byte("exporter:\n console: {}\nmax_queue_size: -1"),
1060 wantErrT: newErrGreaterThanZero("max_queue_size"),
1061 },
1062 {
1063 name: "invalid schedule_delay negative",
1064 jsonConfig: []byte(`{"exporter":{"console":{}},"schedule_delay":-1}`),
1065 yamlConfig: []byte("exporter:\n console: {}\nschedule_delay: -1"),
1066 wantErrT: newErrGreaterOrEqualZero("schedule_delay"),
1067 },
1068 } {
1069 t.Run(tt.name, func(t *testing.T) {
1070 cl := BatchSpanProcessor{}
1071 err := cl.UnmarshalJSON(tt.jsonConfig)
1072 assert.ErrorIs(t, err, tt.wantErrT)
1073 assert.Equal(t, tt.wantExporter, cl.Exporter)
1074
1075 cl = BatchSpanProcessor{}
1076 err = yaml.Unmarshal(tt.yamlConfig, &cl)
1077 assert.ErrorIs(t, err, tt.wantErrT)
1078 assert.Equal(t, tt.wantExporter, cl.Exporter)
1079 })
1080 }
1081 }
1082
1083 func TestParseYAMLWithEnvironmentVariables(t *testing.T) {
1084 tests := []struct {
1085 name string
1086 input string
1087 wantErr error
1088 wantType any
1089 }{
1090 {
1091 name: "valid v1.0.0 config with env vars",
1092 input: "v1.0.0_env_var.yaml",
1093 wantType: &v100OpenTelemetryConfigEnvParsing,
1094 },
1095 }
1096
1097 t.Setenv("OTEL_SDK_DISABLED", "false")
1098 t.Setenv("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT", "4096")
1099 t.Setenv("OTEL_EXPORTER_OTLP_PROTOCOL", "http/protobuf")
1100 t.Setenv("STRING_VALUE", "value")
1101 t.Setenv("BOOL_VALUE", "true")
1102 t.Setenv("INT_VALUE", "1")
1103 t.Setenv("FLOAT_VALUE", "1.1")
1104 t.Setenv("HEX_VALUE", "0xbeef") // A valid integer value (i.e. 3735928559) written in hexadecimal
1105 t.Setenv("INVALID_MAP_VALUE", "value\\nkey:value") // An invalid attempt to inject a map key into the YAML
1106 t.Setenv("ENV_VAR_IN_KEY", "env_var_in_key") // An env var in key
1107 t.Setenv("DO_NOT_REPLACE_ME", "Never use this value") // An unused environment variable
1108 t.Setenv("REPLACE_ME", "${DO_NOT_REPLACE_ME}") // A valid replacement text, used verbatim, not replaced with "Never use this value"
1109 t.Setenv("VALUE_WITH_ESCAPE", "value$$") // A valid replacement text, used verbatim, not replaced with "Never use this value"
1110 for _, tt := range tests {
1111 t.Run(tt.name, func(t *testing.T) {
1112 b, err := os.ReadFile(filepath.Join("testdata", tt.input))
1113 require.NoError(t, err)
1114
1115 got, err := ParseYAML(b)
1116 if tt.wantErr != nil {
1117 require.Equal(t, tt.wantErr.Error(), err.Error())
1118 } else {
1119 require.NoError(t, err)
1120 assert.Equal(t, tt.wantType, got)
1121 }
1122 })
1123 }
1124 }
1125
1126 func TestUnmarshalPeriodicMetricReader(t *testing.T) {
1127 for _, tt := range []struct {
1128 name string
1129 yamlConfig []byte
1130 jsonConfig []byte
1131 wantErrT error
1132 wantExporter PushMetricExporter
1133 }{
1134 {
1135 name: "valid with null console exporter",
1136 jsonConfig: []byte(`{"exporter":{"console":null}}`),
1137 yamlConfig: []byte("exporter:\n console:\n"),
1138 wantExporter: PushMetricExporter{Console: &ConsoleMetricExporter{}},
1139 },
1140 {
1141 name: "valid with console exporter",
1142 jsonConfig: []byte(`{"exporter":{"console":{}}}`),
1143 yamlConfig: []byte("exporter:\n console: {}"),
1144 wantExporter: PushMetricExporter{Console: &ConsoleMetricExporter{}},
1145 },
1146 {
1147 name: "valid with all fields positive",
1148 jsonConfig: []byte(`{"exporter":{"console":{}},"timeout":5000,"interval":1000}`),
1149 yamlConfig: []byte("exporter:\n console: {}\ntimeout: 5000\ninterval: 1000"),
1150 wantExporter: PushMetricExporter{Console: &ConsoleMetricExporter{}},
1151 },
1152 {
1153 name: "valid with zero timeout",
1154 jsonConfig: []byte(`{"exporter":{"console":{}},"timeout":0}`),
1155 yamlConfig: []byte("exporter:\n console: {}\ntimeout: 0"),
1156 wantExporter: PushMetricExporter{Console: &ConsoleMetricExporter{}},
1157 },
1158 {
1159 name: "valid with zero interval",
1160 jsonConfig: []byte(`{"exporter":{"console":{}},"interval":0}`),
1161 yamlConfig: []byte("exporter:\n console: {}\ninterval: 0"),
1162 wantExporter: PushMetricExporter{Console: &ConsoleMetricExporter{}},
1163 },
1164 {
1165 name: "missing required exporter field",
1166 jsonConfig: []byte(`{}`),
1167 yamlConfig: []byte("{}"),
1168 wantErrT: newErrRequired(&PeriodicMetricReader{}, "exporter"),
1169 },
1170 {
1171 name: "invalid data",
1172 jsonConfig: []byte(`{:2000}`),
1173 yamlConfig: []byte("exporter:\n console: {}\ntimeout: !!str str"),
1174 wantErrT: newErrUnmarshal(&PeriodicMetricReader{}),
1175 },
1176 {
1177 name: "invalid timeout negative",
1178 jsonConfig: []byte(`{"exporter":{"console":{}},"timeout":-1}`),
1179 yamlConfig: []byte("exporter:\n console: {}\ntimeout: -1"),
1180 wantErrT: newErrGreaterOrEqualZero("timeout"),
1181 },
1182 {
1183 name: "invalid interval negative",
1184 jsonConfig: []byte(`{"exporter":{"console":{}},"interval":-1}`),
1185 yamlConfig: []byte("exporter:\n console: {}\ninterval: -1"),
1186 wantErrT: newErrGreaterOrEqualZero("interval"),
1187 },
1188 } {
1189 t.Run(tt.name, func(t *testing.T) {
1190 pmr := PeriodicMetricReader{}
1191 err := pmr.UnmarshalJSON(tt.jsonConfig)
1192 assert.ErrorIs(t, err, tt.wantErrT)
1193 assert.Equal(t, tt.wantExporter, pmr.Exporter)
1194
1195 pmr = PeriodicMetricReader{}
1196 err = yaml.Unmarshal(tt.yamlConfig, &pmr)
1197 assert.ErrorIs(t, err, tt.wantErrT)
1198 assert.Equal(t, tt.wantExporter, pmr.Exporter)
1199 })
1200 }
1201 }
1202
1203 func TestUnmarshalCardinalityLimits(t *testing.T) {
1204 for _, tt := range []struct {
1205 name string
1206 yamlConfig []byte
1207 jsonConfig []byte
1208 wantErrT error
1209 }{
1210 {
1211 name: "valid with all fields positive",
1212 jsonConfig: []byte(`{"counter":100,"default":200,"gauge":300,"histogram":400,"observable_counter":500,"observable_gauge":600,"observable_up_down_counter":700,"up_down_counter":800}`),
1213 yamlConfig: []byte("counter: 100\ndefault: 200\ngauge: 300\nhistogram: 400\nobservable_counter: 500\nobservable_gauge: 600\nobservable_up_down_counter: 700\nup_down_counter: 800"),
1214 },
1215 {
1216 name: "valid with single field",
1217 jsonConfig: []byte(`{"default":2000}`),
1218 yamlConfig: []byte("default: 2000"),
1219 },
1220 {
1221 name: "valid empty",
1222 jsonConfig: []byte(`{}`),
1223 yamlConfig: []byte("{}"),
1224 },
1225 {
1226 name: "invalid data",
1227 jsonConfig: []byte(`{:2000}`),
1228 yamlConfig: []byte("counter: !!str 2000"),
1229 wantErrT: newErrUnmarshal(&CardinalityLimits{}),
1230 },
1231 {
1232 name: "invalid counter zero",
1233 jsonConfig: []byte(`{"counter":0}`),
1234 yamlConfig: []byte("counter: 0"),
1235 wantErrT: newErrGreaterThanZero("counter"),
1236 },
1237 {
1238 name: "invalid counter negative",
1239 jsonConfig: []byte(`{"counter":-1}`),
1240 yamlConfig: []byte("counter: -1"),
1241 wantErrT: newErrGreaterThanZero("counter"),
1242 },
1243 {
1244 name: "invalid default zero",
1245 jsonConfig: []byte(`{"default":0}`),
1246 yamlConfig: []byte("default: 0"),
1247 wantErrT: newErrGreaterThanZero("default"),
1248 },
1249 {
1250 name: "invalid default negative",
1251 jsonConfig: []byte(`{"default":-1}`),
1252 yamlConfig: []byte("default: -1"),
1253 wantErrT: newErrGreaterThanZero("default"),
1254 },
1255 {
1256 name: "invalid gauge zero",
1257 jsonConfig: []byte(`{"gauge":0}`),
1258 yamlConfig: []byte("gauge: 0"),
1259 wantErrT: newErrGreaterThanZero("gauge"),
1260 },
1261 {
1262 name: "invalid gauge negative",
1263 jsonConfig: []byte(`{"gauge":-1}`),
1264 yamlConfig: []byte("gauge: -1"),
1265 wantErrT: newErrGreaterThanZero("gauge"),
1266 },
1267 {
1268 name: "invalid histogram zero",
1269 jsonConfig: []byte(`{"histogram":0}`),
1270 yamlConfig: []byte("histogram: 0"),
1271 wantErrT: newErrGreaterThanZero("histogram"),
1272 },
1273 {
1274 name: "invalid histogram negative",
1275 jsonConfig: []byte(`{"histogram":-1}`),
1276 yamlConfig: []byte("histogram: -1"),
1277 wantErrT: newErrGreaterThanZero("histogram"),
1278 },
1279 {
1280 name: "invalid observable_counter zero",
1281 jsonConfig: []byte(`{"observable_counter":0}`),
1282 yamlConfig: []byte("observable_counter: 0"),
1283 wantErrT: newErrGreaterThanZero("observable_counter"),
1284 },
1285 {
1286 name: "invalid observable_counter negative",
1287 jsonConfig: []byte(`{"observable_counter":-1}`),
1288 yamlConfig: []byte("observable_counter: -1"),
1289 wantErrT: newErrGreaterThanZero("observable_counter"),
1290 },
1291 {
1292 name: "invalid observable_gauge zero",
1293 jsonConfig: []byte(`{"observable_gauge":0}`),
1294 yamlConfig: []byte("observable_gauge: 0"),
1295 wantErrT: newErrGreaterThanZero("observable_gauge"),
1296 },
1297 {
1298 name: "invalid observable_gauge negative",
1299 jsonConfig: []byte(`{"observable_gauge":-1}`),
1300 yamlConfig: []byte("observable_gauge: -1"),
1301 wantErrT: newErrGreaterThanZero("observable_gauge"),
1302 },
1303 {
1304 name: "invalid observable_up_down_counter zero",
1305 jsonConfig: []byte(`{"observable_up_down_counter":0}`),
1306 yamlConfig: []byte("observable_up_down_counter: 0"),
1307 wantErrT: newErrGreaterThanZero("observable_up_down_counter"),
1308 },
1309 {
1310 name: "invalid observable_up_down_counter negative",
1311 jsonConfig: []byte(`{"observable_up_down_counter":-1}`),
1312 yamlConfig: []byte("observable_up_down_counter: -1"),
1313 wantErrT: newErrGreaterThanZero("observable_up_down_counter"),
1314 },
1315 {
1316 name: "invalid up_down_counter zero",
1317 jsonConfig: []byte(`{"up_down_counter":0}`),
1318 yamlConfig: []byte("up_down_counter: 0"),
1319 wantErrT: newErrGreaterThanZero("up_down_counter"),
1320 },
1321 {
1322 name: "invalid up_down_counter negative",
1323 jsonConfig: []byte(`{"up_down_counter":-1}`),
1324 yamlConfig: []byte("up_down_counter: -1"),
1325 wantErrT: newErrGreaterThanZero("up_down_counter"),
1326 },
1327 } {
1328 t.Run(tt.name, func(t *testing.T) {
1329 cl := CardinalityLimits{}
1330 err := cl.UnmarshalJSON(tt.jsonConfig)
1331 assert.ErrorIs(t, err, tt.wantErrT)
1332
1333 cl = CardinalityLimits{}
1334 err = yaml.Unmarshal(tt.yamlConfig, &cl)
1335 assert.ErrorIs(t, err, tt.wantErrT)
1336 })
1337 }
1338 }
1339
1340 func TestCreateHeadersConfig(t *testing.T) {
1341 tests := []struct {
1342 name string
1343 headers []NameStringValuePair
1344 headersList *string
1345 wantHeaders map[string]string
1346 wantErr error
1347 }{
1348 {
1349 name: "no headers",
1350 headers: []NameStringValuePair{},
1351 headersList: nil,
1352 wantHeaders: map[string]string{},
1353 },
1354 {
1355 name: "headerslist only",
1356 headers: []NameStringValuePair{},
1357 headersList: ptr("a=b,c=d"),
1358 wantHeaders: map[string]string{
1359 "a": "b",
1360 "c": "d",
1361 },
1362 },
1363 {
1364 name: "headers only",
1365 headers: []NameStringValuePair{
1366 {
1367 Name: "a",
1368 Value: ptr("b"),
1369 },
1370 {
1371 Name: "c",
1372 Value: ptr("d"),
1373 },
1374 },
1375 headersList: nil,
1376 wantHeaders: map[string]string{
1377 "a": "b",
1378 "c": "d",
1379 },
1380 },
1381 {
1382 name: "both headers and headerslist",
1383 headers: []NameStringValuePair{
1384 {
1385 Name: "a",
1386 Value: ptr("b"),
1387 },
1388 },
1389 headersList: ptr("c=d"),
1390 wantHeaders: map[string]string{
1391 "a": "b",
1392 "c": "d",
1393 },
1394 },
1395 {
1396 name: "headers supersedes headerslist",
1397 headers: []NameStringValuePair{
1398 {
1399 Name: "a",
1400 Value: ptr("b"),
1401 },
1402 {
1403 Name: "c",
1404 Value: ptr("override"),
1405 },
1406 },
1407 headersList: ptr("c=d"),
1408 wantHeaders: map[string]string{
1409 "a": "b",
1410 "c": "override",
1411 },
1412 },
1413 {
1414 name: "invalid headerslist",
1415 headersList: ptr("==="),
1416 wantErr: newErrInvalid("invalid headers_list"),
1417 },
1418 }
1419 for _, tt := range tests {
1420 t.Run(tt.name, func(t *testing.T) {
1421 headersMap, err := createHeadersConfig(tt.headers, tt.headersList)
1422 require.ErrorIs(t, err, tt.wantErr)
1423 require.Equal(t, tt.wantHeaders, headersMap)
1424 })
1425 }
1426 }
1427
1428 func TestUnmarshalSpanLimits(t *testing.T) {
1429 for _, tt := range []struct {
1430 name string
1431 yamlConfig []byte
1432 jsonConfig []byte
1433 wantErrT error
1434 }{
1435 {
1436 name: "valid with all fields positive",
1437 jsonConfig: []byte(`{"attribute_count_limit":100,"attribute_value_length_limit":200,"event_attribute_count_limit":300,"event_count_limit":400,"link_attribute_count_limit":500,"link_count_limit":600}`),
1438 yamlConfig: []byte("attribute_count_limit: 100\nattribute_value_length_limit: 200\nevent_attribute_count_limit: 300\nevent_count_limit: 400\nlink_attribute_count_limit: 500\nlink_count_limit: 600"),
1439 },
1440 {
1441 name: "valid with single field",
1442 jsonConfig: []byte(`{"attribute_value_length_limit":2000}`),
1443 yamlConfig: []byte("attribute_value_length_limit: 2000"),
1444 },
1445 {
1446 name: "valid empty",
1447 jsonConfig: []byte(`{}`),
1448 yamlConfig: []byte("{}"),
1449 },
1450 {
1451 name: "invalid data",
1452 jsonConfig: []byte(`{:2000}`),
1453 yamlConfig: []byte("attribute_count_limit: !!str 2000"),
1454 wantErrT: newErrUnmarshal(&SpanLimits{}),
1455 },
1456 {
1457 name: "invalid attribute_count_limit negative",
1458 jsonConfig: []byte(`{"attribute_count_limit":-1}`),
1459 yamlConfig: []byte("attribute_count_limit: -1"),
1460 wantErrT: newErrGreaterOrEqualZero("attribute_count_limit"),
1461 },
1462 {
1463 name: "invalid attribute_value_length_limit negative",
1464 jsonConfig: []byte(`{"attribute_value_length_limit":-1}`),
1465 yamlConfig: []byte("attribute_value_length_limit: -1"),
1466 wantErrT: newErrGreaterOrEqualZero("attribute_value_length_limit"),
1467 },
1468 {
1469 name: "invalid event_attribute_count_limit negative",
1470 jsonConfig: []byte(`{"event_attribute_count_limit":-1}`),
1471 yamlConfig: []byte("event_attribute_count_limit: -1"),
1472 wantErrT: newErrGreaterOrEqualZero("event_attribute_count_limit"),
1473 },
1474 {
1475 name: "invalid event_count_limit negative",
1476 jsonConfig: []byte(`{"event_count_limit":-1}`),
1477 yamlConfig: []byte("event_count_limit: -1"),
1478 wantErrT: newErrGreaterOrEqualZero("event_count_limit"),
1479 },
1480 {
1481 name: "invalid link_attribute_count_limit negative",
1482 jsonConfig: []byte(`{"link_attribute_count_limit":-1}`),
1483 yamlConfig: []byte("link_attribute_count_limit: -1"),
1484 wantErrT: newErrGreaterOrEqualZero("link_attribute_count_limit"),
1485 },
1486 {
1487 name: "invalid link_count_limit negative",
1488 jsonConfig: []byte(`{"link_count_limit":-1}`),
1489 yamlConfig: []byte("link_count_limit: -1"),
1490 wantErrT: newErrGreaterOrEqualZero("link_count_limit"),
1491 },
1492 } {
1493 t.Run(tt.name, func(t *testing.T) {
1494 cl := SpanLimits{}
1495 err := cl.UnmarshalJSON(tt.jsonConfig)
1496 assert.ErrorIs(t, err, tt.wantErrT)
1497
1498 cl = SpanLimits{}
1499 err = yaml.Unmarshal(tt.yamlConfig, &cl)
1500 assert.ErrorIs(t, err, tt.wantErrT)
1501 })
1502 }
1503 }
1504
1505 func TestUnmarshalOTLPHttpExporter(t *testing.T) {
1506 for _, tt := range []struct {
1507 name string
1508 yamlConfig []byte
1509 jsonConfig []byte
1510 wantErrT error
1511 wantExporter OTLPHttpExporter
1512 }{
1513 {
1514 name: "valid with exporter",
1515 jsonConfig: []byte(`{"endpoint":"localhost:4318"}`),
1516 yamlConfig: []byte("endpoint: localhost:4318\n"),
1517 wantExporter: OTLPHttpExporter{Endpoint: ptr("localhost:4318")},
1518 },
1519 {
1520 name: "missing required endpoint field",
1521 jsonConfig: []byte(`{}`),
1522 yamlConfig: []byte("{}"),
1523 wantErrT: newErrRequired(&OTLPHttpExporter{}, "endpoint"),
1524 },
1525 {
1526 name: "valid with zero timeout",
1527 jsonConfig: []byte(`{"endpoint":"localhost:4318", "timeout":0}`),
1528 yamlConfig: []byte("endpoint: localhost:4318\ntimeout: 0"),
1529 wantExporter: OTLPHttpExporter{Endpoint: ptr("localhost:4318"), Timeout: ptr(0)},
1530 },
1531 {
1532 name: "invalid data",
1533 jsonConfig: []byte(`{:2000}`),
1534 yamlConfig: []byte("endpoint: localhost:4318\ntimeout: !!str str"),
1535 wantErrT: newErrUnmarshal(&OTLPHttpExporter{}),
1536 },
1537 {
1538 name: "invalid timeout negative",
1539 jsonConfig: []byte(`{"endpoint":"localhost:4318", "timeout":-1}`),
1540 yamlConfig: []byte("endpoint: localhost:4318\ntimeout: -1"),
1541 wantErrT: newErrGreaterOrEqualZero("timeout"),
1542 },
1543 } {
1544 t.Run(tt.name, func(t *testing.T) {
1545 cl := OTLPHttpExporter{}
1546 err := cl.UnmarshalJSON(tt.jsonConfig)
1547 assert.ErrorIs(t, err, tt.wantErrT)
1548 assert.Equal(t, tt.wantExporter, cl)
1549
1550 cl = OTLPHttpExporter{}
1551 err = yaml.Unmarshal(tt.yamlConfig, &cl)
1552 assert.ErrorIs(t, err, tt.wantErrT)
1553 assert.Equal(t, tt.wantExporter, cl)
1554 })
1555 }
1556 }
1557
1558 func TestUnmarshalOTLPGrpcExporter(t *testing.T) {
1559 for _, tt := range []struct {
1560 name string
1561 yamlConfig []byte
1562 jsonConfig []byte
1563 wantErrT error
1564 wantExporter OTLPGrpcExporter
1565 }{
1566 {
1567 name: "valid with exporter",
1568 jsonConfig: []byte(`{"endpoint":"localhost:4318"}`),
1569 yamlConfig: []byte("endpoint: localhost:4318\n"),
1570 wantExporter: OTLPGrpcExporter{Endpoint: ptr("localhost:4318")},
1571 },
1572 {
1573 name: "missing required endpoint field",
1574 jsonConfig: []byte(`{}`),
1575 yamlConfig: []byte("{}"),
1576 wantErrT: newErrRequired(&OTLPGrpcExporter{}, "endpoint"),
1577 },
1578 {
1579 name: "valid with zero timeout",
1580 jsonConfig: []byte(`{"endpoint":"localhost:4318", "timeout":0}`),
1581 yamlConfig: []byte("endpoint: localhost:4318\ntimeout: 0"),
1582 wantExporter: OTLPGrpcExporter{Endpoint: ptr("localhost:4318"), Timeout: ptr(0)},
1583 },
1584 {
1585 name: "invalid data",
1586 jsonConfig: []byte(`{:2000}`),
1587 yamlConfig: []byte("endpoint: localhost:4318\ntimeout: !!str str"),
1588 wantErrT: newErrUnmarshal(&OTLPGrpcExporter{}),
1589 },
1590 {
1591 name: "invalid timeout negative",
1592 jsonConfig: []byte(`{"endpoint":"localhost:4318", "timeout":-1}`),
1593 yamlConfig: []byte("endpoint: localhost:4318\ntimeout: -1"),
1594 wantErrT: newErrGreaterOrEqualZero("timeout"),
1595 },
1596 } {
1597 t.Run(tt.name, func(t *testing.T) {
1598 cl := OTLPGrpcExporter{}
1599 err := cl.UnmarshalJSON(tt.jsonConfig)
1600 assert.ErrorIs(t, err, tt.wantErrT)
1601 assert.Equal(t, tt.wantExporter, cl)
1602
1603 cl = OTLPGrpcExporter{}
1604 err = yaml.Unmarshal(tt.yamlConfig, &cl)
1605 assert.ErrorIs(t, err, tt.wantErrT)
1606 assert.Equal(t, tt.wantExporter, cl)
1607 })
1608 }
1609 }
1610
1611 func TestUnmarshalOTLPHttpMetricExporter(t *testing.T) {
1612 for _, tt := range []struct {
1613 name string
1614 yamlConfig []byte
1615 jsonConfig []byte
1616 wantErrT error
1617 wantExporter OTLPHttpMetricExporter
1618 }{
1619 {
1620 name: "valid with exporter",
1621 jsonConfig: []byte(`{"endpoint":"localhost:4318"}`),
1622 yamlConfig: []byte("endpoint: localhost:4318\n"),
1623 wantExporter: OTLPHttpMetricExporter{Endpoint: ptr("localhost:4318")},
1624 },
1625 {
1626 name: "missing required endpoint field",
1627 jsonConfig: []byte(`{}`),
1628 yamlConfig: []byte("{}"),
1629 wantErrT: newErrRequired(&OTLPHttpMetricExporter{}, "endpoint"),
1630 },
1631 {
1632 name: "valid with zero timeout",
1633 jsonConfig: []byte(`{"endpoint":"localhost:4318", "timeout":0}`),
1634 yamlConfig: []byte("endpoint: localhost:4318\ntimeout: 0"),
1635 wantExporter: OTLPHttpMetricExporter{Endpoint: ptr("localhost:4318"), Timeout: ptr(0)},
1636 },
1637 {
1638 name: "invalid data",
1639 jsonConfig: []byte(`{:2000}`),
1640 yamlConfig: []byte("endpoint: localhost:4318\ntimeout: !!str str"),
1641 wantErrT: newErrUnmarshal(&OTLPHttpMetricExporter{}),
1642 },
1643 {
1644 name: "invalid timeout negative",
1645 jsonConfig: []byte(`{"endpoint":"localhost:4318", "timeout":-1}`),
1646 yamlConfig: []byte("endpoint: localhost:4318\ntimeout: -1"),
1647 wantErrT: newErrGreaterOrEqualZero("timeout"),
1648 },
1649 } {
1650 t.Run(tt.name, func(t *testing.T) {
1651 cl := OTLPHttpMetricExporter{}
1652 err := cl.UnmarshalJSON(tt.jsonConfig)
1653 assert.ErrorIs(t, err, tt.wantErrT)
1654 assert.Equal(t, tt.wantExporter, cl)
1655
1656 cl = OTLPHttpMetricExporter{}
1657 err = yaml.Unmarshal(tt.yamlConfig, &cl)
1658 assert.ErrorIs(t, err, tt.wantErrT)
1659 assert.Equal(t, tt.wantExporter, cl)
1660 })
1661 }
1662 }
1663
1664 func TestUnmarshalOTLPGrpcMetricExporter(t *testing.T) {
1665 for _, tt := range []struct {
1666 name string
1667 yamlConfig []byte
1668 jsonConfig []byte
1669 wantErrT error
1670 wantExporter OTLPGrpcMetricExporter
1671 }{
1672 {
1673 name: "valid with exporter",
1674 jsonConfig: []byte(`{"endpoint":"localhost:4318"}`),
1675 yamlConfig: []byte("endpoint: localhost:4318\n"),
1676 wantExporter: OTLPGrpcMetricExporter{Endpoint: ptr("localhost:4318")},
1677 },
1678 {
1679 name: "missing required endpoint field",
1680 jsonConfig: []byte(`{}`),
1681 yamlConfig: []byte("{}"),
1682 wantErrT: newErrRequired(&OTLPGrpcMetricExporter{}, "endpoint"),
1683 },
1684 {
1685 name: "valid with zero timeout",
1686 jsonConfig: []byte(`{"endpoint":"localhost:4318", "timeout":0}`),
1687 yamlConfig: []byte("endpoint: localhost:4318\ntimeout: 0"),
1688 wantExporter: OTLPGrpcMetricExporter{Endpoint: ptr("localhost:4318"), Timeout: ptr(0)},
1689 },
1690 {
1691 name: "invalid data",
1692 jsonConfig: []byte(`{:2000}`),
1693 yamlConfig: []byte("endpoint: localhost:4318\ntimeout: !!str str"),
1694 wantErrT: newErrUnmarshal(&OTLPGrpcMetricExporter{}),
1695 },
1696 {
1697 name: "invalid timeout negative",
1698 jsonConfig: []byte(`{"endpoint":"localhost:4318", "timeout":-1}`),
1699 yamlConfig: []byte("endpoint: localhost:4318\ntimeout: -1"),
1700 wantErrT: newErrGreaterOrEqualZero("timeout"),
1701 },
1702 } {
1703 t.Run(tt.name, func(t *testing.T) {
1704 cl := OTLPGrpcMetricExporter{}
1705 err := cl.UnmarshalJSON(tt.jsonConfig)
1706 assert.ErrorIs(t, err, tt.wantErrT)
1707 assert.Equal(t, tt.wantExporter, cl)
1708
1709 cl = OTLPGrpcMetricExporter{}
1710 err = yaml.Unmarshal(tt.yamlConfig, &cl)
1711 assert.ErrorIs(t, err, tt.wantErrT)
1712 assert.Equal(t, tt.wantExporter, cl)
1713 })
1714 }
1715 }
1716
1717 func TestUnmarshalAttributeNameValueType(t *testing.T) {
1718 for _, tt := range []struct {
1719 name string
1720 yamlConfig []byte
1721 jsonConfig []byte
1722 wantErrT error
1723 wantAttributeNameValue AttributeNameValue
1724 }{
1725 {
1726 name: "invalid data",
1727 jsonConfig: []byte(`{:2000}`),
1728 yamlConfig: []byte("name: []\nvalue: true\ntype: bool\n"),
1729 wantErrT: newErrUnmarshal(&AttributeNameValue{}),
1730 },
1731 {
1732 name: "missing required name field",
1733 jsonConfig: []byte(`{}`),
1734 yamlConfig: []byte("{}"),
1735 wantErrT: newErrRequired(&AttributeNameValue{}, "name"),
1736 },
1737 {
1738 name: "missing required value field",
1739 jsonConfig: []byte(`{"name":"test"}`),
1740 yamlConfig: []byte("name: test"),
1741 wantErrT: newErrRequired(&AttributeNameValue{}, "value"),
1742 },
1743 {
1744 name: "valid string value",
1745 jsonConfig: []byte(`{"name":"test", "value": "test-val", "type": "string"}`),
1746 yamlConfig: []byte("name: test\nvalue: test-val\ntype: string\n"),
1747 wantAttributeNameValue: AttributeNameValue{
1748 Name: "test",
1749 Value: "test-val",
1750 Type: ptr(AttributeTypeString),
1751 },
1752 },
1753 {
1754 name: "valid string_array value",
1755 jsonConfig: []byte(`{"name":"test", "value": ["test-val", "test-val-2"], "type": "string_array"}`),
1756 yamlConfig: []byte("name: test\nvalue: [test-val, test-val-2]\ntype: string_array\n"),
1757 wantAttributeNameValue: AttributeNameValue{
1758 Name: "test",
1759 Value: []any{"test-val", "test-val-2"},
1760 Type: ptr(AttributeTypeStringArray),
1761 },
1762 },
1763 {
1764 name: "valid bool value",
1765 jsonConfig: []byte(`{"name":"test", "value": true, "type": "bool"}`),
1766 yamlConfig: []byte("name: test\nvalue: true\ntype: bool\n"),
1767 wantAttributeNameValue: AttributeNameValue{
1768 Name: "test",
1769 Value: true,
1770 Type: ptr(AttributeTypeBool),
1771 },
1772 },
1773 {
1774 name: "valid string_array value",
1775 jsonConfig: []byte(`{"name":"test", "value": ["test-val", "test-val-2"], "type": "string_array"}`),
1776 yamlConfig: []byte("name: test\nvalue: [test-val, test-val-2]\ntype: string_array\n"),
1777 wantAttributeNameValue: AttributeNameValue{
1778 Name: "test",
1779 Value: []any{"test-val", "test-val-2"},
1780 Type: ptr(AttributeTypeStringArray),
1781 },
1782 },
1783 {
1784 name: "valid int value",
1785 jsonConfig: []byte(`{"name":"test", "value": 1, "type": "int"}`),
1786 yamlConfig: []byte("name: test\nvalue: 1\ntype: int\n"),
1787 wantAttributeNameValue: AttributeNameValue{
1788 Name: "test",
1789 Value: int(1),
1790 Type: ptr(AttributeTypeInt),
1791 },
1792 },
1793 {
1794 name: "valid int_array value",
1795 jsonConfig: []byte(`{"name":"test", "value": [1, 2], "type": "int_array"}`),
1796 yamlConfig: []byte("name: test\nvalue: [1, 2]\ntype: int_array\n"),
1797 wantAttributeNameValue: AttributeNameValue{
1798 Name: "test",
1799 Value: []any{1, 2},
1800 Type: ptr(AttributeTypeIntArray),
1801 },
1802 },
1803 {
1804 name: "valid double value",
1805 jsonConfig: []byte(`{"name":"test", "value": 1, "type": "double"}`),
1806 yamlConfig: []byte("name: test\nvalue: 1\ntype: double\n"),
1807 wantAttributeNameValue: AttributeNameValue{
1808 Name: "test",
1809 Value: float64(1),
1810 Type: ptr(AttributeTypeDouble),
1811 },
1812 },
1813 {
1814 name: "valid double_array value",
1815 jsonConfig: []byte(`{"name":"test", "value": [1, 2], "type": "double_array"}`),
1816 yamlConfig: []byte("name: test\nvalue: [1.0, 2.0]\ntype: double_array\n"),
1817 wantAttributeNameValue: AttributeNameValue{
1818 Name: "test",
1819 Value: []any{float64(1), float64(2)},
1820 Type: ptr(AttributeTypeDoubleArray),
1821 },
1822 },
1823 {
1824 name: "invalid type",
1825 jsonConfig: []byte(`{"name":"test", "value": 1, "type": "float"}`),
1826 yamlConfig: []byte("name: test\nvalue: 1\ntype: float\n"),
1827 wantErrT: newErrInvalid("unexpected value type"),
1828 },
1829 } {
1830 t.Run(tt.name, func(t *testing.T) {
1831 val := AttributeNameValue{}
1832 err := val.UnmarshalJSON(tt.jsonConfig)
1833 assert.ErrorIs(t, err, tt.wantErrT)
1834 assert.Equal(t, tt.wantAttributeNameValue, val)
1835
1836 val = AttributeNameValue{}
1837 err = yaml.Unmarshal(tt.yamlConfig, &val)
1838 assert.ErrorIs(t, err, tt.wantErrT)
1839 assert.Equal(t, tt.wantAttributeNameValue, val)
1840 })
1841 }
1842 }
1843
1844 func TestUnmarshalNameStringValuePairType(t *testing.T) {
1845 for _, tt := range []struct {
1846 name string
1847 yamlConfig []byte
1848 jsonConfig []byte
1849 wantErrT error
1850 wantNameStringValuePair NameStringValuePair
1851 }{
1852 {
1853 name: "invalid data",
1854 jsonConfig: []byte(`{:2000}`),
1855 yamlConfig: []byte("name: []\nvalue: true\ntype: bool\n"),
1856 wantErrT: newErrUnmarshal(&NameStringValuePair{}),
1857 },
1858 {
1859 name: "missing required name field",
1860 jsonConfig: []byte(`{}`),
1861 yamlConfig: []byte("{}"),
1862 wantErrT: newErrRequired(&NameStringValuePair{}, "name"),
1863 },
1864 {
1865 name: "missing required value field",
1866 jsonConfig: []byte(`{"name":"test"}`),
1867 yamlConfig: []byte("name: test"),
1868 wantErrT: newErrRequired(&NameStringValuePair{}, "value"),
1869 },
1870 {
1871 name: "invalid array name",
1872 jsonConfig: []byte(`{"name":[], "value": ["test-val", "test-val-2"], "type": "string_array"}`),
1873 yamlConfig: []byte("name: []\nvalue: [test-val, test-val-2]\ntype: string_array\n"),
1874 wantErrT: newErrUnmarshal(&NameStringValuePair{}),
1875 },
1876 {
1877 name: "valid string value",
1878 jsonConfig: []byte(`{"name":"test", "value": "test-val", "type": "string"}`),
1879 yamlConfig: []byte("name: test\nvalue: test-val\ntype: string\n"),
1880 wantNameStringValuePair: NameStringValuePair{
1881 Name: "test",
1882 Value: ptr("test-val"),
1883 },
1884 },
1885 {
1886 name: "invalid string_array value",
1887 jsonConfig: []byte(`{"name":"test", "value": ["test-val", "test-val-2"], "type": "string_array"}`),
1888 yamlConfig: []byte("name: test\nvalue: [test-val, test-val-2]\ntype: string_array\n"),
1889 wantErrT: newErrUnmarshal(&NameStringValuePair{}),
1890 },
1891 } {
1892 t.Run(tt.name, func(t *testing.T) {
1893 val := NameStringValuePair{}
1894 err := val.UnmarshalJSON(tt.jsonConfig)
1895 assert.ErrorIs(t, err, tt.wantErrT)
1896 assert.Equal(t, tt.wantNameStringValuePair, val)
1897
1898 val = NameStringValuePair{}
1899 err = yaml.Unmarshal(tt.yamlConfig, &val)
1900 assert.ErrorIs(t, err, tt.wantErrT)
1901 assert.Equal(t, tt.wantNameStringValuePair, val)
1902 })
1903 }
1904 }
1905
1906 func TestUnmarshalInstrumentType(t *testing.T) {
1907 var instrumentType InstrumentType
1908 for _, tt := range []struct {
1909 name string
1910 yamlConfig []byte
1911 jsonConfig []byte
1912 wantErrT error
1913 wantInstrumentType InstrumentType
1914 }{
1915 {
1916 name: "invalid data",
1917 jsonConfig: []byte(`{:2000}`),
1918 yamlConfig: []byte("name: []\nvalue: true\ntype: bool\n"),
1919 wantErrT: newErrUnmarshal(&instrumentType),
1920 },
1921 {
1922 name: "invalid instrument type",
1923 jsonConfig: []byte(`"test"`),
1924 yamlConfig: []byte("test"),
1925 wantErrT: newErrInvalid(`invalid selector (expected one of []interface {}{"counter", "gauge", "histogram", "observable_counter", "observable_gauge", "observable_up_down_counter", "up_down_counter"}): "test""`),
1926 },
1927 {
1928 name: "valid instrument type",
1929 jsonConfig: []byte(`"counter"`),
1930 yamlConfig: []byte("counter"),
1931 wantInstrumentType: InstrumentTypeCounter,
1932 },
1933 } {
1934 t.Run(tt.name, func(t *testing.T) {
1935 val := InstrumentType("")
1936 err := val.UnmarshalJSON(tt.jsonConfig)
1937 assert.ErrorIs(t, err, tt.wantErrT)
1938 assert.Equal(t, tt.wantInstrumentType, val)
1939
1940 val = InstrumentType("")
1941 err = yaml.Unmarshal(tt.yamlConfig, &val)
1942 assert.ErrorIs(t, err, tt.wantErrT)
1943 assert.Equal(t, tt.wantInstrumentType, val)
1944 })
1945 }
1946 }
1947
1948 func TestUnmarshalExporterDefaultHistogramAggregation(t *testing.T) {
1949 var exporterDefaultHistogramAggregation ExporterDefaultHistogramAggregation
1950 for _, tt := range []struct {
1951 name string
1952 yamlConfig []byte
1953 jsonConfig []byte
1954 wantErrT error
1955 wantExporterDefaultHistogramAggregation ExporterDefaultHistogramAggregation
1956 }{
1957 {
1958 name: "invalid data",
1959 jsonConfig: []byte(`{:2000}`),
1960 yamlConfig: []byte("name: []\nvalue: true\ntype: bool\n"),
1961 wantErrT: newErrUnmarshal(&exporterDefaultHistogramAggregation),
1962 },
1963 {
1964 name: "invalid histogram aggregation",
1965 jsonConfig: []byte(`"test"`),
1966 yamlConfig: []byte("test"),
1967 wantErrT: newErrInvalid(`invalid histogram aggregation (expected one of []interface {}{"explicit_bucket_histogram", "base2_exponential_bucket_histogram"}): "test""`),
1968 },
1969 {
1970 name: "valid histogram aggregation",
1971 jsonConfig: []byte(`"base2_exponential_bucket_histogram"`),
1972 yamlConfig: []byte("base2_exponential_bucket_histogram"),
1973 wantExporterDefaultHistogramAggregation: ExporterDefaultHistogramAggregationBase2ExponentialBucketHistogram,
1974 },
1975 } {
1976 t.Run(tt.name, func(t *testing.T) {
1977 val := ExporterDefaultHistogramAggregation("")
1978 err := val.UnmarshalJSON(tt.jsonConfig)
1979 assert.ErrorIs(t, err, tt.wantErrT)
1980 assert.Equal(t, tt.wantExporterDefaultHistogramAggregation, val)
1981
1982 val = ExporterDefaultHistogramAggregation("")
1983 err = yaml.Unmarshal(tt.yamlConfig, &val)
1984 assert.ErrorIs(t, err, tt.wantErrT)
1985 assert.Equal(t, tt.wantExporterDefaultHistogramAggregation, val)
1986 })
1987 }
1988 }
1989
1990 func TestUnmarshalPullMetricReader(t *testing.T) {
1991 for _, tt := range []struct {
1992 name string
1993 yamlConfig []byte
1994 jsonConfig []byte
1995 wantErrT error
1996 wantExporter PullMetricExporter
1997 }{
1998 {
1999 name: "valid with proemtheus exporter",
2000 jsonConfig: []byte(`{"exporter":{"prometheus/development":{}}}`),
2001 yamlConfig: []byte("exporter:\n prometheus/development: {}"),
2002 wantExporter: PullMetricExporter{},
2003 },
2004 {
2005 name: "missing required exporter field",
2006 jsonConfig: []byte(`{}`),
2007 yamlConfig: []byte("{}"),
2008 wantErrT: newErrRequired(&PullMetricReader{}, "exporter"),
2009 },
2010 } {
2011 t.Run(tt.name, func(t *testing.T) {
2012 cl := PullMetricReader{}
2013 err := cl.UnmarshalJSON(tt.jsonConfig)
2014 assert.ErrorIs(t, err, tt.wantErrT)
2015 assert.Equal(t, tt.wantExporter, cl.Exporter)
2016
2017 cl = PullMetricReader{}
2018 err = yaml.Unmarshal(tt.yamlConfig, &cl)
2019 assert.ErrorIs(t, err, tt.wantErrT)
2020 assert.Equal(t, tt.wantExporter, cl.Exporter)
2021 })
2022 }
2023 }
2024
2025 func TestUnmarshalResourceJson(t *testing.T) {
2026 for _, tt := range []struct {
2027 name string
2028 yamlConfig []byte
2029 jsonConfig []byte
2030 wantErrT error
2031 wantResource Resource
2032 }{
2033 {
2034 name: "valid with all detectors",
2035 jsonConfig: []byte(`{"detection/development": {"detectors": [{"container": null},{"host": null},{"process": null},{"service": null}]}}`),
2036 yamlConfig: []byte("detection/development:\n detectors:\n - container:\n - host:\n - process:\n - service:"),
2037 wantResource: Resource{},
2038 },
2039 {
2040 name: "valid non-nil with all detectors",
2041 jsonConfig: []byte(`{"detection/development": {"detectors": [{"container": {}},{"host": {}},{"process": {}},{"service": {}}]}}`),
2042 yamlConfig: []byte("detection/development:\n detectors:\n - container: {}\n - host: {}\n - process: {}\n - service: {}"),
2043 wantResource: Resource{},
2044 },
2045 } {
2046 t.Run(tt.name, func(t *testing.T) {
2047 r := Resource{}
2048 err := json.Unmarshal(tt.jsonConfig, &r)
2049 assert.ErrorIs(t, err, tt.wantErrT)
2050 assert.Equal(t, tt.wantResource, r)
2051
2052 r = Resource{}
2053 err = yaml.Unmarshal(tt.yamlConfig, &r)
2054 assert.ErrorIs(t, err, tt.wantErrT)
2055 assert.Equal(t, tt.wantResource, r)
2056 })
2057 }
2058 }