fix: retry assertion (#599)
Co-authored-by: kimura <takeshki@yahoo-corp.jp>
### Motivation
in `consumer_regex_test.go`, sometimes consumers take more than 2 seconds (waiting time) subscribing, and assertions fail.
### Modifications
instead of waiting and asserting just once, repeat it a specified number of times so that consumers have enough time to subscribe.
diff --git a/pulsar/consumer_regex_test.go b/pulsar/consumer_regex_test.go
index 228fc2d..9cb600f 100644
--- a/pulsar/consumer_regex_test.go
+++ b/pulsar/consumer_regex_test.go
@@ -177,10 +177,11 @@
t.Fatal(err)
}
rc.discover()
- time.Sleep(2000 * time.Millisecond)
-
- consumers = cloneConsumers(rc)
- assert.Equal(t, 1, len(consumers))
+ retryAssert(t, 5, 2000, func() {
+ consumers = cloneConsumers(rc)
+ }, func(x assert.TestingT) bool {
+ return assert.Equal(x, 1, len(consumers))
+ })
}
func runRegexConsumerDiscoverPatternFoo(t *testing.T, c Client, namespace string) {
@@ -216,10 +217,11 @@
defer deleteTopic(myTopic)
rc.discover()
- time.Sleep(2000 * time.Millisecond)
-
- consumers = cloneConsumers(rc)
- assert.Equal(t, 0, len(consumers))
+ retryAssert(t, 5, 2000, func() {
+ consumers = cloneConsumers(rc)
+ }, func(x assert.TestingT) bool {
+ return assert.Equal(x, 0, len(consumers))
+ })
// create a topic not in the regex
fooTopic := namespace + "/foo-topic"
@@ -229,10 +231,11 @@
}
rc.discover()
- time.Sleep(2000 * time.Millisecond)
-
- consumers = cloneConsumers(rc)
- assert.Equal(t, 1, len(consumers))
+ retryAssert(t, 5, 2000, func() {
+ consumers = cloneConsumers(rc)
+ }, func(x assert.TestingT) bool {
+ return assert.Equal(x, 1, len(consumers))
+ })
}
func TestRegexConsumer(t *testing.T) {
diff --git a/pulsar/test_helper.go b/pulsar/test_helper.go
index 273169a..d6a4f00 100644
--- a/pulsar/test_helper.go
+++ b/pulsar/test_helper.go
@@ -30,6 +30,7 @@
"time"
"github.com/apache/pulsar-client-go/pulsar/internal"
+ "github.com/stretchr/testify/assert"
pkgerrors "github.com/pkg/errors"
)
@@ -165,3 +166,14 @@
}
return tn.Name
}
+
+func retryAssert(t assert.TestingT, times int, milliseconds int, update func(), assert func(assert.TestingT) bool) {
+ for i := 0; i < times; i++ {
+ time.Sleep(time.Duration(milliseconds) * time.Millisecond)
+ update()
+ if assert(nil) {
+ break
+ }
+ }
+ assert(t)
+}