refactor(cloudformation): tell each provisioner what the update changed in its properties (#8087)

This commit is contained in:
Oleksandr Nikolaichuk authored and GitHub committed 2026-11-12 16:20:30 -04:00
1 parent c0ef5b2bfd
commit 5876a37888
15 files changed
+1069 -31

No files matched your search

@@ -0,0 +1,191 @@
package io.floci.aws.services.cloudformation;
import com.fasterxml.jackson.databind.JsonNode;
import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.cloudformation.provisioners.PropertyChanges;
import io.floci.aws.services.cloudformation.provisioners.PropertyChanges.Kind;
import io.floci.aws.services.cloudformation.provisioners.ProvisionContext;
import io.floci.aws.services.cloudformation.provisioners.SqsCfnProvisioner;
import io.floci.aws.testing.CfnStackWaits;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.mockito.InjectSpy;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static io.floci.aws.testing.CfnRequests.cfn;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.verify;
/**
* UpdateStack hands the provisioner the engine's statement of what happened to each top-level
* property: the {@link ProvisionContext} it receives carries a {@link PropertyChanges} whose kinds
* decide CHANGED against UNCHANGED by the forms CloudFormation compares, so a value rewritten
* without changing what it resolves to is UNCHANGED.
*
* <p>Observed by spying on the real SQS provisioner and capturing the context of each call.
*/
@QuarkusTest
class CfnPropertyChangesIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20261110/us-east-1/cloudformation/aws4_request";
@InjectSpy
SqsCfnProvisioner sqsProvisioner;
private static String template(String queueName, String properties) {
return """
{
"Resources": {
"Queue": {
"Type": "AWS::SQS::Queue",
"Properties": {"QueueName": "%s", %s}
}
}
}
""".formatted(queueName, properties);
}
@Test
void updateGivesTheProvisionerTheKindOfEveryProperty() {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "changes-" + suffix;
String queue = "changes-q-" + suffix;
cfn("CreateStack", stack).header("Authorization", CFN_AUTH)
.formParam("TemplateBody", template(queue, """
"VisibilityTimeout": "30", "DelaySeconds": "5", "MessageRetentionPeriod": "600"
"""))
.when().post("/").then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE", CFN_AUTH);
cfn("UpdateStack", stack).header("Authorization", CFN_AUTH)
.formParam("TemplateBody", template(queue, """
"VisibilityTimeout": {"Fn::Join": ["", ["3", "0"]]},
"MaximumMessageSize": "2048", "MessageRetentionPeriod": "1200"
"""))
.when().post("/").then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "UPDATE_COMPLETE", CFN_AUTH);
ArgumentCaptor<ProvisionContext> contexts = ArgumentCaptor.forClass(ProvisionContext.class);
verify(sqsProvisioner, atLeast(2)).provision(any(), any(), contexts.capture());
List<ProvisionContext> seen = contexts.getAllValues().stream()
.filter(ctx -> ctx.stackName().equals(stack))
.toList();
ProvisionContext created = seen.get(0);
ProvisionContext updated = seen.get(seen.size() - 1);
PropertyChanges onCreate = created.changes();
assertNotNull(onCreate, "the engine supplies the object on a create too");
assertEquals(Set.of("QueueName", "VisibilityTimeout", "DelaySeconds", "MessageRetentionPeriod"),
onCreate.added());
assertTrue(onCreate.dropped().isEmpty());
PropertyChanges changes = updated.changes();
assertNotNull(changes, "the engine supplies the object on an update");
assertEquals(Kind.UNCHANGED, changes.kindOf("QueueName"));
assertEquals(Kind.UNCHANGED, changes.kindOf("VisibilityTimeout"),
"written as an Fn::Join but resolving to the same value");
assertEquals(Kind.CHANGED, changes.kindOf("MessageRetentionPeriod"));
assertEquals(Kind.DROPPED, changes.kindOf("DelaySeconds"));
assertEquals(Kind.ADDED, changes.kindOf("MaximumMessageSize"));
assertEquals(Set.of("DelaySeconds"), changes.dropped());
assertEquals(Set.of("MaximumMessageSize"), changes.added());
assertTrue(changes.byName().get("QueueName").createOnly());
}
/** What one provision call saw, read before the real provisioner runs. */
private record Seen(String stack, boolean isUpdate, List<String> contextDropped,
PropertyChanges changes) {
}
/**
* Creates then updates a queue stack, recording what each provision call saw. When
* {@code overwriteId} is true, the spy overwrites the
* resource's physical id after the real call, so the next update meets a resource kept with
* a null or blank physical id.
*/
private List<Seen> createThenUpdateDroppingDelay(String stack, boolean overwriteId,
String physicalIdAfterProvision) {
List<Seen> seen = new ArrayList<>();
doAnswer(invocation -> {
StackResource resource = invocation.getArgument(0);
JsonNode props = invocation.getArgument(1);
ProvisionContext ctx = invocation.getArgument(2);
seen.add(new Seen(ctx.stackName(), ctx.isUpdate(),
new ArrayList<>(ctx.droppedProperties(props)), ctx.changes()));
Object result = invocation.callRealMethod();
if (overwriteId) {
resource.setPhysicalId(physicalIdAfterProvision);
}
return result;
}).when(sqsProvisioner).provision(any(), any(), any());
String queue = stack + "-q";
cfn("CreateStack", stack).header("Authorization", CFN_AUTH)
.formParam("TemplateBody", template(queue, """
"VisibilityTimeout": "30", "DelaySeconds": "5"
"""))
.when().post("/").then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE", CFN_AUTH);
cfn("UpdateStack", stack).header("Authorization", CFN_AUTH)
.formParam("TemplateBody", template(queue, """
"VisibilityTimeout": "30"
"""))
.when().post("/").then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "UPDATE_COMPLETE", CFN_AUTH);
return seen.stream().filter(s -> s.stack().equals(stack)).toList();
}
private void assertEngineSaysNothingIsDropped(List<Seen> forStack) {
assertEquals(2, forStack.size(), "one provision call for the create, one for the update");
Seen update = forStack.get(1);
assertFalse(update.isUpdate(), "a resource without a physical id is not an update");
assertEquals(List.of(), update.contextDropped());
PropertyChanges changes = update.changes();
assertNotNull(changes, "the engine supplies the object on every call");
assertEquals(List.of(), List.copyOf(changes.dropped()),
"the engine agrees with the context that nothing is dropped");
assertEquals(Set.of(), changes.changed());
assertEquals(Set.of(), changes.unchanged());
assertEquals(Set.of("QueueName", "VisibilityTimeout"), changes.added(),
"every property of the current template is ADDED when the context is not an update");
}
@Test
void engineAndContextAgreeOnDroppedForANormalUpdate() {
String stack = "agree-" + Long.toString(System.nanoTime(), 36);
List<Seen> forStack = createThenUpdateDroppingDelay(stack, false, null);
assertEquals(2, forStack.size());
Seen update = forStack.get(1);
assertTrue(update.isUpdate());
assertEquals(List.of("DelaySeconds"), update.contextDropped());
assertNotNull(update.changes());
assertEquals(update.contextDropped(), List.copyOf(update.changes().dropped()));
}
@Test
void updateOfAResourceWithANullPhysicalIdIsNotAnUpdateForTheEngineEither() {
String stack = "nullid-" + Long.toString(System.nanoTime(), 36);
assertEngineSaysNothingIsDropped(createThenUpdateDroppingDelay(stack, true, null));
}
@Test
void updateOfAResourceWithABlankPhysicalIdIsNotAnUpdateForTheEngineEither() {
String stack = "blankid-" + Long.toString(System.nanoTime(), 36);
assertEngineSaysNothingIsDropped(createThenUpdateDroppingDelay(stack, true, " "));
}
}
@@ -51,7 +51,7 @@ class CloudFormationStackPolicyServiceTest {
void setUp() {
provisioner = mock(CfnResourceDispatcher.class);
when(provisioner.provision(anyString(), anyString(), any(), any(), anyString(), anyString(), anyString(),
any(), any(), any(), any())).thenAnswer(invocation -> {
any(), any(), any(), any(), any())).thenAnswer(invocation -> {
StackResource resource = new StackResource();
resource.setLogicalId(invocation.getArgument(0));
resource.setResourceType(invocation.getArgument(1));
@@ -0,0 +1,44 @@
package io.floci.aws.services.cloudformation.provisioners;
import org.mockito.ArgumentCaptor;
import org.mockito.MockMakers;
import org.mockito.MockedStatic;
import java.util.Map;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.CALLS_REAL_METHODS;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.withSettings;
/**
* Test support for provisioners that rebuild their {@link ProvisionContext} mid-provision: the
* engine's {@link PropertyChanges} must still be on the context they hand to
* {@link ReplacementCleanup#record}.
*/
final class CarriedChanges {
/** A distinct instance, so a test can tell the engine's statement from one derived afterwards. */
static final PropertyChanges ENGINE_STATEMENT = new PropertyChanges(Map.of());
private CarriedChanges() {
}
/** {@code base} with the engine's statement attached. */
static ProvisionContext withEngineStatement(ProvisionContext base) {
return new ProvisionContext(base.engine(), base.region(), base.accountId(), base.stackName(),
base.priorPhysicalId(), base.progress(), base.priorProperties(), ENGINE_STATEMENT);
}
/** Runs {@code provision} and returns the context its last {@code ReplacementCleanup.record} call received. */
static ProvisionContext contextRecorded(Runnable provision) {
try (MockedStatic<ReplacementCleanup> cleanup = mockStatic(ReplacementCleanup.class,
withSettings().mockMaker(MockMakers.INLINE).defaultAnswer(CALLS_REAL_METHODS))) {
provision.run();
ArgumentCaptor<ProvisionContext> recorded = ArgumentCaptor.forClass(ProvisionContext.class);
cleanup.verify(() -> ReplacementCleanup.record(any(), recorded.capture(), any()), atLeastOnce());
return recorded.getAllValues().getLast();
}
}
}
@@ -21,6 +21,7 @@ import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -583,6 +584,19 @@ class CognitoResourceServerCfnProvisionerTest {
verify(cognito, never()).deleteResourceServer(NEW_POOL, IDENTIFIER);
}
@Test
void aReplacementKeepsTheEnginesChangesOnTheCleanupContext() {
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(server(POOL, IDENTIFIER, "Old API"));
StackResource resource = resource(IDENTIFIER, POOL);
ProvisionContext engineContext = CarriedChanges.withEngineStatement(ctx(IDENTIFIER));
ObjectNode desired = properties(NEW_POOL, IDENTIFIER, "New API");
ProvisionContext recorded = CarriedChanges.contextRecorded(
() -> provisioner.provision(resource, desired, engineContext));
assertSame(CarriedChanges.ENGINE_STATEMENT, recorded.changes("AWS::Cognito::UserPoolResourceServer", null));
}
@Test
void retainingAReplacementDoesNotDeleteThePriorResource() {
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(server(POOL, IDENTIFIER, "Old API"));
@@ -0,0 +1,402 @@
package io.floci.aws.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.NullNode;
import io.floci.aws.services.cloudformation.provisioners.PropertyChanges.Kind;
import io.floci.aws.services.cloudformation.provisioners.PropertyChanges.PropertyChange;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* What the engine tells a provisioner about each top-level property of an update: added, changed,
* dropped or unchanged. Every expected value is written out by hand from the rules of the design
* (floci-spine 1.1), never read back from the implementation.
*/
class PropertyChangesTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static JsonNode json(String json) {
try {
return MAPPER.readTree(json);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
private static List<String> names(PropertyChanges changes) {
return List.copyOf(changes.byName().keySet());
}
// Rule 2: not an update, or no usable prior properties.
@Test
void createMarksEveryPropertyAddedAndNothingElse() {
PropertyChanges changes = PropertyChanges.between("AWS::SQS::Queue", false, null,
json("{\"QueueName\": \"q\", \"DelaySeconds\": 5}"));
assertEquals(List.of("QueueName", "DelaySeconds"), names(changes));
assertEquals(Kind.ADDED, changes.kindOf("QueueName"));
assertEquals(Kind.ADDED, changes.kindOf("DelaySeconds"));
assertEquals(Set.of("QueueName", "DelaySeconds"), changes.added());
assertTrue(changes.changed().isEmpty());
assertTrue(changes.dropped().isEmpty());
assertTrue(changes.unchanged().isEmpty());
}
@Test
void createIgnoresPriorPropertiesEvenWhenTheyAreSupplied() {
PropertyChanges changes = PropertyChanges.between(null, false,
json("{\"Gone\": 1, \"Same\": 2}"), json("{\"Same\": 2, \"New\": 3}"));
assertEquals(List.of("Same", "New"), names(changes));
assertEquals(Set.of("Same", "New"), changes.added());
assertTrue(changes.dropped().isEmpty());
assertTrue(changes.unchanged().isEmpty());
assertNull(changes.kindOf("Gone"));
}
@Test
void createWithComparedFormsStillMarksEveryPropertyAdded() {
PropertyChanges changes = PropertyChanges.between(null, false, null, json("{\"A\": 1}"),
json("{\"A\": 1}"), json("{\"A\": 1}"));
assertEquals(Kind.ADDED, changes.kindOf("A"));
}
@Test
void createWithNullPropertiesHasNoChanges() {
PropertyChanges changes = PropertyChanges.between(null, false, null, null);
assertTrue(changes.byName().isEmpty());
assertTrue(changes.added().isEmpty());
assertTrue(changes.dropped().isEmpty());
}
@Test
void createMarksAJsonNullPropertyAdded() {
PropertyChanges changes = PropertyChanges.between(null, false, null, json("{\"A\": null}"));
assertEquals(Kind.ADDED, changes.kindOf("A"));
}
@Test
void updateWithNullPriorPropertiesMarksEveryPropertyAdded() {
PropertyChanges changes = PropertyChanges.between(null, true, null, json("{\"A\": 1, \"B\": 2}"));
assertEquals(Set.of("A", "B"), changes.added());
assertTrue(changes.changed().isEmpty());
assertTrue(changes.dropped().isEmpty());
assertTrue(changes.unchanged().isEmpty());
}
@Test
void updateWithANonObjectPriorMarksEveryPropertyAdded() {
for (String prior : List.of("[1, 2]", "\"text\"", "7", "null", "true")) {
PropertyChanges changes = PropertyChanges.between(null, true, json(prior), json("{\"A\": 1, \"B\": 2}"));
assertEquals(List.of("A", "B"), names(changes), prior);
assertEquals(Set.of("A", "B"), changes.added(), prior);
assertTrue(changes.dropped().isEmpty(), prior);
assertTrue(changes.unchanged().isEmpty(), prior);
}
}
// Rule 3: update with prior properties.
@Test
void updateClassifiesAddedChangedDroppedAndUnchangedAsWritten() {
PropertyChanges changes = PropertyChanges.between("AWS::SQS::Queue", true,
json("{\"Kept\": \"a\", \"Edited\": \"b\", \"Removed\": \"c\"}"),
json("{\"Kept\": \"a\", \"Edited\": \"B\", \"Fresh\": \"d\"}"));
assertEquals(Kind.UNCHANGED, changes.kindOf("Kept"));
assertEquals(Kind.CHANGED, changes.kindOf("Edited"));
assertEquals(Kind.DROPPED, changes.kindOf("Removed"));
assertEquals(Kind.ADDED, changes.kindOf("Fresh"));
assertEquals(Set.of("Fresh"), changes.added());
assertEquals(Set.of("Edited"), changes.changed());
assertEquals(Set.of("Removed"), changes.dropped());
assertEquals(Set.of("Kept"), changes.unchanged());
}
@Test
void aNameInNeitherTemplateHasNoKind() {
PropertyChanges changes = PropertyChanges.between(null, true, json("{\"A\": 1}"), json("{\"A\": 1}"));
assertNull(changes.kindOf("Absent"));
assertFalse(changes.byName().containsKey("Absent"));
}
@Test
void asWrittenComparisonIsStructuralJsonEquality() {
PropertyChanges changes = PropertyChanges.between(null, true,
json("{\"Obj\": {\"x\": [1, 2]}, \"Num\": 1, \"Str\": \"1\"}"),
json("{\"Obj\": {\"x\": [1, 2]}, \"Num\": 1, \"Str\": 1}"));
assertEquals(Kind.UNCHANGED, changes.kindOf("Obj"));
assertEquals(Kind.UNCHANGED, changes.kindOf("Num"));
assertEquals(Kind.CHANGED, changes.kindOf("Str"), "the text \"1\" is not the number 1 as written");
}
// Rule 1: JSON null.
@Test
void aJsonNullBeforeIsNotDeclaredSoANonNullNowIsAdded() {
PropertyChanges changes = PropertyChanges.between(null, true,
json("{\"A\": null}"), json("{\"A\": \"v\"}"));
PropertyChange change = changes.byName().get("A");
assertEquals(Kind.ADDED, change.kind());
assertNull(change.prior(), "not declared before, so no prior node");
assertEquals("v", change.current().asText());
}
@Test
void aJsonNullNowIsDeclaredSoANonNullBeforeIsChanged() {
JsonNode current = json("{\"A\": null}");
PropertyChanges changes = PropertyChanges.between(null, true, json("{\"A\": \"v\"}"), current);
PropertyChange change = changes.byName().get("A");
assertEquals(Kind.CHANGED, change.kind());
assertEquals("v", change.prior().asText());
assertSame(current.get("A"), change.current());
assertTrue(change.current().isNull());
}
@Test
void aJsonNullOnBothSidesIsAddedBecauseOnlyNowIsDeclared() {
PropertyChanges changes = PropertyChanges.between(null, true, json("{\"A\": null}"), json("{\"A\": null}"));
PropertyChange change = changes.byName().get("A");
assertEquals(Kind.ADDED, change.kind());
assertNull(change.prior());
assertEquals(NullNode.getInstance(), change.current());
}
@Test
void aJsonNullBeforeAndAbsentNowIsInNeitherTemplate() {
PropertyChanges changes = PropertyChanges.between(null, true, json("{\"A\": null, \"B\": 1}"), json("{}"));
assertNull(changes.kindOf("A"));
assertEquals(Set.of("B"), changes.dropped());
}
// Rule 8: properties null (or not an object) on an update.
@Test
void nullPropertiesOnAnUpdateDropEveryPreviouslyDeclaredName() {
PropertyChanges changes = PropertyChanges.between("AWS::SQS::Queue", true,
json("{\"A\": 1, \"Nothing\": null, \"B\": 2}"), null);
assertEquals(List.of("A", "B"), names(changes));
assertEquals(Set.of("A", "B"), changes.dropped());
assertTrue(changes.added().isEmpty());
assertTrue(changes.changed().isEmpty());
assertTrue(changes.unchanged().isEmpty());
}
@Test
void nonObjectPropertiesOnAnUpdateDropEveryPreviouslyDeclaredName() {
PropertyChanges changes = PropertyChanges.between(null, true, json("{\"A\": 1}"), json("[\"A\"]"));
assertEquals(Set.of("A"), changes.dropped());
}
// Rule 4: compared forms.
@Test
void aDifferenceOnlyAsWrittenIsUnchangedWhenTheComparedFormsAgree() {
PropertyChanges changes = PropertyChanges.between(null, true,
json("{\"Timeout\": \"30\"}"),
json("{\"Timeout\": {\"Fn::Join\": [\"\", [\"3\", \"0\"]]}}"),
json("{\"Timeout\": \"30\"}"), json("{\"Timeout\": \"30\"}"));
assertEquals(Kind.UNCHANGED, changes.kindOf("Timeout"));
assertEquals(Set.of("Timeout"), changes.unchanged());
assertTrue(changes.changed().isEmpty());
}
@Test
void anAsWrittenEqualityIsChangedWhenTheComparedFormsDiffer() {
PropertyChanges changes = PropertyChanges.between(null, true,
json("{\"Size\": {\"Ref\": \"P\"}}"), json("{\"Size\": {\"Ref\": \"P\"}}"),
json("{\"Size\": \"1\"}"), json("{\"Size\": \"2\"}"));
assertEquals(Kind.CHANGED, changes.kindOf("Size"));
}
@Test
void withoutComparedFormsTheAsWrittenValuesDecide() {
PropertyChanges nullForms = PropertyChanges.between(null, true,
json("{\"A\": 1, \"B\": 1}"), json("{\"A\": 1, \"B\": 2}"), null, null);
PropertyChanges shortForm = PropertyChanges.between(null, true,
json("{\"A\": 1, \"B\": 1}"), json("{\"A\": 1, \"B\": 2}"));
assertEquals(Kind.UNCHANGED, nullForms.kindOf("A"));
assertEquals(Kind.CHANGED, nullForms.kindOf("B"));
assertEquals(shortForm.kindOf("A"), nullForms.kindOf("A"));
assertEquals(shortForm.kindOf("B"), nullForms.kindOf("B"));
}
@Test
void aNullComparedPriorOrCurrentFallsBackToAsWritten() {
JsonNode prior = json("{\"Same\": 1, \"Diff\": 1}");
JsonNode current = json("{\"Same\": 1, \"Diff\": 2}");
JsonNode compared = json("{\"Same\": \"x\", \"Diff\": \"x\"}");
PropertyChanges noPrior = PropertyChanges.between(null, true, prior, current, null, compared);
PropertyChanges noCurrent = PropertyChanges.between(null, true, prior, current, compared, null);
assertEquals(Kind.UNCHANGED, noPrior.kindOf("Same"));
assertEquals(Kind.CHANGED, noPrior.kindOf("Diff"), "the compared forms agree but one side is absent");
assertEquals(Kind.UNCHANGED, noCurrent.kindOf("Same"));
assertEquals(Kind.CHANGED, noCurrent.kindOf("Diff"));
}
@Test
void aNameMissingFromTheComparedCurrentUsesTheAsWrittenValues() {
PropertyChanges differs = PropertyChanges.between(null, true,
json("{\"A\": 1}"), json("{\"A\": 2}"),
json("{\"A\": \"x\"}"), json("{}"));
PropertyChanges equal = PropertyChanges.between(null, true,
json("{\"A\": 1}"), json("{\"A\": 1}"),
json("{\"A\": \"x\"}"), json("{}"));
assertEquals(Kind.CHANGED, differs.kindOf("A"));
assertEquals(Kind.UNCHANGED, equal.kindOf("A"));
}
@Test
void aNameMissingFromBothComparedFormsUsesTheAsWrittenValues() {
PropertyChanges changes = PropertyChanges.between(null, true,
json("{\"A\": 1}"), json("{\"A\": 2}"), json("{}"), json("{}"));
assertEquals(Kind.CHANGED, changes.kindOf("A"), "two missing nodes are not an agreement");
}
@Test
void comparedFormsNeverTurnAnAddedOrDroppedNameIntoAnythingElse() {
PropertyChanges changes = PropertyChanges.between(null, true,
json("{\"Old\": 1}"), json("{\"New\": 1}"),
json("{\"Old\": 1, \"New\": 1}"), json("{\"Old\": 1, \"New\": 1}"));
assertEquals(Kind.DROPPED, changes.kindOf("Old"));
assertEquals(Kind.ADDED, changes.kindOf("New"));
}
// Rule 5: prior and current are the raw nodes.
@Test
void priorAndCurrentAreTheNodesOfTheTemplatePropertiesNotTheComparedForms() {
JsonNode prior = json("{\"A\": {\"Fn::Join\": [\"\", [\"a\"]]}, \"Gone\": \"g\"}");
JsonNode current = json("{\"A\": \"a\", \"New\": \"n\"}");
PropertyChanges changes = PropertyChanges.between(null, true, prior, current,
json("{\"A\": \"COMPARED-PRIOR\"}"), json("{\"A\": \"COMPARED-PRIOR\"}"));
PropertyChange a = changes.byName().get("A");
assertSame(prior.get("A"), a.prior());
assertSame(current.get("A"), a.current());
assertEquals("A", a.name());
PropertyChange gone = changes.byName().get("Gone");
assertSame(prior.get("Gone"), gone.prior());
assertNull(gone.current(), "a dropped property has no current node");
PropertyChange added = changes.byName().get("New");
assertNull(added.prior(), "an added property has no prior node");
assertSame(current.get("New"), added.current());
}
// Rule 6: createOnly.
/** {@code create-only-properties.json}: {@code AWS::SQS::Queue} lists FifoQueue and QueueName. */
@Test
void createOnlyFollowsTheRegistryForTheResourceType() {
PropertyChanges changes = PropertyChanges.between("AWS::SQS::Queue", true,
json("{\"QueueName\": \"a\", \"VisibilityTimeout\": 1, \"FifoQueue\": true}"),
json("{\"QueueName\": \"b\", \"VisibilityTimeout\": 2, \"New\": 1}"));
assertTrue(changes.byName().get("QueueName").createOnly());
assertTrue(changes.byName().get("FifoQueue").createOnly(), "also true for a dropped create-only property");
assertFalse(changes.byName().get("VisibilityTimeout").createOnly());
assertFalse(changes.byName().get("New").createOnly());
}
@Test
void createOnlyIsFalseForEveryNameWithoutAResourceType() {
PropertyChanges changes = PropertyChanges.between(null, true,
json("{\"QueueName\": \"a\"}"), json("{\"QueueName\": \"b\"}"));
assertFalse(changes.byName().get("QueueName").createOnly());
}
@Test
void createOnlyIsFalseForATypeTheRegistryDoesNotKnow() {
PropertyChanges changes = PropertyChanges.between("Custom::Thing", false, null, json("{\"QueueName\": \"a\"}"));
assertFalse(changes.byName().get("QueueName").createOnly());
}
// Rule 7: order and unmodifiable views.
@Test
void byNameFollowsThePriorTemplatesOrderThenTheRemainingNamesInPropertiesOrder() {
PropertyChanges changes = PropertyChanges.between(null, true,
json("{\"B\": 1, \"A\": 2, \"C\": 3}"), json("{\"D\": 4, \"A\": 2, \"B\": 9, \"E\": 5}"));
assertEquals(List.of("B", "A", "C", "D", "E"), names(changes));
assertEquals(Kind.CHANGED, changes.kindOf("B"));
assertEquals(Kind.UNCHANGED, changes.kindOf("A"));
assertEquals(Kind.DROPPED, changes.kindOf("C"));
assertEquals(Kind.ADDED, changes.kindOf("D"));
}
@Test
void eachSetKeepsThatOrder() {
PropertyChanges changes = PropertyChanges.between(null, true,
json("{\"Z\": 1, \"A\": 2, \"M\": 3, \"Keep\": 0}"),
json("{\"Y\": 1, \"Keep\": 0, \"X\": 2}"));
assertEquals(List.of("Z", "A", "M"), List.copyOf(changes.dropped()));
assertEquals(List.of("Y", "X"), List.copyOf(changes.added()));
assertEquals(List.of("Keep"), List.copyOf(changes.unchanged()));
assertTrue(changes.changed().isEmpty());
}
@Test
void theFourSetsAreUnmodifiable() {
PropertyChanges changes = PropertyChanges.between(null, true,
json("{\"A\": 1, \"B\": 1, \"C\": 1}"), json("{\"A\": 2, \"B\": 1, \"D\": 1}"));
assertThrows(UnsupportedOperationException.class, () -> changes.added().add("X"));
assertThrows(UnsupportedOperationException.class, () -> changes.changed().add("X"));
assertThrows(UnsupportedOperationException.class, () -> changes.dropped().add("X"));
assertThrows(UnsupportedOperationException.class, () -> changes.unchanged().add("X"));
assertThrows(UnsupportedOperationException.class, () -> changes.dropped().clear());
}
@Test
void theFourSetsPartitionByName() {
PropertyChanges changes = PropertyChanges.between(null, true,
json("{\"A\": 1, \"B\": 1, \"C\": 1}"), json("{\"A\": 2, \"B\": 1, \"D\": 1}"));
Map<String, PropertyChange> byName = changes.byName();
assertEquals(byName.size(), changes.added().size() + changes.changed().size()
+ changes.dropped().size() + changes.unchanged().size());
assertEquals(Set.of("D"), changes.added());
assertEquals(Set.of("A"), changes.changed());
assertEquals(Set.of("C"), changes.dropped());
assertEquals(Set.of("B"), changes.unchanged());
}
}
@@ -6,15 +6,21 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import java.lang.reflect.RecordComponent;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -59,6 +65,25 @@ class ProvisionContextTest {
event -> { }, priorProperties == null ? null : props(priorProperties));
}
@Test
void withPriorPhysicalIdChangesOnlyThePriorPhysicalId() throws Exception {
PropertyChanges changes = PropertyChanges.between("AWS::SQS::Queue", true,
props("{\"A\":1}"), props("{\"A\":2}"));
ProvisionContext original = new ProvisionContext(engine, "eu-west-1", "123456789012", "stack",
"old-id", event -> {}, props("{\"A\":1}"), changes);
for (String replacement : new String[] {"new-id", null}) {
ProvisionContext copy = original.withPriorPhysicalId(replacement);
for (RecordComponent component : ProvisionContext.class.getRecordComponents()) {
Object expected = component.getName().equals("priorPhysicalId")
? replacement : component.getAccessor().invoke(original);
assertSame(expected, component.getAccessor().invoke(copy), component.getName());
}
}
assertEquals("old-id", original.priorPhysicalId());
}
@Test
void previouslyDeclaredReadsThePreviousTemplatesProperties() {
ProvisionContext ctx = contextWithPriorProperties("""
@@ -83,6 +108,110 @@ class ProvisionContextTest {
assertEquals(Set.of("Kept", "Dropped", "DroppedIf"), ctx.droppedProperties(null));
}
/** One prior/current pair for the rule that {@code changes(...).dropped()} is {@code droppedProperties}. */
private record DroppedCase(String label, String priorPhysicalId, String prior, String props,
List<String> expected) {
@Override
public String toString() {
return label;
}
}
private static DroppedCase dropped(String label, String prior, String props, String... expected) {
return new DroppedCase(label, "prior-id", prior, props, List.of(expected));
}
/** Expected lists are the result of today's droppedProperties, worked out by hand from its definition. */
static Stream<DroppedCase> droppedCases() {
return Stream.of(
dropped("one name removed", "{\"A\":1,\"B\":2}", "{\"A\":1}", "B"),
dropped("everything removed, empty props", "{\"A\":1,\"B\":2}", "{}", "A", "B"),
dropped("everything removed, null props", "{\"A\":1,\"B\":2}", null, "A", "B"),
dropped("a prior JSON null was never declared", "{\"A\":null,\"B\":2}", "{}", "B"),
dropped("a JSON null now still counts as declared now", "{\"A\":1}", "{\"A\":null}"),
dropped("same names in another order", "{\"A\":1,\"B\":2}", "{\"B\":2,\"A\":1}"),
dropped("prior field order is kept", "{\"Z\":1,\"A\":2,\"M\":3}", "{\"A\":2}", "Z", "M"),
dropped("no prior properties", null, "{}"),
dropped("prior is an array", "[1,2]", "{}"),
dropped("prior is a string", "\"x\"", "{}"),
dropped("props is an array", "{\"A\":1}", "[\"A\"]", "A"),
new DroppedCase("not an update", null, "{\"A\":1}", "{}", List.of()),
dropped("empty prior, new property", "{}", "{\"A\":1}"),
dropped("a prior Fn::If is declared", "{\"A\":{\"Fn::If\":[\"C\",\"x\",\"y\"]}}", "{\"B\":1}", "A"),
dropped("a null in the middle is skipped", "{\"A\":1,\"B\":null,\"C\":3}", "{\"B\":1}", "A", "C"),
new DroppedCase("a blank prior physical id is not an update", " ", "{\"A\":1}", "{}", List.of()));
}
@ParameterizedTest
@MethodSource("droppedCases")
void changesDroppedEqualsDroppedPropertiesAndTheHandWrittenSet(DroppedCase c) {
ProvisionContext ctx = new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack",
c.priorPhysicalId(), event -> { }, c.prior() == null ? null : props(c.prior()));
JsonNode current = c.props() == null ? null : props(c.props());
Set<String> viaChanges = ctx.changes("AWS::SQS::Queue", current).dropped();
assertEquals(c.expected(), List.copyOf(viaChanges), c.label());
assertEquals(Set.copyOf(c.expected()), viaChanges, c.label());
assertEquals(ctx.droppedProperties(current), viaChanges, c.label());
assertEquals(List.copyOf(ctx.droppedProperties(current)), List.copyOf(viaChanges), c.label());
}
@Test
void changesReturnsTheEngineSuppliedObjectWhenTheContextWasBuiltWithOne() {
PropertyChanges supplied = PropertyChanges.between("AWS::SQS::Queue", true,
props("{\"A\":1}"), props("{\"A\":2}"));
ProvisionContext ctx = new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack",
"prior-id", event -> { }, props("{\"Other\":1}"), supplied);
assertSame(supplied, ctx.changes());
assertSame(supplied, ctx.changes("AWS::SQS::Queue", props("{\"Different\":1}")),
"the engine's statement wins over what the arguments would derive");
assertSame(supplied, ctx.changes("AWS::S3::Bucket", null));
}
@Test
void changesIsDerivedFromTheContextsOwnInputsWhenTheEngineSuppliedNone() {
JsonNode prior = props("{\"QueueName\":\"q\",\"Old\":1,\"Same\":2}");
JsonNode current = props("{\"QueueName\":\"q\",\"Same\":3,\"New\":4}");
ProvisionContext ctx = new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack",
"prior-id", event -> { }, prior);
PropertyChanges derived = ctx.changes("AWS::SQS::Queue", current);
assertNotNull(derived);
assertEquals(PropertyChanges.between("AWS::SQS::Queue", true, prior, current), derived);
assertEquals(PropertyChanges.Kind.UNCHANGED, derived.kindOf("QueueName"));
assertTrue(derived.byName().get("QueueName").createOnly(), "the resource type given to changes() is used");
assertEquals(Set.of("Old"), derived.dropped());
assertEquals(Set.of("New"), derived.added());
assertEquals(Set.of("Same"), derived.changed());
}
@Test
void changesDerivedOnACreateMarksEveryPropertyAdded() {
ProvisionContext ctx = new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");
PropertyChanges derived = ctx.changes("AWS::SQS::Queue", props("{\"A\":1,\"B\":2}"));
assertEquals(Set.of("A", "B"), derived.added());
assertTrue(derived.dropped().isEmpty());
}
@Test
void everyExistingConstructorYieldsNoSuppliedChanges() {
ProvisionContext four = new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");
ProvisionContext five = new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", "prior-id");
ProvisionContext seven = new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", "prior-id",
event -> { }, props("{\"A\":1}"));
assertNull(four.changes());
assertNull(five.changes());
assertNull(seven.changes());
assertEquals("prior-id", seven.priorPhysicalId());
assertEquals(props("{\"A\":1}"), seven.priorProperties());
}
@Test
void nothingIsDroppedOnACreateOrWithoutAPreviousTemplate() {
ProvisionContext create = new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", null,
@@ -26,6 +26,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -99,6 +100,36 @@ class SchedulerScheduleCfnProvisionerTest {
resource.getAttributes().get("Arn"));
}
@Test
void theCleanupContextKeepsTheEnginesChanges() throws Exception {
StackResource resource = resource();
provisioner.provision(resource, properties("same", "a"), context(null));
trackScheduleUpdates("same", "a");
ProvisionContext engineContext = CarriedChanges.withEngineStatement(context("same"));
ObjectNode desired = properties("same", "a").put("ScheduleExpression", "rate(10 minutes)");
ProvisionContext recorded = CarriedChanges.contextRecorded(
() -> provisioner.provision(resource, desired, engineContext));
assertSame(CarriedChanges.ENGINE_STATEMENT, recorded.changes("AWS::Scheduler::Schedule", null));
}
@Test
void aRecoveredRollbackKeepsTheEnginesChangesOnTheCleanupContext() throws Exception {
StackResource resource = resource();
provisioner.provision(resource, properties("same", "a"), context(null));
trackScheduleUpdates("same", "a");
provisioner.provision(resource, properties("same", "a").put("ScheduleExpression", "rate(10 minutes)"),
context("same"));
ProvisionContext engineContext = CarriedChanges.withEngineStatement(context("same"));
ObjectNode desired = properties("same", "a").put("ScheduleExpression", "rate(15 minutes)");
ProvisionContext recorded = CarriedChanges.contextRecorded(
() -> provisioner.provision(resource, desired, engineContext));
assertSame(CarriedChanges.ENGINE_STATEMENT, recorded.changes("AWS::Scheduler::Schedule", null));
}
@Test
void unnamedScheduleKeepsItsGeneratedNameOnUpdate() throws Exception {
ObjectNode props = properties(null, null);
@@ -19,6 +19,7 @@ import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -404,6 +405,23 @@ class SesCfnProvisionerTest {
verify(ses, never()).createEmailIdentity(anyString(), any(), any(), anyString());
}
@Test
void aRecoveredUpdateSnapshotKeepsTheEnginesChangesOnTheRecordedContext() throws Exception {
Identity identity = domain("example.com");
when(identities.getIdentityVerificationAttributes("example.com", "us-east-1")).thenReturn(identity);
when(ses.listResourceTags(anyString(), eq("us-east-1"))).thenReturn(List.of());
StackResource resource = resource();
resource.setPhysicalId("example.com");
resource.getAttributes().put("__FlociSesUpdateSnapshot", "{\"managedTags\":\"[]\"}");
ProvisionContext engineContext = CarriedChanges.withEngineStatement(context("example.com"));
JsonNode desired = props("{\"EmailIdentity\":\"example.com\"}");
ProvisionContext recorded = CarriedChanges.contextRecorded(
() -> provisioner.provision(resource, desired, engineContext));
assertSame(CarriedChanges.ENGINE_STATEMENT, recorded.changes("AWS::SES::EmailIdentity", null));
}
@Test
void deleteDelegatesToSes() {
provisioner.delete("AWS::SES::EmailIdentity", "example.com", "us-east-1");