Debian Codegraph @

sdk/resource/resource_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package resource_test
5
6 import (
7 "context"
8 "encoding/json"
9 "errors"
10 "fmt"
11 "os"
12 "strings"
13 "sync"
14 "testing"
15
16 "github.com/google/go-cmp/cmp"
17 "github.com/stretchr/testify/assert"
18 "github.com/stretchr/testify/require"
19
20 "go.opentelemetry.io/otel/attribute"
21 "go.opentelemetry.io/otel/sdk"
22 "go.opentelemetry.io/otel/sdk/resource"
23 semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
24 )
25
26 var (
27 kv11 = attribute.String("k1", "v11")
28 kv12 = attribute.String("k1", "v12")
29 kv21 = attribute.String("k2", "v21")
30 kv31 = attribute.String("k3", "v31")
31 kv41 = attribute.String("k4", "v41")
32 kv42 = attribute.String("k4", "")
33 )
34
35 const v121 = "https://opentelemetry.io/schemas/1.21.0"
36
37 func TestNewWithAttributes(t *testing.T) {
38 cases := []struct {
39 name string
40 in []attribute.KeyValue
41 want []attribute.KeyValue
42 }{
43 {
44 name: "Key with common key order1",
45 in: []attribute.KeyValue{kv12, kv11, kv21},
46 want: []attribute.KeyValue{kv11, kv21},
47 },
48 {
49 name: "Key with common key order2",
50 in: []attribute.KeyValue{kv11, kv12, kv21},
51 want: []attribute.KeyValue{kv12, kv21},
52 },
53 {
54 name: "Key with nil",
55 in: nil,
56 want: nil,
57 },
58 }
59 for _, c := range cases {
60 t.Run(fmt.Sprintf("case-%s", c.name), func(t *testing.T) {
61 res := resource.NewSchemaless(c.in...)
62 if diff := cmp.Diff(
63 res.Attributes(),
64 c.want,
65 cmp.AllowUnexported(attribute.Value{})); diff != "" {
66 t.Fatalf("unwanted result: diff %+v,", diff)
67 }
68 })
69 }
70 }
71
72 func TestMerge(t *testing.T) {
73 cases := []struct {
74 name string
75 a, b *resource.Resource
76 want []attribute.KeyValue
77 isErr bool
78 schemaURL string
79 }{
80 {
81 name: "Merge 2 nils",
82 a: nil,
83 b: nil,
84 want: nil,
85 },
86 {
87 name: "Merge with no overlap, no nil",
88 a: resource.NewSchemaless(kv11, kv31),
89 b: resource.NewSchemaless(kv21, kv41),
90 want: []attribute.KeyValue{kv11, kv21, kv31, kv41},
91 },
92 {
93 name: "Merge with no overlap, no nil, not interleaved",
94 a: resource.NewSchemaless(kv11, kv21),
95 b: resource.NewSchemaless(kv31, kv41),
96 want: []attribute.KeyValue{kv11, kv21, kv31, kv41},
97 },
98 {
99 name: "Merge with common key order1",
100 a: resource.NewSchemaless(kv11),
101 b: resource.NewSchemaless(kv12, kv21),
102 want: []attribute.KeyValue{kv12, kv21},
103 },
104 {
105 name: "Merge with common key order2",
106 a: resource.NewSchemaless(kv12, kv21),
107 b: resource.NewSchemaless(kv11),
108 want: []attribute.KeyValue{kv11, kv21},
109 },
110 {
111 name: "Merge with common key order4",
112 a: resource.NewSchemaless(kv11, kv21, kv41),
113 b: resource.NewSchemaless(kv31, kv41),
114 want: []attribute.KeyValue{kv11, kv21, kv31, kv41},
115 },
116 {
117 name: "Merge with no keys",
118 a: resource.NewSchemaless(),
119 b: resource.NewSchemaless(),
120 want: nil,
121 },
122 {
123 name: "Merge with first resource no keys",
124 a: resource.NewSchemaless(),
125 b: resource.NewSchemaless(kv21),
126 want: []attribute.KeyValue{kv21},
127 },
128 {
129 name: "Merge with second resource no keys",
130 a: resource.NewSchemaless(kv11),
131 b: resource.NewSchemaless(),
132 want: []attribute.KeyValue{kv11},
133 },
134 {
135 name: "Merge with first resource nil",
136 a: nil,
137 b: resource.NewSchemaless(kv21),
138 want: []attribute.KeyValue{kv21},
139 },
140 {
141 name: "Merge with second resource nil",
142 a: resource.NewSchemaless(kv11),
143 b: nil,
144 want: []attribute.KeyValue{kv11},
145 },
146 {
147 name: "Merge with first resource value empty string",
148 a: resource.NewSchemaless(kv42),
149 b: resource.NewSchemaless(kv41),
150 want: []attribute.KeyValue{kv41},
151 },
152 {
153 name: "Merge with second resource value empty string",
154 a: resource.NewSchemaless(kv41),
155 b: resource.NewSchemaless(kv42),
156 want: []attribute.KeyValue{kv42},
157 },
158 {
159 name: "Merge with first resource with schema",
160 a: resource.NewWithAttributes(v121, kv41),
161 b: resource.NewSchemaless(kv42),
162 want: []attribute.KeyValue{kv42},
163 schemaURL: v121,
164 },
165 {
166 name: "Merge with second resource with schema",
167 a: resource.NewSchemaless(kv41),
168 b: resource.NewWithAttributes(v121, kv42),
169 want: []attribute.KeyValue{kv42},
170 schemaURL: v121,
171 },
172 {
173 name: "Merge with different schemas",
174 a: resource.NewWithAttributes(v121, kv41),
175 b: resource.NewWithAttributes("https://opentelemetry.io/schemas/1.20.0", kv42),
176 want: []attribute.KeyValue{kv42},
177 isErr: true,
178 },
179 }
180 for _, c := range cases {
181 t.Run(fmt.Sprintf("case-%s", c.name), func(t *testing.T) {
182 res, err := resource.Merge(c.a, c.b)
183 if c.isErr {
184 assert.Error(t, err)
185 } else {
186 assert.NoError(t, err)
187 }
188 assert.Equal(t, c.schemaURL, res.SchemaURL())
189 if diff := cmp.Diff(
190 res.Attributes(),
191 c.want,
192 cmp.AllowUnexported(attribute.Value{})); diff != "" {
193 t.Fatalf("unwanted result: diff %+v,", diff)
194 }
195 })
196 }
197 }
198
199 func TestMergeIdempotent(t *testing.T) {
200 r := resource.NewSchemaless(
201 attribute.String("k1", "v1"),
202 attribute.String("k2", "v2"),
203 )
204
205 merged, err := resource.Merge(r, r)
206 require.NoError(t, err)
207
208 require.True(t, r.Equal(merged))
209 require.Equal(t, r.SchemaURL(), merged.SchemaURL())
210 }
211
212 func TestMergeIdempotentWithSchema(t *testing.T) {
213 r := resource.NewWithAttributes(
214 v121,
215 attribute.String("k1", "v1"),
216 attribute.String("k2", "v2"),
217 )
218
219 merged, err := resource.Merge(r, r)
220 require.NoError(t, err)
221
222 require.True(t, r.Equal(merged))
223 require.Equal(t, r.SchemaURL(), merged.SchemaURL())
224 }
225
226 func TestEmpty(t *testing.T) {
227 var res *resource.Resource
228 assert.Empty(t, res.SchemaURL())
229 assert.Empty(t, res.String())
230 assert.Equal(t, []attribute.KeyValue(nil), res.Attributes())
231
232 it := res.Iter()
233 assert.Equal(t, 0, it.Len())
234 assert.True(t, res.Equal(res))
235 }
236
237 func TestDefault(t *testing.T) {
238 res := resource.Default()
239 require.False(t, res.Equal(resource.Empty()))
240 require.True(t, res.Set().HasValue(semconv.ServiceNameKey))
241
242 serviceName, _ := res.Set().Value(semconv.ServiceNameKey)
243 require.True(t, strings.HasPrefix(serviceName.AsString(), "unknown_service:"))
244 require.Greaterf(t, len(serviceName.AsString()), len("unknown_service:"),
245 "default service.name should include executable name")
246
247 require.Contains(t, res.Attributes(), semconv.TelemetrySDKLanguageGo)
248 require.Contains(t, res.Attributes(), semconv.TelemetrySDKVersion(sdk.Version()))
249 require.Contains(t, res.Attributes(), semconv.TelemetrySDKName("opentelemetry"))
250 }
251
252 func TestDefaultWithContext(t *testing.T) {
253 ctx := t.Context()
254 res1 := resource.DefaultWithContext(ctx)
255 res2 := resource.DefaultWithContext(ctx)
256 assert.Same(t, res1, res2)
257 }
258
259 func TestEnvironmentWithContext(t *testing.T) {
260 t.Setenv(envVar, "key=value")
261 ctx := t.Context()
262 res := resource.EnvironmentWithContext(ctx)
263 assert.Equal(t, map[string]string{"key": "value"}, toMap(res))
264 }
265
266 func TestEquivalentStability(t *testing.T) {
267 r1 := resource.NewSchemaless(
268 attribute.String("a", "1"),
269 attribute.String("b", "2"),
270 )
271
272 r2 := resource.NewSchemaless(
273 attribute.String("b", "2"),
274 attribute.String("a", "1"),
275 )
276
277 require.Equal(t, r1.Equivalent(), r2.Equivalent())
278 require.True(t, r1.Equal(r2))
279 }
280
281 func TestString(t *testing.T) {
282 for _, test := range []struct {
283 kvs []attribute.KeyValue
284 want string
285 }{
286 {
287 kvs: nil,
288 want: "",
289 },
290 {
291 kvs: []attribute.KeyValue{},
292 want: "",
293 },
294 {
295 kvs: []attribute.KeyValue{kv11},
296 want: "k1=v11",
297 },
298 {
299 kvs: []attribute.KeyValue{kv11, kv12},
300 want: "k1=v12",
301 },
302 {
303 kvs: []attribute.KeyValue{kv11, kv21},
304 want: "k1=v11,k2=v21",
305 },
306 {
307 kvs: []attribute.KeyValue{kv21, kv11},
308 want: "k1=v11,k2=v21",
309 },
310 {
311 kvs: []attribute.KeyValue{kv11, kv21, kv31},
312 want: "k1=v11,k2=v21,k3=v31",
313 },
314 {
315 kvs: []attribute.KeyValue{kv31, kv11, kv21},
316 want: "k1=v11,k2=v21,k3=v31",
317 },
318 {
319 kvs: []attribute.KeyValue{attribute.String("A", "a"), attribute.String("B", "b")},
320 want: "A=a,B=b",
321 },
322 {
323 kvs: []attribute.KeyValue{attribute.String("A", "a,B=b")},
324 want: `A=a\,B\=b`,
325 },
326 {
327 kvs: []attribute.KeyValue{attribute.String("A", `a,B\=b`)},
328 want: `A=a\,B\\\=b`,
329 },
330 {
331 kvs: []attribute.KeyValue{attribute.String("A=a,B", `b`)},
332 want: `A\=a\,B=b`,
333 },
334 {
335 kvs: []attribute.KeyValue{attribute.String(`A=a\,B`, `b`)},
336 want: `A\=a\\\,B=b`,
337 },
338 {
339 kvs: []attribute.KeyValue{attribute.String("", "invalid")},
340 want: "",
341 },
342 {
343 kvs: []attribute.KeyValue{attribute.String("", "invalid"), attribute.String("B", "b")},
344 want: "B=b",
345 },
346 } {
347 if got := resource.NewSchemaless(test.kvs...).String(); got != test.want {
348 t.Errorf("Resource(%v).String() = %q, want %q", test.kvs, got, test.want)
349 }
350 }
351 }
352
353 const envVar = "OTEL_RESOURCE_ATTRIBUTES"
354
355 func TestMarshalJSON(t *testing.T) {
356 r := resource.NewSchemaless(attribute.Int64("A", 1), attribute.String("C", "D"))
357 data, err := json.Marshal(r)
358 require.NoError(t, err)
359 require.JSONEq(t,
360 `[{"Key":"A","Value":{"Type":"INT64","Value":1}},{"Key":"C","Value":{"Type":"STRING","Value":"D"}}]`,
361 string(data))
362 }
363
364 func TestNew(t *testing.T) {
365 tc := []struct {
366 name string
367 envars string
368 detectors []resource.Detector
369 options []resource.Option
370
371 resourceValues map[string]string
372 schemaURL string
373 wantErr error
374 }{
375 {
376 name: "No Options returns empty resource",
377 envars: "key=value,other=attr",
378 options: nil,
379 resourceValues: map[string]string{},
380 },
381 {
382 name: "Nil Detectors works",
383 envars: "key=value,other=attr",
384 options: []resource.Option{
385 resource.WithDetectors(),
386 },
387 resourceValues: map[string]string{},
388 },
389 {
390 name: "Only Host",
391 envars: "from=here",
392 options: []resource.Option{
393 resource.WithHost(),
394 },
395 resourceValues: map[string]string{
396 "host.name": hostname(),
397 },
398 schemaURL: semconv.SchemaURL,
399 },
400 {
401 name: "Only Env",
402 envars: "key=value,other=attr",
403 options: []resource.Option{
404 resource.WithFromEnv(),
405 },
406 resourceValues: map[string]string{
407 "key": "value",
408 "other": "attr",
409 },
410 },
411 {
412 name: "Only TelemetrySDK",
413 envars: "",
414 options: []resource.Option{
415 resource.WithTelemetrySDK(),
416 },
417 resourceValues: map[string]string{
418 "telemetry.sdk.name": "opentelemetry",
419 "telemetry.sdk.language": "go",
420 "telemetry.sdk.version": sdk.Version(),
421 },
422 schemaURL: semconv.SchemaURL,
423 },
424 {
425 name: "WithAttributes",
426 envars: "key=value,other=attr",
427 options: []resource.Option{
428 resource.WithAttributes(attribute.String("A", "B")),
429 },
430 resourceValues: map[string]string{
431 "A": "B",
432 },
433 },
434 {
435 name: "With schema url",
436 envars: "",
437 options: []resource.Option{
438 resource.WithAttributes(attribute.String("A", "B")),
439 resource.WithSchemaURL(v121),
440 },
441 resourceValues: map[string]string{
442 "A": "B",
443 },
444 schemaURL: v121,
445 },
446 {
447 name: "With conflicting schema urls",
448 envars: "",
449 options: []resource.Option{
450 resource.WithDetectors(
451 resource.StringDetector(
452 "https://opentelemetry.io/schemas/1.20.0",
453 semconv.HostNameKey,
454 os.Hostname,
455 ),
456 ),
457 resource.WithSchemaURL(v121),
458 },
459 resourceValues: map[string]string{
460 string(semconv.HostNameKey): func() (hostname string) {
461 hostname, _ = os.Hostname()
462 return hostname
463 }(),
464 },
465 schemaURL: "",
466 wantErr: resource.ErrSchemaURLConflict,
467 },
468 {
469 name: "With conflicting detector schema urls",
470 envars: "",
471 options: []resource.Option{
472 resource.WithDetectors(
473 resource.StringDetector(
474 "https://opentelemetry.io/schemas/1.19.0",
475 semconv.HostNameKey,
476 os.Hostname,
477 ),
478 resource.StringDetector(
479 "https://opentelemetry.io/schemas/1.20.0",
480 semconv.HostNameKey,
481 func() (string, error) { return "", errors.New("fail") },
482 ),
483 ),
484 resource.WithSchemaURL(v121),
485 },
486 resourceValues: map[string]string{
487 string(semconv.HostNameKey): func() (hostname string) {
488 hostname, _ = os.Hostname()
489 return hostname
490 }(),
491 },
492 schemaURL: "",
493 wantErr: resource.ErrSchemaURLConflict,
494 },
495 }
496 for _, tt := range tc {
497 t.Run(tt.name, func(t *testing.T) {
498 t.Setenv(envVar, tt.envars)
499 ctx := t.Context()
500 res, err := resource.New(ctx, tt.options...)
501
502 if tt.wantErr != nil {
503 assert.ErrorIs(t, err, tt.wantErr)
504 } else {
505 assert.NoError(t, err)
506 }
507
508 require.Equal(t, tt.resourceValues, toMap(res))
509
510 // TODO: do we need to ensure that resource is never nil and eliminate the
511 // following if?
512 if res != nil {
513 assert.Equal(t, tt.schemaURL, res.SchemaURL())
514 }
515 })
516 }
517 }
518
519 func TestNewWrappedError(t *testing.T) {
520 localErr := errors.New("local error")
521 _, err := resource.New(
522 t.Context(),
523 resource.WithDetectors(
524 resource.StringDetector("", "", func() (string, error) {
525 return "", localErr
526 }),
527 resource.StringDetector("", "", func() (string, error) {
528 return "", assert.AnError
529 }),
530 ),
531 )
532
533 assert.ErrorIs(t, err, localErr)
534 assert.ErrorIs(t, err, assert.AnError)
535 assert.NotErrorIs(t, err, errors.New("false positive error"))
536 }
537
538 func TestWithHostID(t *testing.T) {
539 mockHostIDProvider()
540 t.Cleanup(restoreHostIDProvider)
541
542 ctx := t.Context()
543
544 res, err := resource.New(ctx,
545 resource.WithHostID(),
546 )
547
548 require.NoError(t, err)
549 require.Equal(t, map[string]string{
550 "host.id": "f2c668b579780554f70f72a063dc0864",
551 }, toMap(res))
552 }
553
554 func TestWithHostIDError(t *testing.T) {
555 mockHostIDProviderWithError()
556 t.Cleanup(restoreHostIDProvider)
557
558 ctx := t.Context()
559
560 res, err := resource.New(ctx,
561 resource.WithHostID(),
562 )
563
564 assert.ErrorIs(t, err, assert.AnError)
565 require.Equal(t, map[string]string{}, toMap(res))
566 }
567
568 func TestWithOSType(t *testing.T) {
569 mockRuntimeProviders()
570 t.Cleanup(restoreAttributesProviders)
571
572 ctx := t.Context()
573
574 res, err := resource.New(ctx,
575 resource.WithOSType(),
576 )
577
578 require.NoError(t, err)
579 require.Equal(t, map[string]string{
580 "os.type": "linux",
581 }, toMap(res))
582 }
583
584 func TestWithOSDescription(t *testing.T) {
585 mockRuntimeProviders()
586 t.Cleanup(restoreAttributesProviders)
587
588 ctx := t.Context()
589
590 res, err := resource.New(ctx,
591 resource.WithOSDescription(),
592 )
593
594 require.NoError(t, err)
595 require.Equal(t, map[string]string{
596 "os.description": "Test",
597 }, toMap(res))
598 }
599
600 func TestWithOS(t *testing.T) {
601 mockRuntimeProviders()
602 t.Cleanup(restoreAttributesProviders)
603
604 ctx := t.Context()
605
606 res, err := resource.New(ctx,
607 resource.WithOS(),
608 )
609
610 require.NoError(t, err)
611 require.Equal(t, map[string]string{
612 "os.type": "linux",
613 "os.description": "Test",
614 }, toMap(res))
615 }
616
617 func TestWithProcessPID(t *testing.T) {
618 mockProcessAttributesProvidersWithErrors()
619 ctx := t.Context()
620
621 res, err := resource.New(ctx,
622 resource.WithProcessPID(),
623 )
624
625 require.NoError(t, err)
626 require.Equal(t, map[string]string{
627 "process.pid": fmt.Sprint(fakePID),
628 }, toMap(res))
629 }
630
631 func TestWithProcessExecutableName(t *testing.T) {
632 mockProcessAttributesProvidersWithErrors()
633 ctx := t.Context()
634
635 res, err := resource.New(ctx,
636 resource.WithProcessExecutableName(),
637 )
638
639 require.NoError(t, err)
640 require.Equal(t, map[string]string{
641 "process.executable.name": fakeExecutableName,
642 }, toMap(res))
643 }
644
645 func TestWithProcessExecutablePath(t *testing.T) {
646 mockProcessAttributesProviders()
647 ctx := t.Context()
648
649 res, err := resource.New(ctx,
650 resource.WithProcessExecutablePath(),
651 )
652
653 require.NoError(t, err)
654 require.Equal(t, map[string]string{
655 "process.executable.path": fakeExecutablePath,
656 }, toMap(res))
657 }
658
659 func TestWithProcessCommandArgs(t *testing.T) {
660 mockProcessAttributesProvidersWithErrors()
661 ctx := t.Context()
662
663 res, err := resource.New(ctx,
664 resource.WithProcessCommandArgs(),
665 )
666
667 require.NoError(t, err)
668 jsonCommandArgs, _ := json.Marshal(fakeCommandArgs)
669 require.Equal(t, map[string]string{
670 "process.command_args": string(jsonCommandArgs),
671 }, toMap(res))
672 }
673
674 func TestWithProcessOwner(t *testing.T) {
675 mockProcessAttributesProviders()
676 ctx := t.Context()
677
678 res, err := resource.New(ctx,
679 resource.WithProcessOwner(),
680 )
681
682 require.NoError(t, err)
683 require.Equal(t, map[string]string{
684 "process.owner": fakeOwner,
685 }, toMap(res))
686 }
687
688 func TestWithProcessRuntimeName(t *testing.T) {
689 mockProcessAttributesProvidersWithErrors()
690 ctx := t.Context()
691
692 res, err := resource.New(ctx,
693 resource.WithProcessRuntimeName(),
694 )
695
696 require.NoError(t, err)
697 require.Equal(t, map[string]string{
698 "process.runtime.name": fakeRuntimeName,
699 }, toMap(res))
700 }
701
702 func TestWithProcessRuntimeVersion(t *testing.T) {
703 mockProcessAttributesProvidersWithErrors()
704 ctx := t.Context()
705
706 res, err := resource.New(ctx,
707 resource.WithProcessRuntimeVersion(),
708 )
709
710 require.NoError(t, err)
711 require.Equal(t, map[string]string{
712 "process.runtime.version": fakeRuntimeVersion,
713 }, toMap(res))
714 }
715
716 func TestWithProcessRuntimeDescription(t *testing.T) {
717 mockProcessAttributesProvidersWithErrors()
718 ctx := t.Context()
719
720 res, err := resource.New(ctx,
721 resource.WithProcessRuntimeDescription(),
722 )
723
724 require.NoError(t, err)
725 require.Equal(t, map[string]string{
726 "process.runtime.description": fakeRuntimeDescription,
727 }, toMap(res))
728 }
729
730 func TestWithProcess(t *testing.T) {
731 mockProcessAttributesProviders()
732 ctx := t.Context()
733
734 res, err := resource.New(ctx,
735 resource.WithProcess(),
736 )
737
738 require.NoError(t, err)
739 jsonCommandArgs, _ := json.Marshal(fakeCommandArgs)
740 require.Equal(t, map[string]string{
741 "process.pid": fmt.Sprint(fakePID),
742 "process.executable.name": fakeExecutableName,
743 "process.executable.path": fakeExecutablePath,
744 "process.command_args": string(jsonCommandArgs),
745 "process.owner": fakeOwner,
746 "process.runtime.name": fakeRuntimeName,
747 "process.runtime.version": fakeRuntimeVersion,
748 "process.runtime.description": fakeRuntimeDescription,
749 }, toMap(res))
750 }
751
752 func toMap(res *resource.Resource) map[string]string {
753 m := map[string]string{}
754 for _, attr := range res.Attributes() {
755 m[string(attr.Key)] = attr.Value.Emit()
756 }
757 return m
758 }
759
760 func hostname() string {
761 hn, err := os.Hostname()
762 if err != nil {
763 return fmt.Sprintf("hostname(%s)", err)
764 }
765 return hn
766 }
767
768 func TestWithContainerID(t *testing.T) {
769 t.Cleanup(restoreAttributesProviders)
770
771 fakeContainerID := "fake-container-id"
772
773 testCases := []struct {
774 name string
775 containerIDProvider func() (string, error)
776 expectedResource map[string]string
777 expectedErr bool
778 }{
779 {
780 name: "get container id",
781 containerIDProvider: func() (string, error) {
782 return fakeContainerID, nil
783 },
784 expectedResource: map[string]string{
785 string(semconv.ContainerIDKey): fakeContainerID,
786 },
787 },
788 {
789 name: "no container id found",
790 containerIDProvider: func() (string, error) {
791 return "", nil
792 },
793 expectedResource: map[string]string{},
794 },
795 {
796 name: "error",
797 containerIDProvider: func() (string, error) {
798 return "", fmt.Errorf("unable to get container id")
799 },
800 expectedResource: map[string]string{},
801 expectedErr: true,
802 },
803 }
804
805 for _, tc := range testCases {
806 t.Run(tc.name, func(t *testing.T) {
807 resource.SetContainerProviders(tc.containerIDProvider)
808
809 res, err := resource.New(t.Context(),
810 resource.WithContainerID(),
811 )
812
813 if tc.expectedErr {
814 assert.Error(t, err)
815 }
816 assert.Equal(t, tc.expectedResource, toMap(res))
817 })
818 }
819 }
820
821 func TestWithContainer(t *testing.T) {
822 t.Cleanup(restoreAttributesProviders)
823
824 fakeContainerID := "fake-container-id"
825 resource.SetContainerProviders(func() (string, error) {
826 return fakeContainerID, nil
827 })
828
829 res, err := resource.New(t.Context(),
830 resource.WithContainer(),
831 )
832
833 assert.NoError(t, err)
834 assert.Equal(t, map[string]string{
835 string(semconv.ContainerIDKey): fakeContainerID,
836 }, toMap(res))
837 }
838
839 func TestWithService(t *testing.T) {
840 res, err := resource.New(t.Context(),
841 resource.WithService(),
842 )
843
844 assert.NoError(t, err)
845
846 resMap := toMap(res)
847
848 // Verify service.name exists
849 _, ok := resMap[string(semconv.ServiceNameKey)]
850 require.True(t, ok, "service.name should be present")
851
852 // Verify service.instance.id exists
853 _, ok = resMap[string(semconv.ServiceInstanceIDKey)]
854 require.True(t, ok, "service.instance.id should be present")
855 }
856
857 func TestResourceConcurrentSafe(t *testing.T) {
858 // Creating Resources should also be free of any data races,
859 // because Resources are immutable.
860 var wg sync.WaitGroup
861 for range 2 {
862 wg.Go(func() {
863 d := &fakeDetector{}
864 _, err := resource.Detect(t.Context(), d)
865 assert.NoError(t, err)
866 })
867 }
868 wg.Wait()
869 }
870
871 type fakeDetector struct{}
872
873 func (fakeDetector) Detect(context.Context) (*resource.Resource, error) {
874 // A bit pedantic, but resource.NewWithAttributes returns an empty Resource when
875 // no attributes specified. We want to make sure that this is concurrent-safe.
876 return resource.NewWithAttributes(v121), nil
877 }
878
879 var _ resource.Detector = &fakeDetector{}