feat(ses): paginate template lists and align ListExportJobs paging (#4465)

* feat(ses): paginate template lists and align ListExportJobs paging

Add a namespaced Pagination.paginate overload and SesListPaging, which
holds the probed per-operation page-size bounds, default page sizes,
error messages and empty-token handling. ListTemplates (v1) and
ListEmailTemplates (v2) now page newest first and share one token
namespace, so a token from either continues the other. Without a page
size the template lists serve 10, as SES does. ListExportJobs refuses a
PageSize above 100 instead of clamping it, returns a null NextToken on
the last page, and uses SES's own error messages.

* refactor(ses): inject the template service clock and drop the paging test sleeps

* test(ses): tick the clock between template create and update
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-09-27 08:44:58 -04:00
1 parent 53de56f487
commit 3441532a9d
15 files changed
+807 -86

No files matched your search

@@ -0,0 +1,95 @@
package io.github.hectorvent.floci.core.common;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.function.Function;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
class PaginationTest {
private static final List<String> ITEMS = List.of("c", "a", "b");
private static final AwsException INVALID = new AwsException("BadRequestException", "bad", 400);
private static final Function<String, AwsException> INVALID_TOKEN = token -> INVALID;
@Test
void namespacedPaging_walksTheSortedListAndEndsWithoutAToken() {
PaginatedResult<String> first = page(2, null, "ns");
assertThat(first.items(), contains("a", "b"));
assertThat(decode(first.nextToken()), startsWith("ns:"));
PaginatedResult<String> last = page(2, first.nextToken(), "ns");
assertThat(last.items(), contains("c"));
assertNull(last.nextToken());
}
@Test
void namespacedPaging_refusesATokenFromAnotherNamespace() {
String foreign = page(1, null, "other").nextToken();
assertSame(INVALID, assertThrows(AwsException.class, () -> page(1, foreign, "ns")));
}
@Test
void namespacedPaging_refusesATokenThatDoesNotDecode() {
assertSame(INVALID, assertThrows(AwsException.class, () -> page(1, "!!!", "ns")));
}
@Test
void namespacedPaging_passesTheRawTokenToTheErrorFactory() {
AwsException e = assertThrows(AwsException.class, () -> Pagination.paginate(ITEMS,
Function.identity(), 1, "!!!", "ns",
token -> new AwsException("BadRequestException", "bad " + token, 400)));
assertEquals("bad !!!", e.getMessage());
}
@Test
void namespacedPaging_treatsAnEmptyTokenAsTheFirstPage() {
assertThat(page(1, "", "ns").items(), contains("a"));
}
@Test
void namespacedPaging_refusesALimitBelowOne() {
assertThrows(IllegalArgumentException.class, () -> page(0, null, "ns"));
}
@Test
void paging_aLimitNearIntMaxDoesNotReportAFurtherPage() {
String afterFirst = page(1, null, "ns").nextToken();
PaginatedResult<String> rest = page(Integer.MAX_VALUE, afterFirst, "ns");
assertThat(rest.items(), contains("b", "c"));
assertNull(rest.nextToken());
}
@Test
void legacyPaging_keepsItsTokenFormatAndError() {
PaginatedResult<String> first = Pagination.paginate(ITEMS, Function.identity(), 1, null, 3,
"ValidationException");
assertEquals("a", decode(first.nextToken()));
assertThat(Pagination.paginate(ITEMS, Function.identity(), 1, first.nextToken(), 3,
"ValidationException").items(), contains("b"));
AwsException e = assertThrows(AwsException.class, () -> Pagination.paginate(ITEMS,
Function.identity(), 1, "!!!", 3, "ValidationException"));
assertEquals("ValidationException", e.getErrorCode());
assertEquals("Invalid nextToken.", e.getMessage());
}
private static PaginatedResult<String> page(int limit, String token, String namespace) {
return Pagination.paginate(ITEMS, Function.identity(), limit, token, namespace, INVALID_TOKEN);
}
private static String decode(String token) {
return new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8);
}
}
@@ -19,6 +19,7 @@ import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -395,7 +396,17 @@ class SesExportJobV2IntegrationTest {
void malformedPagingAndResultLimitsAreRefused() {
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"PageSize\": \"ten\"}")
.when().post("/v2/email/list-export-jobs").then().statusCode(400);
.when().post("/v2/email/list-export-jobs").then().statusCode(400)
.body("__type", equalTo("SerializationException"));
// The body is deserialized before any member is validated, so a mistyped member wins.
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"JobStatus\": \"BOGUS\", \"PageSize\": \"ten\"}")
.when().post("/v2/email/list-export-jobs").then().statusCode(400)
.body("__type", equalTo("SerializationException"));
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"ExportSourceType\": \"BOGUS\", \"NextToken\": 5}")
.when().post("/v2/email/list-export-jobs").then().statusCode(400)
.body("__type", equalTo("SerializationException"));
create("""
{"ExportDataSource": {"MessageInsightsDataSource":
@@ -454,18 +465,21 @@ class SesExportJobV2IntegrationTest {
@Test
@Order(16)
void listExportJobs_acceptsAPageSizeAboveTheDefault() {
// PageSize carries no bound in the model, so a large page is a normal request.
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"PageSize\": 250}")
.when().post("/v2/email/list-export-jobs").then().statusCode(200);
void listExportJobs_boundsPagingTheWaySesDoes() {
for (String size : new String[] {"0", "101", "250"}) {
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"PageSize\": %s}".formatted(size))
.when().post("/v2/email/list-export-jobs").then().statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo("PageSize must be between 1 and 100"));
}
for (String token : new String[] {"garbage", ""}) {
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"NextToken\": \"%s\"}".formatted(token))
.when().post("/v2/email/list-export-jobs").then().statusCode(400)
.body("message", equalTo("Failed to deserialize token. "));
}
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"PageSize\": 0}")
.when().post("/v2/email/list-export-jobs").then().statusCode(400);
// A page size at the int ceiling is clamped, not refused, and must not report a further
// page: the paginator adds the page size to the offset as an int.
String token = given().contentType("application/json").header("Authorization", AUTH)
.body("{\"PageSize\": 1}")
.when().post("/v2/email/list-export-jobs").then().statusCode(200)
@@ -473,9 +487,10 @@ class SesExportJobV2IntegrationTest {
assertNotNull(token, "the fixture needs more than one job for this to mean anything");
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"PageSize\": 2147483647, \"NextToken\": \"%s\"}".formatted(token))
.body("{\"PageSize\": 100, \"NextToken\": \"%s\"}".formatted(token))
.when().post("/v2/email/list-export-jobs").then().statusCode(200)
.body("$", not(hasKey("NextToken")));
.body("$", hasKey("NextToken"))
.body("NextToken", nullValue());
}
@Test
@@ -0,0 +1,127 @@
package io.github.hectorvent.floci.services.ses;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.List;
import java.util.function.Function;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
class SesListPagingTest {
private static final List<String> ITEMS = List.of("a", "b", "c");
@Test
void pageSize_defaultsPerOperation() {
assertEquals(10, SesListPaging.V2_LIST_EMAIL_TEMPLATES.pageSize(null));
assertEquals(10, SesListPaging.V1_LIST_TEMPLATES.pageSize(null));
assertEquals(100, SesListPaging.V2_LIST_EXPORT_JOBS.pageSize(null));
assertEquals(1, SesListPaging.V2_LIST_EMAIL_TEMPLATES.pageSize(1));
assertEquals(100, SesListPaging.V2_LIST_EMAIL_TEMPLATES.pageSize(100));
}
@Test
void pageSize_outOfRangeIsRefusedWithThePerOperationMessage() {
assertError("BadRequestException", "The page size must be between 1 and 100",
() -> SesListPaging.V2_LIST_EMAIL_TEMPLATES.pageSize(101));
assertError("BadRequestException", "PageSize must be between 1 and 100",
() -> SesListPaging.V2_LIST_EXPORT_JOBS.pageSize(0));
}
@Test
void pageSize_v1TemplatesServeTheBoundForAnOutOfRangeValue() {
for (int size : new int[] {0, -1, 101, Integer.MAX_VALUE}) {
assertEquals(100, SesListPaging.V1_LIST_TEMPLATES.pageSize(size));
}
}
@Test
void templateTokens_areSharedBetweenV1AndV2AndRefusedByExportJobs() {
String v1Token = page(SesListPaging.V1_LIST_TEMPLATES, 1, null).nextToken();
assertThat(page(SesListPaging.V2_LIST_EMAIL_TEMPLATES, 1, v1Token).items(), contains("b"));
assertError("BadRequestException", "Failed to deserialize token. ",
() -> page(SesListPaging.V2_LIST_EXPORT_JOBS, 1, v1Token));
}
@Test
void invalidToken_messagesQuoteTheToken() {
assertError("BadRequestException", "Invalid PageToken <garbage>.",
() -> page(SesListPaging.V2_LIST_EMAIL_TEMPLATES, 1, "garbage"));
assertError("InvalidParameterValue", "Invalid PageToken <garbage>.",
() -> page(SesListPaging.V1_LIST_TEMPLATES, 1, "garbage"));
}
@Test
void emptyToken_isTheFirstPageForTemplatesAndAnErrorForExportJobs() {
assertThat(page(SesListPaging.V2_LIST_EMAIL_TEMPLATES, 1, "").items(), contains("a"));
assertError("BadRequestException", "Failed to deserialize token. ",
() -> page(SesListPaging.V2_LIST_EXPORT_JOBS, 1, ""));
}
@Test
void lastPage_hasNoToken() {
PaginatedResult<String> page = page(SesListPaging.V2_LIST_EMAIL_TEMPLATES, 3, null);
assertThat(page.items(), contains("a", "b", "c"));
assertNull(page.nextToken());
}
@Test
void newestFirst_ordersByTimeDescendingThenById() {
Instant earlier = Instant.parse("2026-09-25T00:00:00Z");
Instant later = earlier.plusMillis(1);
assertThat(SesListPaging.newestFirst(later, "z"),
lessThan(SesListPaging.newestFirst(earlier, "a")));
assertThat(SesListPaging.newestFirst(later, "a"),
lessThan(SesListPaging.newestFirst(later, "b")));
}
@Test
void parseQueryPageSize_refusesANonInteger() {
assertNull(SesListPaging.parseQueryPageSize(null));
assertNull(SesListPaging.parseQueryPageSize(""));
assertEquals(5, SesListPaging.parseQueryPageSize("5"));
assertError("SerializationException", "'99999999999' can not be converted to Integer",
() -> SesListPaging.parseQueryPageSize("99999999999"));
}
@Test
void parseQueryProtocolPageSize_refusesANonIntegerWithoutAMessage() {
assertNull(SesListPaging.parseQueryProtocolPageSize(null));
assertEquals(5, SesListPaging.parseQueryProtocolPageSize("5"));
assertError("MalformedInput", null, () -> SesListPaging.parseQueryProtocolPageSize("1.5"));
}
@Test
void parseQueryProtocolPageSize_refusesAnEmptyValue() {
assertError("MalformedInput", "missing value for decimal type",
() -> SesListPaging.parseQueryProtocolPageSize(""));
}
@Test
void pageSize_isReportedBeforeTheToken() {
assertError("BadRequestException", "PageSize must be between 1 and 100",
() -> SesListPaging.V2_LIST_EXPORT_JOBS.page(ITEMS, Function.identity(), 0, ""));
assertError("BadRequestException", "The page size must be between 1 and 100",
() -> SesListPaging.V2_LIST_EMAIL_TEMPLATES.page(ITEMS, Function.identity(), 0, "garbage"));
}
private static PaginatedResult<String> page(SesListPaging paging, int size, String token) {
return paging.page(ITEMS, Function.identity(), size, token);
}
private static void assertError(String code, String message, Runnable call) {
AwsException e = assertThrows(AwsException.class, call::run);
assertEquals(code, e.getErrorCode());
assertEquals(message, e.getMessage());
}
}
@@ -168,7 +168,7 @@ final class SesServiceTestBuilder {
return new SesService(
identityService,
sentEmailService,
new SesTemplateService(templateStore, objectMapper, new SecureRandom()),
new SesTemplateService(templateStore, objectMapper, new SecureRandom(), clock),
configSetService,
suppressionService,
new SesDedicatedIpService(dedicatedIpPoolStore),
@@ -0,0 +1,223 @@
package io.github.hectorvent.floci.services.ses;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.xml.XmlPath;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.emptyOrNullString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/**
* Paging of the v1 {@code ListTemplates} and v2 {@code ListEmailTemplates} lists, which share one
* token namespace. Runs in its own region so the three templates are the whole list.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class SesTemplatePagingIntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/ap-southeast-2/ses/aws4_request";
// A second region holding eleven templates, one more than the default page.
private static final String AUTH_ELEVEN =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/ap-southeast-3/ses/aws4_request";
private static final String V1_ROOT = "ListTemplatesResponse.ListTemplatesResult.";
@Test
@Order(1)
void createTemplatesOutOfNameOrder() {
// The test-scope MutableClock advances on every read, so each template gets a later
// creation time and the order below is by time, not by the name tiebreak.
for (String name : new String[] {"page-b", "page-c", "page-a"}) {
given().contentType("application/json").header("Authorization", AUTH)
.body("""
{"TemplateName": "%s", "TemplateContent": {"Subject": "s", "Text": "t"}}
""".formatted(name))
.when().post("/v2/email/templates").then().statusCode(200);
}
}
@Test
@Order(2)
void v2_walksNewestFirstAndEndsOnANullToken() {
String token = given().header("Authorization", AUTH).queryParam("PageSize", 1)
.when().get("/v2/email/templates").then().statusCode(200)
.body("TemplatesMetadata.TemplateName", contains("page-a"))
.body("NextToken", notNullValue())
.extract().path("NextToken");
token = given().header("Authorization", AUTH)
.queryParam("PageSize", 1).queryParam("NextToken", token)
.when().get("/v2/email/templates").then().statusCode(200)
.body("TemplatesMetadata.TemplateName", contains("page-c"))
.extract().path("NextToken");
given().header("Authorization", AUTH)
.queryParam("PageSize", 1).queryParam("NextToken", token)
.when().get("/v2/email/templates").then().statusCode(200)
.body("TemplatesMetadata.TemplateName", contains("page-b"))
.body("$", hasKey("NextToken"))
.body("NextToken", nullValue());
}
@Test
@Order(3)
void v2_withoutPagingReturnsTheWholeListAndANullToken() {
given().header("Authorization", AUTH)
.when().get("/v2/email/templates").then().statusCode(200)
.body("TemplatesMetadata.TemplateName", contains("page-a", "page-c", "page-b"))
.body("$", hasKey("NextToken"))
.body("NextToken", nullValue());
given().header("Authorization", AUTH).queryParam("NextToken", "").queryParam("PageSize", "")
.when().get("/v2/email/templates").then().statusCode(200)
.body("TemplatesMetadata.TemplateName", contains("page-a", "page-c", "page-b"));
}
@Test
@Order(4)
void v2_refusesAPageSizeOutsideOneToAHundred() {
for (int size : new int[] {0, 101}) {
given().header("Authorization", AUTH).queryParam("PageSize", size)
.when().get("/v2/email/templates").then().statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo("The page size must be between 1 and 100"));
}
given().header("Authorization", AUTH).queryParam("PageSize", 100)
.when().get("/v2/email/templates").then().statusCode(200);
}
@Test
@Order(5)
void v2_refusesANonIntegerPageSizeAndAnUnreadableToken() {
given().header("Authorization", AUTH).queryParam("PageSize", "abc")
.when().get("/v2/email/templates").then().statusCode(400)
.body("__type", equalTo("SerializationException"))
.body("message", equalTo("'abc' can not be converted to Integer"));
given().header("Authorization", AUTH).queryParam("NextToken", "garbage")
.when().get("/v2/email/templates").then().statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo("Invalid PageToken <garbage>."));
}
@Test
@Order(6)
void v1_walksNewestFirstAndOmitsTheTokenOnTheLastPage() {
XmlPath first = listV1("1", null);
assertThat(first.getList(V1_ROOT + "TemplatesMetadata.member.Name"), contains("page-a"));
String token = first.getString(V1_ROOT + "NextToken");
XmlPath second = listV1("1", token);
assertThat(second.getList(V1_ROOT + "TemplatesMetadata.member.Name"), contains("page-c"));
given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH)
.formParam("Action", "ListTemplates").formParam("MaxItems", "1")
.formParam("NextToken", second.getString(V1_ROOT + "NextToken"))
.when().post("/").then().statusCode(200)
.body(containsString("<Name>page-b</Name>"))
.body(not(containsString("<NextToken>")));
}
@Test
@Order(7)
void v1_servesAnOutOfRangeMaxItemsInsteadOfRefusingIt() {
for (String size : new String[] {"0", "-1", "1001"}) {
XmlPath page = listV1(size, null);
assertThat(page.getList(V1_ROOT + "TemplatesMetadata.member.Name"),
contains("page-a", "page-c", "page-b"));
}
}
@Test
@Order(8)
void v1_refusesANonIntegerMaxItemsAndAnUnreadableToken() {
given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH)
.formParam("Action", "ListTemplates").formParam("MaxItems", "abc")
.when().post("/").then().statusCode(400)
.body(containsString("<Code>MalformedInput</Code>"))
.body(not(containsString("<Message>")));
given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH)
.formParam("Action", "ListTemplates").formParam("MaxItems", "")
.when().post("/").then().statusCode(400)
.body(containsString("<Code>MalformedInput</Code>"))
.body(containsString("<Message>missing value for decimal type</Message>"));
given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH)
.formParam("Action", "ListTemplates").formParam("NextToken", "garbage")
.when().post("/").then().statusCode(400)
.body(containsString("<Code>InvalidParameterValue</Code>"))
.body(containsString("<Message>Invalid PageToken &lt;garbage&gt;.</Message>"));
}
@Test
@Order(9)
void tokensCarryOverBetweenV1AndV2() {
String v1Token = listV1("1", null).getString(V1_ROOT + "NextToken");
given().header("Authorization", AUTH).queryParam("NextToken", v1Token)
.when().get("/v2/email/templates").then().statusCode(200)
.body("TemplatesMetadata.TemplateName", contains("page-c", "page-b"));
String v2Token = given().header("Authorization", AUTH).queryParam("PageSize", 1)
.when().get("/v2/email/templates").then().statusCode(200)
.extract().path("NextToken");
assertThat(listV1(null, v2Token).getList(V1_ROOT + "TemplatesMetadata.member.Name"),
contains("page-c", "page-b"));
}
@Test
@Order(10)
void withoutAPageSizeBothListsServeTen() {
for (int i = 0; i < 11; i++) {
given().contentType("application/json").header("Authorization", AUTH_ELEVEN)
.body("""
{"TemplateName": "eleven-%02d", "TemplateContent": {"Subject": "s", "Text": "t"}}
""".formatted(i))
.when().post("/v2/email/templates").then().statusCode(200);
}
given().header("Authorization", AUTH_ELEVEN)
.when().get("/v2/email/templates").then().statusCode(200)
.body("TemplatesMetadata", hasSize(10))
.body("NextToken", notNullValue());
XmlPath v1Default = given().contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_ELEVEN).formParam("Action", "ListTemplates")
.when().post("/").then().statusCode(200).extract().xmlPath();
assertThat(v1Default.getList(V1_ROOT + "TemplatesMetadata.member.Name"), hasSize(10));
assertThat(v1Default.getString(V1_ROOT + "NextToken"), not(emptyOrNullString()));
// An out-of-range MaxItems is served the bound, not the default.
XmlPath outOfRange = given().contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_ELEVEN)
.formParam("Action", "ListTemplates").formParam("MaxItems", "0")
.when().post("/").then().statusCode(200).extract().xmlPath();
assertThat(outOfRange.getList(V1_ROOT + "TemplatesMetadata.member.Name"), hasSize(11));
}
private static XmlPath listV1(String maxItems, String nextToken) {
RequestSpecification request = given()
.contentType("application/x-www-form-urlencoded").header("Authorization", AUTH)
.formParam("Action", "ListTemplates");
if (maxItems != null) {
request.formParam("MaxItems", maxItems);
}
if (nextToken != null) {
request.formParam("NextToken", nextToken);
}
return request.when().post("/").then().statusCode(200).extract().xmlPath();
}
}
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.ses.model.EmailTemplate;
import io.github.hectorvent.floci.services.ses.model.Tag;
import io.github.hectorvent.floci.testing.MutableClock;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.provider.MethodSource;
@@ -14,9 +15,13 @@ import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.ParameterizedTest;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Instant;
import java.util.List;
import java.util.stream.Stream;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -37,7 +42,8 @@ class SesTemplateServiceTest {
@BeforeEach
void setUp() {
service = new SesTemplateService(new InMemoryStorage<>(), new ObjectMapper(), new SecureRandom());
service = new SesTemplateService(new InMemoryStorage<>(), new ObjectMapper(), new SecureRandom(),
Clock.systemUTC());
}
private static EmailTemplate template(String name) {
@@ -98,15 +104,27 @@ class SesTemplateServiceTest {
}
@Test
void list_isSortedByCreationAndPerRegion() {
void create_andUpdate_stampTheInjectedClock() {
SesTemplateService ticking = new SesTemplateService(new InMemoryStorage<>(), new ObjectMapper(),
new SecureRandom(), new MutableClock());
Instant created = ticking.createTemplate(template("welcome"), REGION).getCreatedTimestamp();
ticking.updateTemplate(template("welcome"), REGION);
EmailTemplate stored = ticking.getTemplate("welcome", REGION);
assertEquals(created, stored.getCreatedTimestamp());
assertEquals(created.plusMillis(1), stored.getLastUpdatedTimestamp());
}
@Test
void list_isPerRegion() {
service.createTemplate(template("a"), REGION);
service.createTemplate(template("b"), REGION);
service.createTemplate(template("other"), "eu-west-1");
List<EmailTemplate> list = service.listTemplates(REGION);
assertEquals(2, list.size());
assertEquals("a", list.get(0).getTemplateName());
assertEquals("b", list.get(1).getTemplateName());
List<String> names = service.listTemplates(REGION).stream()
.map(EmailTemplate::getTemplateName).toList();
assertThat(names, containsInAnyOrder("a", "b"));
}
@Test