...

Source file src/go.opentelemetry.io/otel/sdk/resource/builtin_test.go

Documentation: go.opentelemetry.io/otel/sdk/resource

     1  // Copyright The OpenTelemetry Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package resource_test
    16  
    17  import (
    18  	"context"
    19  	"errors"
    20  	"fmt"
    21  	"testing"
    22  
    23  	"github.com/stretchr/testify/require"
    24  
    25  	"go.opentelemetry.io/otel/attribute"
    26  	"go.opentelemetry.io/otel/sdk/resource"
    27  )
    28  
    29  func TestBuiltinStringDetector(t *testing.T) {
    30  	E := fmt.Errorf("no K")
    31  	res, err := resource.StringDetector("", attribute.Key("K"), func() (string, error) {
    32  		return "", E
    33  	}).Detect(context.Background())
    34  	require.True(t, errors.Is(err, E))
    35  	require.NotEqual(t, E, err)
    36  	require.Nil(t, res)
    37  }
    38  
    39  func TestStringDetectorErrors(t *testing.T) {
    40  	tests := []struct {
    41  		desc        string
    42  		s           resource.Detector
    43  		errContains string
    44  	}{
    45  		{
    46  			desc: "explicit error from func should be returned",
    47  			s: resource.StringDetector("", attribute.Key("K"), func() (string, error) {
    48  				return "", fmt.Errorf("k-is-missing")
    49  			}),
    50  			errContains: "k-is-missing",
    51  		},
    52  		{
    53  			desc: "empty key is an invalid",
    54  			s: resource.StringDetector("", attribute.Key(""), func() (string, error) {
    55  				return "not-empty", nil
    56  			}),
    57  			errContains: "invalid attribute: \"\" -> \"not-empty\"",
    58  		},
    59  	}
    60  
    61  	for _, test := range tests {
    62  		res, err := resource.New(
    63  			context.Background(),
    64  			resource.WithAttributes(attribute.String("A", "B")),
    65  			resource.WithDetectors(test.s),
    66  		)
    67  		require.Error(t, err, test.desc)
    68  		require.Contains(t, err.Error(), test.errContains)
    69  		require.NotNil(t, res, "resource contains remaining valid entries")
    70  
    71  		m := map[string]string{}
    72  		for _, kv := range res.Attributes() {
    73  			m[string(kv.Key)] = kv.Value.Emit()
    74  		}
    75  		require.EqualValues(t, map[string]string{"A": "B"}, m)
    76  	}
    77  }
    78  

View as plain text