refactor(cloudformation): move the Batch types into BatchCfnProvisioner (#3285)

* refactor(cloudformation): move the Batch types into a per-service provisioner

AWS::Batch::ComputeEnvironment, JobQueue and JobDefinition move out of the
legacy monolith into BatchCfnProvisioner, continuing the decomposition. The
three provisioning methods and the three helpers only they called
(computeEnvironmentOrder, containerProperties, retryStrategy) move across
unchanged; the generic property helpers they leaned on have other callers and
stay behind, re-expressed here against ProvisionContext, which already offers
resolveOptional, generatePhysicalName and resolveTags.

Behaviour preserving: same request shapes, same physical ids, same Fn::GetAtt
attributes. The defects these arms carry (nothing is deleted on stack delete,
updates re-create rather than update, Priority is defaulted although the schema
requires it) are left exactly as they were and are fixed in the commits that
follow, so this move stays reviewable on its own.

BatchService was the monolith's only remaining use of the field, so the field,
its constructor parameter and its import go too. Batch is absent from
DELETE_NEEDS_STACK_RESOURCE, so that set is untouched.

The inventory rows move from LEGACY_SWITCH to BatchCfnProvisioner and the test
fixture gains the inferred wiring; without the latter a fixture test naming
Batch would fall through to the stub arm and pass on a fake id. docs-sync
reports the generated table already current, and the schema-coverage gate finds
no new attribute gaps: each type's only top-level read-only property is its ARN,
which was already set.

Monolith 6,457 to 6,292 lines, legacy types 47 to 44.

* fix(cloudformation): delete Batch resources when their stack is deleted

The legacy switch had no AWS::Batch arm in any of its delete paths, so deleting
a stack left the compute environment, job queue and job definition behind. The
stack reported DELETE_COMPLETE over resources that were still there, and a
re-created stack then failed on the names it had supposedly released.

Batch refuses to remove a running entity, as AWS does: DeleteJobQueue rejects an
ENABLED queue, and DeleteComputeEnvironment rejects one that is not DISABLED or
is still referenced by a queue. So each delete disables first and then removes,
which is what the real resource handlers do. CloudFormation already tears down
in reverse dependency order, so a queue is gone before the environment it
points at. A job definition is deregistered, which is AWS's own semantic for
that type: the revision goes INACTIVE rather than disappearing.

Deliberately not CfnDeletes.safeDelete. Every BatchService failure carries the
same ClientException code, so tolerating it would be the catch-all AGENTS.md
rules out: a genuine refusal such as "still associated with a job queue" would
be swallowed into a green stack delete instead of surfacing as DELETE_FAILED.
Already-gone is handled by looking first instead, which also keeps the disable
step from throwing on a resource removed out of band, and makes a repeated
delete idempotent. That check matters most for the job definition, the one call
of the three that throws when its target is missing.

Nine unit tests cover the ordering, the idempotent repeat, and that a refused
delete propagates rather than being swallowed.

* fix(cloudformation): update Batch resources in place instead of re-creating them

provision runs again on every UpdateStack, and the legacy switch always created.
That broke both ways. A named compute environment or job queue called create a
second time under the same name, and createComputeEnvironment and createJobQueue
both reject a duplicate, so the stack update failed. An unnamed one generated a
fresh random name each time, creating a second entity and orphaning the first.

An update that keeps the name now goes through UpdateComputeEnvironment or
UpdateJobQueue, the schemas' update handlers, and keeps the prior physical id.
Only the properties those handlers accept are pushed through: the names, Type
and JobQueueType are createOnly, so a change there is a replacement the engine
drives rather than something to force into an update. A job definition needs no
update branch, because RegisterJobDefinition on an existing name records a new
revision, which is exactly how AWS updates one.

The name is kept steady by reading the attribute recorded at create time, the
way SqsCfnProvisioner reads QueueName beside the queue URL. ProvisionContext's
stablePhysicalName and reusesPriorEntity do not fit here: both fall back to the
prior physical id, which for Batch is an ARN rather than a name, so they would
feed an ARN back in as a name. Their javadoc says as much. For a stack created
before that attribute was recorded, the name is recovered from the prior ARN so
those stacks update in place too rather than duplicating.

Six more unit tests: in-place update for both types, a rename creating instead
of updating, an unnamed resource keeping its generated name, the ARN fallback,
and a job definition re-registering under the same name.

* fix(cloudformation): enforce the Batch schemas' required properties

Three properties the registry schemas mark required were optional here, so a
template missing one applied cleanly against floci and then failed on AWS, which
is the divergence the emulator exists to prevent.

AWS::Batch::JobQueue requires Priority; the switch substituted 1, so the
service's own "priority is required" check could never fire. ComputeEnvironment
and JobDefinition both require Type; an absent one reached the service as a null
and JobDefinition additionally defaulted to "container". All three now fail the
resource with the repo's ValidationError wording, matching how
Ec2NetworkCfnProvisioner reports a missing required property.

Also drops the Revision attribute from AWS::Batch::JobDefinition. Revision is
not a property of that type in the registry schema, and the legacy resource
spec gives the type no attributes at all, so Fn::GetAtt on it fails on AWS.
Offering it let a template pass here and break there. Nothing in the repo reads
it. The physical id stays the job definition ARN despite the schema's
primaryIdentifier naming JobDefinitionName, because the legacy spec and the
type's documented Ref both point at the ARN; changing it would be visible to
existing templates on evidence that does not agree with itself.

The integration test now covers the two stack-level defects end to end: an
update that changes only updatable properties keeps both physical ids and moves
the queue's priority, and a stack delete leaves neither entity behind. Both
assertions fail without the preceding two commits.

* fix(cloudformation): clean up the Batch entity a replacing update displaces

Renaming a compute environment or job queue creates the replacement and leaves the
original live in Batch forever. The provisioner recorded nothing, so the engine was
never told a replacement had happened: no DELETE_IN_PROGRESS event, no cleanup phase,
and nothing to delete the displaced entity even under the default UpdateReplacePolicy.

Wired to the shared ReplacementCleanup the way CloudFrontCfnProvisioner does it rather
than re-derived: attributesBefore is copied as the first statement of provision, and
record runs at the end of each arm once the new physical id is assigned, which is what
lets it compare the prior id against the new one. The four hooks delegate straight
through. An in-place update keeps the prior ARN, so it records nothing and stays
outside the cleanup path.

AWS::Batch::JobDefinition is deliberately not wired the same way. The registry schema
gives it primaryIdentifier JobDefinitionName, not the ARN, and registering revision 2
does not retire revision 1 on AWS: the prior revision stays ACTIVE and a running job
may still name it. Every registration mints a new ARN, so treating a changed physical
id as a replacement here would have the cleanup deregister a live revision. Only a
changed name replaces the definition, and that decision is taken before the register
call overwrites the recorded name, since the check reads that attribute.

Five unit tests: a renamed environment recording its predecessor, completeUpdate
actually deleting it, an in-place update owing nothing, a revision bump owing nothing,
and a renamed definition owing its predecessor. Mutation checked by dropping the record
call, which fails the first two and nothing else.

* fix(cloudformation): restore an in-place Batch update when the stack rolls back

An in-place compute environment or job queue update committed and then could not be
undone. Without a rollbackUpdate hook the resource fell to "Rollback is not implemented
for AWS::Batch::JobQueue", which is not a quiet gap: CloudFormationService adds it to
the rollback failures, so the whole stack reports UPDATE_ROLLBACK_FAILED and the
committed template is not restored either. A stack whose Batch resource sat anywhere
ahead of the failing one could not roll back at all.

Snapshot the entity before the update call and put it back, following
LambdaEventInvokeConfigCfnProvisioner: replacement first through the cleanup record,
then the snapshot for the in-place case. The describe is the only source, because the
template holds the desired state rather than the current one. The snapshot is spent
only once the restore succeeded, so a restore that throws leaves it for the next
attempt instead of reporting a rollback that never happened, and a resource this update
never touched carries none and answers false rather than claiming one.

Simpler than the Events rule this pattern comes from: each Batch update is a single
service call, so a throw leaves nothing half-applied and no in-provision restore arm is
needed. A job definition instead names the revision the failed update registered, which
is deregistered on rollback while the resource points at the prior one again.

Snapshotting is best effort. An entity the describe cannot find leaves none, and
rollbackUpdate then answers false rather than restoring a guess; failing the update
there would break a working update over missing rollback insurance.

The integration test is the one that proves the hook is reached: a stack whose later
resource cannot provision now reaches UPDATE_ROLLBACK_COMPLETE with the queue back on
its original priority. Reverting rollbackUpdate puts it back to
UPDATE_ROLLBACK_FAILED, reason "The following resource(s) failed to roll back:
[Queue, Compute]".

* fix(cloudformation): reject a Batch job queue Priority that is not a valid integer

Priority reached Integer.parseInt unguarded on both the create and the update path, so
a template carrying "high", or a Ref resolving to something that is not a number, threw
NumberFormatException out of the provisioner. The stack surfaced that as a 500 rather
than the failed validation it is, while every other bad property in this class raises
ValidationError with a 400.

Parsed through a helper that raises the same ValidationError instead, and bounded while
there: the registry schema types AWS::Batch::JobQueue Priority as integer with minimum 0
and maximum 1000, so a value outside that is as invalid as a non-numeric one and AWS
rejects both. This is the same schema-sourced enforcement the required-properties commit
already applies, reaching the one property it left parsing unchecked.

Three unit tests: a non-numeric value on create, the same on the update path, and an
out-of-range one. Mutation checked by restoring Integer.parseInt, which fails all three
and nothing else.

* docs(cloudformation): say why the Batch deletes cannot use CfnDeletes.safeDelete

The javadoc already said safeDelete was deliberate, but not enough to stop the question
being asked again: it read as a limitation of BatchService rather than of the API.

It is the API. Batch declares exactly two errors on DeleteComputeEnvironment,
DeleteJobQueue and DeregisterJobDefinition, ClientException at 400 and ServerException
at 500, and no not-found code anywhere in the service model. safeDelete takes the
specific already-gone code by design, so there is none here to pass it. Tolerating
ClientException instead would be the catch-all AGENTS.md rules out, swallowing a real
refusal such as "Cannot delete compute environment still associated with a job queue"
into a green stack delete. Giving Batch a Floci-only not-found code to satisfy the
pattern would put a code on the wire AWS never sends, which is the wire contract this
emulator exists to keep.

Also names EcsCfnProvisioner, which does tolerate a blanket ClientException for its
task-definition arm, so the divergence reads as deliberate rather than as an oversight.

Comments only. No behaviour change, so the existing tests are what prove it inert.

* docs(cloudformation): record what a Batch rollback cannot undo

A compute-environment rollback restores every value the environment already
carried and cannot remove one the failed update introduced. The snapshot holds
what the describe returned, so a serviceRole or computeResources key that was
absent beforehand is absent from the snapshot, the restore call omits it, and
UpdateComputeEnvironment leaves an omitted field alone while merging
computeResources rather than replacing it. The value survives a rollback the
stack reports as successful.

That cannot be closed here. UpdateComputeEnvironment is the only way to put the
environment back and its request shape has no removal: every member other than
computeEnvironment is an optional set-value, and the partial-merge semantics are
AWS's own. So this is disclosed on rollbackUpdate and pinned by a test, the way
CognitoCfnProvisioner records its own in-place rollback limitation, rather than
worked around.

Job queues are not affected. updateJobQueue assigns computeEnvironmentOrder
wholesale rather than merging it, and state and priority are always present, so
that restore is exact.

The test asserts the surviving value rather than only that the rollback returned
true, so it goes red if the merge semantics ever change without this note
changing with them. Mutation-checked: making the restore send an empty
serviceRole fails it.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-09-10 07:20:44 -04:00
1 parent 65a9a65d8d
commit 82eaaaeee7
7 files changed
+1548 -169

No files matched your search

@@ -31,6 +31,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewa
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingLifecycleHookCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingScalingPolicyCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.BackupVaultCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.BatchCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.EventsCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CdkMetadataCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudTrailCfnProvisioner;
@@ -312,6 +313,9 @@ final class CfnProvisionerFixture {
if (eventBridgeService != null) {
discovered.add(new EventsCfnProvisioner(eventBridgeService));
}
if (batchService != null) {
discovered.add(new BatchCfnProvisioner(batchService));
}
if (wafV2Service != null) {
discovered.add(new WafV2CfnProvisioner(wafV2Service));
}
@@ -618,7 +622,6 @@ final class CfnProvisionerFixture {
customResourceResponseStore,
reachableEndpoint,
stepFunctionsService,
batchService,
ec2Service,
rdsService,
eksService,
@@ -190,6 +190,210 @@ class CloudFormationBatchIntegrationTest {
.body(containsString("CREATE_COMPLETE"));
}
/**
* The two defects the legacy switch carried, end to end: an update re-created rather than
* updating (the second create was rejected as a duplicate name), and a stack delete removed
* nothing at all.
*/
@Test
void updatingAndDeletingABatchStackUpdatesInPlaceAndRemovesTheResources() {
String suffix = Long.toString(System.nanoTime(), 36);
String computeName = "cfn-batch-ud-ce-" + suffix;
String queueName = "cfn-batch-ud-queue-" + suffix;
String stackName = "cfn-batch-ud-stack-" + suffix;
String template = """
{
"Resources": {
"Compute": {
"Type": "AWS::Batch::ComputeEnvironment",
"Properties": {
"ComputeEnvironmentName": "%s",
"Type": "MANAGED",
"ComputeResources": {"Type": "FARGATE", "MaxvCpus": %d}
}
},
"Queue": {
"Type": "AWS::Batch::JobQueue",
"Properties": {
"JobQueueName": "%s",
"Priority": %d,
"ComputeEnvironmentOrder": [{
"Order": 1,
"ComputeEnvironment": {"Ref": "Compute"}
}]
}
}
},
"Outputs": {
"ComputeArn": {"Value": {"Fn::GetAtt": ["Compute", "ComputeEnvironmentArn"]}},
"QueueArn": {"Value": {"Fn::GetAtt": ["Queue", "JobQueueArn"]}}
}
}
""";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template.formatted(computeName, 4, queueName, 1))
.when()
.post("/")
.then()
.statusCode(200);
// The update changes only updatable properties, so the entities must be mutated, not
// replaced: the physical ids the outputs carry have to survive it.
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "UpdateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template.formatted(computeName, 8, queueName, 5))
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("UPDATE_COMPLETE"))
.body(containsString("compute-environment/" + computeName))
.body(containsString("job-queue/" + queueName));
givenBatchJson("{\"jobQueues\":[\"%s\"]}".formatted(queueName))
.when()
.post("/v1/describejobqueues")
.then()
.statusCode(200)
.body("jobQueues", hasSize(1))
.body("jobQueues[0].priority", equalTo(5));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteStack")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200);
// Both entities are gone. Under the legacy switch these describes still returned them.
givenBatchJson("{\"jobQueues\":[\"%s\"]}".formatted(queueName))
.when()
.post("/v1/describejobqueues")
.then()
.statusCode(200)
.body("jobQueues", hasSize(0));
givenBatchJson("{\"computeEnvironments\":[\"%s\"]}".formatted(computeName))
.when()
.post("/v1/describecomputeenvironments")
.then()
.statusCode(200)
.body("computeEnvironments", hasSize(0));
}
/**
* A failed stack update puts an in-place Batch change back. Without {@code rollbackUpdate} the
* queue fell to "Rollback is not implemented for AWS::Batch::JobQueue", which drives the whole
* stack to UPDATE_ROLLBACK_FAILED and leaves the queue on the failed update's priority. The
* status assertion is the one that proves the hook is reached: the unit tests can show the
* provisioner restores, only this shows the engine asks it to.
*/
@Test
void aFailedUpdateRollsBackAnInPlaceJobQueueChange() {
String suffix = Long.toString(System.nanoTime(), 36);
String computeName = "cfn-batch-rb-ce-" + suffix;
String queueName = "cfn-batch-rb-queue-" + suffix;
String stackName = "cfn-batch-rb-stack-" + suffix;
createStack(stackName, queueTemplate(computeName, queueName, 5, false));
assertStackStatus(stackName, "CREATE_COMPLETE");
assertQueuePriority(queueName, 5);
// The nested stack has no TemplateURL so it cannot provision, and it depends on the queue,
// so the queue's in-place update commits first and the failure lands after it.
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "UpdateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", queueTemplate(computeName, queueName, 9, true))
.when()
.post("/")
.then()
.statusCode(200);
assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
assertQueuePriority(queueName, 5);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteStack")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200);
}
private static void createStack(String stackName, String template) {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
}
private static String queueTemplate(String computeName, String queueName, int priority,
boolean withFailingResource) {
return "{\"Resources\":{"
+ "\"Compute\":{\"Type\":\"AWS::Batch::ComputeEnvironment\",\"Properties\":{"
+ "\"ComputeEnvironmentName\":\"" + computeName + "\",\"Type\":\"MANAGED\","
+ "\"ComputeResources\":{\"Type\":\"FARGATE\",\"MaxvCpus\":4,"
+ "\"Subnets\":[\"subnet-local\"],\"SecurityGroupIds\":[\"sg-local\"]}}},"
+ "\"Queue\":{\"Type\":\"AWS::Batch::JobQueue\",\"Properties\":{"
+ "\"JobQueueName\":\"" + queueName + "\",\"Priority\":" + priority + ","
+ "\"ComputeEnvironmentOrder\":[{\"Order\":1,"
+ "\"ComputeEnvironment\":{\"Ref\":\"Compute\"}}]}}"
+ (withFailingResource
? ",\"Nested\":{\"Type\":\"AWS::CloudFormation::Stack\","
+ "\"DependsOn\":\"Queue\",\"Properties\":{}}"
: "")
+ "}}";
}
private static void assertQueuePriority(String queueName, int priority) {
givenBatchJson("{\"jobQueues\":[\"%s\"]}".formatted(queueName))
.when()
.post("/v1/describejobqueues")
.then()
.statusCode(200)
.body("jobQueues", hasSize(1))
.body("jobQueues[0].priority", equalTo(priority));
}
private static void assertStackStatus(String stackName, String status) {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>" + status + "</StackStatus>"));
}
private static io.restassured.specification.RequestSpecification givenBatchJson(String body) {
return given()
.header("Authorization", BATCH_AUTH)
@@ -0,0 +1,683 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.batch.BatchService;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import java.util.HashMap;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** The Batch CFN provisioner in isolation, with only {@link BatchService} mocked. */
class BatchCfnProvisionerTest {
private static final String CE_ARN =
"arn:aws:batch:us-east-1:000000000000:compute-environment/my-stack-Compute-ab12cd";
private static final String JQ_ARN =
"arn:aws:batch:us-east-1:000000000000:job-queue/my-stack-Queue-ab12cd";
private static final String JD_ARN =
"arn:aws:batch:us-east-1:000000000000:job-definition/my-stack-Definition-ab12cd:1";
private final BatchService batch = mock(BatchService.class);
private final BatchCfnProvisioner provisioner = new BatchCfnProvisioner(batch);
private final ObjectMapper mapper = new ObjectMapper();
private ProvisionContext ctx() {
// The engine is a collaborator; these cases use scalar properties and flat objects, so a
// pass-through stub keeps this a true isolated unit test.
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
return node == null ? null : node.asText();
});
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");
}
private StackResource resource(String type, String logicalId) {
StackResource r = new StackResource();
r.setResourceType(type);
r.setLogicalId(logicalId);
r.setAttributes(new HashMap<>());
return r;
}
private ObjectNode describeWith(String key, String arn) {
ObjectNode out = mapper.createObjectNode();
out.putArray(key).addObject().put("arn", arn);
return out;
}
private ObjectNode describeEmpty(String key) {
ObjectNode out = mapper.createObjectNode();
out.putArray(key);
return out;
}
// ── create ───────────────────────────────────────────────────────────────
@Test
void computeEnvironmentSetsPhysicalIdAndTheSchemaAttribute() {
when(batch.createComputeEnvironment(any(), anyString()))
.thenReturn(mapper.createObjectNode().put("computeEnvironmentArn", CE_ARN));
ObjectNode props = mapper.createObjectNode();
props.put("ComputeEnvironmentName", "envy");
props.put("Type", "MANAGED");
StackResource r = resource("AWS::Batch::ComputeEnvironment", "Compute");
provisioner.provision(r, props, ctx());
ArgumentCaptor<JsonNode> req = ArgumentCaptor.forClass(JsonNode.class);
verify(batch).createComputeEnvironment(req.capture(), anyString());
assertEquals("envy", req.getValue().path("computeEnvironmentName").asText());
assertEquals("MANAGED", req.getValue().path("type").asText());
// Ref resolves to the physical id, and ComputeEnvironmentArn is the type's only
// top-level read-only property in the registry schema.
assertEquals(CE_ARN, r.getPhysicalId());
assertEquals(CE_ARN, r.getAttributes().get("ComputeEnvironmentArn"));
assertEquals("envy", r.getAttributes().get("ComputeEnvironmentName"));
}
@Test
void jobQueueCarriesPriorityAndComputeEnvironmentOrder() {
when(batch.createJobQueue(any(), anyString()))
.thenReturn(mapper.createObjectNode().put("jobQueueArn", JQ_ARN));
ObjectNode props = mapper.createObjectNode();
props.put("JobQueueName", "queue");
props.put("Priority", "7");
props.putArray("ComputeEnvironmentOrder").addObject()
.put("Order", 1).put("ComputeEnvironment", CE_ARN);
StackResource r = resource("AWS::Batch::JobQueue", "Queue");
provisioner.provision(r, props, ctx());
ArgumentCaptor<JsonNode> req = ArgumentCaptor.forClass(JsonNode.class);
verify(batch).createJobQueue(req.capture(), anyString());
assertEquals(7, req.getValue().path("priority").asInt());
assertEquals(CE_ARN,
req.getValue().path("computeEnvironmentOrder").get(0).path("computeEnvironment").asText());
assertEquals(JQ_ARN, r.getAttributes().get("JobQueueArn"));
}
@Test
void jobDefinitionDefaultsTypeToContainer() {
when(batch.registerJobDefinition(any(), anyString()))
.thenReturn(mapper.createObjectNode().put("jobDefinitionArn", JD_ARN).put("revision", 1));
ObjectNode props = mapper.createObjectNode();
props.put("JobDefinitionName", "def");
props.put("Type", "container");
props.putObject("ContainerProperties").put("Image", "busybox");
StackResource r = resource("AWS::Batch::JobDefinition", "Definition");
provisioner.provision(r, props, ctx());
ArgumentCaptor<JsonNode> req = ArgumentCaptor.forClass(JsonNode.class);
verify(batch).registerJobDefinition(req.capture(), anyString());
assertEquals("container", req.getValue().path("type").asText());
assertEquals("busybox", req.getValue().path("containerProperties").path("image").asText());
assertEquals(JD_ARN, r.getAttributes().get("JobDefinitionArn"));
}
// ── update ───────────────────────────────────────────────────────────────
private ProvisionContext updateCtx(String priorPhysicalId) {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
return node == null ? null : node.asText();
});
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId);
}
@Test
void updatingAComputeEnvironmentUpdatesInPlaceInsteadOfCreatingAgain() {
// createComputeEnvironment rejects a duplicate name, so the second UpdateStack used to
// fail the whole stack rather than update the environment.
StackResource r = resource("AWS::Batch::ComputeEnvironment", "Compute");
r.getAttributes().put("ComputeEnvironmentName", "envy");
ObjectNode props = mapper.createObjectNode();
props.put("ComputeEnvironmentName", "envy");
props.put("Type", "MANAGED");
props.put("State", "DISABLED");
provisioner.provision(r, props, updateCtx(CE_ARN));
ArgumentCaptor<JsonNode> update = ArgumentCaptor.forClass(JsonNode.class);
verify(batch).updateComputeEnvironment(update.capture());
verify(batch, never()).createComputeEnvironment(any(), anyString());
assertEquals(CE_ARN, update.getValue().path("computeEnvironment").asText());
assertEquals("DISABLED", update.getValue().path("state").asText());
assertEquals(CE_ARN, r.getPhysicalId(), "an in-place update keeps the physical id");
}
@Test
void updatingAJobQueueUpdatesInPlace() {
StackResource r = resource("AWS::Batch::JobQueue", "Queue");
r.getAttributes().put("JobQueueName", "queue");
ObjectNode props = mapper.createObjectNode();
props.put("JobQueueName", "queue");
props.put("Priority", "9");
provisioner.provision(r, props, updateCtx(JQ_ARN));
ArgumentCaptor<JsonNode> update = ArgumentCaptor.forClass(JsonNode.class);
verify(batch).updateJobQueue(update.capture());
verify(batch, never()).createJobQueue(any(), anyString());
assertEquals(9, update.getValue().path("priority").asInt());
assertEquals(JQ_ARN, r.getPhysicalId());
}
@Test
void renamingAComputeEnvironmentCreatesRatherThanUpdates() {
// The name is createOnly, so a changed name is a replacing update: it still arrives with a
// prior physical id, but must create a new entity rather than mutate one that has that name.
when(batch.createComputeEnvironment(any(), anyString()))
.thenReturn(mapper.createObjectNode().put("computeEnvironmentArn", CE_ARN + "-new"));
StackResource r = resource("AWS::Batch::ComputeEnvironment", "Compute");
r.getAttributes().put("ComputeEnvironmentName", "envy");
ObjectNode props = mapper.createObjectNode();
props.put("ComputeEnvironmentName", "renamed");
props.put("Type", "MANAGED");
provisioner.provision(r, props, updateCtx(CE_ARN));
verify(batch).createComputeEnvironment(any(), anyString());
verify(batch, never()).updateComputeEnvironment(any());
assertEquals(CE_ARN + "-new", r.getPhysicalId());
}
@Test
void anUnnamedComputeEnvironmentKeepsItsGeneratedNameAcrossUpdates() {
// The defect this guards: generating unconditionally gave an unnamed resource a fresh
// random name on every update, creating a second environment and orphaning the first.
StackResource r = resource("AWS::Batch::ComputeEnvironment", "Compute");
r.getAttributes().put("ComputeEnvironmentName", "my-stack-Compute-ab12cd");
provisioner.provision(r, mapper.createObjectNode().put("Type", "MANAGED"), updateCtx(CE_ARN));
verify(batch).updateComputeEnvironment(any());
verify(batch, never()).createComputeEnvironment(any(), anyString());
}
@Test
void anUnnamedResourceRecoversItsNameFromThePriorArn() {
// Stacks provisioned before the name attribute was recorded still have to update in place
// rather than create a duplicate.
StackResource r = resource("AWS::Batch::JobQueue", "Queue");
provisioner.provision(r, mapper.createObjectNode().put("Priority", "1"), updateCtx(JQ_ARN));
verify(batch).updateJobQueue(any());
verify(batch, never()).createJobQueue(any(), anyString());
}
@Test
void updatingAJobDefinitionRegistersANewRevisionUnderTheSameName() {
// AWS updates a job definition by recording a new revision, which is what
// registerJobDefinition already does, so there is no separate update call.
when(batch.registerJobDefinition(any(), anyString()))
.thenReturn(mapper.createObjectNode().put("jobDefinitionArn", JD_ARN).put("revision", 2));
StackResource r = resource("AWS::Batch::JobDefinition", "Definition");
r.getAttributes().put("JobDefinitionName", "def");
ObjectNode props = mapper.createObjectNode();
props.put("Type", "container");
props.putObject("ContainerProperties").put("Image", "busybox");
provisioner.provision(r, props, updateCtx(JD_ARN));
ArgumentCaptor<JsonNode> req = ArgumentCaptor.forClass(JsonNode.class);
verify(batch).registerJobDefinition(req.capture(), anyString());
assertEquals("def", req.getValue().path("jobDefinitionName").asText());
}
// ── required properties ──────────────────────────────────────────────────
@Test
void aJobQueueWithoutPriorityIsRejected() {
// Priority is the schema's only required property for this type. The switch substituted 1,
// so a template missing it applied cleanly here and failed on AWS.
ObjectNode props = mapper.createObjectNode();
props.put("JobQueueName", "queue");
AwsException thrown = assertThrows(AwsException.class, () -> provisioner.provision(
resource("AWS::Batch::JobQueue", "Queue"), props, ctx()));
assertEquals("ValidationError", thrown.getErrorCode());
assertTrue(thrown.getMessage().contains("Priority"));
verify(batch, never()).createJobQueue(any(), anyString());
}
@Test
void aComputeEnvironmentWithoutTypeIsRejected() {
AwsException thrown = assertThrows(AwsException.class, () -> provisioner.provision(
resource("AWS::Batch::ComputeEnvironment", "Compute"),
mapper.createObjectNode().put("ComputeEnvironmentName", "envy"), ctx()));
assertEquals("ValidationError", thrown.getErrorCode());
assertTrue(thrown.getMessage().contains("Type"));
}
@Test
void aJobDefinitionWithoutTypeIsRejected() {
// The switch defaulted this to "container"; the schema makes it required.
AwsException thrown = assertThrows(AwsException.class, () -> provisioner.provision(
resource("AWS::Batch::JobDefinition", "Definition"),
mapper.createObjectNode().put("JobDefinitionName", "def"), ctx()));
assertEquals("ValidationError", thrown.getErrorCode());
assertTrue(thrown.getMessage().contains("Type"));
}
@Test
void aJobDefinitionDoesNotAdvertiseARevisionAttribute() {
// Revision is not a property of AWS::Batch::JobDefinition in the registry schema and the
// legacy spec gives the type no attributes either, so Fn::GetAtt on it fails on AWS.
// Offering it here would let a template pass on floci and break on AWS.
when(batch.registerJobDefinition(any(), anyString()))
.thenReturn(mapper.createObjectNode().put("jobDefinitionArn", JD_ARN).put("revision", 1));
ObjectNode props = mapper.createObjectNode();
props.put("JobDefinitionName", "def");
props.put("Type", "container");
props.putObject("ContainerProperties").put("Image", "busybox");
StackResource r = resource("AWS::Batch::JobDefinition", "Definition");
provisioner.provision(r, props, ctx());
assertFalse(r.getAttributes().containsKey("Revision"));
assertEquals(JD_ARN, r.getAttributes().get("JobDefinitionArn"));
}
// ── delete ───────────────────────────────────────────────────────────────
@Test
void deletingAJobQueueDisablesItFirst() {
// DeleteJobQueue refuses an ENABLED queue, as on AWS, so the disable has to come first
// and in this order.
when(batch.describeJobQueues(any())).thenReturn(describeWith("jobQueues", JQ_ARN));
provisioner.delete("AWS::Batch::JobQueue", JQ_ARN, "us-east-1");
InOrder order = inOrder(batch);
ArgumentCaptor<JsonNode> disable = ArgumentCaptor.forClass(JsonNode.class);
order.verify(batch).updateJobQueue(disable.capture());
order.verify(batch).deleteJobQueue(any());
assertEquals("DISABLED", disable.getValue().path("state").asText());
assertEquals(JQ_ARN, disable.getValue().path("jobQueue").asText());
}
@Test
void deletingAComputeEnvironmentDisablesItFirst() {
when(batch.describeComputeEnvironments(any()))
.thenReturn(describeWith("computeEnvironments", CE_ARN));
provisioner.delete("AWS::Batch::ComputeEnvironment", CE_ARN, "us-east-1");
InOrder order = inOrder(batch);
ArgumentCaptor<JsonNode> disable = ArgumentCaptor.forClass(JsonNode.class);
order.verify(batch).updateComputeEnvironment(disable.capture());
order.verify(batch).deleteComputeEnvironment(any());
assertEquals("DISABLED", disable.getValue().path("state").asText());
}
@Test
void deletingAJobDefinitionDeregistersIt() {
when(batch.describeJobDefinitions(any())).thenReturn(describeWith("jobDefinitions", JD_ARN));
provisioner.delete("AWS::Batch::JobDefinition", JD_ARN, "us-east-1");
ArgumentCaptor<JsonNode> req = ArgumentCaptor.forClass(JsonNode.class);
verify(batch).deregisterJobDefinition(req.capture());
assertEquals(JD_ARN, req.getValue().path("jobDefinition").asText());
}
@Test
void deletingAnEntityThatIsAlreadyGoneDoesNothing() {
// A repeated stack delete must be idempotent. It matters most for the job definition:
// deregister throws when the definition is missing, so the existence check is the guard.
when(batch.describeComputeEnvironments(any())).thenReturn(describeEmpty("computeEnvironments"));
when(batch.describeJobQueues(any())).thenReturn(describeEmpty("jobQueues"));
when(batch.describeJobDefinitions(any())).thenReturn(describeEmpty("jobDefinitions"));
provisioner.delete("AWS::Batch::ComputeEnvironment", CE_ARN, "us-east-1");
provisioner.delete("AWS::Batch::JobQueue", JQ_ARN, "us-east-1");
provisioner.delete("AWS::Batch::JobDefinition", JD_ARN, "us-east-1");
verify(batch, never()).updateComputeEnvironment(any());
verify(batch, never()).deleteComputeEnvironment(any());
verify(batch, never()).updateJobQueue(any());
verify(batch, never()).deleteJobQueue(any());
verify(batch, never()).deregisterJobDefinition(any());
}
@Test
void aRefusedDeletePropagatesInsteadOfBeingSwallowed() {
// The failure that must not be tolerated: a compute environment still attached to a queue.
// Swallowing it would report a green stack delete over a resource that is still there.
when(batch.describeComputeEnvironments(any()))
.thenReturn(describeWith("computeEnvironments", CE_ARN));
when(batch.deleteComputeEnvironment(any())).thenThrow(new AwsException("ClientException",
"Cannot delete compute environment still associated with a job queue: envy", 400));
AwsException thrown = assertThrows(AwsException.class,
() -> provisioner.delete("AWS::Batch::ComputeEnvironment", CE_ARN, "us-east-1"));
assertTrue(thrown.getMessage().contains("still associated with a job queue"));
}
@Test
void deleteWithoutAPhysicalIdTouchesNothing() {
provisioner.delete("AWS::Batch::JobQueue", null, "us-east-1");
provisioner.delete("AWS::Batch::JobQueue", "", "us-east-1");
verify(batch, never()).describeJobQueues(any());
verify(batch, never()).deleteJobQueue(any());
}
// ── replacement cleanup ──────────────────────────────────────────────────
private ObjectNode detail(String key, String arn, java.util.Map<String, Object> fields) {
ObjectNode out = mapper.createObjectNode();
ObjectNode item = out.putArray(key).addObject();
item.put("arn", arn);
fields.forEach((k, v) -> {
if (v instanceof Integer i) {
item.put(k, i);
} else {
item.put(k, String.valueOf(v));
}
});
return out;
}
@Test
void renamingAComputeEnvironmentRecordsTheDisplacedOneForCleanup() {
// The leak this closes: the rename created the replacement, but the engine was never told
// a replacement happened, so the old environment stayed live in Batch forever.
when(batch.createComputeEnvironment(any(), anyString()))
.thenReturn(mapper.createObjectNode().put("computeEnvironmentArn", CE_ARN + "-new"));
StackResource r = resource("AWS::Batch::ComputeEnvironment", "Compute");
r.getAttributes().put("ComputeEnvironmentName", "envy");
ObjectNode props = mapper.createObjectNode();
props.put("ComputeEnvironmentName", "renamed");
props.put("Type", "MANAGED");
provisioner.provision(r, props, updateCtx(CE_ARN));
assertTrue(provisioner.hasReplacementUpdate(r), "the engine has to learn a replacement happened");
assertEquals(CE_ARN, provisioner.updateCleanupPhysicalId(r), "the displaced environment is owed a delete");
}
@Test
void completingTheUpdateDeletesTheDisplacedComputeEnvironment() {
when(batch.createComputeEnvironment(any(), anyString()))
.thenReturn(mapper.createObjectNode().put("computeEnvironmentArn", CE_ARN + "-new"));
when(batch.describeComputeEnvironments(any()))
.thenReturn(describeWith("computeEnvironments", CE_ARN));
StackResource r = resource("AWS::Batch::ComputeEnvironment", "Compute");
r.getAttributes().put("ComputeEnvironmentName", "envy");
ObjectNode props = mapper.createObjectNode();
props.put("ComputeEnvironmentName", "renamed");
props.put("Type", "MANAGED");
provisioner.provision(r, props, updateCtx(CE_ARN));
UpdateCleanupResult result = provisioner.completeUpdate(r);
assertTrue(result.applicable());
assertTrue(result.complete(), "the displaced environment was deleted");
ArgumentCaptor<JsonNode> deleted = ArgumentCaptor.forClass(JsonNode.class);
verify(batch).deleteComputeEnvironment(deleted.capture());
assertEquals(CE_ARN, deleted.getValue().path("computeEnvironment").asText());
}
@Test
void anInPlaceUpdateOwesNoReplacementCleanup() {
StackResource r = resource("AWS::Batch::JobQueue", "Queue");
r.getAttributes().put("JobQueueName", "queue");
ObjectNode props = mapper.createObjectNode();
props.put("JobQueueName", "queue");
props.put("Priority", "9");
provisioner.provision(r, props, updateCtx(JQ_ARN));
assertFalse(provisioner.hasReplacementUpdate(r), "nothing was displaced");
}
@Test
void aJobDefinitionRevisionBumpIsNotAReplacement() {
// The prior revision stays ACTIVE on AWS, and the schema's primaryIdentifier for this type
// is JobDefinitionName rather than the ARN. Recording the bump as a replacement would have
// the cleanup deregister a revision a running job may still name.
when(batch.registerJobDefinition(any(), anyString()))
.thenReturn(mapper.createObjectNode().put("jobDefinitionArn", JD_ARN + "-r2"));
StackResource r = resource("AWS::Batch::JobDefinition", "Definition");
r.getAttributes().put("JobDefinitionName", "my-stack-Definition-ab12cd");
ObjectNode props = mapper.createObjectNode();
props.put("JobDefinitionName", "my-stack-Definition-ab12cd");
props.put("Type", "container");
provisioner.provision(r, props, updateCtx(JD_ARN));
assertFalse(provisioner.hasReplacementUpdate(r),
"a new revision under the same name replaces nothing");
}
@Test
void renamingAJobDefinitionIsAReplacement() {
when(batch.registerJobDefinition(any(), anyString()))
.thenReturn(mapper.createObjectNode().put("jobDefinitionArn", JD_ARN + "-renamed"));
StackResource r = resource("AWS::Batch::JobDefinition", "Definition");
r.getAttributes().put("JobDefinitionName", "my-stack-Definition-ab12cd");
ObjectNode props = mapper.createObjectNode();
props.put("JobDefinitionName", "renamed");
props.put("Type", "container");
provisioner.provision(r, props, updateCtx(JD_ARN));
assertTrue(provisioner.hasReplacementUpdate(r), "a changed name replaces the definition");
assertEquals(JD_ARN, provisioner.updateCleanupPhysicalId(r));
}
// ── update rollback ──────────────────────────────────────────────────────
@Test
void rollingBackAnInPlaceComputeEnvironmentUpdateRestoresWhatItFound() {
// Without this the resource fell to "Rollback is not implemented", which drives the whole
// stack to UPDATE_ROLLBACK_FAILED and leaves the environment on the failed update's values.
when(batch.describeComputeEnvironments(any())).thenReturn(
detail("computeEnvironments", CE_ARN,
java.util.Map.of("state", "ENABLED", "serviceRole", "role-before")));
StackResource r = resource("AWS::Batch::ComputeEnvironment", "Compute");
r.getAttributes().put("ComputeEnvironmentName", "envy");
ObjectNode props = mapper.createObjectNode();
props.put("ComputeEnvironmentName", "envy");
props.put("Type", "MANAGED");
props.put("State", "DISABLED");
props.put("ServiceRole", "role-after");
provisioner.provision(r, props, updateCtx(CE_ARN));
assertTrue(provisioner.rollbackUpdate(r), "an in-place update is restorable from the snapshot");
ArgumentCaptor<JsonNode> calls = ArgumentCaptor.forClass(JsonNode.class);
verify(batch, org.mockito.Mockito.times(2)).updateComputeEnvironment(calls.capture());
JsonNode restore = calls.getAllValues().get(1);
assertEquals(CE_ARN, restore.path("computeEnvironment").asText());
assertEquals("ENABLED", restore.path("state").asText(), "the state it was found with");
assertEquals("role-before", restore.path("serviceRole").asText());
}
/**
* Pins a known limitation rather than a fix, the way
* {@code CognitoCfnProvisionerTest.anInPlaceUserPoolClientUpdateCannotBeRolledBack} pins
* Cognito's. The snapshot records what the describe returned, so a field that was absent
* before the update is absent from the snapshot and omitted from the restore call, and
* UpdateComputeEnvironment leaves an omitted field alone. The value the failed update added
* therefore survives.
*
* <p>Asserting the survivor explicitly, rather than just that the rollback returned true, is
* what makes this test useful: it goes red if the merge semantics ever change without the
* disclosure on {@code rollbackUpdate} changing with them.
*/
@Test
void aRollbackCannotRemoveAValueTheFailedUpdateAdded() {
// No serviceRole before the update: the environment simply does not carry one.
when(batch.describeComputeEnvironments(any())).thenReturn(
detail("computeEnvironments", CE_ARN, java.util.Map.of("state", "ENABLED")));
StackResource r = resource("AWS::Batch::ComputeEnvironment", "Compute");
r.getAttributes().put("ComputeEnvironmentName", "envy");
ObjectNode props = mapper.createObjectNode();
props.put("ComputeEnvironmentName", "envy");
props.put("Type", "MANAGED");
props.put("State", "DISABLED");
props.put("ServiceRole", "role-the-update-added");
provisioner.provision(r, props, updateCtx(CE_ARN));
assertTrue(provisioner.rollbackUpdate(r));
ArgumentCaptor<JsonNode> calls = ArgumentCaptor.forClass(JsonNode.class);
verify(batch, org.mockito.Mockito.times(2)).updateComputeEnvironment(calls.capture());
JsonNode failedUpdate = calls.getAllValues().get(0);
JsonNode restore = calls.getAllValues().get(1);
assertEquals("role-the-update-added", failedUpdate.path("serviceRole").asText(),
"the failed update did set a serviceRole");
assertEquals("ENABLED", restore.path("state").asText(),
"a value the environment already carried is restored exactly");
assertFalse(restore.has("serviceRole"),
"the restore cannot ask for a serviceRole it never saw, so the added one survives");
}
@Test
void rollingBackAnInPlaceJobQueueUpdateRestoresPriorityAndState() {
when(batch.describeJobQueues(any())).thenReturn(
detail("jobQueues", JQ_ARN, java.util.Map.of("state", "ENABLED", "priority", 3)));
StackResource r = resource("AWS::Batch::JobQueue", "Queue");
r.getAttributes().put("JobQueueName", "queue");
ObjectNode props = mapper.createObjectNode();
props.put("JobQueueName", "queue");
props.put("Priority", "9");
props.put("State", "DISABLED");
provisioner.provision(r, props, updateCtx(JQ_ARN));
assertTrue(provisioner.rollbackUpdate(r));
ArgumentCaptor<JsonNode> calls = ArgumentCaptor.forClass(JsonNode.class);
verify(batch, org.mockito.Mockito.times(2)).updateJobQueue(calls.capture());
JsonNode restore = calls.getAllValues().get(1);
assertEquals(3, restore.path("priority").asInt(), "the priority it was found with");
assertEquals("ENABLED", restore.path("state").asText());
}
@Test
void rollingBackAJobDefinitionRevisionDeregistersTheOneTheUpdateRegistered() {
when(batch.registerJobDefinition(any(), anyString()))
.thenReturn(mapper.createObjectNode().put("jobDefinitionArn", JD_ARN + "-r2"));
when(batch.describeJobDefinitions(any()))
.thenReturn(describeWith("jobDefinitions", JD_ARN + "-r2"));
StackResource r = resource("AWS::Batch::JobDefinition", "Definition");
r.getAttributes().put("JobDefinitionName", "my-stack-Definition-ab12cd");
ObjectNode props = mapper.createObjectNode();
props.put("JobDefinitionName", "my-stack-Definition-ab12cd");
props.put("Type", "container");
provisioner.provision(r, props, updateCtx(JD_ARN));
assertTrue(provisioner.rollbackUpdate(r));
ArgumentCaptor<JsonNode> deregistered = ArgumentCaptor.forClass(JsonNode.class);
verify(batch).deregisterJobDefinition(deregistered.capture());
assertEquals(JD_ARN + "-r2", deregistered.getValue().path("jobDefinition").asText(),
"the revision the failed update registered, not the one it started from");
assertEquals(JD_ARN, r.getPhysicalId(), "the resource names the prior revision again");
}
@Test
void aResourceThisUpdateNeverTouchedReportsItCannotBeRolledBack() {
// Answering true here would claim a restore that never happened. False is the honest
// answer and is what makes the engine report the resource accurately.
StackResource r = resource("AWS::Batch::JobQueue", "Queue");
assertFalse(provisioner.rollbackUpdate(r));
}
@Test
void clearingTheUpdateDropsTheSnapshot() {
when(batch.describeJobQueues(any())).thenReturn(
detail("jobQueues", JQ_ARN, java.util.Map.of("state", "ENABLED", "priority", 3)));
StackResource r = resource("AWS::Batch::JobQueue", "Queue");
r.getAttributes().put("JobQueueName", "queue");
ObjectNode props = mapper.createObjectNode();
props.put("JobQueueName", "queue");
props.put("Priority", "9");
provisioner.provision(r, props, updateCtx(JQ_ARN));
provisioner.clearUpdate(r);
assertFalse(r.getAttributes().containsKey(CfnRollback.BATCH_UPDATE_SNAPSHOT_ATTR));
assertFalse(provisioner.rollbackUpdate(r), "a spent snapshot cannot be replayed");
}
// ── Priority validation ──────────────────────────────────────────────────
@Test
void aNonNumericPriorityFailsValidationInsteadOfThrowingNumberFormatException() {
// It used to reach Integer.parseInt unguarded and escape as a 500 rather than the failed
// validation it is.
StackResource r = resource("AWS::Batch::JobQueue", "Queue");
ObjectNode props = mapper.createObjectNode();
props.put("JobQueueName", "queue");
props.put("Priority", "high");
AwsException thrown = assertThrows(AwsException.class,
() -> provisioner.provision(r, props, ctx()));
assertEquals("ValidationError", thrown.getErrorCode());
assertEquals(400, thrown.getHttpStatus());
assertTrue(thrown.getMessage().contains("must be an integer"));
verify(batch, never()).createJobQueue(any(), anyString());
}
@Test
void anOutOfRangePriorityFailsValidation() {
// The registry schema types Priority as integer, minimum 0, maximum 1000.
StackResource r = resource("AWS::Batch::JobQueue", "Queue");
ObjectNode props = mapper.createObjectNode();
props.put("JobQueueName", "queue");
props.put("Priority", "1001");
AwsException thrown = assertThrows(AwsException.class,
() -> provisioner.provision(r, props, ctx()));
assertEquals("ValidationError", thrown.getErrorCode());
assertTrue(thrown.getMessage().contains("between 0 and 1000"));
verify(batch, never()).createJobQueue(any(), anyString());
}
@Test
void aNonNumericPriorityIsRejectedOnTheUpdatePathToo() {
StackResource r = resource("AWS::Batch::JobQueue", "Queue");
r.getAttributes().put("JobQueueName", "queue");
ObjectNode props = mapper.createObjectNode();
props.put("JobQueueName", "queue");
props.put("Priority", "high");
assertThrows(AwsException.class, () -> provisioner.provision(r, props, updateCtx(JQ_ARN)));
verify(batch, never()).updateJobQueue(any());
}
}