|
37 | 37 | import java.io.ByteArrayOutputStream;
|
38 | 38 | import java.io.PrintStream;
|
39 | 39 | import java.util.ArrayList;
|
| 40 | +import java.util.HashSet; |
40 | 41 | import java.util.List;
|
41 | 42 | import java.util.UUID;
|
42 | 43 | import org.junit.After;
|
@@ -84,6 +85,32 @@ private static void publishSomeMessages(Integer numOfMessages) throws Exception
|
84 | 85 | ApiFutures.allAsList(messageIdFutures).get();
|
85 | 86 | }
|
86 | 87 |
|
| 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 | + |
87 | 114 | @Rule public Timeout globalTimeout = Timeout.seconds(600); // 10 minute timeout
|
88 | 115 |
|
89 | 116 | @BeforeClass
|
@@ -168,17 +195,17 @@ public void testSubscriber() throws Exception {
|
168 | 195 | publishSomeMessages(3);
|
169 | 196 | bout.reset();
|
170 | 197 | // 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)); |
175 | 200 |
|
176 | 201 | publishSomeMessages(3);
|
177 | 202 | bout.reset();
|
178 | 203 | // 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)); |
183 | 210 | }
|
184 | 211 | }
|
0 commit comments