Skip to content

Commit

Permalink
make random.Unique more forgiving
Browse files Browse the repository at this point in the history
  • Loading branch information
adamluzsi committed Jul 22, 2024
1 parent 8d2a375 commit c77c046
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
7 changes: 5 additions & 2 deletions random/Unique.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,11 @@ func Unique[T any](blk func() T, excludeList ...T) T {
if len(excludeList) == 0 {
return blk()
}
deadline := clock.Now().Add(5 * time.Second)
for clock.Now().Before(deadline) {
var (
retries int
deadline = clock.Now().Add(5 * time.Second)
)
for ; clock.Now().Before(deadline) || retries < 5; retries++ {
var (
v T = blk()
ok bool = true
Expand Down
29 changes: 29 additions & 0 deletions random/Unique_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package random_test

import (
"testing"
"time"

"go.llib.dev/testcase/assert"
"go.llib.dev/testcase/clock/timecop"
Expand Down Expand Up @@ -62,4 +63,32 @@ func TestUnique(t *testing.T) {
assert.False(t, out.OK)
assert.NotEmpty(t, out.PanicValue)
})
t.Run("creating an item takes a lot of time then instead of time based retry, we make at least 5 attempts", func(t *testing.T) {
now := time.Now()
timecop.Travel(t, now, timecop.Freeze)
out := sandbox.Run(func() {
var i int
random.Unique(func() int {
timecop.Travel(t, 10*time.Second)
i++
if 5 <= i {
return i
}
return 0
}, 0)
})
assert.True(t, out.OK)
})
t.Run("if the unique's make function is fast enough, then more than 5 tries will be made, as long it can fit within the deadline", func(t *testing.T) {
timecop.SetSpeed(t, 1000 /* times */)
var n int
out := sandbox.Run(func() {
random.Unique(func() int {
n++
return 0
}, 0)
})
assert.False(t, out.OK)
assert.True(t, 6 < n) // probably it runs at least 20000 times, so it should be definetly bigger than 6
})
}

0 comments on commit c77c046

Please sign in to comment.