Skip to content

Commit d981b4e

Browse files
fix: fix flakiness in subscriberIT integration test (#476)
* fix: retrying sync pulls in subscriberIT test
1 parent f01bb0d commit d981b4e

File tree

1 file changed

+35
-8
lines changed

1 file changed

+35
-8
lines changed

samples/snippets/src/test/java/pubsub/SubscriberIT.java

+35-8
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
import java.io.ByteArrayOutputStream;
3838
import java.io.PrintStream;
3939
import java.util.ArrayList;
40+
import java.util.HashSet;
4041
import java.util.List;
4142
import java.util.UUID;
4243
import org.junit.After;
@@ -84,6 +85,32 @@ private static void publishSomeMessages(Integer numOfMessages) throws Exception
8485
ApiFutures.allAsList(messageIdFutures).get();
8586
}
8687

88+
// Helper function to retry synchronous pull attempts until all outstanding messages are received.
89+
private void syncPullWithRetries(
90+
Integer numOfMessages, Integer maxRetries, CheckedRunnable syncPull) throws Exception {
91+
HashSet<String> outstandingMessages = new HashSet<>();
92+
for (int i = 0; i < numOfMessages; i++) {
93+
outstandingMessages.add("Hello " + i);
94+
}
95+
int attempt = 1;
96+
while ((outstandingMessages.size() > 0) && (attempt <= maxRetries)) {
97+
syncPull.run();
98+
HashSet<String> clone = (HashSet) outstandingMessages.clone();
99+
for (String message : clone) {
100+
if (bout.toString().contains(message)) {
101+
outstandingMessages.remove(message);
102+
}
103+
}
104+
attempt++;
105+
}
106+
assertThat(outstandingMessages).isEmpty();
107+
}
108+
109+
@FunctionalInterface
110+
public interface CheckedRunnable {
111+
void run() throws Exception;
112+
}
113+
87114
@Rule public Timeout globalTimeout = Timeout.seconds(600); // 10 minute timeout
88115

89116
@BeforeClass
@@ -168,17 +195,17 @@ public void testSubscriber() throws Exception {
168195
publishSomeMessages(3);
169196
bout.reset();
170197
// Test subscribe synchronously.
171-
SubscribeSyncExample.subscribeSyncExample(projectId, subscriptionId, 10);
172-
for (int i = 0; i < 3; i++) {
173-
assertThat(bout.toString()).contains("Hello " + i);
174-
}
198+
syncPullWithRetries(
199+
3, 3, () -> SubscribeSyncExample.subscribeSyncExample(projectId, subscriptionId, 3));
175200

176201
publishSomeMessages(3);
177202
bout.reset();
178203
// Test subscribe synchronously with lease management.
179-
SubscribeSyncWithLeaseExample.subscribeSyncWithLeaseExample(projectId, subscriptionId, 10);
180-
for (int i = 0; i < 3; i++) {
181-
assertThat(bout.toString()).contains("Hello " + i);
182-
}
204+
syncPullWithRetries(
205+
3,
206+
3,
207+
() ->
208+
SubscribeSyncWithLeaseExample.subscribeSyncWithLeaseExample(
209+
projectId, subscriptionId, 10));
183210
}
184211
}

0 commit comments

Comments
 (0)