|
| 1 | +/* |
| 2 | +Copyright 2025 The Dapr Authors |
| 3 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +you may not use this file except in compliance with the License. |
| 5 | +You may obtain a copy of the License at |
| 6 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +Unless required by applicable law or agreed to in writing, software |
| 8 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 9 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 10 | +See the License for the specific language governing permissions and |
| 11 | +limitations under the License. |
| 12 | +*/ |
| 13 | + |
| 14 | +package compstore |
| 15 | + |
| 16 | +import ( |
| 17 | + "sync" |
| 18 | + "testing" |
| 19 | + |
| 20 | + rtpubsub "github.com/dapr/dapr/pkg/runtime/pubsub" |
| 21 | + "github.com/stretchr/testify/assert" |
| 22 | +) |
| 23 | + |
| 24 | +func TestNextSubscriberIndex(t *testing.T) { |
| 25 | + t.Run("sequential calls return incrementing values", func(t *testing.T) { |
| 26 | + store := New() |
| 27 | + |
| 28 | + id1 := store.NextSubscriberIndex() |
| 29 | + id2 := store.NextSubscriberIndex() |
| 30 | + id3 := store.NextSubscriberIndex() |
| 31 | + |
| 32 | + assert.Equal(t, rtpubsub.ConnectionID(1), id1) |
| 33 | + assert.Equal(t, rtpubsub.ConnectionID(2), id2) |
| 34 | + assert.Equal(t, rtpubsub.ConnectionID(3), id3) |
| 35 | + }) |
| 36 | + |
| 37 | + t.Run("concurrent calls return unique values", func(t *testing.T) { |
| 38 | + store := New() |
| 39 | + const numGoroutines = 100 |
| 40 | + const numCallsPerGoroutine = 10 |
| 41 | + var wg sync.WaitGroup |
| 42 | + var mu sync.Mutex |
| 43 | + ids := make(map[rtpubsub.ConnectionID]bool) |
| 44 | + |
| 45 | + wg.Add(numGoroutines) |
| 46 | + for i := 0; i < numGoroutines; i++ { |
| 47 | + go func() { |
| 48 | + defer wg.Done() |
| 49 | + for j := 0; j < numCallsPerGoroutine; j++ { |
| 50 | + id := store.NextSubscriberIndex() |
| 51 | + mu.Lock() |
| 52 | + ids[id] = true |
| 53 | + mu.Unlock() |
| 54 | + } |
| 55 | + }() |
| 56 | + } |
| 57 | + wg.Wait() |
| 58 | + |
| 59 | + assert.Len(t, ids, numGoroutines*numCallsPerGoroutine, "Expected all IDs to be unique") |
| 60 | + |
| 61 | + for i := 1; i <= numGoroutines*numCallsPerGoroutine; i++ { |
| 62 | + assert.True(t, ids[rtpubsub.ConnectionID(i)], "Expected ID %d to be present", i) |
| 63 | + } |
| 64 | + }) |
| 65 | +} |
0 commit comments