Package oteltest provides testing utilities for the otel package.

This package is currently in a pre-GA phase. Backwards incompatible changes may be introduced in subsequent minor version releases as we work to track the evolving OpenTelemetry specification and user feedback.

API Validation

The Harness can be used to validate an implementation of the OpenTelemetry API defined by the `otel` package.

func TestCustomSDKTracingImplementation(t *testing.T) {
	yourTraceProvider := NewTracerProvider()
	subjectFactory := func() otel.Tracer {
		return yourTraceProvider.Tracer("testing")


Currently the Harness only provides testing of the trace portion of the OpenTelemetry API.

Trace Testing

To test tracing functionality a full testing implementation of the OpenTelemetry tracing API are provided. The provided TracerProvider, Tracer, and Span all implement their related interface and are designed to allow introspection of their state and history. Additionally, a SpanRecorder can be provided to the TracerProvider to record all Spans started and ended by the testing structures.

sr := new(oteltest.SpanRecorder)
tp := oteltest.NewTracerProvider(oteltest.WithSpanRecorder(sr))



This section is empty.


This section is empty.


func DefaultTracer

func DefaultTracer() trace.Tracer

    DefaulTracer returns a default tracer for testing purposes.

    func LabelsToMap

    func LabelsToMap(kvs ...attribute.KeyValue) map[attribute.Key]attribute.Value

      LabelsToMap converts label set to keyValue map, to be easily used in tests

      func ResolveNumberByKind

      func ResolveNumberByKind(t *testing.T, kind number.Kind, value float64) number.Number

        ResolveNumberByKind takes defined metric descriptor creates a concrete typed metric number


        type Async

        type Async struct {
        	// contains filtered or unexported fields

        func (*Async) Implementation

        func (a *Async) Implementation() interface{}

        type Batch

        type Batch struct {
        	// Measurement needs to be aligned for 64-bit atomic operations.
        	Measurements []Measurement
        	Ctx          context.Context
        	Labels       []attribute.KeyValue
        	LibraryName  string

        type Event

        type Event struct {
        	Timestamp  time.Time
        	Name       string
        	Attributes map[attribute.Key]attribute.Value

          Event encapsulates the properties of calls to AddEvent.

          type Handle

          type Handle struct {
          	Instrument *Sync
          	Labels     []attribute.KeyValue

          func (*Handle) RecordOne

          func (h *Handle) RecordOne(ctx context.Context, number number.Number)

          func (*Handle) Unbind

          func (h *Handle) Unbind()

          type Harness

          type Harness struct {
          	// contains filtered or unexported fields

            Harness is a testing harness used to test implementations of the OpenTelemetry API.

            func NewHarness

            func NewHarness(t *testing.T) *Harness

              NewHarness returns an instantiated *Harness using t.

              func (*Harness) TestTracer

              func (h *Harness) TestTracer(subjectFactory func() trace.Tracer)

                TestTracer runs validation tests for an implementation of the OpenTelemetry Tracer API.

                type Instrument

                type Instrument struct {
                	// contains filtered or unexported fields

                func (Instrument) Descriptor

                func (i Instrument) Descriptor() metric.Descriptor

                type Measured

                type Measured struct {
                	Name                   string
                	InstrumentationName    string
                	InstrumentationVersion string
                	Labels                 map[attribute.Key]attribute.Value
                	Number                 number.Number

                  Measured is the helper struct which provides flat representation of recorded measurements to simplify testing

                  func AsStructs

                  func AsStructs(batches []Batch) []Measured

                    AsStructs converts recorded batches to array of flat, readable Measured helper structures

                    type Measurement

                    type Measurement struct {
                    	// Number needs to be aligned for 64-bit atomic operations.
                    	Number     number.Number
                    	Instrument metric.InstrumentImpl

                    type MeterImpl

                    type MeterImpl struct {
                    	MeasurementBatches []Batch
                    	// contains filtered or unexported fields

                      MeterImpl is an OpenTelemetry Meter implementation used for testing.

                      func NewMeter

                      func NewMeter() (*MeterImpl, metric.Meter)

                      func NewMeterProvider

                      func NewMeterProvider() (*MeterImpl, metric.MeterProvider)

                      func (*MeterImpl) CollectAsync

                      func (m *MeterImpl) CollectAsync(labels []attribute.KeyValue, obs ...metric.Observation)

                      func (*MeterImpl) NewAsyncInstrument

                      func (m *MeterImpl) NewAsyncInstrument(descriptor metric.Descriptor, runner metric.AsyncRunner) (metric.AsyncImpl, error)

                      func (*MeterImpl) NewSyncInstrument

                      func (m *MeterImpl) NewSyncInstrument(descriptor metric.Descriptor) (metric.SyncImpl, error)

                      func (*MeterImpl) RecordBatch

                      func (m *MeterImpl) RecordBatch(ctx context.Context, labels []attribute.KeyValue, measurements ...metric.Measurement)

                      func (*MeterImpl) RunAsyncInstruments

                      func (m *MeterImpl) RunAsyncInstruments()

                      type Option

                      type Option interface {
                      	// contains filtered or unexported methods

                        Option applies an option to a config.

                        func WithSpanContextFunc

                        func WithSpanContextFunc(f func(context.Context) trace.SpanContext) Option

                          WithSpanContextFunc sets the SpanContextFunc used to generate a new Spans context from a parent SpanContext.

                          func WithSpanRecorder

                          func WithSpanRecorder(sr *SpanRecorder) Option

                            WithSpanRecorder sets the SpanRecorder to use with the TracerProvider for testing.

                            type Span

                            type Span struct {
                            	// contains filtered or unexported fields

                              Span is an OpenTelemetry Span used for testing.

                              func (*Span) AddEvent

                              func (s *Span) AddEvent(name string, o ...trace.EventOption)

                                AddEvent adds an event to s.

                                func (*Span) Attributes

                                func (s *Span) Attributes() map[attribute.Key]attribute.Value

                                  Attributes returns the attributes set on s, either at or after creation time. If the same attribute key was set multiple times, the last call will be used. Attributes cannot be changed after End has been called on s.

                                  func (*Span) End

                                  func (s *Span) End(opts ...trace.SpanOption)

                                    End ends s. If the Tracer that created s was configured with a SpanRecorder, that recorder's OnEnd method is called as the final part of this method.

                                    func (*Span) EndTime

                                    func (s *Span) EndTime() (time.Time, bool)

                                      EndTime returns the time at which s was ended if at has been ended, or false otherwise. If the span has been ended, the returned time will be the wall-clock time unless a specific end time was provided.

                                      func (*Span) Ended

                                      func (s *Span) Ended() bool

                                        Ended returns whether s has been ended, i.e. whether End has been called at least once on s.

                                        func (*Span) Events

                                        func (s *Span) Events() []Event

                                          Events returns the events set on s. Events cannot be changed after End has been called on s.

                                          func (*Span) IsRecording

                                          func (s *Span) IsRecording() bool

                                            IsRecording returns the recording state of s.

                                            func (s *Span) Links() []trace.Link

                                              Links returns the links set on s at creation time. If multiple links for the same SpanContext were set, the last link will be used.

                                              func (*Span) Name

                                              func (s *Span) Name() string

                                                Name returns the name most recently set on s, either at or after creation time. It cannot be change after End has been called on s.

                                                func (*Span) ParentSpanID

                                                func (s *Span) ParentSpanID() trace.SpanID

                                                  ParentSpanID returns the SpanID of the parent Span. If s is a root Span, and therefore does not have a parent, the returned SpanID will be invalid (i.e., it will contain all zeroes).

                                                  func (*Span) RecordError

                                                  func (s *Span) RecordError(err error, opts ...trace.EventOption)

                                                    RecordError records an error as a Span event.

                                                    func (*Span) SetAttributes

                                                    func (s *Span) SetAttributes(attrs ...attribute.KeyValue)

                                                      SetAttributes sets attrs as attributes of s.

                                                      func (*Span) SetName

                                                      func (s *Span) SetName(name string)

                                                        SetName sets the name of s.

                                                        func (*Span) SetStatus

                                                        func (s *Span) SetStatus(code codes.Code, msg string)

                                                          SetStatus sets the status of s in the form of a code and a message.

                                                          func (*Span) SpanContext

                                                          func (s *Span) SpanContext() trace.SpanContext

                                                            SpanContext returns the SpanContext of s.

                                                            func (*Span) SpanKind

                                                            func (s *Span) SpanKind() trace.SpanKind

                                                              SpanKind returns the span kind of s.

                                                              func (*Span) StartTime

                                                              func (s *Span) StartTime() time.Time

                                                                StartTime returns the time at which s was started. This will be the wall-clock time unless a specific start time was provided.

                                                                func (*Span) StatusCode

                                                                func (s *Span) StatusCode() codes.Code

                                                                  StatusCode returns the code of the status most recently set on s, or codes.OK if no status has been explicitly set. It cannot be changed after End has been called on s.

                                                                  func (*Span) StatusMessage

                                                                  func (s *Span) StatusMessage() string

                                                                    StatusMessage returns the status message most recently set on s or the empty string if no status message was set.

                                                                    func (*Span) Tracer

                                                                    func (s *Span) Tracer() trace.Tracer

                                                                      Tracer returns the Tracer that created s.

                                                                      type SpanRecorder

                                                                      type SpanRecorder struct {
                                                                      	// contains filtered or unexported fields

                                                                        SpanRecorder performs operations to record a span as it starts and ends. It is designed to be concurrent safe and can by used by multiple goroutines.

                                                                        func (*SpanRecorder) Completed

                                                                        func (ssr *SpanRecorder) Completed() []*Span

                                                                          Completed returns a copy of all ended Spans in the order they were ended.

                                                                          func (*SpanRecorder) OnEnd

                                                                          func (ssr *SpanRecorder) OnEnd(span *Span)

                                                                            OnEnd records span as completed.

                                                                            func (*SpanRecorder) OnStart

                                                                            func (ssr *SpanRecorder) OnStart(span *Span)

                                                                              OnStart records span as started.

                                                                              func (*SpanRecorder) Started

                                                                              func (ssr *SpanRecorder) Started() []*Span

                                                                                Started returns a copy of all started Spans in the order they were started.

                                                                                type Sync

                                                                                type Sync struct {

                                                                                func (*Sync) Bind

                                                                                func (s *Sync) Bind(labels []attribute.KeyValue) metric.BoundSyncImpl

                                                                                func (*Sync) Implementation

                                                                                func (s *Sync) Implementation() interface{}

                                                                                func (*Sync) RecordOne

                                                                                func (s *Sync) RecordOne(ctx context.Context, number number.Number, labels []attribute.KeyValue)

                                                                                type TextMapCarrier

                                                                                type TextMapCarrier struct {
                                                                                	// contains filtered or unexported fields

                                                                                  TextMapCarrier provides a testing storage medium to for a TextMapPropagator. It records all the operations it performs.

                                                                                  func NewTextMapCarrier

                                                                                  func NewTextMapCarrier(data map[string]string) *TextMapCarrier

                                                                                    NewTextMapCarrier returns a new *TextMapCarrier populated with data.

                                                                                    func (*TextMapCarrier) Get

                                                                                    func (c *TextMapCarrier) Get(key string) string

                                                                                      Get returns the value associated with the passed key.

                                                                                      func (*TextMapCarrier) GotKey

                                                                                      func (c *TextMapCarrier) GotKey(t *testing.T, key string) bool

                                                                                        GotKey tests if c.Get has been called for key.

                                                                                        func (*TextMapCarrier) GotN

                                                                                        func (c *TextMapCarrier) GotN(t *testing.T, n int) bool

                                                                                          GotN tests if n calls to c.Get have been made.

                                                                                          func (*TextMapCarrier) Keys

                                                                                          func (c *TextMapCarrier) Keys() []string

                                                                                            Keys returns the keys for which this carrier has a value.

                                                                                            func (*TextMapCarrier) Reset

                                                                                            func (c *TextMapCarrier) Reset()

                                                                                              Reset zeros out the internal state recording of c.

                                                                                              func (*TextMapCarrier) Set

                                                                                              func (c *TextMapCarrier) Set(key, value string)

                                                                                                Set stores the key-value pair.

                                                                                                func (*TextMapCarrier) SetKeyValue

                                                                                                func (c *TextMapCarrier) SetKeyValue(t *testing.T, key, value string) bool

                                                                                                  SetKeyValue tests if c.Set has been called for the key-value pair.

                                                                                                  func (*TextMapCarrier) SetN

                                                                                                  func (c *TextMapCarrier) SetN(t *testing.T, n int) bool

                                                                                                    SetN tests if n calls to c.Set have been made.

                                                                                                    type TextMapPropagator

                                                                                                    type TextMapPropagator struct {
                                                                                                    	Name string
                                                                                                    	// contains filtered or unexported fields

                                                                                                    func NewTextMapPropagator

                                                                                                    func NewTextMapPropagator(name string) *TextMapPropagator

                                                                                                    func (*TextMapPropagator) Extract

                                                                                                      Extract reads cross-cutting concerns for p from the carrier into a Context.

                                                                                                      func (*TextMapPropagator) ExtractedN

                                                                                                      func (p *TextMapPropagator) ExtractedN(t *testing.T, ctx context.Context, n int) bool

                                                                                                        ExtractedN tests if p has made n extractions from the lineage of ctx. nolint (context is not first arg)

                                                                                                        func (*TextMapPropagator) Fields

                                                                                                        func (p *TextMapPropagator) Fields() []string

                                                                                                          Fields returns p.Name as the key who's value is set with Inject.

                                                                                                          func (*TextMapPropagator) Inject

                                                                                                            Inject set cross-cutting concerns for p from the Context into the carrier.

                                                                                                            func (*TextMapPropagator) InjectedN

                                                                                                            func (p *TextMapPropagator) InjectedN(t *testing.T, carrier *TextMapCarrier, n int) bool

                                                                                                              InjectedN tests if p has made n injections to carrier.

                                                                                                              type Tracer

                                                                                                              type Tracer struct {
                                                                                                              	// Name is the instrumentation name.
                                                                                                              	Name string
                                                                                                              	// Version is the instrumentation version.
                                                                                                              	Version string
                                                                                                              	// contains filtered or unexported fields

                                                                                                                Tracer is an OpenTelemetry Tracer implementation used for testing.

                                                                                                                func (*Tracer) Start

                                                                                                                func (t *Tracer) Start(ctx context.Context, name string, opts ...trace.SpanOption) (context.Context, trace.Span)

                                                                                                                  Start creates a span. If t is configured with a SpanRecorder its OnStart method will be called after the created Span has been initialized.

                                                                                                                  type TracerProvider

                                                                                                                  type TracerProvider struct {
                                                                                                                  	// contains filtered or unexported fields

                                                                                                                    TracerProvider is a testing TracerProvider. It is an functioning implementation of an OpenTelemetry TracerProvider and can be configured with a SpanRecorder that it configure all Tracers it creates to record their Spans with.

                                                                                                                    func NewTracerProvider

                                                                                                                    func NewTracerProvider(options ...Option) *TracerProvider

                                                                                                                      NewTracerProvider returns a *TracerProvider configured with options.

                                                                                                                      func (*TracerProvider) Tracer

                                                                                                                      func (p *TracerProvider) Tracer(instName string, opts ...trace.TracerOption) trace.Tracer

                                                                                                                        Tracer returns an OpenTelemetry Tracer used for testing.