From 6a7190e8de54cfe3446255ffcbd25a293cc84ce8 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Tue, 24 Nov 2026 18:43:51 -0600 Subject: [PATCH] test(ec2): build the dry-run fixtures once per class (#9403) --- .../ec2/Ec2InstanceDryRunIntegrationTest.java | 245 ++++++++++-------- .../ec2/Ec2VolumeDryRunIntegrationTest.java | 52 ++-- .../ec2/Ec2VpcDryRunIntegrationTest.java | 106 +++++--- 3 files changed, 243 insertions(+), 160 deletions(-) diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2InstanceDryRunIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2InstanceDryRunIntegrationTest.java index aad7abedda..c662b0d695 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2InstanceDryRunIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2InstanceDryRunIntegrationTest.java @@ -1,17 +1,20 @@ package io.floci.aws.services.ec2; import io.floci.aws.testing.QueryRequests; +import io.quarkus.test.common.http.TestHTTPResource; import io.quarkus.test.junit.QuarkusTest; import io.restassured.path.xml.XmlPath; import io.restassured.specification.RequestSpecification; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; +import java.net.URI; import java.time.Duration; import java.util.List; import java.util.Map; @@ -29,77 +32,88 @@ import static org.junit.jupiter.api.Assertions.assertEquals; * TerminateInstances, monitoring, metadata options and attributes, the EBS encryption defaults, and Spot * requests. A dry run the real call would refuse keeps that call's error, even when it also names an * instance it would accept. + * + *

The cases that only read share one fixture, built once for the class. The two that change an + * instance or a Spot request, the terminated start and the Spot cancel, build a fixture of their own. */ @QuarkusTest +@TestInstance(TestInstance.Lifecycle.PER_CLASS) class Ec2InstanceDryRunIntegrationTest { - /** Each test works in an account of its own, so DescribeInstances lists only the fixture's instances. */ + /** Each fixture works in an account of its own, so DescribeInstances lists only the fixture's instances. */ private static final AtomicLong ACCOUNTS = new AtomicLong(726200000000L); private static final String MISSING_INSTANCE = "i-0123456789abcdef0"; private static final String IMAGE = "ami-1234567890abcdef0"; private static final String USER_DATA = "IyEvYmluL3NoCg=="; private static final String INSTANCE = "DescribeInstancesResponse.reservationSet.item.instancesSet.item"; - private String account; - private String runningId; - private String stoppedId; + private static Fixture shared; - @BeforeEach + /** The test port: RestAssured learns it only per test, and the fixture is built before the first one. */ + private static int port; + + @TestHTTPResource("/") + URI baseUri; + + @BeforeAll void launchARunningAndAStoppedInstance() { - account = Long.toString(ACCOUNTS.incrementAndGet()); - runningId = launch(); - stoppedId = launch(); - ec2("StopInstances", "InstanceId.1", stoppedId); - awaitState(stoppedId, "stopped"); + port = baseUri.getPort(); + shared = Fixture.launch(); } - @AfterEach + @AfterAll void terminateTheInstances() { - ec2("TerminateInstances", "InstanceId.1", runningId, "InstanceId.2", stoppedId); + shared.terminate(); } @ParameterizedTest @ValueSource(strings = {"StartInstances", "StopInstances", "RebootInstances", "TerminateInstances"}) void aDryRunIsAnsweredWithDryRunOperationAndChangesNothing(String action) { - Map before = states(); + Map before = shared.states(); - request(action, "InstanceId.1", "StartInstances".equals(action) ? stoppedId : runningId) + shared.request(action, "InstanceId.1", "StartInstances".equals(action) ? shared.stoppedId : shared.runningId) .formParam("DryRun", "true").post("/").then() .statusCode(412) .body("Response.Errors.Error.Code", equalTo("DryRunOperation")) .body("Response.Errors.Error.Message", equalTo("Request would have succeeded, but DryRun flag is set.")); - assertEquals(before, states()); + assertEquals(before, shared.states()); } /** Every instance is checked before the dry run is answered, so one the call would refuse refuses it. */ @ParameterizedTest @ValueSource(strings = {"StartInstances", "StopInstances", "RebootInstances", "TerminateInstances"}) void aDryRunNamingAMissingInstanceKeepsTheRealCallsError(String action) { - Map before = states(); + Map before = shared.states(); - request(action, "InstanceId.1", "StartInstances".equals(action) ? stoppedId : runningId, + shared.request(action, "InstanceId.1", "StartInstances".equals(action) ? shared.stoppedId : shared.runningId, "InstanceId.2", MISSING_INSTANCE).formParam("DryRun", "true").post("/").then() .statusCode(400) .body("Response.Errors.Error.Code", equalTo("InvalidInstanceID.NotFound")); - assertEquals(before, states()); + assertEquals(before, shared.states()); } @Test void aDryRunStartOfATerminatedInstanceKeepsTheRealCallsError() { - ec2("TerminateInstances", "InstanceId.1", runningId); - awaitState(runningId, "terminated"); - Map before = states(); + Fixture own = Fixture.launch(); + try { + own.ec2("TerminateInstances", "InstanceId.1", own.runningId); + own.awaitState(own.runningId, "terminated"); + Map before = own.states(); - for (String dryRun : List.of("true", "false")) { - request("StartInstances", "InstanceId.1", runningId).formParam("DryRun", dryRun).post("/").then() - .statusCode(400) - .body("Response.Errors.Error.Code", equalTo("IncorrectInstanceState")); + for (String dryRun : List.of("true", "false")) { + own.request("StartInstances", "InstanceId.1", own.runningId).formParam("DryRun", dryRun) + .post("/").then() + .statusCode(400) + .body("Response.Errors.Error.Code", equalTo("IncorrectInstanceState")); + } + + assertEquals(before, own.states()); + } finally { + own.terminate(); } - - assertEquals(before, states()); } /** A DryRun value that is not a boolean is refused as one, and no instance changes. */ @@ -111,15 +125,15 @@ class Ec2InstanceDryRunIntegrationTest { "TerminateInstances, maybe", "TerminateInstances, ''" }) void aDryRunValueThatIsNotABooleanIsRefused(String action, String value) { - Map before = states(); + Map before = shared.states(); - request(action, "InstanceId.1", "StartInstances".equals(action) ? stoppedId : runningId) + shared.request(action, "InstanceId.1", "StartInstances".equals(action) ? shared.stoppedId : shared.runningId) .formParam("DryRun", value).post("/").then() .statusCode(400) .body("Response.Errors.Error.Code", equalTo("InvalidParameterValue")) .body("Response.Errors.Error.Message", equalTo("DryRun is not a valid boolean.")); - assertEquals(before, states()); + assertEquals(before, shared.states()); } /** Requests the real call accepts, for the instance calls other than start, stop, reboot and terminate. */ @@ -142,26 +156,26 @@ class Ec2InstanceDryRunIntegrationTest { @ParameterizedTest @MethodSource("otherInstanceCalls") void aDryRunOfAnotherInstanceCallIsAnsweredWithDryRunOperationAndChangesNothing(String action, String params) { - String before = snapshot(); + String before = shared.snapshot(); - request(action, params(params)).formParam("DryRun", "true").post("/").then() + shared.request(action, shared.params(params)).formParam("DryRun", "true").post("/").then() .statusCode(412) .body("Response.Errors.Error.Code", equalTo("DryRunOperation")); - assertEquals(before, snapshot()); + assertEquals(before, shared.snapshot()); } @ParameterizedTest @MethodSource("otherInstanceCalls") void aDryRunValueThatIsNotABooleanIsRefusedByTheOtherInstanceCalls(String action, String params) { - String before = snapshot(); + String before = shared.snapshot(); - request(action, params(params)).formParam("DryRun", "maybe").post("/").then() + shared.request(action, shared.params(params)).formParam("DryRun", "maybe").post("/").then() .statusCode(400) .body("Response.Errors.Error.Code", equalTo("InvalidParameterValue")) .body("Response.Errors.Error.Message", equalTo("DryRun is not a valid boolean.")); - assertEquals(before, snapshot()); + assertEquals(before, shared.snapshot()); } /** The real call refuses each of these; its dry run keeps the same error, and neither changes anything. */ @@ -176,99 +190,128 @@ class Ec2InstanceDryRunIntegrationTest { "CancelSpotInstanceRequests | SpotInstanceRequestId.1=sir-01234567 | InvalidSpotInstanceRequestID.NotFound" }) void aDryRunTheRealCallWouldRefuseKeepsItsError(String action, String params, String code) { - String before = snapshot(); + String before = shared.snapshot(); for (String dryRun : List.of("true", "false")) { - request(action, params(params)).formParam("DryRun", dryRun).post("/").then() + shared.request(action, shared.params(params)).formParam("DryRun", dryRun).post("/").then() .statusCode(400) .body("Response.Errors.Error.Code", equalTo(code)); } - assertEquals(before, snapshot()); + assertEquals(before, shared.snapshot()); } @Test void aDryRunCancelOfASpotRequestCancelsNothing() { - XmlPath requested = ec2("RequestSpotInstances", "LaunchSpecification.ImageId", IMAGE, + Fixture own = Fixture.launch(); + XmlPath requested = own.ec2("RequestSpotInstances", "LaunchSpecification.ImageId", IMAGE, "LaunchSpecification.InstanceType", "t3.micro"); String request = "RequestSpotInstancesResponse.spotInstanceRequestSet.item"; String requestId = requested.getString(request + ".spotInstanceRequestId"); String instanceId = requested.getString(request + ".instanceId"); try { - awaitState(instanceId, "running"); - String before = snapshot(); + own.awaitState(instanceId, "running"); + String before = own.snapshot(); - request("CancelSpotInstanceRequests", "SpotInstanceRequestId.1", requestId) + own.request("CancelSpotInstanceRequests", "SpotInstanceRequestId.1", requestId) .formParam("DryRun", "true").post("/").then() .statusCode(412) .body("Response.Errors.Error.Code", equalTo("DryRunOperation")); - assertEquals(before, snapshot()); + assertEquals(before, own.snapshot()); } finally { - ec2("CancelSpotInstanceRequests", "SpotInstanceRequestId.1", requestId); - ec2("TerminateInstances", "InstanceId.1", instanceId); + own.ec2("CancelSpotInstanceRequests", "SpotInstanceRequestId.1", requestId); + own.ec2("TerminateInstances", "InstanceId.1", instanceId); + own.terminate(); } } - /** - * Everything the instance calls can change in the test's account, as the describe calls report it: - * the instances, the stopped instance's user data, the EBS encryption defaults and the Spot requests. - */ - private String snapshot() { - return String.join("\n", - body("DescribeInstances"), - body("DescribeInstanceAttribute", "InstanceId", stoppedId, "Attribute", "userData"), - body("GetEbsEncryptionByDefault"), - body("GetEbsDefaultKmsKeyId"), - body("DescribeSpotInstanceRequests")); - } + /** An account holding a running instance and a stopped one. */ + private static final class Fixture { - /** A describe call's answer without the request id, the one part that differs on every call. */ - private String body(String action, String... params) { - return request(action, params).post("/").then().statusCode(200).extract().asString() - .replaceAll("[^<]*", ""); - } + private final String account; + private final String runningId; + private final String stoppedId; - /** {@code Key=Value} pairs separated by spaces, with {running} and {stopped} standing for the fixture's ids. */ - private String[] params(String spec) { - if (spec == null || spec.isBlank()) { - return new String[0]; + private Fixture(String account, String runningId, String stoppedId) { + this.account = account; + this.runningId = runningId; + this.stoppedId = stoppedId; } - return Stream.of(spec.trim().split(" +")) - .flatMap(pair -> Stream.of(pair.split("=", 2))) - .map(part -> part.replace("{running}", runningId).replace("{stopped}", stoppedId)) - .toArray(String[]::new); - } - private String launch() { - String instanceId = ec2("RunInstances", "ImageId", IMAGE, "InstanceType", "t3.micro", - "MinCount", "1", "MaxCount", "1").getString("RunInstancesResponse.instancesSet.item.instanceId"); - awaitState(instanceId, "running"); - return instanceId; - } - - private void awaitState(String instanceId, String state) { - await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(100)).untilAsserted(() -> - assertEquals(state, states().get(instanceId))); - } - - /** Every instance of the account with its state, ordered by instance id. */ - private Map states() { - XmlPath described = ec2("DescribeInstances"); - List ids = described.getList(INSTANCE + ".instanceId", String.class); - List states = described.getList(INSTANCE + ".instanceState.name", String.class); - Map byId = new TreeMap<>(); - for (int i = 0; i < ids.size(); i++) { - byId.put(ids.get(i), states.get(i)); + static Fixture launch() { + Fixture empty = new Fixture(Long.toString(ACCOUNTS.incrementAndGet()), null, null); + String runningId = empty.launchInstance(); + String stoppedId = empty.launchInstance(); + empty.ec2("StopInstances", "InstanceId.1", stoppedId); + empty.awaitState(stoppedId, "stopped"); + return new Fixture(empty.account, runningId, stoppedId); } - return byId; - } - private XmlPath ec2(String action, String... params) { - return request(action, params).post("/").then().statusCode(200).extract().xmlPath(); - } + void terminate() { + ec2("TerminateInstances", "InstanceId.1", runningId, "InstanceId.2", stoppedId); + } - private RequestSpecification request(String action, String... params) { - return QueryRequests.request(account, "ec2", action, params); + /** + * Everything the instance calls can change in the fixture's account, as the describe calls report it: + * the instances, the stopped instance's user data, the EBS encryption defaults and the Spot requests. + */ + String snapshot() { + return String.join("\n", + body("DescribeInstances"), + body("DescribeInstanceAttribute", "InstanceId", stoppedId, "Attribute", "userData"), + body("GetEbsEncryptionByDefault"), + body("GetEbsDefaultKmsKeyId"), + body("DescribeSpotInstanceRequests")); + } + + /** A describe call's answer without the request id, the one part that differs on every call. */ + private String body(String action, String... params) { + return request(action, params).post("/").then().statusCode(200).extract().asString() + .replaceAll("[^<]*", ""); + } + + /** {@code Key=Value} pairs separated by spaces, with {running} and {stopped} standing for the fixture's ids. */ + String[] params(String spec) { + if (spec == null || spec.isBlank()) { + return new String[0]; + } + return Stream.of(spec.trim().split(" +")) + .flatMap(pair -> Stream.of(pair.split("=", 2))) + .map(part -> part.replace("{running}", runningId).replace("{stopped}", stoppedId)) + .toArray(String[]::new); + } + + private String launchInstance() { + String instanceId = ec2("RunInstances", "ImageId", IMAGE, "InstanceType", "t3.micro", + "MinCount", "1", "MaxCount", "1").getString("RunInstancesResponse.instancesSet.item.instanceId"); + awaitState(instanceId, "running"); + return instanceId; + } + + void awaitState(String instanceId, String state) { + await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(100)).untilAsserted(() -> + assertEquals(state, states().get(instanceId))); + } + + /** Every instance of the account with its state, ordered by instance id. */ + Map states() { + XmlPath described = ec2("DescribeInstances"); + List ids = described.getList(INSTANCE + ".instanceId", String.class); + List states = described.getList(INSTANCE + ".instanceState.name", String.class); + Map byId = new TreeMap<>(); + for (int i = 0; i < ids.size(); i++) { + byId.put(ids.get(i), states.get(i)); + } + return byId; + } + + XmlPath ec2(String action, String... params) { + return request(action, params).post("/").then().statusCode(200).extract().xmlPath(); + } + + RequestSpecification request(String action, String... params) { + return QueryRequests.request(account, "ec2", action, params).port(port); + } } } diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2VolumeDryRunIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2VolumeDryRunIntegrationTest.java index 0d3d311eed..3c8e19af3a 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2VolumeDryRunIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2VolumeDryRunIntegrationTest.java @@ -2,19 +2,21 @@ package io.floci.aws.services.ec2; import io.floci.aws.testing.QueryRequests; import io.quarkus.test.InjectMock; +import io.quarkus.test.common.http.TestHTTPResource; import io.quarkus.test.junit.QuarkusTest; import io.restassured.path.xml.XmlPath; import io.restassured.specification.RequestSpecification; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; +import java.net.URI; import java.time.Duration; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.atomic.AtomicLong; import static org.awaitility.Awaitility.await; import static org.hamcrest.Matchers.equalTo; @@ -22,7 +24,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -31,12 +32,16 @@ import static org.mockito.Mockito.verify; * HTTP 412 once the request has passed every check the real call makes, and it changes nothing: no * volume is created or deleted, no attachment made or ended, no tag written or removed, and no * backing device touched. The driver's controller sends a dry run CreateVolume each time it starts. + * + *

No case changes the fixture, so every case shares one, built once for the class. It is built before + * the first case installs its mock block device manager, so each case's mock sees only that case's calls. */ @QuarkusTest +@TestInstance(TestInstance.Lifecycle.PER_CLASS) class Ec2VolumeDryRunIntegrationTest { - /** Each test works in an account of its own, so DescribeVolumes lists only the fixture's volumes. */ - private static final AtomicLong ACCOUNTS = new AtomicLong(726100000000L); + /** The class works in an account of its own, so DescribeVolumes lists only the fixture's volumes. */ + private static final String ACCOUNT = "726100000001"; private static final String MISSING_VOLUME = "vol-0123456789abcdef0"; private static final String VOLUME = "DescribeVolumesResponse.volumeSet.item"; private static final String INSTANCE = "DescribeInstancesResponse.reservationSet.item.instancesSet.item"; @@ -44,17 +49,22 @@ class Ec2VolumeDryRunIntegrationTest { @InjectMock Ec2VolumeBlockDeviceManager blockDevices; - private String account; - private String instanceId; - private String zone; + private static String instanceId; + private static String zone; /** Attached to the instance at /dev/xvdf. */ - private String attachedVolumeId; + private static String attachedVolumeId; /** Not attached, tagged team=storage. */ - private String availableVolumeId; + private static String availableVolumeId; - @BeforeEach + /** The test port: RestAssured learns it only per test, and the fixture is built before the first one. */ + private static int port; + + @TestHTTPResource("/") + URI baseUri; + + @BeforeAll void launchAnInstanceWithAnAttachedAndAnAvailableVolume() { - account = Long.toString(ACCOUNTS.incrementAndGet()); + port = baseUri.getPort(); XmlPath launched = ec2("RunInstances", "ImageId", "ami-1234567890abcdef0", "InstanceType", "t3.micro", "MinCount", "1", "MaxCount", "1"); instanceId = launched.getString("RunInstancesResponse.instancesSet.item.instanceId"); @@ -67,11 +77,13 @@ class Ec2VolumeDryRunIntegrationTest { ec2("AttachVolume", "VolumeId", attachedVolumeId, "InstanceId", instanceId, "Device", "/dev/xvdf"); availableVolumeId = createVolume(); ec2("CreateTags", "ResourceId.1", availableVolumeId, "Tag.1.Key", "team", "Tag.1.Value", "storage"); - clearInvocations(blockDevices); } - @AfterEach - void terminateTheInstance() { + @AfterAll + void deleteTheVolumesAndTerminateTheInstance() { + ec2("DetachVolume", "VolumeId", attachedVolumeId, "InstanceId", instanceId); + ec2("DeleteVolume", "VolumeId", attachedVolumeId); + ec2("DeleteVolume", "VolumeId", availableVolumeId); ec2("TerminateInstances", "InstanceId.1", instanceId); } @@ -192,16 +204,16 @@ class Ec2VolumeDryRunIntegrationTest { return volumes; } - private String createVolume() { + private static String createVolume() { return ec2("CreateVolume", "AvailabilityZone", zone, "Size", "1") .getString("CreateVolumeResponse.volumeId"); } - private XmlPath ec2(String action, String... params) { + private static XmlPath ec2(String action, String... params) { return request(action, params).post("/").then().statusCode(200).extract().xmlPath(); } - private RequestSpecification request(String action, String... params) { - return QueryRequests.request(account, "ec2", action, params); + private static RequestSpecification request(String action, String... params) { + return QueryRequests.request(ACCOUNT, "ec2", action, params).port(port); } } diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2VpcDryRunIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2VpcDryRunIntegrationTest.java index 5c8f1f255f..46229425c7 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2VpcDryRunIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2VpcDryRunIntegrationTest.java @@ -1,18 +1,21 @@ package io.floci.aws.services.ec2; import io.floci.aws.testing.QueryRequests; +import io.quarkus.test.common.http.TestHTTPResource; import io.quarkus.test.junit.QuarkusTest; import io.restassured.path.xml.XmlPath; import io.restassured.specification.RequestSpecification; -import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.MethodSource; +import java.net.URI; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Stream; import static org.hamcrest.Matchers.equalTo; @@ -22,12 +25,15 @@ import static org.junit.jupiter.api.Assertions.assertEquals; * DryRun on the VPC, subnet, internet gateway, route table and security group rule calls is answered with * DryRunOperation and HTTP 412 once the request has passed the checks the real call makes, and changes nothing. * A dry run the real call would refuse keeps that call's error. + * + *

No case changes the network, so every case shares one, built once for the class. */ @QuarkusTest +@TestInstance(TestInstance.Lifecycle.PER_CLASS) class Ec2VpcDryRunIntegrationTest { - /** Each test works in an account of its own, so the describe calls list only the fixture's resources. */ - private static final AtomicLong ACCOUNTS = new AtomicLong(726300000000L); + /** The class works in an account of its own, so the describe calls list only the fixture's resources. */ + private static final String ACCOUNT = "726300000001"; private static final String MISSING_VPC = "vpc-0123456789abcdef0"; private static final String MISSING_GATEWAY = "igw-0123456789abcdef0"; private static final String MISSING_TABLE = "rtb-0123456789abcdef0"; @@ -37,9 +43,14 @@ class Ec2VpcDryRunIntegrationTest { private static final String PERMISSION = "IpPermissions.1.IpProtocol=tcp IpPermissions.1.FromPort=%1$d" + " IpPermissions.1.ToPort=%1$d IpPermissions.1.IpRanges.1.CidrIp=10.0.0.0/8"; - private String account; /** The fixture's ids by the names the requests below give them in braces, such as {vpc}. */ - private final Map ids = new HashMap<>(); + private static final Map IDS = new HashMap<>(); + + /** The test port: RestAssured learns it only per test, and the fixture is built before the first one. */ + private static int port; + + @TestHTTPResource("/") + URI baseUri; /** * A VPC with two subnets, one holding a network interface; an internet gateway attached to it; a route @@ -47,30 +58,47 @@ class Ec2VpcDryRunIntegrationTest { * neither. Beside them, an empty VPC and a gateway attached to nothing. In the first VPC, a security group * allowing port 22 in and port 443 out, from and to 10.0.0.0/8. */ - @BeforeEach + @BeforeAll void buildTheNetwork() { - account = Long.toString(ACCOUNTS.incrementAndGet()); - ids.clear(); - ids.put("vpc", create("CreateVpc", "vpc.vpcId", "CidrBlock", "10.0.0.0/16")); - ids.put("emptyVpc", create("CreateVpc", "vpc.vpcId", "CidrBlock", "10.1.0.0/16")); - ids.put("subnet", create("CreateSubnet", "subnet.subnetId", "VpcId", ids.get("vpc"), + port = baseUri.getPort(); + IDS.clear(); + IDS.put("vpc", create("CreateVpc", "vpc.vpcId", "CidrBlock", "10.0.0.0/16")); + IDS.put("emptyVpc", create("CreateVpc", "vpc.vpcId", "CidrBlock", "10.1.0.0/16")); + IDS.put("subnet", create("CreateSubnet", "subnet.subnetId", "VpcId", IDS.get("vpc"), "CidrBlock", "10.0.1.0/24")); - ids.put("freeSubnet", create("CreateSubnet", "subnet.subnetId", "VpcId", ids.get("vpc"), + IDS.put("freeSubnet", create("CreateSubnet", "subnet.subnetId", "VpcId", IDS.get("vpc"), "CidrBlock", "10.0.2.0/24")); - create("CreateNetworkInterface", "networkInterface.networkInterfaceId", "SubnetId", ids.get("subnet")); - ids.put("gateway", create("CreateInternetGateway", "internetGateway.internetGatewayId")); - ids.put("spareGateway", create("CreateInternetGateway", "internetGateway.internetGatewayId")); - ec2("AttachInternetGateway", "InternetGatewayId", ids.get("gateway"), "VpcId", ids.get("vpc")); - ids.put("table", create("CreateRouteTable", "routeTable.routeTableId", "VpcId", ids.get("vpc"))); - ids.put("spareTable", create("CreateRouteTable", "routeTable.routeTableId", "VpcId", ids.get("vpc"))); - ec2("CreateRoute", "RouteTableId", ids.get("table"), "DestinationCidrBlock", "0.0.0.0/0", - "GatewayId", ids.get("gateway")); - ids.put("association", create("AssociateRouteTable", "associationId", "RouteTableId", ids.get("table"), - "SubnetId", ids.get("subnet"))); - ids.put("group", create("CreateSecurityGroup", "groupId", "GroupName", "dry-run", - "GroupDescription", "dry run", "VpcId", ids.get("vpc"))); - ids.put("ingressRule", authorize("AuthorizeSecurityGroupIngress", 22)); - ids.put("egressRule", authorize("AuthorizeSecurityGroupEgress", 443)); + IDS.put("networkInterface", create("CreateNetworkInterface", "networkInterface.networkInterfaceId", + "SubnetId", IDS.get("subnet"))); + IDS.put("gateway", create("CreateInternetGateway", "internetGateway.internetGatewayId")); + IDS.put("spareGateway", create("CreateInternetGateway", "internetGateway.internetGatewayId")); + ec2("AttachInternetGateway", "InternetGatewayId", IDS.get("gateway"), "VpcId", IDS.get("vpc")); + IDS.put("table", create("CreateRouteTable", "routeTable.routeTableId", "VpcId", IDS.get("vpc"))); + IDS.put("spareTable", create("CreateRouteTable", "routeTable.routeTableId", "VpcId", IDS.get("vpc"))); + ec2("CreateRoute", "RouteTableId", IDS.get("table"), "DestinationCidrBlock", "0.0.0.0/0", + "GatewayId", IDS.get("gateway")); + IDS.put("association", create("AssociateRouteTable", "associationId", "RouteTableId", IDS.get("table"), + "SubnetId", IDS.get("subnet"))); + IDS.put("group", create("CreateSecurityGroup", "groupId", "GroupName", "dry-run", + "GroupDescription", "dry run", "VpcId", IDS.get("vpc"))); + IDS.put("ingressRule", authorize("AuthorizeSecurityGroupIngress", 22)); + IDS.put("egressRule", authorize("AuthorizeSecurityGroupEgress", 443)); + } + + @AfterAll + void deleteTheNetwork() { + ec2("DeleteSecurityGroup", "GroupId", IDS.get("group")); + ec2("DisassociateRouteTable", "AssociationId", IDS.get("association")); + ec2("DeleteRouteTable", "RouteTableId", IDS.get("table")); + ec2("DeleteRouteTable", "RouteTableId", IDS.get("spareTable")); + ec2("DetachInternetGateway", "InternetGatewayId", IDS.get("gateway"), "VpcId", IDS.get("vpc")); + ec2("DeleteInternetGateway", "InternetGatewayId", IDS.get("gateway")); + ec2("DeleteInternetGateway", "InternetGatewayId", IDS.get("spareGateway")); + ec2("DeleteNetworkInterface", "NetworkInterfaceId", IDS.get("networkInterface")); + ec2("DeleteSubnet", "SubnetId", IDS.get("subnet")); + ec2("DeleteSubnet", "SubnetId", IDS.get("freeSubnet")); + ec2("DeleteVpc", "VpcId", IDS.get("vpc")); + ec2("DeleteVpc", "VpcId", IDS.get("emptyVpc")); } /** A request each call's real call accepts in the fixture. */ @@ -185,12 +213,12 @@ class Ec2VpcDryRunIntegrationTest { } /** - * Everything these calls can change in the test's account, as the describe calls report it: the VPCs + * Everything these calls can change in the class's account, as the describe calls report it: the VPCs * and what DeleteVpc removes with one (its default security group and network ACL), the subnets, the * network interface, the internet gateways, the route tables with their routes and associations, and the * security groups with their rules. */ - private String snapshot() { + private static String snapshot() { return String.join("\n", body("DescribeVpcs"), body("DescribeSubnets"), @@ -203,46 +231,46 @@ class Ec2VpcDryRunIntegrationTest { } /** A describe call's answer without the request id, the one part that differs on every call. */ - private String body(String action) { + private static String body(String action) { return request(action).post("/").then().statusCode(200).extract().asString() .replaceAll("[^<]*", ""); } /** {@code Key=Value} pairs separated by spaces, with a fixture's name in braces standing for its id. */ - private String[] params(String spec) { + private static String[] params(String spec) { if (spec == null || spec.isBlank()) { return new String[0]; } return Stream.of(spec.trim().split(" +")) .flatMap(pair -> Stream.of(pair.split("=", 2))) - .map(this::withIds) + .map(Ec2VpcDryRunIntegrationTest::withIds) .toArray(String[]::new); } - private String withIds(String part) { + private static String withIds(String part) { String result = part; - for (Map.Entry id : ids.entrySet()) { + for (Map.Entry id : IDS.entrySet()) { result = result.replace("{" + id.getKey() + "}", id.getValue()); } return result; } /** Adds {@code port} to the fixture's group in the direction {@code action} names, and returns the rule's id. */ - private String authorize(String action, int port) { + private static String authorize(String action, int port) { return create(action, "securityGroupRuleSet.item.securityGroupRuleId", params("GroupId={group} " + PERMISSION.formatted(port))); } /** Runs {@code action} and returns what its answer holds at {@code path}. */ - private String create(String action, String path, String... params) { + private static String create(String action, String path, String... params) { return ec2(action, params).getString(action + "Response." + path); } - private XmlPath ec2(String action, String... params) { + private static XmlPath ec2(String action, String... params) { return request(action, params).post("/").then().statusCode(200).extract().xmlPath(); } - private RequestSpecification request(String action, String... params) { - return QueryRequests.request(account, "ec2", action, params); + private static RequestSpecification request(String action, String... params) { + return QueryRequests.request(ACCOUNT, "ec2", action, params).port(port); } }