| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package metric // import "go.opentelemetry.io/otel/sdk/metric" |
| 5 |
|
| 6 |
import ( |
| 7 |
"sync" |
| 8 |
"testing" |
| 9 |
"time" |
| 10 |
|
| 11 |
"github.com/stretchr/testify/assert" |
| 12 |
"github.com/stretchr/testify/require" |
| 13 |
) |
| 14 |
|
| 15 |
func TestCache(t *testing.T) { |
| 16 |
k0, k1 := "one", "two" |
| 17 |
v0, v1 := 1, 2 |
| 18 |
|
| 19 |
c := cache[string, int]{} |
| 20 |
|
| 21 |
var got int |
| 22 |
require.NotPanics(t, func() { |
| 23 |
got = c.Lookup(k0, func() int { return v0 }) |
| 24 |
}, "zero-value cache panics on Lookup") |
| 25 |
assert.Equal(t, v0, got, "zero-value cache did not return fallback") |
| 26 |
|
| 27 |
assert.Equal(t, v0, c.Lookup(k0, func() int { return v1 }), "existing key") |
| 28 |
|
| 29 |
assert.Equal(t, v1, c.Lookup(k1, func() int { return v1 }), "non-existing key") |
| 30 |
} |
| 31 |
|
| 32 |
func TestCacheConcurrentSafe(t *testing.T) { |
| 33 |
const ( |
| 34 |
key = "k" |
| 35 |
goroutines = 10 |
| 36 |
) |
| 37 |
|
| 38 |
c := cache[string, int]{} |
| 39 |
var wg sync.WaitGroup |
| 40 |
for n := range goroutines { |
| 41 |
wg.Add(1) |
| 42 |
go func(i int) { |
| 43 |
defer wg.Done() |
| 44 |
assert.NotPanics(t, func() { |
| 45 |
c.Lookup(key, func() int { return i }) |
| 46 |
}) |
| 47 |
}(n) |
| 48 |
} |
| 49 |
|
| 50 |
done := make(chan struct{}) |
| 51 |
go func() { |
| 52 |
wg.Wait() |
| 53 |
close(done) |
| 54 |
}() |
| 55 |
|
| 56 |
select { |
| 57 |
case <-done: |
| 58 |
case <-time.After(5 * time.Second): |
| 59 |
assert.Fail(t, "timeout") |
| 60 |
} |
| 61 |
} |