|
| 1 | +// Copyright The OpenTelemetry Authors |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +package ottlfuncs |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "errors" |
| 9 | + "testing" |
| 10 | + |
| 11 | + "github.com/stretchr/testify/assert" |
| 12 | + |
| 13 | + "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl" |
| 14 | +) |
| 15 | + |
| 16 | +type getterFunc[K any] func(ctx context.Context, tCtx K) (any, error) |
| 17 | + |
| 18 | +func (g getterFunc[K]) Get(ctx context.Context, tCtx K) (any, error) { |
| 19 | + return g(ctx, tCtx) |
| 20 | +} |
| 21 | + |
| 22 | +func Test_Format(t *testing.T) { |
| 23 | + tests := []struct { |
| 24 | + name string |
| 25 | + formatString string |
| 26 | + formatArgs []ottl.Getter[any] |
| 27 | + expected string |
| 28 | + }{ |
| 29 | + { |
| 30 | + name: "non formatting string", |
| 31 | + formatString: "test", |
| 32 | + formatArgs: []ottl.Getter[any]{}, |
| 33 | + expected: "test", |
| 34 | + }, |
| 35 | + { |
| 36 | + name: "padded int", |
| 37 | + formatString: "test-%04d", |
| 38 | + formatArgs: []ottl.Getter[any]{ |
| 39 | + getterFunc[any](func(_ context.Context, _ any) (any, error) { |
| 40 | + return 2, nil |
| 41 | + }), |
| 42 | + }, |
| 43 | + expected: "test-0002", |
| 44 | + }, |
| 45 | + { |
| 46 | + name: "multiple-args", |
| 47 | + formatString: "test-%04d-%4s", |
| 48 | + formatArgs: []ottl.Getter[any]{ |
| 49 | + getterFunc[any](func(_ context.Context, _ any) (any, error) { |
| 50 | + return 2, nil |
| 51 | + }), |
| 52 | + getterFunc[any](func(_ context.Context, _ any) (any, error) { |
| 53 | + return "te", nil |
| 54 | + }), |
| 55 | + }, |
| 56 | + expected: "test-0002- te", |
| 57 | + }, |
| 58 | + } |
| 59 | + |
| 60 | + for _, tt := range tests { |
| 61 | + t.Run(tt.name, func(t *testing.T) { |
| 62 | + exprFunc := format(tt.formatString, tt.formatArgs) |
| 63 | + result, err := exprFunc(nil, nil) |
| 64 | + assert.NoError(t, err) |
| 65 | + assert.Equal(t, tt.expected, result) |
| 66 | + }) |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +func TestFormat_error(t *testing.T) { |
| 71 | + target := getterFunc[any](func(_ context.Context, _ any) (any, error) { |
| 72 | + return nil, errors.New("failed to get") |
| 73 | + }) |
| 74 | + |
| 75 | + exprFunc := format[any]("test-%d", []ottl.Getter[any]{target}) |
| 76 | + _, err := exprFunc(context.Background(), nil) |
| 77 | + assert.Error(t, err) |
| 78 | +} |
0 commit comments