diff --git a/CHANGELOG.md b/CHANGELOG.md index db0b9f625eb..e573f61e55e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,10 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm ## [Unreleased] +### Added + +- Add `Reset` method to `SpanRecorder` in `go.opentelemetry.io/otel/sdk/trace/tracetest`. (#5994) + ### Changed - The default global API now supports full auto-instrumentation from the `go.opentelemetry.io/auto` package. diff --git a/sdk/trace/tracetest/recorder.go b/sdk/trace/tracetest/recorder.go index 7aababbbf2f..732669a17ad 100644 --- a/sdk/trace/tracetest/recorder.go +++ b/sdk/trace/tracetest/recorder.go @@ -69,6 +69,19 @@ func (sr *SpanRecorder) Started() []sdktrace.ReadWriteSpan { return dst } +// Reset clears the recorded spans. +// +// This method is safe to be called concurrently. +func (sr *SpanRecorder) Reset() { + sr.startedMu.Lock() + sr.endedMu.Lock() + defer sr.startedMu.Unlock() + defer sr.endedMu.Unlock() + + sr.started = nil + sr.ended = nil +} + // Ended returns a copy of all ended spans that have been recorded. // // This method is safe to be called concurrently. diff --git a/sdk/trace/tracetest/recorder_test.go b/sdk/trace/tracetest/recorder_test.go index 5fd2eecd11a..1d7c7723111 100644 --- a/sdk/trace/tracetest/recorder_test.go +++ b/sdk/trace/tracetest/recorder_test.go @@ -112,3 +112,27 @@ func TestStartingConcurrentSafe(t *testing.T) { assert.Len(t, sr.Started(), 2) } + +func TestResetConcurrentSafe(t *testing.T) { + sr := NewSpanRecorder() + ctx := context.Background() + + runConcurrently( + func() { sr.OnStart(ctx, new(rwSpan)) }, + func() { sr.OnStart(ctx, new(rwSpan)) }, + func() { sr.OnEnd(new(roSpan)) }, + func() { sr.OnEnd(new(roSpan)) }, + ) + + assert.Len(t, sr.Started(), 2) + assert.Len(t, sr.Ended(), 2) + + runConcurrently( + func() { sr.Reset() }, + func() { sr.Reset() }, + func() { sr.Reset() }, + ) + + assert.Empty(t, sr.Started()) + assert.Empty(t, sr.Ended()) +}