| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package resource_test |
| 5 |
|
| 6 |
import ( |
| 7 |
"fmt" |
| 8 |
"testing" |
| 9 |
|
| 10 |
"github.com/stretchr/testify/require" |
| 11 |
|
| 12 |
"go.opentelemetry.io/otel/attribute" |
| 13 |
"go.opentelemetry.io/otel/sdk/resource" |
| 14 |
) |
| 15 |
|
| 16 |
func TestBuiltinStringDetector(t *testing.T) { |
| 17 |
E := fmt.Errorf("no K") |
| 18 |
res, err := resource.StringDetector("", attribute.Key("K"), func() (string, error) { |
| 19 |
return "", E |
| 20 |
}).Detect(t.Context()) |
| 21 |
require.ErrorIs(t, err, E) |
| 22 |
require.NotEqual(t, E, err) |
| 23 |
require.Nil(t, res) |
| 24 |
} |
| 25 |
|
| 26 |
func TestStringDetectorErrors(t *testing.T) { |
| 27 |
tests := []struct { |
| 28 |
desc string |
| 29 |
s resource.Detector |
| 30 |
errContains string |
| 31 |
}{ |
| 32 |
{ |
| 33 |
desc: "explicit error from func should be returned", |
| 34 |
s: resource.StringDetector("", attribute.Key("K"), func() (string, error) { |
| 35 |
return "", fmt.Errorf("k-is-missing") |
| 36 |
}), |
| 37 |
errContains: "k-is-missing", |
| 38 |
}, |
| 39 |
{ |
| 40 |
desc: "empty key is an invalid", |
| 41 |
s: resource.StringDetector("", attribute.Key(""), func() (string, error) { |
| 42 |
return "not-empty", nil |
| 43 |
}), |
| 44 |
errContains: "invalid attribute: \"\" -> \"not-empty\"", |
| 45 |
}, |
| 46 |
} |
| 47 |
|
| 48 |
for _, test := range tests { |
| 49 |
res, err := resource.New( |
| 50 |
t.Context(), |
| 51 |
resource.WithAttributes(attribute.String("A", "B")), |
| 52 |
resource.WithDetectors(test.s), |
| 53 |
) |
| 54 |
require.Error(t, err, test.desc) |
| 55 |
require.Contains(t, err.Error(), test.errContains) |
| 56 |
require.NotNil(t, res, "resource contains remaining valid entries") |
| 57 |
|
| 58 |
m := map[string]string{} |
| 59 |
for _, kv := range res.Attributes() { |
| 60 |
m[string(kv.Key)] = kv.Value.Emit() |
| 61 |
} |
| 62 |
require.Equal(t, map[string]string{"A": "B"}, m) |
| 63 |
} |
| 64 |
} |