knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/observability/metrics/metricstest/doc.go (about)

     1  /*
     2  Copyright 2025 The Knative Authors
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  /*
    18  Package metricstest provides test helpers to assert OTel metrics
    19  are recorded properly.
    20  
    21  When setting up your package for unit tests it is recommended that
    22  your instrumentation can be reset between tests. This can be accomplished
    23  using the following structure.
    24  
    25  	func init() {
    26  		resetPackageMetrics()
    27  	}
    28  
    29  	var instrument metric.Int64Counter
    30  
    31  	func resetPackageMetrics() {
    32  		// Reset the meter
    33  		var meter = otel.Meter("com.some.scope")
    34  
    35  		// Reset the instrumentation
    36  		instrument = meter.Int64Counter("some.metric")
    37  	}
    38  
    39  Then in your tests you can setup the metrics pipeline as follows:
    40  
    41  	func TestMetricsRecorded(t *testing.T) {
    42  		reader := metric.NewManualReader()
    43  		provider := metric.NewMeterProvider(metric.WithReader(reader))
    44  
    45  		// Set the global provider
    46  		otel.SetMeterProvider(provider)
    47  
    48  		// This rebuilds instruments with the new provider and directs
    49  		// the metrics to be recorded in the manual reader declared above.
    50  		resetPackageMetrics()
    51  
    52  		doSomething()
    53  
    54  
    55  		metricstest.AssertMetrics(t, reader,
    56  			metricstest.MetricPresent(...),
    57  			metricstest.HasAttributes(...),
    58  		)
    59  	}
    60  */
    61  package metricstest