Skip to content

Commit

Permalink
feat(trace): add concurrent-safe Reset method to SpanRecorder (#5994)
Browse files Browse the repository at this point in the history
Add Reset method to reuse it for testing. Just like in InMemoryExporter.
  • Loading branch information
flc1125 authored Nov 25, 2024
1 parent e98ef1b commit 814a413
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
13 changes: 13 additions & 0 deletions sdk/trace/tracetest/recorder.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
24 changes: 24 additions & 0 deletions sdk/trace/tracetest/recorder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}

0 comments on commit 814a413

Please sign in to comment.