Skip to content

Commit

Permalink
use atomic counter in tests
Browse files Browse the repository at this point in the history
  • Loading branch information
janezpodhostnik committed Oct 2, 2024
1 parent 44112e1 commit df0be10
Showing 1 changed file with 13 additions and 8 deletions.
21 changes: 13 additions & 8 deletions models/stream_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package models_test
import (
"fmt"
"sync"
"sync/atomic"
"testing"
"time"

Expand Down Expand Up @@ -31,15 +32,15 @@ func Test_Stream(t *testing.T) {

p.Publish(mockData{})

require.Equal(t, uint(1), s1.callCount)
require.Equal(t, uint(1), s2.callCount)
require.Equal(t, uint64(1), s1.CallCount())
require.Equal(t, uint64(1), s2.CallCount())

p.Unsubscribe(s1)

p.Publish(mockData{})

require.Equal(t, uint(1), s1.callCount)
require.Equal(t, uint(2), s2.callCount)
require.Equal(t, uint64(1), s1.CallCount())
require.Equal(t, uint64(2), s2.CallCount())
})

t.Run("concurrent subscribe, publish, unsubscribe, publish", func(t *testing.T) {
Expand Down Expand Up @@ -86,7 +87,7 @@ func Test_Stream(t *testing.T) {

// there should be at least 50 calls
for j := 0; j < 10; j++ {
require.Greater(t, subscriptions[j].callCount, uint(50))
require.Greater(t, subscriptions[j].CallCount(), uint64(50))
}
}()
}
Expand All @@ -101,7 +102,7 @@ func Test_Stream(t *testing.T) {
errContent := fmt.Errorf("failed to process data")

s.Subscription = models.NewSubscription[mockData](func(data mockData) error {
s.callCount++
s.callCount.Add(1)
return errContent
})

Expand All @@ -127,18 +128,22 @@ type mockData struct{}

type mockSubscription struct {
*models.Subscription[mockData]
callCount uint
callCount atomic.Uint64
}

func newMockSubscription() *mockSubscription {
s := &mockSubscription{}
s.Subscription = models.NewSubscription[mockData](func(data mockData) error {
s.callCount++
s.callCount.Add(1)
return nil
})
return s
}

func (s *mockSubscription) CallCount() uint64 {
return s.callCount.Load()
}

func newMockPublisher() *models.Publisher[mockData] {
return models.NewPublisher[mockData]()
}

0 comments on commit df0be10

Please sign in to comment.