From 7d62ae453b3df91a26db4073fecb6347c9c82589 Mon Sep 17 00:00:00 2001 From: Jon M Date: Fri, 4 Dec 2026 10:48:21 +0000 Subject: [PATCH 1/4] Share the poll delay rule and test it offline Search and preview polling now read x-ms-delay through one package-private pollDelay function. An entry that is empty, negative or not a number counts as 1000 ms instead of throwing NumberFormatException. Package-private hooks let tests swap the HTTP transport, sleep and clock without changing the public API. PollingTest covers the shared spec's 14 cases with MockHttpTransport and a fake clock, so it runs without secrets: mvn test -Dtest=PollingTest --- src/main/java/com/mailosaur/Files.java | 20 +- .../java/com/mailosaur/MailosaurClient.java | 47 +++- src/main/java/com/mailosaur/Messages.java | 20 +- src/test/java/com/mailosaur/PollingTest.java | 225 ++++++++++++++++++ 4 files changed, 269 insertions(+), 43 deletions(-) create mode 100644 src/test/java/com/mailosaur/PollingTest.java diff --git a/src/main/java/com/mailosaur/Files.java b/src/main/java/com/mailosaur/Files.java index e32630f..10df38c 100644 --- a/src/main/java/com/mailosaur/Files.java +++ b/src/main/java/com/mailosaur/Files.java @@ -6,8 +6,6 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.util.Date; -import java.util.List; /** * Operations for downloading the raw content associated with a message — file attachments, @@ -58,7 +56,7 @@ public byte[] getEmail(String messageId) throws MailosaurException, IOException public byte[] getPreview(String previewId) throws MailosaurException, IOException { int timeout = 120000; int pollCount = 0; - long startTime = new Date().getTime(); + long startTime = client.clock.currentTimeMillis(); while(true) { HttpResponse response = client.request("GET", "api/files/screenshots/" + previewId); @@ -69,26 +67,16 @@ public byte[] getPreview(String previewId) throws MailosaurException, IOExceptio return stream.toByteArray(); } - List headerValues = response.getHeaders().getHeaderStringValues("x-ms-delay"); - String[] delayStrings = (headerValues.size() == 0 ? "1000" : headerValues.get(0)).split(","); - int delayPattern[] = new int[delayStrings.length]; - for (int i = 0; i < delayStrings.length; i++) { - delayPattern[i] = Integer.parseInt(delayStrings[i].trim()); - } - - int delay = pollCount >= delayPattern.length ? - delayPattern[delayPattern.length - 1] : - delayPattern[pollCount]; - + int delay = MailosaurClient.pollDelay(response.getHeaders().getFirstHeaderStringValue("x-ms-delay"), pollCount); pollCount++; // Stop if timeout will be exceeded - if ((new Date().getTime() - startTime) + delay > timeout) { + if ((client.clock.currentTimeMillis() - startTime) + delay > timeout) { throw new MailosaurException("An email preview was not generated in time. The email client may not be available, or the preview ID ["+previewId+"] may be incorrect.", "preview_timeout"); } try { - Thread.sleep(delay); + client.sleeper.sleep(delay); } catch (InterruptedException e) { e.printStackTrace(); } diff --git a/src/main/java/com/mailosaur/MailosaurClient.java b/src/main/java/com/mailosaur/MailosaurClient.java index e10d459..ebb500b 100644 --- a/src/main/java/com/mailosaur/MailosaurClient.java +++ b/src/main/java/com/mailosaur/MailosaurClient.java @@ -14,6 +14,8 @@ import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonObjectParser; import com.google.api.client.json.gson.GsonFactory; +import com.google.api.client.util.Clock; +import com.google.api.client.util.Sleeper; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; @@ -30,16 +32,13 @@ public class MailosaurClient { final String VERSION = "9.0.0"; final String API_KEY; final String BASE_URL; - final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); + final HttpTransport HTTP_TRANSPORT; final JsonFactory JSON_FACTORY = new GsonFactory(); - - final HttpRequestFactory requestFactory = - HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() { - public void initialize(HttpRequest request) { - request.setParser(new JsonObjectParser(JSON_FACTORY)); - } - }); - + final HttpRequestFactory requestFactory; + + Sleeper sleeper = Sleeper.DEFAULT; + Clock clock = Clock.SYSTEM; + /** * Initializes an instance of the Mailosaur client using the * MAILOSAUR_API_KEY environment variable. @@ -66,9 +65,19 @@ public MailosaurClient(String apiKey) { * @param baseUrl Alternative base URL of the Mailosaur service. */ public MailosaurClient(String apiKey, String baseUrl) { + this(apiKey, baseUrl, new NetHttpTransport()); + } + + MailosaurClient(String apiKey, String baseUrl, HttpTransport transport) { API_KEY = apiKey; BASE_URL = baseUrl != null ? baseUrl : "https://mailosaur.com/"; - + HTTP_TRANSPORT = transport; + requestFactory = transport.createRequestFactory(new HttpRequestInitializer() { + public void initialize(HttpRequest request) { + request.setParser(new JsonObjectParser(JSON_FACTORY)); + } + }); + this.analysis = new Analysis(this); this.files = new Files(this); this.messages = new Messages(this); @@ -87,7 +96,23 @@ private static String resolveApiKeyFromEnv() throws MailosaurException { } return apiKey; } - + + static int pollDelay(String header, int pollCount) { + if (header == null) { + return 1000; + } + + String[] entries = header.split(",", -1); + String entry = entries[Math.min(pollCount, entries.length - 1)].trim(); + + try { + int delay = Integer.parseInt(entry); + return delay < 0 ? 1000 : delay; + } catch (NumberFormatException e) { + return 1000; + } + } + /** * Operations for analyzing email content and deliverability, including spam scoring. */ diff --git a/src/main/java/com/mailosaur/Messages.java b/src/main/java/com/mailosaur/Messages.java index 1c65179..1edfe03 100644 --- a/src/main/java/com/mailosaur/Messages.java +++ b/src/main/java/com/mailosaur/Messages.java @@ -1,9 +1,7 @@ package com.mailosaur; import java.io.IOException; -import java.util.Date; import java.util.HashMap; -import java.util.List; import com.google.api.client.http.HttpResponse; import com.google.gson.Gson; @@ -315,7 +313,7 @@ public MessageListResult search(MessageSearchParams params, SearchCriteria crite } int pollCount = 0; - long startTime = new Date().getTime(); + long startTime = client.clock.currentTimeMillis(); while(true) { HttpResponse response = client.request("POST", "api/messages/search", criteria, query); @@ -325,21 +323,11 @@ public MessageListResult search(MessageSearchParams params, SearchCriteria crite return result; } - List headerValues = response.getHeaders().getHeaderStringValues("x-ms-delay"); - String[] delayStrings = (headerValues.size() == 0 ? "1000" : headerValues.get(0)).split(","); - int delayPattern[] = new int[delayStrings.length]; - for (int i = 0; i < delayStrings.length; i++) { - delayPattern[i] = Integer.parseInt(delayStrings[i].trim()); - } - - int delay = pollCount >= delayPattern.length ? - delayPattern[delayPattern.length - 1] : - delayPattern[pollCount]; - + int delay = MailosaurClient.pollDelay(response.getHeaders().getFirstHeaderStringValue("x-ms-delay"), pollCount); pollCount++; // Stop if timeout will be exceeded - if ((new Date().getTime() - startTime) + delay > params.timeout()) { + if ((client.clock.currentTimeMillis() - startTime) + delay > params.timeout()) { if (params.errorOnTimeout() == false) { return result; } @@ -349,7 +337,7 @@ public MessageListResult search(MessageSearchParams params, SearchCriteria crite } try { - Thread.sleep(delay); + client.sleeper.sleep(delay); } catch (InterruptedException e) { e.printStackTrace(); } diff --git a/src/test/java/com/mailosaur/PollingTest.java b/src/test/java/com/mailosaur/PollingTest.java new file mode 100644 index 0000000..5eb9bb7 --- /dev/null +++ b/src/test/java/com/mailosaur/PollingTest.java @@ -0,0 +1,225 @@ +package com.mailosaur; + +import com.google.api.client.http.LowLevelHttpRequest; +import com.google.api.client.http.LowLevelHttpResponse; +import com.google.api.client.testing.http.MockHttpTransport; +import com.google.api.client.testing.http.MockLowLevelHttpRequest; +import com.google.api.client.testing.http.MockLowLevelHttpResponse; +import com.mailosaur.models.MessageListResult; +import com.mailosaur.models.MessageSearchParams; +import com.mailosaur.models.SearchCriteria; +import org.junit.Test; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.*; + +public class PollingTest { + private static final byte[] IMAGE = { (byte) 0x89, 'P', 'N', 'G' }; + private static final SearchCriteria CRITERIA = new SearchCriteria().withSentTo("test@abcd1234.mailosaur.net"); + + private final List waits = new ArrayList<>(); + private long now; + private int requests; + + private interface Reply { + MockLowLevelHttpResponse create(); + } + + @Test + public void searchWaits1000MsWhenThereIsNoDelayHeader() throws IOException, MailosaurException { + MessageListResult result = stubClient(empty(null), match(null)).messages().search(params(60000), CRITERIA); + + assertEquals(Arrays.asList(1000L), waits); + assertEquals(2, requests); + assertEquals("match-id", result.items().get(0).id()); + } + + @Test + public void searchWaitsASubSecondDelayAsGiven() throws IOException, MailosaurException { + MessageListResult result = stubClient(empty("500"), match("500")).messages().search(params(60000), CRITERIA); + + assertEquals(Arrays.asList(500L), waits); + assertEquals(2, requests); + assertEquals("match-id", result.items().get(0).id()); + } + + @Test + public void searchWaitsADelayOverOneSecondAsGiven() throws IOException, MailosaurException { + MessageListResult result = stubClient(empty("1500"), match("1500")).messages().search(params(60000), CRITERIA); + + assertEquals(Arrays.asList(1500L), waits); + assertEquals(2, requests); + assertEquals("match-id", result.items().get(0).id()); + } + + @Test + public void searchUsesEachListedDelayInTurnThenRepeatsTheLast() throws IOException, MailosaurException { + String delay = "1000,2000,3000"; + MessageListResult result = stubClient(empty(delay), empty(delay), empty(delay), empty(delay), match(delay)) + .messages().search(params(60000), CRITERIA); + + assertEquals(Arrays.asList(1000L, 2000L, 3000L, 3000L), waits); + assertEquals(5, requests); + assertEquals("match-id", result.items().get(0).id()); + } + + @Test + public void searchStopsBeforeAWaitThatWouldPassTheTimeout() throws IOException, MailosaurException { + MessageListResult result = stubClient(empty("1000,2000,3000")) + .messages().search(params(5000).withErrorOnTimeout(false), CRITERIA); + + assertEquals(Arrays.asList(1000L, 2000L), waits); + assertEquals(3, requests); + assertTrue(result.items().isEmpty()); + } + + @Test + public void searchThrowsATimeoutErrorWhenNothingMatchesInTime() { + final MailosaurClient client = stubClient(empty("1000,2000,3000")); + + MailosaurException error = assertThrows(MailosaurException.class, + () -> client.messages().search(params(5000), CRITERIA)); + + assertEquals(Arrays.asList(1000L, 2000L), waits); + assertEquals(3, requests); + assertEquals("search_timeout", error.errorType()); + } + + @Test + public void searchTreatsADelayThatIsNotANumberAs1000Ms() throws IOException, MailosaurException { + String delay = "abc,,1500"; + MessageListResult result = stubClient(empty(delay), empty(delay), empty(delay), match(delay)) + .messages().search(params(60000), CRITERIA); + + assertEquals(Arrays.asList(1000L, 1000L, 1500L), waits); + assertEquals(4, requests); + assertEquals("match-id", result.items().get(0).id()); + } + + @Test + public void searchStillWaitsWhenTheWaitEndsExactlyAtTheTimeout() throws IOException, MailosaurException { + MessageListResult result = stubClient(empty("1000,2000,3000")) + .messages().search(params(6000).withErrorOnTimeout(false), CRITERIA); + + assertEquals(Arrays.asList(1000L, 2000L, 3000L), waits); + assertEquals(4, requests); + assertTrue(result.items().isEmpty()); + } + + @Test + public void previewWaits1000MsWhenThereIsNoDelayHeader() throws IOException, MailosaurException { + byte[] bytes = stubClient(pending(null), ready(null)).files().getPreview("preview-id"); + + assertEquals(Arrays.asList(1000L), waits); + assertEquals(2, requests); + assertArrayEquals(IMAGE, bytes); + } + + @Test + public void previewWaitsASubSecondDelayAsGiven() throws IOException, MailosaurException { + byte[] bytes = stubClient(pending("500"), ready("500")).files().getPreview("preview-id"); + + assertEquals(Arrays.asList(500L), waits); + assertEquals(2, requests); + assertArrayEquals(IMAGE, bytes); + } + + @Test + public void previewWaitsADelayOverOneSecondAsGiven() throws IOException, MailosaurException { + byte[] bytes = stubClient(pending("1500"), ready("1500")).files().getPreview("preview-id"); + + assertEquals(Arrays.asList(1500L), waits); + assertEquals(2, requests); + assertArrayEquals(IMAGE, bytes); + } + + @Test + public void previewUsesEachListedDelayInTurnThenRepeatsTheLast() throws IOException, MailosaurException { + String delay = "1000,2000,3000"; + byte[] bytes = stubClient(pending(delay), pending(delay), pending(delay), pending(delay), ready(delay)) + .files().getPreview("preview-id"); + + assertEquals(Arrays.asList(1000L, 2000L, 3000L, 3000L), waits); + assertEquals(5, requests); + assertArrayEquals(IMAGE, bytes); + } + + @Test + public void previewTreatsADelayThatIsNotANumberAs1000Ms() throws IOException, MailosaurException { + String delay = "abc,,1500"; + byte[] bytes = stubClient(pending(delay), pending(delay), pending(delay), ready(delay)) + .files().getPreview("preview-id"); + + assertEquals(Arrays.asList(1000L, 1000L, 1500L), waits); + assertEquals(4, requests); + assertArrayEquals(IMAGE, bytes); + } + + @Test + public void previewThrowsATimeoutErrorWhenThePreviewIsNotReadyInTime() { + final MailosaurClient client = stubClient(pending("60000")); + + MailosaurException error = assertThrows(MailosaurException.class, + () -> client.files().getPreview("preview-id")); + + assertEquals(Arrays.asList(60000L, 60000L), waits); + assertEquals(3, requests); + assertEquals("preview_timeout", error.errorType()); + } + + private MailosaurClient stubClient(final Reply... replies) { + MockHttpTransport transport = new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) { + return new MockLowLevelHttpRequest(url) { + @Override + public LowLevelHttpResponse execute() { + Reply reply = replies[Math.min(requests, replies.length - 1)]; + requests++; + return reply.create(); + } + }; + } + }; + + MailosaurClient client = new MailosaurClient("placeholder-api-key", null, transport); + client.sleeper = millis -> { + waits.add(millis); + now += millis; + }; + client.clock = () -> now; + return client; + } + + private static MessageSearchParams params(int timeout) { + return new MessageSearchParams().withServer("abcd1234").withTimeout(timeout); + } + + private static Reply empty(final String delay) { + return () -> withDelay(json("{\"items\":[]}"), delay); + } + + private static Reply match(final String delay) { + return () -> withDelay(json("{\"items\":[{\"id\":\"match-id\"}]}"), delay); + } + + private static Reply pending(final String delay) { + return () -> withDelay(new MockLowLevelHttpResponse().setStatusCode(202), delay); + } + + private static Reply ready(final String delay) { + return () -> withDelay(new MockLowLevelHttpResponse().setContentType("image/png").setContent(IMAGE), delay); + } + + private static MockLowLevelHttpResponse json(String body) { + return new MockLowLevelHttpResponse().setContentType("application/json; charset=UTF-8").setContent(body); + } + + private static MockLowLevelHttpResponse withDelay(MockLowLevelHttpResponse response, String delay) { + return delay == null ? response : response.addHeader("x-ms-delay", delay); + } +} From d511c1510c91f5ed42a7859445c4cbe0ec804a08 Mon Sep 17 00:00:00 2001 From: Jon M Date: Fri, 4 Dec 2026 11:48:38 +0000 Subject: [PATCH 2/4] Accept only ASCII digits as poll delays A delay entry now counts only when it is one or more ASCII digits after trimming. Signs, decimals, hex, units, non-ASCII digits and values too big for an int count as 1000 ms, as before for other non-numbers. PollingTest moves to the shared spec's 18 cases: wider not-a-number coverage, elapsed time measured in milliseconds, and the delay read from the latest response. The stub transport fails a test after 20 requests, so a broken timeout check fails instead of hanging. --- .../java/com/mailosaur/MailosaurClient.java | 10 ++- src/test/java/com/mailosaur/PollingTest.java | 64 ++++++++++++++++--- 2 files changed, 62 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/mailosaur/MailosaurClient.java b/src/main/java/com/mailosaur/MailosaurClient.java index ebb500b..23c327d 100644 --- a/src/main/java/com/mailosaur/MailosaurClient.java +++ b/src/main/java/com/mailosaur/MailosaurClient.java @@ -7,6 +7,7 @@ import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; +import java.util.regex.Pattern; import com.google.api.client.http.*; import com.google.api.client.http.javanet.NetHttpTransport; @@ -36,6 +37,8 @@ public class MailosaurClient { final JsonFactory JSON_FACTORY = new GsonFactory(); final HttpRequestFactory requestFactory; + private static final Pattern ASCII_DIGITS = Pattern.compile("[0-9]+"); + Sleeper sleeper = Sleeper.DEFAULT; Clock clock = Clock.SYSTEM; @@ -105,9 +108,12 @@ static int pollDelay(String header, int pollCount) { String[] entries = header.split(",", -1); String entry = entries[Math.min(pollCount, entries.length - 1)].trim(); + if (!ASCII_DIGITS.matcher(entry).matches()) { + return 1000; + } + try { - int delay = Integer.parseInt(entry); - return delay < 0 ? 1000 : delay; + return Integer.parseInt(entry); } catch (NumberFormatException e) { return 1000; } diff --git a/src/test/java/com/mailosaur/PollingTest.java b/src/test/java/com/mailosaur/PollingTest.java index 5eb9bb7..383bd53 100644 --- a/src/test/java/com/mailosaur/PollingTest.java +++ b/src/test/java/com/mailosaur/PollingTest.java @@ -18,6 +18,7 @@ import static org.junit.Assert.*; public class PollingTest { + private static final int MAX_REQUESTS = 20; private static final byte[] IMAGE = { (byte) 0x89, 'P', 'N', 'G' }; private static final SearchCriteria CRITERIA = new SearchCriteria().withSentTo("test@abcd1234.mailosaur.net"); @@ -91,12 +92,12 @@ public void searchThrowsATimeoutErrorWhenNothingMatchesInTime() { @Test public void searchTreatsADelayThatIsNotANumberAs1000Ms() throws IOException, MailosaurException { - String delay = "abc,,1500"; - MessageListResult result = stubClient(empty(delay), empty(delay), empty(delay), match(delay)) + String delay = "abc,,+500,-500,1500"; + MessageListResult result = stubClient(empty(delay), empty(delay), empty(delay), empty(delay), empty(delay), match(delay)) .messages().search(params(60000), CRITERIA); - assertEquals(Arrays.asList(1000L, 1000L, 1500L), waits); - assertEquals(4, requests); + assertEquals(Arrays.asList(1000L, 1000L, 1000L, 1000L, 1500L), waits); + assertEquals(6, requests); assertEquals("match-id", result.items().get(0).id()); } @@ -110,6 +111,26 @@ public void searchStillWaitsWhenTheWaitEndsExactlyAtTheTimeout() throws IOExcept assertTrue(result.items().isEmpty()); } + @Test + public void searchMeasuresElapsedTimeInMilliseconds() throws IOException, MailosaurException { + MessageListResult result = stubClient(empty("700,1500")) + .messages().search(params(2000).withErrorOnTimeout(false), CRITERIA); + + assertEquals(Arrays.asList(700L), waits); + assertEquals(2, requests); + assertTrue(result.items().isEmpty()); + } + + @Test + public void searchReadsTheDelayFromTheLatestResponse() throws IOException, MailosaurException { + MessageListResult result = stubClient(empty("500"), empty("1500"), match(null)) + .messages().search(params(60000), CRITERIA); + + assertEquals(Arrays.asList(500L, 1500L), waits); + assertEquals(3, requests); + assertEquals("match-id", result.items().get(0).id()); + } + @Test public void previewWaits1000MsWhenThereIsNoDelayHeader() throws IOException, MailosaurException { byte[] bytes = stubClient(pending(null), ready(null)).files().getPreview("preview-id"); @@ -150,12 +171,12 @@ public void previewUsesEachListedDelayInTurnThenRepeatsTheLast() throws IOExcept @Test public void previewTreatsADelayThatIsNotANumberAs1000Ms() throws IOException, MailosaurException { - String delay = "abc,,1500"; - byte[] bytes = stubClient(pending(delay), pending(delay), pending(delay), ready(delay)) + String delay = "abc,,+500,-500,1500"; + byte[] bytes = stubClient(pending(delay), pending(delay), pending(delay), pending(delay), pending(delay), ready(delay)) .files().getPreview("preview-id"); - assertEquals(Arrays.asList(1000L, 1000L, 1500L), waits); - assertEquals(4, requests); + assertEquals(Arrays.asList(1000L, 1000L, 1000L, 1000L, 1500L), waits); + assertEquals(6, requests); assertArrayEquals(IMAGE, bytes); } @@ -171,6 +192,27 @@ public void previewThrowsATimeoutErrorWhenThePreviewIsNotReadyInTime() { assertEquals("preview_timeout", error.errorType()); } + @Test + public void previewMeasuresElapsedTimeInMilliseconds() { + final MailosaurClient client = stubClient(pending("60700,59500")); + + MailosaurException error = assertThrows(MailosaurException.class, + () -> client.files().getPreview("preview-id")); + + assertEquals(Arrays.asList(60700L), waits); + assertEquals(2, requests); + assertEquals("preview_timeout", error.errorType()); + } + + @Test + public void previewReadsTheDelayFromTheLatestResponse() throws IOException, MailosaurException { + byte[] bytes = stubClient(pending("500"), pending("1500"), ready(null)).files().getPreview("preview-id"); + + assertEquals(Arrays.asList(500L, 1500L), waits); + assertEquals(3, requests); + assertArrayEquals(IMAGE, bytes); + } + private MailosaurClient stubClient(final Reply... replies) { MockHttpTransport transport = new MockHttpTransport() { @Override @@ -178,9 +220,11 @@ public LowLevelHttpRequest buildRequest(String method, String url) { return new MockLowLevelHttpRequest(url) { @Override public LowLevelHttpResponse execute() { - Reply reply = replies[Math.min(requests, replies.length - 1)]; requests++; - return reply.create(); + if (requests > MAX_REQUESTS) { + fail("The client sent more than " + MAX_REQUESTS + " requests, so polling never stopped"); + } + return replies[Math.min(requests, replies.length) - 1].create(); } }; } From 13107557f6d3babd946abf3bce8939a45b394014 Mon Sep 17 00:00:00 2001 From: Jon M Date: Fri, 4 Dec 2026 12:54:32 +0000 Subject: [PATCH 3/4] Assert the full list of matched ids in polling tests The search tests that end in a match now check that the result holds exactly one item, match-id, so an extra item fails the test. --- src/test/java/com/mailosaur/PollingTest.java | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/test/java/com/mailosaur/PollingTest.java b/src/test/java/com/mailosaur/PollingTest.java index 383bd53..957938b 100644 --- a/src/test/java/com/mailosaur/PollingTest.java +++ b/src/test/java/com/mailosaur/PollingTest.java @@ -7,6 +7,7 @@ import com.google.api.client.testing.http.MockLowLevelHttpResponse; import com.mailosaur.models.MessageListResult; import com.mailosaur.models.MessageSearchParams; +import com.mailosaur.models.MessageSummary; import com.mailosaur.models.SearchCriteria; import org.junit.Test; @@ -14,6 +15,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.stream.Collectors; import static org.junit.Assert.*; @@ -36,7 +38,7 @@ public void searchWaits1000MsWhenThereIsNoDelayHeader() throws IOException, Mail assertEquals(Arrays.asList(1000L), waits); assertEquals(2, requests); - assertEquals("match-id", result.items().get(0).id()); + assertEquals(Arrays.asList("match-id"), ids(result)); } @Test @@ -45,7 +47,7 @@ public void searchWaitsASubSecondDelayAsGiven() throws IOException, MailosaurExc assertEquals(Arrays.asList(500L), waits); assertEquals(2, requests); - assertEquals("match-id", result.items().get(0).id()); + assertEquals(Arrays.asList("match-id"), ids(result)); } @Test @@ -54,7 +56,7 @@ public void searchWaitsADelayOverOneSecondAsGiven() throws IOException, Mailosau assertEquals(Arrays.asList(1500L), waits); assertEquals(2, requests); - assertEquals("match-id", result.items().get(0).id()); + assertEquals(Arrays.asList("match-id"), ids(result)); } @Test @@ -65,7 +67,7 @@ public void searchUsesEachListedDelayInTurnThenRepeatsTheLast() throws IOExcepti assertEquals(Arrays.asList(1000L, 2000L, 3000L, 3000L), waits); assertEquals(5, requests); - assertEquals("match-id", result.items().get(0).id()); + assertEquals(Arrays.asList("match-id"), ids(result)); } @Test @@ -98,7 +100,7 @@ public void searchTreatsADelayThatIsNotANumberAs1000Ms() throws IOException, Mai assertEquals(Arrays.asList(1000L, 1000L, 1000L, 1000L, 1500L), waits); assertEquals(6, requests); - assertEquals("match-id", result.items().get(0).id()); + assertEquals(Arrays.asList("match-id"), ids(result)); } @Test @@ -128,7 +130,7 @@ public void searchReadsTheDelayFromTheLatestResponse() throws IOException, Mailo assertEquals(Arrays.asList(500L, 1500L), waits); assertEquals(3, requests); - assertEquals("match-id", result.items().get(0).id()); + assertEquals(Arrays.asList("match-id"), ids(result)); } @Test @@ -239,6 +241,10 @@ public LowLevelHttpResponse execute() { return client; } + private static List ids(MessageListResult result) { + return result.items().stream().map(MessageSummary::id).collect(Collectors.toList()); + } + private static MessageSearchParams params(int timeout) { return new MessageSearchParams().withServer("abcd1234").withTimeout(timeout); } From 8b362fbeb3176b724b8cd90891868e7cf033fee6 Mon Sep 17 00:00:00 2001 From: Jon M Date: Fri, 4 Dec 2026 15:15:26 +0000 Subject: [PATCH 4/4] Trim the poll-delay tests to the nine that each catch something Parsing is shared, so preview keeps only tests of its own loop. The search and preview timeout tests now use delays whose sum just passes the timeout, so they also catch elapsed time counted in whole seconds or checked only after the timeout has passed. --- src/test/java/com/mailosaur/PollingTest.java | 119 +++---------------- 1 file changed, 17 insertions(+), 102 deletions(-) diff --git a/src/test/java/com/mailosaur/PollingTest.java b/src/test/java/com/mailosaur/PollingTest.java index 957938b..e6411b0 100644 --- a/src/test/java/com/mailosaur/PollingTest.java +++ b/src/test/java/com/mailosaur/PollingTest.java @@ -41,24 +41,6 @@ public void searchWaits1000MsWhenThereIsNoDelayHeader() throws IOException, Mail assertEquals(Arrays.asList("match-id"), ids(result)); } - @Test - public void searchWaitsASubSecondDelayAsGiven() throws IOException, MailosaurException { - MessageListResult result = stubClient(empty("500"), match("500")).messages().search(params(60000), CRITERIA); - - assertEquals(Arrays.asList(500L), waits); - assertEquals(2, requests); - assertEquals(Arrays.asList("match-id"), ids(result)); - } - - @Test - public void searchWaitsADelayOverOneSecondAsGiven() throws IOException, MailosaurException { - MessageListResult result = stubClient(empty("1500"), match("1500")).messages().search(params(60000), CRITERIA); - - assertEquals(Arrays.asList(1500L), waits); - assertEquals(2, requests); - assertEquals(Arrays.asList("match-id"), ids(result)); - } - @Test public void searchUsesEachListedDelayInTurnThenRepeatsTheLast() throws IOException, MailosaurException { String delay = "1000,2000,3000"; @@ -70,28 +52,6 @@ public void searchUsesEachListedDelayInTurnThenRepeatsTheLast() throws IOExcepti assertEquals(Arrays.asList("match-id"), ids(result)); } - @Test - public void searchStopsBeforeAWaitThatWouldPassTheTimeout() throws IOException, MailosaurException { - MessageListResult result = stubClient(empty("1000,2000,3000")) - .messages().search(params(5000).withErrorOnTimeout(false), CRITERIA); - - assertEquals(Arrays.asList(1000L, 2000L), waits); - assertEquals(3, requests); - assertTrue(result.items().isEmpty()); - } - - @Test - public void searchThrowsATimeoutErrorWhenNothingMatchesInTime() { - final MailosaurClient client = stubClient(empty("1000,2000,3000")); - - MailosaurException error = assertThrows(MailosaurException.class, - () -> client.messages().search(params(5000), CRITERIA)); - - assertEquals(Arrays.asList(1000L, 2000L), waits); - assertEquals(3, requests); - assertEquals("search_timeout", error.errorType()); - } - @Test public void searchTreatsADelayThatIsNotANumberAs1000Ms() throws IOException, MailosaurException { String delay = "abc,,+500,-500,1500"; @@ -103,26 +63,6 @@ public void searchTreatsADelayThatIsNotANumberAs1000Ms() throws IOException, Mai assertEquals(Arrays.asList("match-id"), ids(result)); } - @Test - public void searchStillWaitsWhenTheWaitEndsExactlyAtTheTimeout() throws IOException, MailosaurException { - MessageListResult result = stubClient(empty("1000,2000,3000")) - .messages().search(params(6000).withErrorOnTimeout(false), CRITERIA); - - assertEquals(Arrays.asList(1000L, 2000L, 3000L), waits); - assertEquals(4, requests); - assertTrue(result.items().isEmpty()); - } - - @Test - public void searchMeasuresElapsedTimeInMilliseconds() throws IOException, MailosaurException { - MessageListResult result = stubClient(empty("700,1500")) - .messages().search(params(2000).withErrorOnTimeout(false), CRITERIA); - - assertEquals(Arrays.asList(700L), waits); - assertEquals(2, requests); - assertTrue(result.items().isEmpty()); - } - @Test public void searchReadsTheDelayFromTheLatestResponse() throws IOException, MailosaurException { MessageListResult result = stubClient(empty("500"), empty("1500"), match(null)) @@ -134,28 +74,24 @@ public void searchReadsTheDelayFromTheLatestResponse() throws IOException, Mailo } @Test - public void previewWaits1000MsWhenThereIsNoDelayHeader() throws IOException, MailosaurException { - byte[] bytes = stubClient(pending(null), ready(null)).files().getPreview("preview-id"); - - assertEquals(Arrays.asList(1000L), waits); - assertEquals(2, requests); - assertArrayEquals(IMAGE, bytes); - } + public void searchThrowsATimeoutErrorWhenNothingMatchesInTime() { + // 700 + 1500 would pass the 2000 ms timeout, so polling stops. Counting elapsed + // time in whole seconds, or checking only after the timeout has passed, would wait again. + final MailosaurClient client = stubClient(empty("700,1500")); - @Test - public void previewWaitsASubSecondDelayAsGiven() throws IOException, MailosaurException { - byte[] bytes = stubClient(pending("500"), ready("500")).files().getPreview("preview-id"); + MailosaurException error = assertThrows(MailosaurException.class, + () -> client.messages().search(params(2000), CRITERIA)); - assertEquals(Arrays.asList(500L), waits); + assertEquals(Arrays.asList(700L), waits); assertEquals(2, requests); - assertArrayEquals(IMAGE, bytes); + assertEquals("search_timeout", error.errorType()); } @Test - public void previewWaitsADelayOverOneSecondAsGiven() throws IOException, MailosaurException { - byte[] bytes = stubClient(pending("1500"), ready("1500")).files().getPreview("preview-id"); + public void previewWaits1000MsWhenThereIsNoDelayHeader() throws IOException, MailosaurException { + byte[] bytes = stubClient(pending(null), ready(null)).files().getPreview("preview-id"); - assertEquals(Arrays.asList(1500L), waits); + assertEquals(Arrays.asList(1000L), waits); assertEquals(2, requests); assertArrayEquals(IMAGE, bytes); } @@ -172,30 +108,18 @@ public void previewUsesEachListedDelayInTurnThenRepeatsTheLast() throws IOExcept } @Test - public void previewTreatsADelayThatIsNotANumberAs1000Ms() throws IOException, MailosaurException { - String delay = "abc,,+500,-500,1500"; - byte[] bytes = stubClient(pending(delay), pending(delay), pending(delay), pending(delay), pending(delay), ready(delay)) - .files().getPreview("preview-id"); + public void previewReadsTheDelayFromTheLatestResponse() throws IOException, MailosaurException { + byte[] bytes = stubClient(pending("500"), pending("1500"), ready(null)).files().getPreview("preview-id"); - assertEquals(Arrays.asList(1000L, 1000L, 1000L, 1000L, 1500L), waits); - assertEquals(6, requests); + assertEquals(Arrays.asList(500L, 1500L), waits); + assertEquals(3, requests); assertArrayEquals(IMAGE, bytes); } @Test public void previewThrowsATimeoutErrorWhenThePreviewIsNotReadyInTime() { - final MailosaurClient client = stubClient(pending("60000")); - - MailosaurException error = assertThrows(MailosaurException.class, - () -> client.files().getPreview("preview-id")); - - assertEquals(Arrays.asList(60000L, 60000L), waits); - assertEquals(3, requests); - assertEquals("preview_timeout", error.errorType()); - } - - @Test - public void previewMeasuresElapsedTimeInMilliseconds() { + // 60700 + 59500 would pass the fixed 120 s preview timeout, so polling stops. Counting elapsed + // time in whole seconds, or checking only after the timeout has passed, would wait again. final MailosaurClient client = stubClient(pending("60700,59500")); MailosaurException error = assertThrows(MailosaurException.class, @@ -206,15 +130,6 @@ public void previewMeasuresElapsedTimeInMilliseconds() { assertEquals("preview_timeout", error.errorType()); } - @Test - public void previewReadsTheDelayFromTheLatestResponse() throws IOException, MailosaurException { - byte[] bytes = stubClient(pending("500"), pending("1500"), ready(null)).files().getPreview("preview-id"); - - assertEquals(Arrays.asList(500L, 1500L), waits); - assertEquals(3, requests); - assertArrayEquals(IMAGE, bytes); - } - private MailosaurClient stubClient(final Reply... replies) { MockHttpTransport transport = new MockHttpTransport() { @Override