2024-09-21 15:51:58 +00:00
|
|
|
package counter
|
|
|
|
|
2024-09-21 17:43:09 +00:00
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
"testing"
|
|
|
|
)
|
2024-09-21 15:51:58 +00:00
|
|
|
|
2024-09-21 17:47:27 +00:00
|
|
|
// assertCounter
|
|
|
|
// XXX: a copy of Counter is created, but we shouldn't copy a mutex. Use pointer instead.
|
|
|
|
func assertCounter(t testing.TB, got *Counter, want int) {
|
2024-09-21 16:21:56 +00:00
|
|
|
t.Helper()
|
|
|
|
if got.Value() != want {
|
|
|
|
t.Errorf("got %d, want %d", got.Value(), want)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-09-21 15:51:58 +00:00
|
|
|
func TestCounter(t *testing.T) {
|
|
|
|
t.Run("incrementing the counter 3 times leaves it at 3", func(t *testing.T) {
|
2024-09-21 17:48:58 +00:00
|
|
|
counter := NewCounter()
|
2024-09-21 15:51:58 +00:00
|
|
|
|
|
|
|
counter.Inc()
|
|
|
|
counter.Inc()
|
|
|
|
counter.Inc()
|
2024-09-21 16:21:56 +00:00
|
|
|
|
2024-09-21 17:48:58 +00:00
|
|
|
assertCounter(t, counter, 3)
|
2024-09-21 15:51:58 +00:00
|
|
|
})
|
2024-09-21 17:43:09 +00:00
|
|
|
|
|
|
|
t.Run("it runs safely concurrently", func(t *testing.T) {
|
|
|
|
wantedCount := 1000
|
2024-09-21 17:48:58 +00:00
|
|
|
counter := NewCounter()
|
2024-09-21 17:43:09 +00:00
|
|
|
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
wg.Add(wantedCount)
|
|
|
|
|
|
|
|
for i := 0; i < wantedCount; i++ {
|
|
|
|
go func() {
|
|
|
|
counter.Inc()
|
|
|
|
wg.Done()
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
wg.Wait()
|
2024-09-21 17:48:58 +00:00
|
|
|
assertCounter(t, counter, wantedCount)
|
2024-09-21 17:43:09 +00:00
|
|
|
})
|
2024-09-21 15:51:58 +00:00
|
|
|
}
|