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 15package processortest_test 16 17import ( 18 "context" 19 "testing" 20 21 "github.com/stretchr/testify/require" 22 23 "go.opentelemetry.io/otel/attribute" 24 "go.opentelemetry.io/otel/metric" 25 export "go.opentelemetry.io/otel/sdk/export/metric" 26 "go.opentelemetry.io/otel/sdk/export/metric/aggregation" 27 "go.opentelemetry.io/otel/sdk/instrumentation" 28 metricsdk "go.opentelemetry.io/otel/sdk/metric" 29 "go.opentelemetry.io/otel/sdk/metric/processor/processortest" 30 processorTest "go.opentelemetry.io/otel/sdk/metric/processor/processortest" 31 "go.opentelemetry.io/otel/sdk/resource" 32) 33 34func generateTestData(proc export.Processor) { 35 ctx := context.Background() 36 accum := metricsdk.NewAccumulator(proc) 37 meter := metric.WrapMeterImpl(accum) 38 39 counter := metric.Must(meter).NewFloat64Counter("counter.sum") 40 41 _ = metric.Must(meter).NewInt64CounterObserver("observer.sum", 42 func(_ context.Context, result metric.Int64ObserverResult) { 43 result.Observe(10, attribute.String("K1", "V1")) 44 result.Observe(11, attribute.String("K1", "V2")) 45 }, 46 ) 47 48 counter.Add(ctx, 100, attribute.String("K1", "V1")) 49 counter.Add(ctx, 101, attribute.String("K1", "V2")) 50 51 accum.Collect(ctx) 52} 53 54func TestProcessorTesting(t *testing.T) { 55 // Test the Processor test helper using a real Accumulator to 56 // generate Accumulations. 57 checkpointer := processorTest.NewCheckpointer( 58 processorTest.NewProcessor( 59 processorTest.AggregatorSelector(), 60 attribute.DefaultEncoder(), 61 ), 62 ) 63 generateTestData(checkpointer) 64 65 res := resource.NewSchemaless(attribute.String("R", "V")) 66 expect := map[string]float64{ 67 "counter.sum/K1=V1/R=V": 100, 68 "counter.sum/K1=V2/R=V": 101, 69 "observer.sum/K1=V1/R=V": 10, 70 "observer.sum/K1=V2/R=V": 11, 71 } 72 73 // Export the data and validate it again. 74 exporter := processorTest.New( 75 aggregation.StatelessTemporalitySelector(), 76 attribute.DefaultEncoder(), 77 ) 78 79 err := exporter.Export(context.Background(), res, processortest.OneInstrumentationLibraryReader( 80 instrumentation.Library{ 81 Name: "test", 82 }, 83 checkpointer.Reader(), 84 )) 85 require.NoError(t, err) 86 require.EqualValues(t, expect, exporter.Values()) 87} 88