| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package resource_test |
| 5 |
|
| 6 |
import ( |
| 7 |
"context" |
| 8 |
"errors" |
| 9 |
"fmt" |
| 10 |
"testing" |
| 11 |
|
| 12 |
"github.com/stretchr/testify/assert" |
| 13 |
|
| 14 |
"go.opentelemetry.io/otel/attribute" |
| 15 |
"go.opentelemetry.io/otel/sdk/resource" |
| 16 |
) |
| 17 |
|
| 18 |
type detector struct { |
| 19 |
SchemaURL string |
| 20 |
Attributes []attribute.KeyValue |
| 21 |
} |
| 22 |
|
| 23 |
func newDetector(schemaURL string, attrs ...attribute.KeyValue) resource.Detector { |
| 24 |
return detector{schemaURL, attrs} |
| 25 |
} |
| 26 |
|
| 27 |
func (d detector) Detect(context.Context) (*resource.Resource, error) { |
| 28 |
return resource.NewWithAttributes(d.SchemaURL, d.Attributes...), nil |
| 29 |
} |
| 30 |
|
| 31 |
func TestDetect(t *testing.T) { |
| 32 |
v130 := "https://opentelemetry.io/schemas/1.3.0" |
| 33 |
v140 := "https://opentelemetry.io/schemas/1.4.0" |
| 34 |
v150 := "https://opentelemetry.io/schemas/1.5.0" |
| 35 |
|
| 36 |
alice := attribute.String("name", "Alice") |
| 37 |
bob := attribute.String("name", "Bob") |
| 38 |
carol := attribute.String("name", "Carol") |
| 39 |
|
| 40 |
admin := attribute.Bool("admin", true) |
| 41 |
user := attribute.Bool("admin", false) |
| 42 |
|
| 43 |
cases := []struct { |
| 44 |
name string |
| 45 |
detectors []resource.Detector |
| 46 |
want *resource.Resource |
| 47 |
wantErr error |
| 48 |
}{ |
| 49 |
{ |
| 50 |
name: "two different schema urls", |
| 51 |
detectors: []resource.Detector{ |
| 52 |
newDetector(v130, alice, admin), |
| 53 |
newDetector(v140, bob, user), |
| 54 |
}, |
| 55 |
want: resource.NewSchemaless(bob, user), |
| 56 |
wantErr: resource.ErrSchemaURLConflict, |
| 57 |
}, |
| 58 |
{ |
| 59 |
name: "three different schema urls", |
| 60 |
detectors: []resource.Detector{ |
| 61 |
newDetector(v130, alice, admin), |
| 62 |
newDetector(v140, bob, user), |
| 63 |
newDetector(v150, carol), |
| 64 |
}, |
| 65 |
want: resource.NewSchemaless(carol, user), |
| 66 |
wantErr: resource.ErrSchemaURLConflict, |
| 67 |
}, |
| 68 |
{ |
| 69 |
name: "same schema url", |
| 70 |
detectors: []resource.Detector{ |
| 71 |
newDetector(v140, alice, admin), |
| 72 |
newDetector(v140, bob, user), |
| 73 |
}, |
| 74 |
want: resource.NewWithAttributes(v140, bob, user), |
| 75 |
}, |
| 76 |
} |
| 77 |
|
| 78 |
for _, c := range cases { |
| 79 |
t.Run(fmt.Sprintf("case-%s", c.name), func(t *testing.T) { |
| 80 |
r, err := resource.Detect(t.Context(), c.detectors...) |
| 81 |
if c.wantErr != nil { |
| 82 |
assert.ErrorIs(t, err, c.wantErr) |
| 83 |
if errors.Is(c.wantErr, resource.ErrSchemaURLConflict) { |
| 84 |
assert.Empty(t, r.SchemaURL()) |
| 85 |
} |
| 86 |
} else { |
| 87 |
assert.NoError(t, err) |
| 88 |
} |
| 89 |
assert.Equal(t, c.want.SchemaURL(), r.SchemaURL()) |
| 90 |
assert.ElementsMatch(t, c.want.Attributes(), r.Attributes()) |
| 91 |
}) |
| 92 |
} |
| 93 |
} |