mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
chore(style): replace var in files no open PR touches (#4789)
* chore(style): replace var with explicit types in src/main Drop the NoVar suppressions of the src/main files that no open PR touches. * chore(style): replace var with explicit types in src/test Drop the NoVar suppressions of the src/test files that no open PR touches. * chore(style): replace var with explicit types in sdk-test-java Drop the NoVar suppressions of the compatibility test files that no open PR touches.
This commit is contained in:
1 parent
832bd97966
commit
4e842a85aa
392 files changed
+3691
-3463
No files matched your search
@@ -11,11 +11,13 @@ import org.junit.jupiter.api.io.TempDir;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.cert.Certificate;
|
||||
import java.security.cert.CertificateFactory;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
@@ -67,7 +69,7 @@ class ContainerCaBundleTest {
|
||||
byte[] second = Files.readAllBytes(ContainerCaBundle.write(tlsDir, ca.certificatePath()));
|
||||
|
||||
assertTrue(java.util.Arrays.equals(first, second));
|
||||
try (var files = Files.list(tlsDir)) {
|
||||
try (Stream<Path> files = Files.list(tlsDir)) {
|
||||
assertTrue(files.noneMatch(file -> file.getFileName().toString().endsWith(".tmp")), "no temp file left behind");
|
||||
}
|
||||
}
|
||||
@@ -208,7 +210,7 @@ class ContainerCaBundleTest {
|
||||
|
||||
private static List<X509Certificate> parseAll(byte[] pem) throws Exception {
|
||||
List<X509Certificate> certificates = new ArrayList<>();
|
||||
for (var certificate : CertificateFactory.getInstance("X.509").generateCertificates(new ByteArrayInputStream(pem))) {
|
||||
for (Certificate certificate : CertificateFactory.getInstance("X.509").generateCertificates(new ByteArrayInputStream(pem))) {
|
||||
certificates.add((X509Certificate) certificate);
|
||||
}
|
||||
return certificates;
|
||||
|
||||
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
@@ -167,7 +168,7 @@ class CustomDomainTlsIntegrationTest {
|
||||
}
|
||||
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(TLS_DIR);
|
||||
List<String> sans = List.of("localhost", "*.localhost.floci.io");
|
||||
var leaf = ca.issueServerCertificate("localhost", sans, KeyAlgorithm.RSA_2048, null);
|
||||
CertificateGenerator.GeneratedCertificate leaf = ca.issueServerCertificate("localhost", sans, KeyAlgorithm.RSA_2048, null);
|
||||
Files.writeString(TLS_DIR.resolve("floci-server.crt"), leaf.certificatePem());
|
||||
Files.writeString(TLS_DIR.resolve("floci-server.key"), leaf.privateKeyPem());
|
||||
Files.writeString(TLS_DIR.resolve("floci-server.metadata.json"),
|
||||
|
||||
@@ -11,6 +11,7 @@ import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
|
||||
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
|
||||
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
|
||||
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
|
||||
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
|
||||
import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
@@ -134,7 +135,7 @@ class FlociCertificateAuthorityTest {
|
||||
@Test
|
||||
void keyThatDoesNotMatchTheCertificateIsRegenerated() throws Exception {
|
||||
FlociCertificateAuthority first = FlociCertificateAuthority.loadOrCreate(tempDir);
|
||||
var stranger = new CertificateGenerator().generateCaCertificate("Other CA");
|
||||
CertificateGenerator.GeneratedCertificate stranger = new CertificateGenerator().generateCaCertificate("Other CA");
|
||||
Files.writeString(tempDir.resolve("floci-root-ca.key"), stranger.privateKeyPem());
|
||||
|
||||
FlociCertificateAuthority second = FlociCertificateAuthority.loadOrCreate(tempDir);
|
||||
@@ -173,7 +174,7 @@ class FlociCertificateAuthorityTest {
|
||||
|
||||
@Test
|
||||
void aLeafInPlaceOfTheCaIsRegenerated() throws Exception {
|
||||
var leaf = FlociCertificateAuthority.loadOrCreate(tempDir.resolve("another-ca"))
|
||||
CertificateGenerator.GeneratedCertificate leaf = FlociCertificateAuthority.loadOrCreate(tempDir.resolve("another-ca"))
|
||||
.issueServerCertificate("localhost", List.of(), KeyAlgorithm.RSA_2048, null);
|
||||
Files.writeString(tempDir.resolve("floci-root-ca.crt"), leaf.certificatePem());
|
||||
Files.writeString(tempDir.resolve("floci-root-ca.key"), leaf.privateKeyPem());
|
||||
@@ -239,7 +240,7 @@ class FlociCertificateAuthorityTest {
|
||||
@Test
|
||||
void deviceCertificateNeverOutlivesAShortLivedCa() throws Exception {
|
||||
CertificateGenerator gen = new CertificateGenerator();
|
||||
var shortLived = gen.generateCaCertificate(FlociCertificateAuthority.COMMON_NAME,
|
||||
CertificateGenerator.GeneratedCertificate shortLived = gen.generateCaCertificate(FlociCertificateAuthority.COMMON_NAME,
|
||||
java.time.Instant.now().plus(30, java.time.temporal.ChronoUnit.DAYS));
|
||||
Files.writeString(tempDir.resolve("floci-root-ca.crt"), shortLived.certificatePem());
|
||||
Files.writeString(tempDir.resolve("floci-root-ca.key"), shortLived.privateKeyPem());
|
||||
@@ -256,7 +257,7 @@ class FlociCertificateAuthorityTest {
|
||||
@Test
|
||||
void aSelfSignedLeafIsNotOurs() {
|
||||
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tempDir);
|
||||
var stranger = new CertificateGenerator().generateSelfSignedCertificate(
|
||||
CertificateGenerator.GeneratedCertificate stranger = new CertificateGenerator().generateSelfSignedCertificate(
|
||||
"localhost", List.of("localhost"), KeyAlgorithm.RSA_2048);
|
||||
|
||||
assertFalse(ca.isIssuedByUs(parse(stranger.certificatePem())));
|
||||
@@ -265,9 +266,9 @@ class FlociCertificateAuthorityTest {
|
||||
@Test
|
||||
void aLeafNamingOurCaButSignedByAnotherKeyIsNotOurs() {
|
||||
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tempDir);
|
||||
var impostor = new CertificateGenerator().generateCaCertificate(FlociCertificateAuthority.COMMON_NAME);
|
||||
var generator = new CertificateGenerator();
|
||||
var forged = generator.generateIssuedCertificate("localhost", List.of(), KeyAlgorithm.RSA_2048, null,
|
||||
CertificateGenerator.GeneratedCertificate impostor = new CertificateGenerator().generateCaCertificate(FlociCertificateAuthority.COMMON_NAME);
|
||||
CertificateGenerator generator = new CertificateGenerator();
|
||||
CertificateGenerator.GeneratedCertificate forged = generator.generateIssuedCertificate("localhost", List.of(), KeyAlgorithm.RSA_2048, null,
|
||||
new CertificateGenerator.Issuer(parse(impostor.certificatePem()),
|
||||
Pem.parsePrivateKey(impostor.privateKeyPem())),
|
||||
CertificateGenerator.LeafUsage.SERVER);
|
||||
@@ -322,11 +323,11 @@ class FlociCertificateAuthorityTest {
|
||||
}
|
||||
|
||||
private static String csrPem(String subject, KeyPair keyPair) throws Exception {
|
||||
var csr = new JcaPKCS10CertificationRequestBuilder(
|
||||
PKCS10CertificationRequest csr = new JcaPKCS10CertificationRequestBuilder(
|
||||
new X500Name(subject), keyPair.getPublic())
|
||||
.build(new JcaContentSignerBuilder("SHA256withRSA").build(keyPair.getPrivate()));
|
||||
StringWriter out = new StringWriter();
|
||||
try (var writer = new JcaPEMWriter(out)) {
|
||||
try (JcaPEMWriter writer = new JcaPEMWriter(out)) {
|
||||
writer.writeObject(csr);
|
||||
}
|
||||
return out.toString();
|
||||
|
||||
+2
-1
@@ -5,6 +5,7 @@ import io.smallrye.config.SmallRyeConfig;
|
||||
import io.smallrye.config.SmallRyeConfigBuilder;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static java.util.stream.StreamSupport.stream;
|
||||
@@ -59,7 +60,7 @@ class FlociConfigRelocationsInterceptorTest {
|
||||
void nameIterationPresentsOnlyTheRelocatedKey() {
|
||||
SmallRyeConfig config = config(Map.of("floci.max-request-size", "4096"));
|
||||
|
||||
var names = stream(config.getPropertyNames().spliterator(), false).toList();
|
||||
List<String> names = stream(config.getPropertyNames().spliterator(), false).toList();
|
||||
assertTrue(names.contains("floci.protocols.max-request-size"));
|
||||
assertFalse(names.contains("floci.max-request-size"));
|
||||
}
|
||||
|
||||
@@ -390,7 +390,7 @@ class TlsCertificateHostnameTest {
|
||||
|
||||
Path userCert = tempDir.resolve("user.crt");
|
||||
Path userKey = tempDir.resolve("user.key");
|
||||
var user = new CertificateGenerator().generateSelfSignedCertificate("localhost", List.of("localhost"), KeyAlgorithm.RSA_2048);
|
||||
CertificateGenerator.GeneratedCertificate user = new CertificateGenerator().generateSelfSignedCertificate("localhost", List.of("localhost"), KeyAlgorithm.RSA_2048);
|
||||
Files.writeString(userCert, user.certificatePem());
|
||||
Files.writeString(userKey, user.privateKeyPem());
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
@@ -411,7 +411,7 @@ class TlsCertificateHostnameTest {
|
||||
// The exact SAN list TlsConfigSource would compute for this configuration, so only the
|
||||
// issuer check can trigger regeneration here.
|
||||
List<String> sans = TlsConfigSource.DEFAULT_SAN_HOSTNAMES;
|
||||
var legacy = gen.generateSelfSignedCertificate("localhost", sans, KeyAlgorithm.RSA_2048);
|
||||
CertificateGenerator.GeneratedCertificate legacy = gen.generateSelfSignedCertificate("localhost", sans, KeyAlgorithm.RSA_2048);
|
||||
Files.writeString(tlsDir.resolve("floci-server.crt"), legacy.certificatePem());
|
||||
Files.writeString(tlsDir.resolve("floci-server.key"), legacy.privateKeyPem());
|
||||
Files.writeString(tlsDir.resolve("floci-server.metadata.json"),
|
||||
|
||||
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.Pem;
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
|
||||
import io.quarkus.tls.CertificateUpdatedEvent;
|
||||
import io.quarkus.tls.TlsConfiguration;
|
||||
@@ -58,7 +59,7 @@ abstract class TlsCertificateManagerFixture {
|
||||
forgetBootstrapTlsDir();
|
||||
tlsDir = Files.createDirectories(tempDir.resolve("tls"));
|
||||
ca = FlociCertificateAuthority.loadOrCreate(tlsDir);
|
||||
var leaf = ca.issueServerCertificate("localhost", CONFIGURED, KeyAlgorithm.RSA_2048, null);
|
||||
CertificateGenerator.GeneratedCertificate leaf = ca.issueServerCertificate("localhost", CONFIGURED, KeyAlgorithm.RSA_2048, null);
|
||||
Files.writeString(tlsDir.resolve("floci-server.crt"), leaf.certificatePem());
|
||||
Files.writeString(tlsDir.resolve("floci-server.key"), leaf.privateKeyPem());
|
||||
Files.writeString(tlsDir.resolve("floci-server.metadata.json"),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
@@ -158,7 +159,7 @@ class TlsEnsureHostIntegrationTest {
|
||||
}
|
||||
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(TLS_DIR);
|
||||
List<String> sans = List.of("localhost", "*.localhost.floci.io");
|
||||
var leaf = ca.issueServerCertificate("localhost", sans, KeyAlgorithm.RSA_2048, null);
|
||||
CertificateGenerator.GeneratedCertificate leaf = ca.issueServerCertificate("localhost", sans, KeyAlgorithm.RSA_2048, null);
|
||||
Files.writeString(TLS_DIR.resolve("floci-server.crt"), leaf.certificatePem());
|
||||
Files.writeString(TLS_DIR.resolve("floci-server.key"), leaf.privateKeyPem());
|
||||
Files.writeString(TLS_DIR.resolve("floci-server.metadata.json"),
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.config;
|
||||
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
|
||||
import io.github.hectorvent.floci.services.cloudfront.CloudFrontService;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior;
|
||||
@@ -216,7 +217,7 @@ class TlsHttp2HostRoutingIntegrationTest {
|
||||
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(TLS_DIR);
|
||||
List<String> sans = new ArrayList<>(TlsConfigSource.DEFAULT_SAN_HOSTNAMES);
|
||||
sans.add(API_DOMAIN);
|
||||
var leaf = ca.issueServerCertificate("localhost", sans, KeyAlgorithm.RSA_2048, null);
|
||||
CertificateGenerator.GeneratedCertificate leaf = ca.issueServerCertificate("localhost", sans, KeyAlgorithm.RSA_2048, null);
|
||||
Files.writeString(TLS_DIR.resolve("floci-server.crt"), leaf.certificatePem());
|
||||
Files.writeString(TLS_DIR.resolve("floci-server.key"), leaf.privateKeyPem());
|
||||
} catch (IOException e) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.config;
|
||||
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
@@ -109,7 +110,7 @@ class TlsLocalCaIntegrationTest {
|
||||
static {
|
||||
try {
|
||||
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(TLS_DIR);
|
||||
var leaf = ca.issueServerCertificate("localhost", List.of("localhost", "127.0.0.1"),
|
||||
CertificateGenerator.GeneratedCertificate leaf = ca.issueServerCertificate("localhost", List.of("localhost", "127.0.0.1"),
|
||||
KeyAlgorithm.RSA_2048, null);
|
||||
Files.writeString(CERT_FILE, leaf.certificatePem());
|
||||
Files.writeString(KEY_FILE, leaf.privateKeyPem());
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
@@ -27,53 +28,53 @@ class AiMockConfigLoaderTest {
|
||||
Path tempDir;
|
||||
|
||||
private AiMockConfigLoader loader(String content) throws IOException {
|
||||
var file = tempDir.resolve("ai-mock-config.json");
|
||||
Path file = tempDir.resolve("ai-mock-config.json");
|
||||
Files.writeString(file, content);
|
||||
return new AiMockConfigLoader(Optional.of(file.toString()), new ObjectMapper());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesMatchingEntry() throws IOException {
|
||||
var loader = loader(CONFIG);
|
||||
var result = loader.lookup("comprehend", "I love this", "DetectSentiment");
|
||||
AiMockConfigLoader loader = loader(CONFIG);
|
||||
Optional<JsonNode> result = loader.lookup("comprehend", "I love this", "DetectSentiment");
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals("POSITIVE", result.get().path("Sentiment").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackWhenServiceKeyUnmatched() throws IOException {
|
||||
var loader = loader(CONFIG);
|
||||
AiMockConfigLoader loader = loader(CONFIG);
|
||||
assertTrue(loader.lookup("rekognition", "I love this", "DetectSentiment").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackWhenLookupKeyUnmatched() throws IOException {
|
||||
var loader = loader(CONFIG);
|
||||
AiMockConfigLoader loader = loader(CONFIG);
|
||||
assertTrue(loader.lookup("comprehend", "I hate this", "DetectSentiment").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackWhenActionUnmatched() throws IOException {
|
||||
var loader = loader(CONFIG);
|
||||
AiMockConfigLoader loader = loader(CONFIG);
|
||||
assertTrue(loader.lookup("comprehend", "I love this", "DetectKeyPhrases").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackWhenLookupKeyIsNull() throws IOException {
|
||||
// Bytes-backed images/documents have no natural lookup key.
|
||||
var loader = loader(CONFIG);
|
||||
AiMockConfigLoader loader = loader(CONFIG);
|
||||
assertTrue(loader.lookup("comprehend", null, "DetectSentiment").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackWhenNoConfigConfigured() {
|
||||
var loader = new AiMockConfigLoader(Optional.empty(), new ObjectMapper());
|
||||
AiMockConfigLoader loader = new AiMockConfigLoader(Optional.empty(), new ObjectMapper());
|
||||
assertTrue(loader.lookup("comprehend", "I love this", "DetectSentiment").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackWhenFileMissing() {
|
||||
var loader = new AiMockConfigLoader(
|
||||
AiMockConfigLoader loader = new AiMockConfigLoader(
|
||||
Optional.of(tempDir.resolve("absent.json").toString()), new ObjectMapper());
|
||||
assertTrue(loader.lookup("comprehend", "I love this", "DetectSentiment").isEmpty());
|
||||
}
|
||||
@@ -82,33 +83,33 @@ class AiMockConfigLoaderTest {
|
||||
void fallsBackWhenConfiguredPathIsUnparseable() {
|
||||
// An embedded NUL byte makes Path.of() throw InvalidPathException, an unchecked
|
||||
// exception that a plain "catch (IOException)" does not cover.
|
||||
var loader = new AiMockConfigLoader(Optional.of("bad\0path.json"), new ObjectMapper());
|
||||
AiMockConfigLoader loader = new AiMockConfigLoader(Optional.of("bad\0path.json"), new ObjectMapper());
|
||||
assertTrue(loader.lookup("comprehend", "I love this", "DetectSentiment").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackWhenFileIsNotAJsonObject() throws IOException {
|
||||
var loader = loader("[1, 2, 3]");
|
||||
AiMockConfigLoader loader = loader("[1, 2, 3]");
|
||||
assertTrue(loader.lookup("comprehend", "I love this", "DetectSentiment").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackWhenFileIsMalformedJson() throws IOException {
|
||||
var loader = loader("{not valid json");
|
||||
AiMockConfigLoader loader = loader("{not valid json");
|
||||
assertTrue(loader.lookup("comprehend", "I love this", "DetectSentiment").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void treatsBlankConfiguredPathAsUnconfigured() {
|
||||
var loader = new AiMockConfigLoader(Optional.of(" "), new ObjectMapper());
|
||||
AiMockConfigLoader loader = new AiMockConfigLoader(Optional.of(" "), new ObjectMapper());
|
||||
assertTrue(loader.lookup("comprehend", "I love this", "DetectSentiment").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void reloadsFileWhenModified() throws IOException, InterruptedException {
|
||||
var file = tempDir.resolve("ai-mock-config.json");
|
||||
Path file = tempDir.resolve("ai-mock-config.json");
|
||||
Files.writeString(file, CONFIG);
|
||||
var loader = new AiMockConfigLoader(Optional.of(file.toString()), new ObjectMapper());
|
||||
AiMockConfigLoader loader = new AiMockConfigLoader(Optional.of(file.toString()), new ObjectMapper());
|
||||
assertTrue(loader.lookup("comprehend", "I love this", "DetectSentiment").isPresent());
|
||||
assertFalse(loader.lookup("comprehend", "I hate this", "DetectSentiment").isPresent());
|
||||
|
||||
|
||||
@@ -180,7 +180,7 @@ class XmlParserTest {
|
||||
|
||||
@Test
|
||||
void extractElementTreePreservesNestedNamespaceQualifiedBlocks() {
|
||||
var root = XmlParser.extractElementTree("""
|
||||
XmlParser.XmlElement root = XmlParser.extractElementTree("""
|
||||
<Envelope xmlns:cf="https://cloudfront.amazonaws.com/doc/2020-05-31/">
|
||||
<cf:Config>
|
||||
<cf:First><cf:Value>one</cf:Value></cf:First>
|
||||
@@ -386,8 +386,8 @@ class XmlParserTest {
|
||||
</Conf>
|
||||
""";
|
||||
|
||||
var groups = XmlParser.extractGroupsMulti(xml, "QueueConfiguration");
|
||||
var filters = XmlParser.extractPairsPerGroup(xml, "QueueConfiguration",
|
||||
List<Map<String, List<String>>> groups = XmlParser.extractGroupsMulti(xml, "QueueConfiguration");
|
||||
List<Map<String, String>> filters = XmlParser.extractPairsPerGroup(xml, "QueueConfiguration",
|
||||
"FilterRule", "Name", "Value");
|
||||
|
||||
assertEquals(2, groups.size());
|
||||
|
||||
+2
-1
@@ -6,6 +6,7 @@ import com.github.dockerjava.api.model.Frame;
|
||||
import com.github.dockerjava.core.command.WaitContainerResultCallback;
|
||||
import io.github.hectorvent.floci.config.ContainerCaBundle;
|
||||
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
|
||||
import io.github.hectorvent.floci.testing.TestImages;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
@@ -141,7 +142,7 @@ class ContainerCaBundleDockerIntegrationTest {
|
||||
static {
|
||||
try {
|
||||
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(TLS_DIR);
|
||||
var leaf = ca.issueServerCertificate("localhost",
|
||||
CertificateGenerator.GeneratedCertificate leaf = ca.issueServerCertificate("localhost",
|
||||
List.of("localhost", "127.0.0.1", "host.docker.internal"), KeyAlgorithm.RSA_2048, null);
|
||||
Files.writeString(CERT_FILE, leaf.certificatePem());
|
||||
Files.writeString(KEY_FILE, leaf.privateKeyPem());
|
||||
|
||||
@@ -45,12 +45,12 @@ class HybridStorageTest {
|
||||
@Test
|
||||
void explicitFlushPersistsData() {
|
||||
Path filePath = tempDir.resolve("flush-test.json");
|
||||
var store1 = new HybridStorage<>(filePath, new TypeReference<Map<String, String>>() {}, 60000);
|
||||
HybridStorage<String, String> store1 = new HybridStorage<>(filePath, new TypeReference<Map<String, String>>() {}, 60000);
|
||||
store1.put("key1", "value1");
|
||||
store1.flush();
|
||||
store1.shutdown();
|
||||
|
||||
var store2 = new HybridStorage<>(filePath, new TypeReference<Map<String, String>>() {}, 60000);
|
||||
HybridStorage<String, String> store2 = new HybridStorage<>(filePath, new TypeReference<Map<String, String>>() {}, 60000);
|
||||
store2.load();
|
||||
assertEquals("value1", store2.get("key1").orElseThrow());
|
||||
store2.shutdown();
|
||||
@@ -63,7 +63,7 @@ class HybridStorageTest {
|
||||
Path quarantinePath = filePath.resolveSibling("corrupt-hybrid-store.json.corrupt");
|
||||
Files.writeString(filePath, unreadableContents);
|
||||
Files.writeString(quarantinePath, "previous unreadable contents");
|
||||
var loadedStorage = new HybridStorage<>(filePath, new TypeReference<Map<String, String>>() {}, 60000);
|
||||
HybridStorage<String, String> loadedStorage = new HybridStorage<>(filePath, new TypeReference<Map<String, String>>() {}, 60000);
|
||||
|
||||
try {
|
||||
loadedStorage.load();
|
||||
@@ -80,7 +80,7 @@ class HybridStorageTest {
|
||||
void dynamoTableWithLocalSecondaryIndexSurvivesRestart() {
|
||||
Path filePath = tempDir.resolve("dynamodb-tables.json");
|
||||
TypeReference<Map<String, TableDefinition>> type = new TypeReference<>() {};
|
||||
var table = new TableDefinition(
|
||||
TableDefinition table = new TableDefinition(
|
||||
"ConfigTable",
|
||||
List.of(new KeySchemaElement("pk", "HASH"), new KeySchemaElement("sk", "RANGE")),
|
||||
List.of(new AttributeDefinition("pk", "S"), new AttributeDefinition("sk", "S"),
|
||||
@@ -89,11 +89,11 @@ class HybridStorageTest {
|
||||
"lsi", List.of(new KeySchemaElement("pk", "HASH"),
|
||||
new KeySchemaElement("lsiSk", "RANGE")), null, "ALL")));
|
||||
|
||||
var store1 = new HybridStorage<String, TableDefinition>(filePath, type, 60000);
|
||||
HybridStorage<String, TableDefinition> store1 = new HybridStorage<>(filePath, type, 60000);
|
||||
store1.put("000000000000/us-east-1::ConfigTable", table);
|
||||
store1.shutdown();
|
||||
|
||||
var store2 = new HybridStorage<String, TableDefinition>(filePath, type, 60000);
|
||||
HybridStorage<String, TableDefinition> store2 = new HybridStorage<>(filePath, type, 60000);
|
||||
store2.load();
|
||||
TableDefinition restored = store2.get("000000000000/us-east-1::ConfigTable").orElseThrow();
|
||||
assertEquals("lsiSk", restored.getLocalSecondaryIndexes().getFirst().getSortKeyName());
|
||||
@@ -113,7 +113,7 @@ class HybridStorageTest {
|
||||
storage.put("a.2", "v2");
|
||||
storage.put("b.1", "v3");
|
||||
|
||||
var results = storage.scan(key -> key.startsWith("a."));
|
||||
List<String> results = storage.scan(key -> key.startsWith("a."));
|
||||
assertEquals(2, results.size());
|
||||
}
|
||||
|
||||
@@ -121,7 +121,7 @@ class HybridStorageTest {
|
||||
void scanReturnsMutableList() {
|
||||
storage.put("a", "1");
|
||||
storage.put("b", "2");
|
||||
var result = storage.scan(key -> true);
|
||||
List<String> result = storage.scan(key -> true);
|
||||
assertDoesNotThrow(() -> result.sort(String::compareTo));
|
||||
assertDoesNotThrow(() -> result.add("3"));
|
||||
}
|
||||
|
||||
+2
-1
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.GenericArrayType;
|
||||
import java.lang.reflect.Modifier;
|
||||
@@ -132,7 +133,7 @@ class PersistedModelReflectionTest {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
for (var constructor : c.getDeclaredConstructors()) {
|
||||
for (Constructor<?> constructor : c.getDeclaredConstructors()) {
|
||||
for (Class<?> param : constructor.getParameterTypes()) {
|
||||
if (param == StorageFactory.class) {
|
||||
return true;
|
||||
|
||||
+2
-1
@@ -20,6 +20,7 @@ import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.logging.LogRecord;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
@@ -67,7 +68,7 @@ class PersistentPathValidatorTest {
|
||||
validator().validateAtBoot();
|
||||
|
||||
assertTrue(Files.isDirectory(root));
|
||||
try (var entries = Files.list(root)) {
|
||||
try (Stream<Path> entries = Files.list(root)) {
|
||||
assertEquals(0, entries.count(), "write probe must not be left behind");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,11 +33,11 @@ class PersistentStorageTest {
|
||||
@Test
|
||||
void persistsAcrossInstances() {
|
||||
Path filePath = tempDir.resolve("persist-test.json");
|
||||
var store1 = new PersistentStorage<>(filePath, new TypeReference<Map<String, String>>() {});
|
||||
PersistentStorage<String, String> store1 = new PersistentStorage<>(filePath, new TypeReference<Map<String, String>>() {});
|
||||
store1.put("key1", "value1");
|
||||
store1.put("key2", "value2");
|
||||
|
||||
var store2 = new PersistentStorage<>(filePath, new TypeReference<Map<String, String>>() {});
|
||||
PersistentStorage<String, String> store2 = new PersistentStorage<>(filePath, new TypeReference<Map<String, String>>() {});
|
||||
store2.load();
|
||||
assertEquals("value1", store2.get("key1").orElseThrow());
|
||||
assertEquals("value2", store2.get("key2").orElseThrow());
|
||||
|
||||
@@ -2,9 +2,11 @@ package io.github.hectorvent.floci.core.storage;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
@@ -77,8 +79,8 @@ class StorageBackedMapTest
|
||||
CountDownLatch releaseFirstMapping = new CountDownLatch(1);
|
||||
CountDownLatch secondCallStarted = new CountDownLatch(1);
|
||||
|
||||
try (var executor = Executors.newFixedThreadPool(2)) {
|
||||
var first = executor.submit(() -> map.computeIfAbsent("us-west-2", key -> {
|
||||
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
|
||||
Future<Map<String, String>> first = executor.submit(() -> map.computeIfAbsent("us-west-2", key -> {
|
||||
calls.incrementAndGet();
|
||||
firstMappingEntered.countDown();
|
||||
await(releaseFirstMapping);
|
||||
@@ -86,7 +88,7 @@ class StorageBackedMapTest
|
||||
}));
|
||||
await(firstMappingEntered);
|
||||
|
||||
var second = executor.submit(() -> {
|
||||
Future<Map<String, String>> second = executor.submit(() -> {
|
||||
secondCallStarted.countDown();
|
||||
return map.computeIfAbsent("us-west-2", key -> {
|
||||
calls.incrementAndGet();
|
||||
@@ -127,7 +129,7 @@ class StorageBackedMapTest
|
||||
StorageBackedMap<String> map = new StorageBackedMap<>(storage);
|
||||
map.put("alpha", "one");
|
||||
|
||||
var entry = map.entrySet().iterator().next();
|
||||
Map.Entry<String, String> entry = map.entrySet().iterator().next();
|
||||
|
||||
assertEquals("one", entry.setValue("two"));
|
||||
assertEquals("two", storage.get("alpha").orElseThrow());
|
||||
@@ -141,7 +143,7 @@ class StorageBackedMapTest
|
||||
StorageBackedMap<String> map = new StorageBackedMap<>(storage);
|
||||
map.put("alpha", "one");
|
||||
|
||||
var iterator = map.entrySet().iterator();
|
||||
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
|
||||
assertTrue(iterator.hasNext());
|
||||
iterator.next();
|
||||
iterator.remove();
|
||||
|
||||
@@ -14,6 +14,7 @@ import java.io.IOException;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
@@ -62,7 +63,7 @@ class WalStorageTest {
|
||||
storage.put("a.2", "v2");
|
||||
storage.put("b.1", "v3");
|
||||
|
||||
var results = storage.scan(key -> key.startsWith("a."));
|
||||
List<String> results = storage.scan(key -> key.startsWith("a."));
|
||||
assertEquals(2, results.size());
|
||||
}
|
||||
|
||||
@@ -70,7 +71,7 @@ class WalStorageTest {
|
||||
void scanReturnsMutableList() {
|
||||
storage.put("a", "1");
|
||||
storage.put("b", "2");
|
||||
var result = storage.scan(key -> true);
|
||||
List<String> result = storage.scan(key -> true);
|
||||
assertDoesNotThrow(() -> result.sort(String::compareTo));
|
||||
assertDoesNotThrow(() -> result.add("3"));
|
||||
}
|
||||
@@ -89,7 +90,7 @@ class WalStorageTest {
|
||||
Path snapshotPath = tempDir.resolve("persist-snapshot.json");
|
||||
Path walPath = tempDir.resolve("persist-data.wal");
|
||||
|
||||
var store1 = new WalStorage<>(snapshotPath, walPath,
|
||||
WalStorage<String, String> store1 = new WalStorage<>(snapshotPath, walPath,
|
||||
new TypeReference<Map<String, String>>() {}, 60000);
|
||||
store1.load();
|
||||
store1.put("key1", "value1");
|
||||
@@ -97,7 +98,7 @@ class WalStorageTest {
|
||||
store1.flush();
|
||||
store1.shutdown();
|
||||
|
||||
var store2 = new WalStorage<>(snapshotPath, walPath,
|
||||
WalStorage<String, String> store2 = new WalStorage<>(snapshotPath, walPath,
|
||||
new TypeReference<Map<String, String>>() {}, 60000);
|
||||
store2.load();
|
||||
assertEquals("value1", store2.get("key1").orElseThrow());
|
||||
@@ -110,7 +111,7 @@ class WalStorageTest {
|
||||
Path snapshotPath = tempDir.resolve("replay-snapshot.json");
|
||||
Path walPath = tempDir.resolve("replay-data.wal");
|
||||
|
||||
var store1 = new WalStorage<>(snapshotPath, walPath,
|
||||
WalStorage<String, String> store1 = new WalStorage<>(snapshotPath, walPath,
|
||||
new TypeReference<Map<String, String>>() {}, 600000);
|
||||
store1.load();
|
||||
store1.put("key1", "value1");
|
||||
@@ -118,7 +119,7 @@ class WalStorageTest {
|
||||
store1.delete("key1");
|
||||
|
||||
// Load a second instance from the same WAL (before compaction)
|
||||
var store2 = new WalStorage<>(snapshotPath, walPath,
|
||||
WalStorage<String, String> store2 = new WalStorage<>(snapshotPath, walPath,
|
||||
new TypeReference<Map<String, String>>() {}, 600000);
|
||||
store2.load();
|
||||
assertTrue(store2.get("key1").isEmpty());
|
||||
@@ -133,7 +134,7 @@ class WalStorageTest {
|
||||
Path walPath = tempDir.resolve("binary-check.wal");
|
||||
Path snapshotPath = tempDir.resolve("binary-check-snapshot.json");
|
||||
|
||||
var store = new WalStorage<>(snapshotPath, walPath,
|
||||
WalStorage<String, String> store = new WalStorage<>(snapshotPath, walPath,
|
||||
new TypeReference<Map<String, String>>() {}, 600000);
|
||||
store.load();
|
||||
store.put("k", "v");
|
||||
@@ -175,7 +176,7 @@ class WalStorageTest {
|
||||
Path walPath = tempDir.resolve("truncated.wal");
|
||||
Path snapshotPath = tempDir.resolve("truncated-snapshot.json");
|
||||
|
||||
var store1 = new WalStorage<>(snapshotPath, walPath,
|
||||
WalStorage<String, String> store1 = new WalStorage<>(snapshotPath, walPath,
|
||||
new TypeReference<Map<String, String>>() {}, 600000);
|
||||
store1.load();
|
||||
store1.put("good", "data");
|
||||
@@ -188,7 +189,7 @@ class WalStorageTest {
|
||||
}
|
||||
|
||||
// Load a new instance — should recover the first complete entry
|
||||
var store2 = new WalStorage<>(snapshotPath, walPath,
|
||||
WalStorage<String, String> store2 = new WalStorage<>(snapshotPath, walPath,
|
||||
new TypeReference<Map<String, String>>() {}, 600000);
|
||||
store2.load();
|
||||
assertEquals("data", store2.get("good").orElseThrow());
|
||||
|
||||
+3
-1
@@ -10,6 +10,8 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.security.cert.CertificateFactory;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@@ -118,7 +120,7 @@ class EmulatorInfoControllerIntegrationTest {
|
||||
.contentType(startsWith("text/plain"))
|
||||
.extract().body().asString();
|
||||
|
||||
var cert = (java.security.cert.X509Certificate) java.security.cert.CertificateFactory.getInstance("X.509")
|
||||
X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509")
|
||||
.generateCertificate(new java.io.ByteArrayInputStream(pem.getBytes(java.nio.charset.StandardCharsets.US_ASCII)));
|
||||
assertTrue(cert.getBasicConstraints() >= 0, "must be a CA certificate");
|
||||
assertEquals(cert.getSubjectX500Principal(), cert.getIssuerX500Principal());
|
||||
|
||||
@@ -179,7 +179,7 @@ class EmulatorLifecycleTest {
|
||||
|
||||
emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
|
||||
|
||||
var inOrder = Mockito.inOrder(initializationHooksRunner, storageFactory, initLifecycleState,
|
||||
InOrder inOrder = Mockito.inOrder(initializationHooksRunner, storageFactory, initLifecycleState,
|
||||
iamService, rdsService);
|
||||
inOrder.verify(initializationHooksRunner).run(InitializationHook.BOOT);
|
||||
inOrder.verify(initLifecycleState).markBootCompleted();
|
||||
@@ -242,7 +242,7 @@ class EmulatorLifecycleTest {
|
||||
|
||||
emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
|
||||
|
||||
var inOrder = Mockito.inOrder(storageFactory, elbV2Service);
|
||||
InOrder inOrder = Mockito.inOrder(storageFactory, elbV2Service);
|
||||
inOrder.verify(storageFactory).loadAll();
|
||||
inOrder.verify(elbV2Service).restorePersistedRuntime();
|
||||
}
|
||||
@@ -331,7 +331,7 @@ class EmulatorLifecycleTest {
|
||||
|
||||
emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
|
||||
|
||||
var inOrder = Mockito.inOrder(storageFactory, schemaCreationWorker);
|
||||
InOrder inOrder = Mockito.inOrder(storageFactory, schemaCreationWorker);
|
||||
inOrder.verify(storageFactory).loadAll();
|
||||
inOrder.verify(schemaCreationWorker).recoverOrphans();
|
||||
inOrder.verify(schemaCreationWorker).rehydrateSchemas();
|
||||
@@ -346,7 +346,7 @@ class EmulatorLifecycleTest {
|
||||
|
||||
emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
|
||||
|
||||
var inOrder = Mockito.inOrder(storageFactory, stepFunctionsService);
|
||||
InOrder inOrder = Mockito.inOrder(storageFactory, stepFunctionsService);
|
||||
inOrder.verify(storageFactory).loadAll();
|
||||
inOrder.verify(stepFunctionsService).abortAbandonedExecutions();
|
||||
}
|
||||
@@ -360,7 +360,7 @@ class EmulatorLifecycleTest {
|
||||
|
||||
emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
|
||||
|
||||
var inOrder = Mockito.inOrder(initLifecycleState, persistentPathValidator, storageFactory);
|
||||
InOrder inOrder = Mockito.inOrder(initLifecycleState, persistentPathValidator, storageFactory);
|
||||
inOrder.verify(initLifecycleState).markBootCompleted();
|
||||
inOrder.verify(persistentPathValidator).validateAtBoot();
|
||||
inOrder.verify(storageFactory).loadAll();
|
||||
@@ -572,7 +572,7 @@ class EmulatorLifecycleTest {
|
||||
// shutdown can't be cut off by the SIGTERM grace window before data is persisted
|
||||
// (regression guard for issue #1521). shutdownAll() still runs last to stop the flush
|
||||
// schedulers and capture any shutdown-time writes.
|
||||
var inOrder = Mockito.inOrder(storageFactory, rdsContainerManager, elastiCacheContainerManager);
|
||||
InOrder inOrder = Mockito.inOrder(storageFactory, rdsContainerManager, elastiCacheContainerManager);
|
||||
inOrder.verify(storageFactory).flushAll();
|
||||
inOrder.verify(elastiCacheContainerManager).stopAll();
|
||||
inOrder.verify(rdsContainerManager).stopAll();
|
||||
|
||||
+4
-3
@@ -7,6 +7,7 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.ArgumentMatchers;
|
||||
import org.mockito.InOrder;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
@@ -41,7 +42,7 @@ class InitializationHooksRunnerTest {
|
||||
|
||||
initializationHooksRunner.run("startup", hookDirectory);
|
||||
|
||||
var inOrder = Mockito.inOrder(hookScriptExecutorMock);
|
||||
InOrder inOrder = Mockito.inOrder(hookScriptExecutorMock);
|
||||
inOrder.verify(hookScriptExecutorMock).run(hookDirectory, "10-first.sh");
|
||||
inOrder.verify(hookScriptExecutorMock).run(hookDirectory, "15-second.sh");
|
||||
inOrder.verify(hookScriptExecutorMock).run(hookDirectory, "20-third.sh");
|
||||
@@ -118,7 +119,7 @@ class InitializationHooksRunnerTest {
|
||||
IllegalStateException exception = Assertions.assertThrows(IllegalStateException.class, () -> initializationHooksRunner.run("startup", hookDirectory));
|
||||
Assertions.assertSame(illegalStateException, exception);
|
||||
|
||||
var inOrder = Mockito.inOrder(hookScriptExecutorMock);
|
||||
InOrder inOrder = Mockito.inOrder(hookScriptExecutorMock);
|
||||
inOrder.verify(hookScriptExecutorMock).run(hookDirectory, "10-first.sh");
|
||||
inOrder.verify(hookScriptExecutorMock).run(hookDirectory, "20-failing.sh");
|
||||
inOrder.verifyNoMoreInteractions();
|
||||
@@ -222,7 +223,7 @@ class InitializationHooksRunnerTest {
|
||||
initializationHooksRunner.run(hook);
|
||||
|
||||
// 01-seed.sh from primaryDir wins; 02-extra.sh from compatDir is included
|
||||
var inOrder = Mockito.inOrder(hookScriptExecutorMock);
|
||||
InOrder inOrder = Mockito.inOrder(hookScriptExecutorMock);
|
||||
inOrder.verify(hookScriptExecutorMock).run(primaryDir.resolve("01-seed.sh").toFile());
|
||||
inOrder.verify(hookScriptExecutorMock).run(compatDir.resolve("02-extra.sh").toFile());
|
||||
inOrder.verifyNoMoreInteractions();
|
||||
|
||||
+2
-2
@@ -38,8 +38,8 @@ class AmazonMqEngineTypeCaseTest {
|
||||
.thenReturn(AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
|
||||
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
|
||||
var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
var mqConfig = Mockito.mock(EmulatorConfig.AmazonMqServiceConfig.class);
|
||||
EmulatorConfig.ServicesConfig servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.AmazonMqServiceConfig mqConfig = Mockito.mock(EmulatorConfig.AmazonMqServiceConfig.class);
|
||||
when(config.services()).thenReturn(servicesConfig);
|
||||
when(servicesConfig.amazonmq()).thenReturn(mqConfig);
|
||||
when(mqConfig.mock()).thenReturn(true);
|
||||
|
||||
@@ -30,8 +30,8 @@ class AmazonMqServiceTest {
|
||||
.thenReturn(AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
|
||||
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
|
||||
var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
var mqConfig = Mockito.mock(EmulatorConfig.AmazonMqServiceConfig.class);
|
||||
EmulatorConfig.ServicesConfig servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.AmazonMqServiceConfig mqConfig = Mockito.mock(EmulatorConfig.AmazonMqServiceConfig.class);
|
||||
when(config.services()).thenReturn(servicesConfig);
|
||||
when(servicesConfig.amazonmq()).thenReturn(mqConfig);
|
||||
when(mqConfig.mock()).thenReturn(true);
|
||||
@@ -191,8 +191,8 @@ class AmazonMqServiceTest {
|
||||
.thenReturn(AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
|
||||
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
|
||||
var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
var mqConfig = Mockito.mock(EmulatorConfig.AmazonMqServiceConfig.class);
|
||||
EmulatorConfig.ServicesConfig servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.AmazonMqServiceConfig mqConfig = Mockito.mock(EmulatorConfig.AmazonMqServiceConfig.class);
|
||||
when(config.services()).thenReturn(servicesConfig);
|
||||
when(servicesConfig.amazonmq()).thenReturn(mqConfig);
|
||||
when(mqConfig.mock()).thenReturn(false);
|
||||
|
||||
+28
-26
@@ -2,9 +2,11 @@ package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.http.ContentType;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.*;
|
||||
|
||||
import java.util.Map;
|
||||
@@ -141,11 +143,11 @@ class ApiGatewayAwsIntegrationTest {
|
||||
// PUT integration — AWS type targeting SFN StartExecution
|
||||
// Build the integration body programmatically to avoid escaping hell.
|
||||
// The VTL template wraps the input with DynamoDB typed attributes.
|
||||
var integrationNode = mapper.createObjectNode();
|
||||
ObjectNode integrationNode = mapper.createObjectNode();
|
||||
integrationNode.put("type", "AWS");
|
||||
integrationNode.put("httpMethod", "POST");
|
||||
integrationNode.put("uri", "arn:aws:apigateway:us-east-1:states:action/StartExecution");
|
||||
var reqTemplates = mapper.createObjectNode();
|
||||
ObjectNode reqTemplates = mapper.createObjectNode();
|
||||
// VTL template that builds the SFN StartExecution request.
|
||||
// Passes the incoming body as the SFN execution input.
|
||||
String vtl = "{\"stateMachineArn\": \"" + stateMachineArn + "\", "
|
||||
@@ -709,7 +711,7 @@ class ApiGatewayAwsIntegrationTest {
|
||||
|
||||
redeploy();
|
||||
|
||||
var response = given()
|
||||
Response response = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{}")
|
||||
.when().post("/execute-api/" + apiId + "/test/header-static")
|
||||
@@ -747,7 +749,7 @@ class ApiGatewayAwsIntegrationTest {
|
||||
|
||||
redeploy();
|
||||
|
||||
var response = given()
|
||||
Response response = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{
|
||||
@@ -783,11 +785,11 @@ class ApiGatewayAwsIntegrationTest {
|
||||
.then().statusCode(201);
|
||||
|
||||
// Two templates: application/json writes "json-item", application/xml writes "xml-item"
|
||||
var integrationNode = mapper.createObjectNode();
|
||||
ObjectNode integrationNode = mapper.createObjectNode();
|
||||
integrationNode.put("type", "AWS");
|
||||
integrationNode.put("httpMethod", "POST");
|
||||
integrationNode.put("uri", "arn:aws:apigateway:us-east-1:dynamodb:action/PutItem");
|
||||
var rt = mapper.createObjectNode();
|
||||
ObjectNode rt = mapper.createObjectNode();
|
||||
rt.put("application/json",
|
||||
"{\"TableName\": \"" + TABLE_NAME + "\", \"Item\": {\"id\": {\"S\": \"ct-json\"}, \"source\": {\"S\": \"json-template\"}}}");
|
||||
rt.put("application/xml",
|
||||
@@ -848,7 +850,7 @@ class ApiGatewayAwsIntegrationTest {
|
||||
.when().put("/restapis/" + apiId + "/resources/" + resId + "/methods/POST")
|
||||
.then().statusCode(201);
|
||||
|
||||
var integrationNode = mapper.createObjectNode();
|
||||
ObjectNode integrationNode = mapper.createObjectNode();
|
||||
integrationNode.put("type", "AWS");
|
||||
integrationNode.put("httpMethod", "POST");
|
||||
integrationNode.put("uri", "arn:aws:apigateway:us-east-1:dynamodb:action/ListTables");
|
||||
@@ -892,12 +894,12 @@ class ApiGatewayAwsIntegrationTest {
|
||||
.when().put("/restapis/" + apiId + "/resources/" + resId + "/methods/POST")
|
||||
.then().statusCode(201);
|
||||
|
||||
var integrationNode = mapper.createObjectNode();
|
||||
ObjectNode integrationNode = mapper.createObjectNode();
|
||||
integrationNode.put("type", "AWS");
|
||||
integrationNode.put("httpMethod", "POST");
|
||||
integrationNode.put("uri", "arn:aws:apigateway:us-east-1:dynamodb:action/ListTables");
|
||||
integrationNode.put("passthroughBehavior", "WHEN_NO_TEMPLATES");
|
||||
var rt = mapper.createObjectNode();
|
||||
ObjectNode rt = mapper.createObjectNode();
|
||||
rt.put("text/plain", "{}");
|
||||
integrationNode.set("requestTemplates", rt);
|
||||
|
||||
@@ -941,12 +943,12 @@ class ApiGatewayAwsIntegrationTest {
|
||||
.when().put("/restapis/" + apiId + "/resources/" + resId + "/methods/POST")
|
||||
.then().statusCode(201);
|
||||
|
||||
var integrationNode = mapper.createObjectNode();
|
||||
ObjectNode integrationNode = mapper.createObjectNode();
|
||||
integrationNode.put("type", "AWS");
|
||||
integrationNode.put("httpMethod", "POST");
|
||||
integrationNode.put("uri", "arn:aws:apigateway:us-east-1:dynamodb:action/ListTables");
|
||||
integrationNode.put("passthroughBehavior", "WHEN_NO_MATCH");
|
||||
var rt = mapper.createObjectNode();
|
||||
ObjectNode rt = mapper.createObjectNode();
|
||||
rt.put("text/plain", "{\"bad\":true}");
|
||||
integrationNode.set("requestTemplates", rt);
|
||||
|
||||
@@ -994,14 +996,14 @@ class ApiGatewayAwsIntegrationTest {
|
||||
|
||||
// Map method.request.querystring.itemId → integration.request.querystring.itemId
|
||||
// and use it in the template
|
||||
var integrationNode = mapper.createObjectNode();
|
||||
ObjectNode integrationNode = mapper.createObjectNode();
|
||||
integrationNode.put("type", "AWS");
|
||||
integrationNode.put("httpMethod", "POST");
|
||||
integrationNode.put("uri", "arn:aws:apigateway:us-east-1:dynamodb:action/PutItem");
|
||||
var reqParams = mapper.createObjectNode();
|
||||
ObjectNode reqParams = mapper.createObjectNode();
|
||||
reqParams.put("integration.request.querystring.itemId", "method.request.querystring.itemId");
|
||||
integrationNode.set("requestParameters", reqParams);
|
||||
var rt = mapper.createObjectNode();
|
||||
ObjectNode rt = mapper.createObjectNode();
|
||||
rt.put("application/json",
|
||||
"{\"TableName\": \"" + TABLE_NAME + "\", \"Item\": {\"id\": {\"S\": \"$input.params('itemId')\"}, \"source\": {\"S\": \"req-param-mapped\"}}}");
|
||||
integrationNode.set("requestTemplates", rt);
|
||||
@@ -1072,7 +1074,7 @@ class ApiGatewayAwsIntegrationTest {
|
||||
|
||||
redeploy();
|
||||
|
||||
var response = given()
|
||||
Response response = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{
|
||||
@@ -1109,12 +1111,12 @@ class ApiGatewayAwsIntegrationTest {
|
||||
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST")
|
||||
.then().statusCode(201);
|
||||
|
||||
var integrationNode = mapper.createObjectNode();
|
||||
ObjectNode integrationNode = mapper.createObjectNode();
|
||||
integrationNode.put("type", "AWS");
|
||||
integrationNode.put("httpMethod", "POST");
|
||||
integrationNode.put("uri", uri);
|
||||
if (requestTemplate != null) {
|
||||
var rt = mapper.createObjectNode();
|
||||
ObjectNode rt = mapper.createObjectNode();
|
||||
rt.put("application/json", requestTemplate);
|
||||
integrationNode.set("requestTemplates", rt);
|
||||
}
|
||||
@@ -1125,17 +1127,17 @@ class ApiGatewayAwsIntegrationTest {
|
||||
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST/integration")
|
||||
.then().statusCode(201);
|
||||
|
||||
for (var entry : responses.entrySet()) {
|
||||
var irNode = mapper.createObjectNode();
|
||||
for (Map.Entry<String, IntegrationResponseConfig> entry : responses.entrySet()) {
|
||||
ObjectNode irNode = mapper.createObjectNode();
|
||||
irNode.put("selectionPattern", entry.getValue().selectionPattern());
|
||||
var respTemplates = mapper.createObjectNode();
|
||||
ObjectNode respTemplates = mapper.createObjectNode();
|
||||
respTemplates.put("application/json", entry.getValue().responseTemplate());
|
||||
irNode.set("responseTemplates", respTemplates);
|
||||
|
||||
// Add response parameters if provided
|
||||
Map<String, String> params = responseParams != null ? responseParams.get(entry.getKey()) : null;
|
||||
if (params != null && !params.isEmpty()) {
|
||||
var paramsNode = mapper.createObjectNode();
|
||||
ObjectNode paramsNode = mapper.createObjectNode();
|
||||
params.forEach(paramsNode::put);
|
||||
irNode.set("responseParameters", paramsNode);
|
||||
}
|
||||
@@ -1167,12 +1169,12 @@ class ApiGatewayAwsIntegrationTest {
|
||||
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST")
|
||||
.then().statusCode(201);
|
||||
|
||||
var integrationNode = mapper.createObjectNode();
|
||||
ObjectNode integrationNode = mapper.createObjectNode();
|
||||
integrationNode.put("type", "AWS");
|
||||
integrationNode.put("httpMethod", "POST");
|
||||
integrationNode.put("uri", uri);
|
||||
if (requestTemplate != null) {
|
||||
var rt = mapper.createObjectNode();
|
||||
ObjectNode rt = mapper.createObjectNode();
|
||||
rt.put("application/json", requestTemplate);
|
||||
integrationNode.set("requestTemplates", rt);
|
||||
}
|
||||
@@ -1183,10 +1185,10 @@ class ApiGatewayAwsIntegrationTest {
|
||||
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST/integration")
|
||||
.then().statusCode(201);
|
||||
|
||||
for (var entry : responses.entrySet()) {
|
||||
var irNode = mapper.createObjectNode();
|
||||
for (Map.Entry<String, IntegrationResponseConfig> entry : responses.entrySet()) {
|
||||
ObjectNode irNode = mapper.createObjectNode();
|
||||
irNode.put("selectionPattern", entry.getValue().selectionPattern());
|
||||
var respTemplates = mapper.createObjectNode();
|
||||
ObjectNode respTemplates = mapper.createObjectNode();
|
||||
respTemplates.put("application/json", entry.getValue().responseTemplate());
|
||||
irNode.set("responseTemplates", respTemplates);
|
||||
|
||||
|
||||
+4
-3
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.http.ContentType;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -196,17 +197,17 @@ class ApiGatewaySqsIntegrationTest {
|
||||
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST")
|
||||
.then().statusCode(201);
|
||||
|
||||
var integrationNode = mapper.createObjectNode();
|
||||
ObjectNode integrationNode = mapper.createObjectNode();
|
||||
integrationNode.put("type", "AWS");
|
||||
integrationNode.put("httpMethod", "POST");
|
||||
integrationNode.put("uri", "arn:aws:apigateway:us-east-1:sqs:path/" + URI_ACCOUNT_ID + "/" + uriQueueName);
|
||||
integrationNode.put("passthroughBehavior", "NEVER");
|
||||
|
||||
var reqParams = mapper.createObjectNode();
|
||||
ObjectNode reqParams = mapper.createObjectNode();
|
||||
reqParams.put("integration.request.header.Content-Type", "'application/x-www-form-urlencoded'");
|
||||
integrationNode.set("requestParameters", reqParams);
|
||||
|
||||
var reqTemplates = mapper.createObjectNode();
|
||||
ObjectNode reqTemplates = mapper.createObjectNode();
|
||||
reqTemplates.put("application/json", vtl);
|
||||
integrationNode.set("requestTemplates", reqTemplates);
|
||||
|
||||
|
||||
+4
-3
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.http.ContentType;
|
||||
@@ -83,16 +84,16 @@ class ApiGatewaySqsPathIntegrationTest {
|
||||
.then().statusCode(201);
|
||||
|
||||
// PUT integration
|
||||
var integrationNode = mapper.createObjectNode();
|
||||
ObjectNode integrationNode = mapper.createObjectNode();
|
||||
integrationNode.put("type", "AWS");
|
||||
integrationNode.put("httpMethod", "POST");
|
||||
integrationNode.put("uri", "arn:aws:apigateway:eu-west-1:sqs:path/" + ACCOUNT_ID + "/" + QUEUE_NAME);
|
||||
|
||||
var requestParameters = mapper.createObjectNode();
|
||||
ObjectNode requestParameters = mapper.createObjectNode();
|
||||
requestParameters.put("integration.request.header.Content-Type", "'application/x-www-form-urlencoded'");
|
||||
integrationNode.set("requestParameters", requestParameters);
|
||||
|
||||
var reqTemplates = mapper.createObjectNode();
|
||||
ObjectNode reqTemplates = mapper.createObjectNode();
|
||||
String vtl = "Action=SendMessage&QueueUrl=$util.urlEncode(\"http://localhost:4566/" + ACCOUNT_ID + "/" + QUEUE_NAME + "\")&MessageBody=$util.urlEncode($input.body)";
|
||||
reqTemplates.put("application/json", vtl);
|
||||
integrationNode.set("requestTemplates", reqTemplates);
|
||||
|
||||
+9
-8
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -111,28 +112,28 @@ class VtlTemplateEngineTest {
|
||||
@Test
|
||||
void utilEscapeJavaScript_controlChars() {
|
||||
// Test backspace, form feed
|
||||
var util = new VtlTemplateEngine.UtilVariable(new ObjectMapper());
|
||||
VtlTemplateEngine.UtilVariable util = new VtlTemplateEngine.UtilVariable(new ObjectMapper());
|
||||
String result = util.escapeJavaScript("a\bb\fc");
|
||||
assertEquals("a\\bb\\fc", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void utilEscapeJavaScript_unicode() {
|
||||
var util = new VtlTemplateEngine.UtilVariable(new ObjectMapper());
|
||||
VtlTemplateEngine.UtilVariable util = new VtlTemplateEngine.UtilVariable(new ObjectMapper());
|
||||
String result = util.escapeJavaScript("café");
|
||||
assertEquals("caf\\u00e9", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void utilEscapeJavaScript_backslash() {
|
||||
var util = new VtlTemplateEngine.UtilVariable(new ObjectMapper());
|
||||
VtlTemplateEngine.UtilVariable util = new VtlTemplateEngine.UtilVariable(new ObjectMapper());
|
||||
String result = util.escapeJavaScript("a\\b");
|
||||
assertEquals("a\\\\b", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void utilEscapeJavaScript_newlineTabCr() {
|
||||
var util = new VtlTemplateEngine.UtilVariable(new ObjectMapper());
|
||||
VtlTemplateEngine.UtilVariable util = new VtlTemplateEngine.UtilVariable(new ObjectMapper());
|
||||
String result = util.escapeJavaScript("a\nb\tc\rd");
|
||||
assertEquals("a\\nb\\tc\\rd", result);
|
||||
}
|
||||
@@ -291,7 +292,7 @@ class VtlTemplateEngineTest {
|
||||
+ "#end]}";
|
||||
String result = engine.evaluate(template, ctx(body)).body().trim();
|
||||
assertDoesNotThrow(() -> new ObjectMapper().readTree(result));
|
||||
var node = assertDoesNotThrow(() -> new ObjectMapper().readTree(result));
|
||||
JsonNode node = assertDoesNotThrow(() -> new ObjectMapper().readTree(result));
|
||||
assertEquals(2, node.path("results").size());
|
||||
assertEquals("1", node.path("results").get(0).path("key").asText());
|
||||
}
|
||||
@@ -336,7 +337,7 @@ class VtlTemplateEngineTest {
|
||||
{"QueueUrl": "http://localhost:4566/000000000000/my-queue", "MessageBody": "$util.escapeJavaScript($input.json('$'))"}""";
|
||||
String result = engine.evaluate(template, ctx(body)).body();
|
||||
assertDoesNotThrow(() -> new ObjectMapper().readTree(result));
|
||||
var node = assertDoesNotThrow(() -> new ObjectMapper().readTree(result));
|
||||
JsonNode node = assertDoesNotThrow(() -> new ObjectMapper().readTree(result));
|
||||
assertEquals("http://localhost:4566/000000000000/my-queue", node.path("QueueUrl").asText());
|
||||
// MessageBody should be the escaped JSON string
|
||||
assertTrue(node.path("MessageBody").asText().contains("orderId"));
|
||||
@@ -345,14 +346,14 @@ class VtlTemplateEngineTest {
|
||||
@Test
|
||||
void realWorld_dynamoDbQueryWithParams() {
|
||||
// Pattern: use query string params in a DynamoDB query
|
||||
var queryCtx = new VtlTemplateEngine.VtlContext(
|
||||
VtlTemplateEngine.VtlContext queryCtx = new VtlTemplateEngine.VtlContext(
|
||||
"{}", Map.of(), Map.of("userId", "user-42", "status", "active"),
|
||||
Map.of(), "prod", "GET", "/items",
|
||||
"req-456", "000000000000", Map.of("tableName", "orders"), Map.of());
|
||||
String template = """
|
||||
{"TableName": "$stageVariables.tableName", "KeyConditionExpression": "pk = :pk", "ExpressionAttributeValues": {":pk": {"S": "$input.params().querystring.userId"}}}""";
|
||||
String result = engine.evaluate(template, queryCtx).body();
|
||||
var node = assertDoesNotThrow(() -> new ObjectMapper().readTree(result));
|
||||
JsonNode node = assertDoesNotThrow(() -> new ObjectMapper().readTree(result));
|
||||
assertEquals("orders", node.path("TableName").asText());
|
||||
assertEquals("user-42", node.path("ExpressionAttributeValues").path(":pk").path("S").asText());
|
||||
}
|
||||
|
||||
+16
-16
@@ -22,15 +22,15 @@ class ContextValueResolverTest {
|
||||
|
||||
@Test
|
||||
void literalValuePassesThrough() {
|
||||
var r = new ContextValueResolver();
|
||||
ContextValueResolver r = new ContextValueResolver();
|
||||
assertEquals("wallet.internal",
|
||||
r.resolve("wallet.internal", ctx(Map.of(), Map.of(), Map.of(), Map.of(), Map.of())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void contextAuthorizerClaimsResolves() {
|
||||
var r = new ContextValueResolver();
|
||||
var c = ctx(Map.of("userId", "u-123", "email", "a@b.com"),
|
||||
ContextValueResolver r = new ContextValueResolver();
|
||||
RequestContext c = ctx(Map.of("userId", "u-123", "email", "a@b.com"),
|
||||
Map.of(), Map.of(), Map.of(), Map.of());
|
||||
assertEquals("u-123", r.resolve("$context.authorizer.claims.userId", c));
|
||||
assertEquals("a@b.com", r.resolve("$context.authorizer.claims.email", c));
|
||||
@@ -38,51 +38,51 @@ class ContextValueResolverTest {
|
||||
|
||||
@Test
|
||||
void contextAuthorizerClaimsMissingReturnsNull() {
|
||||
var r = new ContextValueResolver();
|
||||
ContextValueResolver r = new ContextValueResolver();
|
||||
assertNull(r.resolve("$context.authorizer.claims.missing",
|
||||
ctx(Map.of(), Map.of(), Map.of(), Map.of(), Map.of())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void contextAuthorizerArbitraryKeyResolves() {
|
||||
var r = new ContextValueResolver();
|
||||
var c = ctx(Map.of(), Map.of("principalId", "p-1"), Map.of(), Map.of(), Map.of());
|
||||
ContextValueResolver r = new ContextValueResolver();
|
||||
RequestContext c = ctx(Map.of(), Map.of("principalId", "p-1"), Map.of(), Map.of(), Map.of());
|
||||
assertEquals("p-1", r.resolve("$context.authorizer.principalId", c));
|
||||
}
|
||||
|
||||
@Test
|
||||
void contextRequestIdResolves() {
|
||||
var r = new ContextValueResolver();
|
||||
ContextValueResolver r = new ContextValueResolver();
|
||||
assertEquals("req-1",
|
||||
r.resolve("$context.requestId", ctx(Map.of(), Map.of(), Map.of(), Map.of(), Map.of())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void contextSourceIpResolves() {
|
||||
var r = new ContextValueResolver();
|
||||
ContextValueResolver r = new ContextValueResolver();
|
||||
assertEquals("1.2.3.4",
|
||||
r.resolve("$context.identity.sourceIp", ctx(Map.of(), Map.of(), Map.of(), Map.of(), Map.of())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestHeaderResolvesCaseInsensitive() {
|
||||
var r = new ContextValueResolver();
|
||||
var c = ctx(Map.of(), Map.of(), Map.of("X-Forwarded-For", "5.6.7.8"), Map.of(), Map.of());
|
||||
ContextValueResolver r = new ContextValueResolver();
|
||||
RequestContext c = ctx(Map.of(), Map.of(), Map.of("X-Forwarded-For", "5.6.7.8"), Map.of(), Map.of());
|
||||
assertEquals("5.6.7.8", r.resolve("$request.header.X-Forwarded-For", c));
|
||||
assertEquals("5.6.7.8", r.resolve("$request.header.x-forwarded-for", c));
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestQuerystringResolves() {
|
||||
var r = new ContextValueResolver();
|
||||
var c = ctx(Map.of(), Map.of(), Map.of(), Map.of("page", "2"), Map.of());
|
||||
ContextValueResolver r = new ContextValueResolver();
|
||||
RequestContext c = ctx(Map.of(), Map.of(), Map.of(), Map.of("page", "2"), Map.of());
|
||||
assertEquals("2", r.resolve("$request.querystring.page", c));
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestPathResolves() {
|
||||
var r = new ContextValueResolver();
|
||||
var c = ctx(Map.of(), Map.of(), Map.of(), Map.of(),
|
||||
ContextValueResolver r = new ContextValueResolver();
|
||||
RequestContext c = ctx(Map.of(), Map.of(), Map.of(), Map.of(),
|
||||
Map.of("proxy", "users/123", "id", "42"));
|
||||
assertEquals("users/123", r.resolve("$request.path.proxy", c));
|
||||
assertEquals("42", r.resolve("$request.path.id", c));
|
||||
@@ -90,14 +90,14 @@ class ContextValueResolverTest {
|
||||
|
||||
@Test
|
||||
void unknownExpressionReturnsNull() {
|
||||
var r = new ContextValueResolver();
|
||||
ContextValueResolver r = new ContextValueResolver();
|
||||
assertNull(r.resolve("$context.unknown",
|
||||
ctx(Map.of(), Map.of(), Map.of(), Map.of(), Map.of())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullExpressionReturnsNull() {
|
||||
var r = new ContextValueResolver();
|
||||
ContextValueResolver r = new ContextValueResolver();
|
||||
assertNull(r.resolve(null, ctx(Map.of(), Map.of(), Map.of(), Map.of(), Map.of())));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -358,7 +358,7 @@ class HttpProxyInvokerTest {
|
||||
backend.createContext("/", exchange -> {
|
||||
exchange.sendResponseHeaders(200, chunked ? 0 : size);
|
||||
byte[] block = new byte[64 * 1024];
|
||||
try (var out = exchange.getResponseBody()) {
|
||||
try (OutputStream out = exchange.getResponseBody()) {
|
||||
for (int written = 0; written < size; written += block.length) {
|
||||
out.write(block, 0, Math.min(block.length, size - written));
|
||||
}
|
||||
|
||||
+2
-1
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.apigatewayv2.proxy;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@@ -104,7 +105,7 @@ class RequestParameterMapperTest {
|
||||
|
||||
@Test
|
||||
void multipleParametersAppliedInOrder() {
|
||||
var params = new java.util.LinkedHashMap<String, String>();
|
||||
LinkedHashMap<String, String> params = new LinkedHashMap<>();
|
||||
params.put("overwrite:header.Host", "wallet.internal");
|
||||
params.put("append:header.x-user-id", "$context.authorizer.claims.userId");
|
||||
params.put("overwrite:path", "/public/$request.path.proxy");
|
||||
|
||||
+3
-1
@@ -1,6 +1,8 @@
|
||||
package io.github.hectorvent.floci.services.appintegrations;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ExtractableResponse;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -220,7 +222,7 @@ class AppIntegrationsIntegrationTest {
|
||||
@Test
|
||||
@Order(11)
|
||||
void createDataIntegration() {
|
||||
var response = given()
|
||||
ExtractableResponse<Response> response = given()
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{
|
||||
|
||||
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.services.appsync.graphql.auth.LambdaAuthorizer
|
||||
import io.github.hectorvent.floci.services.appsync.graphql.auth.LambdaAuthorizerResult;
|
||||
import io.github.hectorvent.floci.services.appsync.model.ApiKey;
|
||||
import io.github.hectorvent.floci.services.appsync.model.AuthenticationType;
|
||||
import io.github.hectorvent.floci.services.appsync.model.FunctionConfiguration;
|
||||
import io.github.hectorvent.floci.services.appsync.model.GraphqlApi;
|
||||
import io.github.hectorvent.floci.services.appsync.model.SchemaCreationStatus;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
@@ -57,7 +58,7 @@ class AppSyncServiceTest {
|
||||
GraphqlApi api = service.createGraphqlApi(
|
||||
Map.of("name", "rename", "authenticationType", "API_KEY"), "us-east-1");
|
||||
service.createDataSource(api.getApiId(), Map.of("name", "ds", "type", "NONE"), "us-east-1");
|
||||
var created = service.createFunction(api.getApiId(),
|
||||
FunctionConfiguration created = service.createFunction(api.getApiId(),
|
||||
Map.of("name", "Query_getMessages_0", "dataSourceName", "ds"), "us-east-1");
|
||||
|
||||
service.updateFunction(api.getApiId(), created.getFunctionId(),
|
||||
|
||||
+146
-146
@@ -40,27 +40,27 @@ class AppSyncVtlEngineTest {
|
||||
|
||||
@Test
|
||||
void a1_nullTemplate() {
|
||||
var result = engine.evaluate(null, defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate(null, defaultCtx());
|
||||
assertEquals("", result.output());
|
||||
assertNull(result.error());
|
||||
}
|
||||
|
||||
@Test
|
||||
void a2_emptyTemplate() {
|
||||
var result = engine.evaluate("", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("", defaultCtx());
|
||||
assertEquals("", result.output());
|
||||
assertNull(result.error());
|
||||
}
|
||||
|
||||
@Test
|
||||
void a3_plainText() {
|
||||
var result = engine.evaluate("hello", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("hello", defaultCtx());
|
||||
assertEquals("hello", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void a4_jsonTemplate() {
|
||||
var result = engine.evaluate("{\"key\": \"value\"}", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("{\"key\": \"value\"}", defaultCtx());
|
||||
assertEquals("{\"key\": \"value\"}", result.output());
|
||||
}
|
||||
}
|
||||
@@ -70,15 +70,15 @@ class AppSyncVtlEngineTest {
|
||||
|
||||
@Test
|
||||
void b1_contextArguments() {
|
||||
var ctx = ctxWith(b -> b.arguments(Map.of("id", "123")));
|
||||
var result = engine.evaluate("$context.arguments.id", ctx);
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.arguments(Map.of("id", "123")));
|
||||
AppSyncVtlResult result = engine.evaluate("$context.arguments.id", ctx);
|
||||
assertEquals("123", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void b2_ctxArgumentsAlias() {
|
||||
var ctx = ctxWith(b -> b.arguments(Map.of("id", "123")));
|
||||
var result = engine.evaluate("$ctx.arguments.id", ctx);
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.arguments(Map.of("id", "123")));
|
||||
AppSyncVtlResult result = engine.evaluate("$ctx.arguments.id", ctx);
|
||||
assertEquals("123", result.output());
|
||||
}
|
||||
|
||||
@@ -91,100 +91,100 @@ class AppSyncVtlEngineTest {
|
||||
|
||||
@Test
|
||||
void b3_argsShortcut() {
|
||||
var ctx = ctxWith(b -> b.arguments(Map.of("id", "123")));
|
||||
var result = engine.evaluate("$args.id", ctx);
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.arguments(Map.of("id", "123")));
|
||||
AppSyncVtlResult result = engine.evaluate("$args.id", ctx);
|
||||
assertEquals("123", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void b4_contextSource() {
|
||||
var ctx = ctxWith(b -> b.source(Map.of("name", "Alice")));
|
||||
var result = engine.evaluate("$context.source.name", ctx);
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.source(Map.of("name", "Alice")));
|
||||
AppSyncVtlResult result = engine.evaluate("$context.source.name", ctx);
|
||||
assertEquals("Alice", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void b5_sourceAlias() {
|
||||
var ctx = ctxWith(b -> b.source(Map.of("name", "Alice")));
|
||||
var result = engine.evaluate("$source.name", ctx);
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.source(Map.of("name", "Alice")));
|
||||
AppSyncVtlResult result = engine.evaluate("$source.name", ctx);
|
||||
assertEquals("Alice", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void b6_contextSourceNullForTopLevel() {
|
||||
var ctx = ctxWith(b -> b.source(null));
|
||||
var result = engine.evaluate("$util.toJson($context.source)", ctx);
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.source(null));
|
||||
AppSyncVtlResult result = engine.evaluate("$util.toJson($context.source)", ctx);
|
||||
assertEquals("null", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void b7_contextResult() {
|
||||
var ctx = ctxWith(b -> b.result(Map.of("id", 1)));
|
||||
var result = engine.evaluate("$util.toJson($context.result)", ctx);
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.result(Map.of("id", 1)));
|
||||
AppSyncVtlResult result = engine.evaluate("$util.toJson($context.result)", ctx);
|
||||
assertEquals("{\"id\":1}", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void b8_contextStash() {
|
||||
var stash = new HashMap<String, Object>();
|
||||
var ctx = ctxWith(b -> b.stash(stash));
|
||||
var result = engine.evaluate("$util.qr($stash.put(\"x\",\"y\"))$stash.get(\"x\")", ctx);
|
||||
HashMap<String, Object> stash = new HashMap<>();
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.stash(stash));
|
||||
AppSyncVtlResult result = engine.evaluate("$util.qr($stash.put(\"x\",\"y\"))$stash.get(\"x\")", ctx);
|
||||
assertEquals("y", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void b9_contextPrevResult() {
|
||||
var ctx = ctxWith(b -> b.prev(Map.of("result", Map.of("id", 1))));
|
||||
var result = engine.evaluate("$util.toJson($ctx.prev.result)", ctx);
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.prev(Map.of("result", Map.of("id", 1))));
|
||||
AppSyncVtlResult result = engine.evaluate("$util.toJson($ctx.prev.result)", ctx);
|
||||
assertEquals("{\"id\":1}", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void b10_contextInfoFieldName() {
|
||||
var ctx = ctxWith(b -> b.info(Map.of("fieldName", "getUser")));
|
||||
var result = engine.evaluate("$context.info.fieldName", ctx);
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.info(Map.of("fieldName", "getUser")));
|
||||
AppSyncVtlResult result = engine.evaluate("$context.info.fieldName", ctx);
|
||||
assertEquals("getUser", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void b11_contextInfoParentTypeName() {
|
||||
var ctx = ctxWith(b -> b.info(Map.of("parentTypeName", "Query")));
|
||||
var result = engine.evaluate("$context.info.parentTypeName", ctx);
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.info(Map.of("parentTypeName", "Query")));
|
||||
AppSyncVtlResult result = engine.evaluate("$context.info.parentTypeName", ctx);
|
||||
assertEquals("Query", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void b12_contextInfoSelectionSetList() {
|
||||
var ctx = ctxWith(b -> b.info(Map.of("selectionSetList", List.of("id", "name"))));
|
||||
var result = engine.evaluate("$util.toJson($context.info.selectionSetList)", ctx);
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.info(Map.of("selectionSetList", List.of("id", "name"))));
|
||||
AppSyncVtlResult result = engine.evaluate("$util.toJson($context.info.selectionSetList)", ctx);
|
||||
assertEquals("[\"id\",\"name\"]", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void b13_contextInfoVariables() {
|
||||
var ctx = ctxWith(b -> b.info(Map.of("variables", Map.of("id", "1"))));
|
||||
var result = engine.evaluate("$util.toJson($context.info.variables)", ctx);
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.info(Map.of("variables", Map.of("id", "1"))));
|
||||
AppSyncVtlResult result = engine.evaluate("$util.toJson($context.info.variables)", ctx);
|
||||
assertEquals("{\"id\":\"1\"}", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void b14_contextIdentity() {
|
||||
var ctx = ctxWith(b -> b.identity(Map.of("username", "alice")));
|
||||
var result = engine.evaluate("$context.identity.username", ctx);
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.identity(Map.of("username", "alice")));
|
||||
AppSyncVtlResult result = engine.evaluate("$context.identity.username", ctx);
|
||||
assertEquals("alice", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void b15_contextRequestHeaders() {
|
||||
var ctx = ctxWith(b -> b.request(Map.of("headers", Map.of("custom", "val"))));
|
||||
var result = engine.evaluate("$context.request.headers.custom", ctx);
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.request(Map.of("headers", Map.of("custom", "val"))));
|
||||
AppSyncVtlResult result = engine.evaluate("$context.request.headers.custom", ctx);
|
||||
assertEquals("val", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void b16_contextRequestDomainName() {
|
||||
var ctx = ctxWith(b -> b.request(Map.of("domainName", "api.example.com")));
|
||||
var result = engine.evaluate("$context.request.domainName", ctx);
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.request(Map.of("domainName", "api.example.com")));
|
||||
AppSyncVtlResult result = engine.evaluate("$context.request.domainName", ctx);
|
||||
assertEquals("api.example.com", result.output());
|
||||
}
|
||||
}
|
||||
@@ -194,124 +194,124 @@ class AppSyncVtlEngineTest {
|
||||
|
||||
@Test
|
||||
void c1_utilTimeNowISO8601() {
|
||||
var result = engine.evaluate("$util.time.nowISO8601()", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$util.time.nowISO8601()", defaultCtx());
|
||||
assertNotNull(result.output());
|
||||
assertTrue(result.output().toString().contains("T"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void c2_utilDynamoDBJson() {
|
||||
var result = engine.evaluate("$util.dynamodb.toDynamoDBJson(\"hello\")", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$util.dynamodb.toDynamoDBJson(\"hello\")", defaultCtx());
|
||||
assertEquals("{\"S\":\"hello\"}", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void c3_utilDynamoDBWithArgs() {
|
||||
var ctx = ctxWith(b -> b.arguments(Map.of("id", "1")));
|
||||
var result = engine.evaluate("$util.dynamodb.toDynamoDBJson($args.id)", ctx);
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.arguments(Map.of("id", "1")));
|
||||
AppSyncVtlResult result = engine.evaluate("$util.dynamodb.toDynamoDBJson($args.id)", ctx);
|
||||
assertEquals("{\"S\":\"1\"}", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void c4_utilAutoId() {
|
||||
var result = engine.evaluate("$util.autoId()", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$util.autoId()", defaultCtx());
|
||||
assertNotNull(result.output());
|
||||
assertTrue(result.output().toString().length() > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void c5_utilToJson() {
|
||||
var ctx = ctxWith(b -> b.arguments(Map.of("id", "1")));
|
||||
var result = engine.evaluate("$util.toJson($args)", ctx);
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.arguments(Map.of("id", "1")));
|
||||
AppSyncVtlResult result = engine.evaluate("$util.toJson($args)", ctx);
|
||||
assertEquals("{\"id\":\"1\"}", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void c6_utilParseJson() {
|
||||
var result = engine.evaluate("#set($m=$util.parseJson('{\"a\":1}'))$m.a", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("#set($m=$util.parseJson('{\"a\":1}'))$m.a", defaultCtx());
|
||||
assertEquals("1", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void c7_utilMatches() {
|
||||
var result = engine.evaluate("#if($util.matches(\"a*b\",\"aaab\"))yes#end", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("#if($util.matches(\"a*b\",\"aaab\"))yes#end", defaultCtx());
|
||||
assertEquals("yes", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void c8_utilIsNull() {
|
||||
var result = engine.evaluate("#if($util.isNull(null))yes#end", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("#if($util.isNull(null))yes#end", defaultCtx());
|
||||
assertEquals("yes", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void c9_utilIsNullOrEmpty() {
|
||||
var result = engine.evaluate("#if($util.isNullOrEmpty(\"\"))yes#end", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("#if($util.isNullOrEmpty(\"\"))yes#end", defaultCtx());
|
||||
assertEquals("yes", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void c10_utilTypeOf() {
|
||||
var result = engine.evaluate("$util.typeOf(\"hello\")", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$util.typeOf(\"hello\")", defaultCtx());
|
||||
assertEquals("String", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void c11_utilEscapeJavaScript() {
|
||||
var result = engine.evaluate("$util.escapeJavaScript(\"it's\")", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$util.escapeJavaScript(\"it's\")", defaultCtx());
|
||||
assertEquals("it\\'s", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void c12_utilUrlEncode() {
|
||||
var result = engine.evaluate("$util.urlEncode(\"hello world\")", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$util.urlEncode(\"hello world\")", defaultCtx());
|
||||
assertEquals("hello+world", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void c13_utilBase64Encode() {
|
||||
var result = engine.evaluate(
|
||||
AppSyncVtlResult result = engine.evaluate(
|
||||
"#set($s = \"hello\")$util.base64Encode($s.getBytes())", defaultCtx());
|
||||
assertEquals("aGVsbG8=", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void c14_utilStrToUpper() {
|
||||
var result = engine.evaluate("$util.str.toUpper(\"hello\")", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$util.str.toUpper(\"hello\")", defaultCtx());
|
||||
assertEquals("HELLO", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void c15_utilMathRoundNum() {
|
||||
var result = engine.evaluate("$util.math.roundNum(3.7)", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$util.math.roundNum(3.7)", defaultCtx());
|
||||
assertEquals("4", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void c18_utilQrSuppressesOutput() {
|
||||
var stash = new HashMap<String, Object>();
|
||||
var ctx = ctxWith(b -> b.stash(stash));
|
||||
var result = engine.evaluate("$util.qr($stash.put(\"k\",\"v\"))", ctx);
|
||||
HashMap<String, Object> stash = new HashMap<>();
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.stash(stash));
|
||||
AppSyncVtlResult result = engine.evaluate("$util.qr($stash.put(\"k\",\"v\"))", ctx);
|
||||
assertEquals("", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void c19_utilQuietSuppressesOutput() {
|
||||
var stash = new HashMap<String, Object>();
|
||||
var ctx = ctxWith(b -> b.stash(stash));
|
||||
var result = engine.evaluate("$util.quiet($stash.put(\"k\",\"v\"))", ctx);
|
||||
HashMap<String, Object> stash = new HashMap<>();
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.stash(stash));
|
||||
AppSyncVtlResult result = engine.evaluate("$util.quiet($stash.put(\"k\",\"v\"))", ctx);
|
||||
assertEquals("", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void c20_utilDefaultIfNull() {
|
||||
var result = engine.evaluate("$util.defaultIfNull(null, \"default\")", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$util.defaultIfNull(null, \"default\")", defaultCtx());
|
||||
assertEquals("default", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void c16_utilListCopyAndRetainAll() {
|
||||
var result = engine.evaluate(
|
||||
AppSyncVtlResult result = engine.evaluate(
|
||||
"#set($list = [\"a\",\"b\",\"c\",\"d\"])" +
|
||||
"#set($keep = [\"a\",\"c\"])" +
|
||||
"$util.toJson($util.list.copyAndRetainAll($list, $keep))",
|
||||
@@ -321,7 +321,7 @@ class AppSyncVtlEngineTest {
|
||||
|
||||
@Test
|
||||
void c17_utilMapCopyAndRemoveAllKeys() {
|
||||
var result = engine.evaluate(
|
||||
AppSyncVtlResult result = engine.evaluate(
|
||||
"#set($map = {})" +
|
||||
"$util.qr($map.put(\"a\", 1))" +
|
||||
"$util.qr($map.put(\"b\", 2))" +
|
||||
@@ -334,7 +334,7 @@ class AppSyncVtlEngineTest {
|
||||
|
||||
@Test
|
||||
void c21_utilTransformAccessible() {
|
||||
var result = engine.evaluate("#set($t = $util.transform)$util.typeOf($t)", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("#set($t = $util.transform)$util.typeOf($t)", defaultCtx());
|
||||
assertEquals("Object", result.output());
|
||||
}
|
||||
}
|
||||
@@ -344,7 +344,7 @@ class AppSyncVtlEngineTest {
|
||||
|
||||
@Test
|
||||
void d1_utilErrorWithMessage() {
|
||||
var result = engine.evaluate("$util.error(\"fail\")", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$util.error(\"fail\")", defaultCtx());
|
||||
assertTrue(result.hasError());
|
||||
assertEquals("fail", result.error().getMessage());
|
||||
assertEquals("Unknown", result.error().getErrorType());
|
||||
@@ -352,21 +352,21 @@ class AppSyncVtlEngineTest {
|
||||
|
||||
@Test
|
||||
void d2_utilErrorWithType() {
|
||||
var result = engine.evaluate("$util.error(\"fail\", \"CustomError\")", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$util.error(\"fail\", \"CustomError\")", defaultCtx());
|
||||
assertTrue(result.hasError());
|
||||
assertEquals("CustomError", result.error().getErrorType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void d3_utilErrorWithData() {
|
||||
var result = engine.evaluate("$util.error(\"fail\", \"E\", {\"key\":\"val\"})", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$util.error(\"fail\", \"E\", {\"key\":\"val\"})", defaultCtx());
|
||||
assertTrue(result.hasError());
|
||||
assertNotNull(result.error().getData());
|
||||
}
|
||||
|
||||
@Test
|
||||
void d4_utilErrorFullForm() {
|
||||
var result = engine.evaluate(
|
||||
AppSyncVtlResult result = engine.evaluate(
|
||||
"$util.error(\"fail\", \"E\", {\"key\":\"val\"}, {\"info\":\"data\"})",
|
||||
defaultCtx());
|
||||
assertTrue(result.hasError());
|
||||
@@ -375,7 +375,7 @@ class AppSyncVtlEngineTest {
|
||||
|
||||
@Test
|
||||
void d5_utilUnauthorized() {
|
||||
var result = engine.evaluate("$util.unauthorized()", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$util.unauthorized()", defaultCtx());
|
||||
assertTrue(result.hasError());
|
||||
assertEquals("Not Authorized", result.error().getMessage());
|
||||
assertEquals("Unauthorized", result.error().getErrorType());
|
||||
@@ -383,27 +383,27 @@ class AppSyncVtlEngineTest {
|
||||
|
||||
@Test
|
||||
void d6_utilValidateTrue() {
|
||||
var result = engine.evaluate("$util.validate(true, \"msg\")", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$util.validate(true, \"msg\")", defaultCtx());
|
||||
assertFalse(result.hasError());
|
||||
}
|
||||
|
||||
@Test
|
||||
void d7_utilValidateFalse() {
|
||||
var result = engine.evaluate("$util.validate(false, \"msg\")", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$util.validate(false, \"msg\")", defaultCtx());
|
||||
assertTrue(result.hasError());
|
||||
assertEquals("CustomTemplateException", result.error().getErrorType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void d8_errorHaltsEvaluation() {
|
||||
var result = engine.evaluate("$util.error(\"stop\")#set($x=\"after\")", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$util.error(\"stop\")#set($x=\"after\")", defaultCtx());
|
||||
assertTrue(result.hasError());
|
||||
assertEquals("", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void d9_errorInConditional() {
|
||||
var result = engine.evaluate("#if(true)$util.error(\"fail\")#end", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("#if(true)$util.error(\"fail\")#end", defaultCtx());
|
||||
assertTrue(result.hasError());
|
||||
}
|
||||
}
|
||||
@@ -413,7 +413,7 @@ class AppSyncVtlEngineTest {
|
||||
|
||||
@Test
|
||||
void e1_appendErrorDoesNotHalt() {
|
||||
var result = engine.evaluate("$util.appendError(\"warn\")after", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$util.appendError(\"warn\")after", defaultCtx());
|
||||
assertFalse(result.hasError());
|
||||
assertTrue(result.output().toString().contains("after"));
|
||||
assertEquals(1, result.appendedErrors().size());
|
||||
@@ -422,29 +422,29 @@ class AppSyncVtlEngineTest {
|
||||
|
||||
@Test
|
||||
void e1_appendErrorDoesNotPopulateContextError() {
|
||||
var ctx = defaultCtx();
|
||||
var result = engine.evaluate("$util.appendError(\"warn\")$context.error", ctx);
|
||||
AppSyncVtlContext ctx = defaultCtx();
|
||||
AppSyncVtlResult result = engine.evaluate("$util.appendError(\"warn\")$context.error", ctx);
|
||||
assertFalse(result.hasError());
|
||||
assertNull(ctx.getContextMap().get("error"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void e2_appendErrorWithType() {
|
||||
var result = engine.evaluate("$util.appendError(\"warn\", \"Type\")", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$util.appendError(\"warn\", \"Type\")", defaultCtx());
|
||||
assertEquals(1, result.appendedErrors().size());
|
||||
assertEquals("Type", result.appendedErrors().get(0).get("type"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void e3_appendErrorWithData() {
|
||||
var result = engine.evaluate("$util.appendError(\"w\", \"T\", {\"k\":\"v\"})", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$util.appendError(\"w\", \"T\", {\"k\":\"v\"})", defaultCtx());
|
||||
assertEquals(1, result.appendedErrors().size());
|
||||
assertNotNull(result.appendedErrors().get(0).get("data"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void e4_multipleAppendError() {
|
||||
var result = engine.evaluate(
|
||||
AppSyncVtlResult result = engine.evaluate(
|
||||
"$util.appendError(\"e1\")$util.appendError(\"e2\")", defaultCtx());
|
||||
assertEquals(2, result.appendedErrors().size());
|
||||
assertEquals("e1", result.appendedErrors().get(0).get("message"));
|
||||
@@ -453,7 +453,7 @@ class AppSyncVtlEngineTest {
|
||||
|
||||
@Test
|
||||
void e5_appendErrorPlusError() {
|
||||
var result = engine.evaluate(
|
||||
AppSyncVtlResult result = engine.evaluate(
|
||||
"$util.appendError(\"warn\")$util.error(\"fatal\")", defaultCtx());
|
||||
assertTrue(result.hasError());
|
||||
assertEquals(1, result.appendedErrors().size());
|
||||
@@ -463,7 +463,7 @@ class AppSyncVtlEngineTest {
|
||||
|
||||
@Test
|
||||
void e6_appendErrorWithErrorInfo() {
|
||||
var result = engine.evaluate(
|
||||
AppSyncVtlResult result = engine.evaluate(
|
||||
"$util.appendError(\"w\", \"T\", {\"k\":\"v\"}, {\"info\":\"data\"})",
|
||||
defaultCtx());
|
||||
assertEquals(1, result.appendedErrors().size());
|
||||
@@ -477,35 +477,35 @@ class AppSyncVtlEngineTest {
|
||||
|
||||
@Test
|
||||
void f1_returnWithValue() {
|
||||
var result = engine.evaluate("#return({\"id\":\"123\"})", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("#return({\"id\":\"123\"})", defaultCtx());
|
||||
assertFalse(result.hasError());
|
||||
assertNotNull(result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void f2_returnWithoutValue() {
|
||||
var result = engine.evaluate("#return", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("#return", defaultCtx());
|
||||
assertFalse(result.hasError());
|
||||
assertNull(result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void f3_returnHaltsEvaluation() {
|
||||
var result = engine.evaluate("before#return(\"mid\")after", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("before#return(\"mid\")after", defaultCtx());
|
||||
assertFalse(result.hasError());
|
||||
assertEquals("mid", result.output().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void f4_returnInIf() {
|
||||
var result = engine.evaluate("#if(true)#return(\"early\")#end", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("#if(true)#return(\"early\")#end", defaultCtx());
|
||||
assertFalse(result.hasError());
|
||||
assertEquals("early", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void f5_returnInForeach() {
|
||||
var result = engine.evaluate(
|
||||
AppSyncVtlResult result = engine.evaluate(
|
||||
"#foreach($i in [1,2,3])#if($i==2)#return(\"stop\")#end$i#end",
|
||||
defaultCtx());
|
||||
assertFalse(result.hasError());
|
||||
@@ -518,35 +518,35 @@ class AppSyncVtlEngineTest {
|
||||
|
||||
@Test
|
||||
void g1_apiKeyAuth() {
|
||||
var ctx = ctxWith(b -> b.authType("API Key Authorization"));
|
||||
var result = engine.evaluate("$util.authType()", ctx);
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.authType("API Key Authorization"));
|
||||
AppSyncVtlResult result = engine.evaluate("$util.authType()", ctx);
|
||||
assertEquals("API Key Authorization", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void g2_iamAuth() {
|
||||
var ctx = ctxWith(b -> b.authType("IAM Authorization"));
|
||||
var result = engine.evaluate("$util.authType()", ctx);
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.authType("IAM Authorization"));
|
||||
AppSyncVtlResult result = engine.evaluate("$util.authType()", ctx);
|
||||
assertEquals("IAM Authorization", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void g3_cognitoAuth() {
|
||||
var ctx = ctxWith(b -> b.authType("User Pool Authorization"));
|
||||
var result = engine.evaluate("$util.authType()", ctx);
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.authType("User Pool Authorization"));
|
||||
AppSyncVtlResult result = engine.evaluate("$util.authType()", ctx);
|
||||
assertEquals("User Pool Authorization", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void g4_oidcAuth() {
|
||||
var ctx = ctxWith(b -> b.authType("Open ID Connect Authorization"));
|
||||
var result = engine.evaluate("$util.authType()", ctx);
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.authType("Open ID Connect Authorization"));
|
||||
AppSyncVtlResult result = engine.evaluate("$util.authType()", ctx);
|
||||
assertEquals("Open ID Connect Authorization", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void g5_noAuthType() {
|
||||
var result = engine.evaluate("$util.authType()", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$util.authType()", defaultCtx());
|
||||
assertEquals("$util.authType()", result.output());
|
||||
}
|
||||
}
|
||||
@@ -556,57 +556,57 @@ class AppSyncVtlEngineTest {
|
||||
|
||||
@Test
|
||||
void h1_setDirective() {
|
||||
var result = engine.evaluate("#set($x = \"hello\")$x", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("#set($x = \"hello\")$x", defaultCtx());
|
||||
assertEquals("hello", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void h2_ifElse() {
|
||||
var result = engine.evaluate("#if(true)yes#{else}no#end", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("#if(true)yes#{else}no#end", defaultCtx());
|
||||
assertEquals("yes", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void h3_foreach() {
|
||||
var result = engine.evaluate("#foreach($i in [1,2,3])$i #end", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("#foreach($i in [1,2,3])$i #end", defaultCtx());
|
||||
assertEquals("1 2 3 ", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void h4_foreachHasNext() {
|
||||
var result = engine.evaluate(
|
||||
AppSyncVtlResult result = engine.evaluate(
|
||||
"#foreach($i in [1,2])$i$foreach.hasNext#end", defaultCtx());
|
||||
assertEquals("1true2false", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void h5_nullReference() {
|
||||
var result = engine.evaluate("$context.nonexistent", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$context.nonexistent", defaultCtx());
|
||||
assertEquals("$context.nonexistent", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void h5b_silentReferenceOnNull() {
|
||||
var result = engine.evaluate("$!context.error", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$!context.error", defaultCtx());
|
||||
assertEquals("", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void h5c_silentReferenceOnNonexistent() {
|
||||
var result = engine.evaluate("$!context.nonexistent", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$!context.nonexistent", defaultCtx());
|
||||
assertEquals("", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void h6_mapPut() {
|
||||
var result = engine.evaluate(
|
||||
AppSyncVtlResult result = engine.evaluate(
|
||||
"#set($m={})$util.qr($m.put(\"k\",\"v\"))$m.k", defaultCtx());
|
||||
assertEquals("v", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void h7_nestedMaps() {
|
||||
var result = engine.evaluate(
|
||||
AppSyncVtlResult result = engine.evaluate(
|
||||
"#set($m={\"a\":{\"b\":\"c\"}})$m.a.b", defaultCtx());
|
||||
assertEquals("c", result.output());
|
||||
}
|
||||
@@ -617,34 +617,34 @@ class AppSyncVtlEngineTest {
|
||||
|
||||
@Test
|
||||
void i1_stashPersistsAcrossEvaluations() {
|
||||
var stash = new HashMap<String, Object>();
|
||||
var ctx1 = ctxWith(b -> b.stash(stash));
|
||||
HashMap<String, Object> stash = new HashMap<>();
|
||||
AppSyncVtlContext ctx1 = ctxWith(b -> b.stash(stash));
|
||||
engine.evaluate("$util.qr($stash.put(\"x\",\"y\"))", ctx1);
|
||||
|
||||
var ctx2 = ctxWith(b -> b.stash(stash));
|
||||
var result = engine.evaluate("$stash.get(\"x\")", ctx2);
|
||||
AppSyncVtlContext ctx2 = ctxWith(b -> b.stash(stash));
|
||||
AppSyncVtlResult result = engine.evaluate("$stash.get(\"x\")", ctx2);
|
||||
assertEquals("y", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void i2_prevResultCarriesBetweenEvaluations() {
|
||||
var ctx1 = ctxWith(b -> b.result("output1"));
|
||||
var result1 = engine.evaluate("$util.toJson($context.result)", ctx1);
|
||||
AppSyncVtlContext ctx1 = ctxWith(b -> b.result("output1"));
|
||||
AppSyncVtlResult result1 = engine.evaluate("$util.toJson($context.result)", ctx1);
|
||||
|
||||
var ctx2 = ctxWith(b -> b.prev(Map.of("result", "output1")));
|
||||
var result2 = engine.evaluate("$ctx.prev.result", ctx2);
|
||||
AppSyncVtlContext ctx2 = ctxWith(b -> b.prev(Map.of("result", "output1")));
|
||||
AppSyncVtlResult result2 = engine.evaluate("$ctx.prev.result", ctx2);
|
||||
assertEquals("output1", result2.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void i3_stashIsolationBetweenPipelines() {
|
||||
var stash1 = new HashMap<String, Object>();
|
||||
var stash2 = new HashMap<String, Object>();
|
||||
HashMap<String, Object> stash1 = new HashMap<>();
|
||||
HashMap<String, Object> stash2 = new HashMap<>();
|
||||
|
||||
var ctx1 = ctxWith(b -> b.stash(stash1));
|
||||
AppSyncVtlContext ctx1 = ctxWith(b -> b.stash(stash1));
|
||||
engine.evaluate("$util.qr($stash.put(\"key\",\"val1\"))", ctx1);
|
||||
|
||||
var ctx2 = ctxWith(b -> b.stash(stash2));
|
||||
AppSyncVtlContext ctx2 = ctxWith(b -> b.stash(stash2));
|
||||
engine.evaluate("$util.qr($stash.put(\"key\",\"val2\"))", ctx2);
|
||||
|
||||
assertEquals("val1", stash1.get("key"));
|
||||
@@ -654,13 +654,13 @@ class AppSyncVtlEngineTest {
|
||||
|
||||
@Test
|
||||
void i4_stashPersistsBetweenRequestResponse() {
|
||||
var stash = new HashMap<String, Object>();
|
||||
HashMap<String, Object> stash = new HashMap<>();
|
||||
|
||||
var reqCtx = ctxWith(b -> b.stash(stash));
|
||||
AppSyncVtlContext reqCtx = ctxWith(b -> b.stash(stash));
|
||||
engine.evaluate("$util.qr($stash.put(\"key\",\"val\"))", reqCtx);
|
||||
|
||||
var resCtx = ctxWith(b -> b.stash(stash).result("data"));
|
||||
var result = engine.evaluate("$stash.get(\"key\")", resCtx);
|
||||
AppSyncVtlContext resCtx = ctxWith(b -> b.stash(stash).result("data"));
|
||||
AppSyncVtlResult result = engine.evaluate("$stash.get(\"key\")", resCtx);
|
||||
assertEquals("val", result.output());
|
||||
}
|
||||
}
|
||||
@@ -670,94 +670,94 @@ class AppSyncVtlEngineTest {
|
||||
|
||||
@Test
|
||||
void j1_unicodeInTemplate() {
|
||||
var result = engine.evaluate("{\"name\": \"日本語\"}", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("{\"name\": \"日本語\"}", defaultCtx());
|
||||
assertEquals("{\"name\": \"日本語\"}", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void j3_specialCharactersInArgs() {
|
||||
var ctx = ctxWith(b -> b.arguments(Map.of("name", "O'Brien")));
|
||||
var result = engine.evaluate("$args.name", ctx);
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.arguments(Map.of("name", "O'Brien")));
|
||||
AppSyncVtlResult result = engine.evaluate("$args.name", ctx);
|
||||
assertEquals("O'Brien", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void j4_deeplyNestedContext() {
|
||||
var ctx = ctxWith(b -> b.arguments(Map.of("a", Map.of("b", Map.of("c", Map.of("d", "deep"))))));
|
||||
var result = engine.evaluate("$context.arguments.a.b.c.d", ctx);
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.arguments(Map.of("a", Map.of("b", Map.of("c", Map.of("d", "deep"))))));
|
||||
AppSyncVtlResult result = engine.evaluate("$context.arguments.a.b.c.d", ctx);
|
||||
assertEquals("deep", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void j7_contextErrorInitiallyNull() {
|
||||
var result = engine.evaluate("$context.error", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$context.error", defaultCtx());
|
||||
assertEquals("$context.error", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void j8_contextErrorNotPopulatedByAppendError() {
|
||||
var ctx = defaultCtx();
|
||||
var result = engine.evaluate(
|
||||
AppSyncVtlContext ctx = defaultCtx();
|
||||
AppSyncVtlResult result = engine.evaluate(
|
||||
"$util.appendError(\"msg\", \"Type\")$context.error", ctx);
|
||||
assertNull(ctx.getContextMap().get("error"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void j9_multiValueHeaders() {
|
||||
var ctx = ctxWith(b -> b.request(
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.request(
|
||||
Map.of("headers", Map.of("custom", List.of("val1", "val2")))));
|
||||
var result = engine.evaluate("$context.request.headers.custom[0]", ctx);
|
||||
AppSyncVtlResult result = engine.evaluate("$context.request.headers.custom[0]", ctx);
|
||||
assertEquals("val1", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void j10_contextResultNullInRequestTemplate() {
|
||||
var ctx = defaultCtx();
|
||||
var result = engine.evaluate("$context.result", ctx);
|
||||
AppSyncVtlContext ctx = defaultCtx();
|
||||
AppSyncVtlResult result = engine.evaluate("$context.result", ctx);
|
||||
assertEquals("$context.result", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void j11_prevDefaultIsNull() {
|
||||
var result = engine.evaluate("$util.toJson($ctx.prev)", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$util.toJson($ctx.prev)", defaultCtx());
|
||||
assertEquals("null", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void j11b_prevUndefinedRendersAsLiteral() {
|
||||
var result = engine.evaluate("$ctx.prev", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$ctx.prev", defaultCtx());
|
||||
assertEquals("$ctx.prev", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void j11c_prevResultUndefinedRendersAsLiteral() {
|
||||
var result = engine.evaluate("$ctx.prev.result", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$ctx.prev.result", defaultCtx());
|
||||
assertEquals("$ctx.prev.result", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void j2_largeTemplateWithLoops() {
|
||||
var sb = new StringBuilder();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("#set($total = 0)");
|
||||
sb.append("#foreach($i in [1,2,3,4,5])");
|
||||
sb.append("#set($total = $total + $i)");
|
||||
sb.append("#end");
|
||||
sb.append("$total");
|
||||
var result = engine.evaluate(sb.toString(), defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate(sb.toString(), defaultCtx());
|
||||
assertEquals("15", result.output());
|
||||
}
|
||||
|
||||
@Test
|
||||
void j5_toJsonExcludesSelectionSetFields() {
|
||||
var info = Map.<String, Object>of(
|
||||
Map<String, Object> info = Map.of(
|
||||
"fieldName", "getPost",
|
||||
"parentTypeName", "Query",
|
||||
"variables", Map.of("id", "1"),
|
||||
"selectionSetList", List.of("id", "title"),
|
||||
"selectionSetGraphQL", "{ id title }"
|
||||
);
|
||||
var ctx = ctxWith(b -> b.info(info));
|
||||
var result = engine.evaluate("$util.toJson($context.info)", ctx);
|
||||
AppSyncVtlContext ctx = ctxWith(b -> b.info(info));
|
||||
AppSyncVtlResult result = engine.evaluate("$util.toJson($context.info)", ctx);
|
||||
String output = result.output().toString();
|
||||
assertTrue(output.contains("fieldName"));
|
||||
assertTrue(output.contains("parentTypeName"));
|
||||
@@ -785,7 +785,7 @@ class AppSyncVtlEngineTest {
|
||||
// evaluating it. Getting the raw template text back verbatim (rather than an actual
|
||||
// ClassLoader instance's toString) proves the call was blocked.
|
||||
String template = "$util.getClass().getClassLoader()";
|
||||
var result = engine.evaluate(template, defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate(template, defaultCtx());
|
||||
assertEquals(template, result.output(),
|
||||
"expected getClassLoader() to be blocked by SecureUberspector and rendered as "
|
||||
+ "an unresolved literal reference, but got: " + result.output());
|
||||
@@ -793,7 +793,7 @@ class AppSyncVtlEngineTest {
|
||||
|
||||
@Test
|
||||
void k2_classForNameIsNotReachable() {
|
||||
var result = engine.evaluate(
|
||||
AppSyncVtlResult result = engine.evaluate(
|
||||
"$util.getClass().forName('java.lang.System').getName()", defaultCtx());
|
||||
assertNotEquals("java.lang.System", result.output(),
|
||||
"expected Class.forName(...) to be blocked by SecureUberspector, but it resolved: "
|
||||
@@ -802,7 +802,7 @@ class AppSyncVtlEngineTest {
|
||||
|
||||
@Test
|
||||
void k3_runtimeClassIsNotLoadableByName() {
|
||||
var result = engine.evaluate(
|
||||
AppSyncVtlResult result = engine.evaluate(
|
||||
"$util.getClass().forName('java.lang.Runtime').getName()", defaultCtx());
|
||||
assertNotEquals("java.lang.Runtime", result.output(),
|
||||
"expected Class.forName('java.lang.Runtime') to be blocked, but it resolved: "
|
||||
@@ -811,7 +811,7 @@ class AppSyncVtlEngineTest {
|
||||
|
||||
@Test
|
||||
void k4_processBuilderClassIsNotLoadableByName() {
|
||||
var result = engine.evaluate(
|
||||
AppSyncVtlResult result = engine.evaluate(
|
||||
"$util.getClass().forName('java.lang.ProcessBuilder').getName()", defaultCtx());
|
||||
assertNotEquals("java.lang.ProcessBuilder", result.output(),
|
||||
"expected Class.forName('java.lang.ProcessBuilder') to be blocked, but it resolved: "
|
||||
@@ -822,7 +822,7 @@ class AppSyncVtlEngineTest {
|
||||
void k5_getClassStillPermitsGetName() {
|
||||
// getName() on a Class receiver must remain permitted (SecureUberspector's one
|
||||
// exception), so ordinary reflection-free VTL idioms relying on it keep working.
|
||||
var result = engine.evaluate("$util.getClass().getName()", defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate("$util.getClass().getName()", defaultCtx());
|
||||
assertTrue(result.output().toString().contains("AppSyncUtil"),
|
||||
"expected getName() on Class to still work, got: " + result.output());
|
||||
}
|
||||
@@ -833,7 +833,7 @@ class AppSyncVtlEngineTest {
|
||||
// renders 50,000 characters; the configured default
|
||||
// (AppSyncServiceConfig.vtlMaxLoops = 10000) must cap the loop well before that.
|
||||
String template = "#foreach($i in [1..50000])x#end";
|
||||
var result = engine.evaluate(template, defaultCtx());
|
||||
AppSyncVtlResult result = engine.evaluate(template, defaultCtx());
|
||||
assertEquals(10000, result.output().toString().length(),
|
||||
"expected #foreach to be capped at the configured vtlMaxLoops, but rendered "
|
||||
+ result.output().toString().length() + " characters");
|
||||
|
||||
+1
-1
@@ -88,7 +88,7 @@ class AppSyncResolverExecutorTest {
|
||||
public JsEvaluation evaluate(String code, String handler, Map<String, Object> context) {
|
||||
calls.add(code + "#" + handler);
|
||||
contexts.add(context);
|
||||
var script = scripts.get(code + "#" + handler);
|
||||
BiFunction<String, Map<String, Object>, JsEvaluation> script = scripts.get(code + "#" + handler);
|
||||
if (script == null) {
|
||||
// Nothing scripted stands for a module that does not export this handler, which is
|
||||
// how a request-only function behaves.
|
||||
|
||||
+4
-3
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.appsync.graphql.util;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -100,11 +101,11 @@ class ListUtilTest {
|
||||
|
||||
@Test
|
||||
void sortList_withFieldName() {
|
||||
var map1 = new java.util.HashMap<String, Object>();
|
||||
HashMap<String, Object> map1 = new HashMap<>();
|
||||
map1.put("name", "Charlie");
|
||||
var map2 = new java.util.HashMap<String, Object>();
|
||||
HashMap<String, Object> map2 = new HashMap<>();
|
||||
map2.put("name", "Alice");
|
||||
var map3 = new java.util.HashMap<String, Object>();
|
||||
HashMap<String, Object> map3 = new HashMap<>();
|
||||
map3.put("name", "Bob");
|
||||
List<Object> input = List.of(map1, map2, map3);
|
||||
List<Object> result = listUtil.sortList(input, false, "name");
|
||||
|
||||
+6
-6
@@ -70,7 +70,7 @@ class AthenaCreateWorkGroupPersistenceIntegrationTest {
|
||||
|
||||
assertTrue(Files.exists(WORKGROUPS_FILE), "CreateWorkGroup should create workgroups.json");
|
||||
|
||||
var store = new PersistentStorage<String, Map<String, Object>>(
|
||||
PersistentStorage<String, Map<String, Object>> store = new PersistentStorage<>(
|
||||
WORKGROUPS_FILE,
|
||||
new TypeReference<Map<String, Map<String, Object>>>() {});
|
||||
store.load();
|
||||
@@ -121,7 +121,7 @@ class AthenaCreateWorkGroupPersistenceIntegrationTest {
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
var store = new PersistentStorage<String, Map<String, Object>>(
|
||||
PersistentStorage<String, Map<String, Object>> store = new PersistentStorage<>(
|
||||
WORKGROUPS_FILE,
|
||||
new TypeReference<Map<String, Map<String, Object>>>() {});
|
||||
store.load();
|
||||
@@ -167,7 +167,7 @@ class AthenaCreateWorkGroupPersistenceIntegrationTest {
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
var store = new PersistentStorage<String, Map<String, Object>>(
|
||||
PersistentStorage<String, Map<String, Object>> store = new PersistentStorage<>(
|
||||
WORKGROUPS_FILE,
|
||||
new TypeReference<Map<String, Map<String, Object>>>() {});
|
||||
store.load();
|
||||
@@ -205,7 +205,7 @@ class AthenaCreateWorkGroupPersistenceIntegrationTest {
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
var store = new PersistentStorage<String, Map<String, Object>>(
|
||||
PersistentStorage<String, Map<String, Object>> store = new PersistentStorage<>(
|
||||
WORKGROUPS_FILE,
|
||||
new TypeReference<Map<String, Map<String, Object>>>() {});
|
||||
store.load();
|
||||
@@ -240,7 +240,7 @@ class AthenaCreateWorkGroupPersistenceIntegrationTest {
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
var store = new PersistentStorage<String, Map<String, Object>>(
|
||||
PersistentStorage<String, Map<String, Object>> store = new PersistentStorage<>(
|
||||
WORKGROUPS_FILE,
|
||||
new TypeReference<Map<String, Map<String, Object>>>() {});
|
||||
store.load();
|
||||
@@ -277,7 +277,7 @@ class AthenaCreateWorkGroupPersistenceIntegrationTest {
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
var store = new PersistentStorage<String, Map<String, Object>>(
|
||||
PersistentStorage<String, Map<String, Object>> store = new PersistentStorage<>(
|
||||
WORKGROUPS_FILE,
|
||||
new TypeReference<Map<String, Map<String, Object>>>() {});
|
||||
store.load();
|
||||
|
||||
+2
-1
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.athena;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -92,7 +93,7 @@ class AthenaGetWorkGroupIntegrationTest {
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
var response = given()
|
||||
ValidatableResponse response = given()
|
||||
.header("X-Amz-Target", "AmazonAthena.GetWorkGroup")
|
||||
.contentType(CONTENT_TYPE)
|
||||
.body("{ \"WorkGroup\": \"timestamp-format-bug-wg\" }")
|
||||
|
||||
+6
-6
@@ -54,14 +54,14 @@ class AutoScalingReconcilerTest {
|
||||
|
||||
@Test
|
||||
void stopTerminatesReconcilerThread() throws Exception {
|
||||
var asgService = mock(AutoScalingService.class);
|
||||
var ec2Service = mock(Ec2Service.class);
|
||||
var elbV2Service = mock(ElbV2Service.class);
|
||||
var reconciler = new AutoScalingReconciler(asgService, ec2Service, elbV2Service);
|
||||
var preexisting = Thread.getAllStackTraces().keySet();
|
||||
AutoScalingService asgService = mock(AutoScalingService.class);
|
||||
Ec2Service ec2Service = mock(Ec2Service.class);
|
||||
ElbV2Service elbV2Service = mock(ElbV2Service.class);
|
||||
AutoScalingReconciler reconciler = new AutoScalingReconciler(asgService, ec2Service, elbV2Service);
|
||||
Set<Thread> preexisting = Thread.getAllStackTraces().keySet();
|
||||
|
||||
reconciler.start();
|
||||
var reconcilerThread = Thread.getAllStackTraces().keySet().stream()
|
||||
Thread reconcilerThread = Thread.getAllStackTraces().keySet().stream()
|
||||
.filter(t -> "asg-reconciler".equals(t.getName()) && !preexisting.contains(t))
|
||||
.findFirst().orElseThrow();
|
||||
|
||||
|
||||
+25
-22
@@ -6,8 +6,11 @@ import io.github.hectorvent.floci.services.autoscaling.model.AsgInstance;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.AsgOptionalFields;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.AutoScalingGroup;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.InstanceRefresh;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.LaunchConfiguration;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.LaunchConfigurationBlockDeviceMapping;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.MixedInstancesPolicy;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.ScheduledAction;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.WarmPoolConfiguration;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.model.GroupIdentifier;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
@@ -91,7 +94,7 @@ class AutoScalingServiceTest {
|
||||
assertEquals(refresh.getInstanceRefreshId(), page.instanceRefreshes().getFirst().getInstanceRefreshId());
|
||||
assertNull(page.nextToken());
|
||||
|
||||
var group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
|
||||
AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
|
||||
assertEquals("lt-updated", group.getLaunchTemplateId());
|
||||
assertEquals("2", group.getLaunchTemplateVersion());
|
||||
assertNull(group.getLaunchConfigurationName());
|
||||
@@ -186,7 +189,7 @@ class AutoScalingServiceTest {
|
||||
when(ec2Service.describeInstances(REGION, List.of("i-1234567890abcdef0"), java.util.Map.of()))
|
||||
.thenReturn(List.of(reservation));
|
||||
|
||||
var launchConfiguration = service.createLaunchConfiguration(REGION,
|
||||
LaunchConfiguration launchConfiguration = service.createLaunchConfiguration(REGION,
|
||||
"lc-from-instance",
|
||||
"i-1234567890abcdef0",
|
||||
null,
|
||||
@@ -210,7 +213,7 @@ class AutoScalingServiceTest {
|
||||
|
||||
@Test
|
||||
void createLaunchConfigurationDefaultsInstanceMonitoringToEnabled() {
|
||||
var lc = service.createLaunchConfiguration(REGION, "lc-default-monitoring", null,
|
||||
LaunchConfiguration lc = service.createLaunchConfiguration(REGION, "lc-default-monitoring", null,
|
||||
"ami-12345678", "t3.micro", null, List.of(), null, null, null);
|
||||
|
||||
assertEquals(Boolean.TRUE, lc.getInstanceMonitoringEnabled());
|
||||
@@ -222,7 +225,7 @@ class AutoScalingServiceTest {
|
||||
|
||||
@Test
|
||||
void createLaunchConfigurationKeepsAnExplicitInstanceMonitoringOverride() {
|
||||
var lc = service.createLaunchConfiguration(REGION, "lc-monitoring-off", null,
|
||||
LaunchConfiguration lc = service.createLaunchConfiguration(REGION, "lc-monitoring-off", null,
|
||||
"ami-12345678", "t3.micro", null, List.of(), null, null, null, Boolean.FALSE, List.of());
|
||||
|
||||
assertEquals(Boolean.FALSE, lc.getInstanceMonitoringEnabled());
|
||||
@@ -233,20 +236,20 @@ class AutoScalingServiceTest {
|
||||
|
||||
@Test
|
||||
void createLaunchConfigurationRoundTripsBlockDeviceMappings() {
|
||||
var ebs = new LaunchConfigurationBlockDeviceMapping.Ebs();
|
||||
LaunchConfigurationBlockDeviceMapping.Ebs ebs = new LaunchConfigurationBlockDeviceMapping.Ebs();
|
||||
ebs.setVolumeSize(100);
|
||||
ebs.setVolumeType("gp3");
|
||||
ebs.setIops(3000);
|
||||
ebs.setThroughput(125);
|
||||
ebs.setDeleteOnTermination(true);
|
||||
var mapping = new LaunchConfigurationBlockDeviceMapping();
|
||||
LaunchConfigurationBlockDeviceMapping mapping = new LaunchConfigurationBlockDeviceMapping();
|
||||
mapping.setDeviceName("/dev/xvda");
|
||||
mapping.setEbs(ebs);
|
||||
|
||||
service.createLaunchConfiguration(REGION, "lc-with-root-device", null,
|
||||
"ami-12345678", "t3.micro", null, List.of(), null, null, null, null, List.of(mapping));
|
||||
|
||||
var stored = service.describeLaunchConfigurations(REGION, List.of("lc-with-root-device"))
|
||||
List<LaunchConfigurationBlockDeviceMapping> stored = service.describeLaunchConfigurations(REGION, List.of("lc-with-root-device"))
|
||||
.getFirst().getBlockDeviceMappings();
|
||||
assertEquals(1, stored.size());
|
||||
assertEquals("/dev/xvda", stored.getFirst().getDeviceName());
|
||||
@@ -319,7 +322,7 @@ class AutoScalingServiceTest {
|
||||
|
||||
assertEquals("ValidationError", error.getErrorCode());
|
||||
assertEquals(AutoScalingService.MISSING_LAUNCH_TEMPLATE_IMAGE_ID_MESSAGE, error.getMessage());
|
||||
var group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
|
||||
AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
|
||||
assertEquals("lt-original", group.getLaunchTemplateId());
|
||||
assertEquals(3, group.getMaxSize());
|
||||
}
|
||||
@@ -346,7 +349,7 @@ class AutoScalingServiceTest {
|
||||
|
||||
assertEquals("ValidationError", error.getErrorCode());
|
||||
assertEquals("LaunchTemplateVersion requires a LaunchTemplateId or LaunchTemplateName.", error.getMessage());
|
||||
var group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
|
||||
AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
|
||||
assertEquals("1", group.getLaunchTemplateVersion());
|
||||
assertEquals(3, group.getMaxSize());
|
||||
}
|
||||
@@ -380,7 +383,7 @@ class AutoScalingServiceTest {
|
||||
assertEquals("ValidationError", error.getErrorCode());
|
||||
assertEquals(AutoScalingService.ACTIVE_INSTANCE_REFRESH_DESIRED_CONFIGURATION_MESSAGE, error.getMessage());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
var group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
|
||||
AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
|
||||
assertEquals("lt-refresh", group.getLaunchTemplateId());
|
||||
assertEquals("2", group.getLaunchTemplateVersion());
|
||||
assertEquals(3, group.getMaxSize());
|
||||
@@ -452,7 +455,7 @@ class AutoScalingServiceTest {
|
||||
|
||||
@Test
|
||||
void startInstanceRefreshWithLaunchTemplateAliasDoesNotSkipExistingInstances() {
|
||||
var group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
|
||||
AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
|
||||
group.setLaunchTemplateVersion("$Latest");
|
||||
AutoScalingGroupFixture.addInstance(service, REGION, "test-asg", "i-original", "InService", "lt-original", "1");
|
||||
InstanceRefresh request = new InstanceRefresh();
|
||||
@@ -479,7 +482,7 @@ class AutoScalingServiceTest {
|
||||
|
||||
@Test
|
||||
void startInstanceRefreshWithDefaultLaunchTemplateAliasDoesNotSkipExistingInstances() {
|
||||
var group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
|
||||
AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
|
||||
group.setLaunchTemplateVersion("$Default");
|
||||
AutoScalingGroupFixture.addInstance(service, REGION, "test-asg", "i-original", "InService", "lt-original", "1");
|
||||
InstanceRefresh request = new InstanceRefresh();
|
||||
@@ -506,7 +509,7 @@ class AutoScalingServiceTest {
|
||||
|
||||
@Test
|
||||
void startInstanceRefreshWithDefaultLaunchTemplateVersionDoesNotSkipExistingInstances() {
|
||||
var group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
|
||||
AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
|
||||
group.setLaunchTemplateVersion(null);
|
||||
AutoScalingGroupFixture.addInstance(service, REGION, "test-asg", "i-original", "InService", "lt-original", "1");
|
||||
InstanceRefresh request = new InstanceRefresh();
|
||||
@@ -522,7 +525,7 @@ class AutoScalingServiceTest {
|
||||
|
||||
@Test
|
||||
void startInstanceRefreshWithBlankLaunchTemplateVersionDoesNotSkipExistingInstances() {
|
||||
var group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
|
||||
AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
|
||||
group.setLaunchTemplateVersion("");
|
||||
AutoScalingGroupFixture.addInstance(service, REGION, "test-asg", "i-original", "InService", "lt-original", "1");
|
||||
InstanceRefresh request = new InstanceRefresh();
|
||||
@@ -543,7 +546,7 @@ class AutoScalingServiceTest {
|
||||
request.setDesiredLaunchTemplateId("lt-updated");
|
||||
request.setDesiredLaunchTemplateVersion("2");
|
||||
InstanceRefresh refresh = service.startInstanceRefresh(REGION, "test-asg", request);
|
||||
var group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
|
||||
AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
|
||||
group.getInstances().clear();
|
||||
AutoScalingGroupFixture.addInstance(service, REGION, "test-asg", "i-replacement", "InService", "lt-updated", "2");
|
||||
|
||||
@@ -563,7 +566,7 @@ class AutoScalingServiceTest {
|
||||
void completeInstanceRefreshWaitsForReplacementCapacity() {
|
||||
AutoScalingGroupFixture.addInstance(service, REGION, "test-asg", "i-original", "InService", "lt-original", "1");
|
||||
InstanceRefresh refresh = service.startInstanceRefresh(REGION, "test-asg", new InstanceRefresh());
|
||||
var group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
|
||||
AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
|
||||
group.getInstances().clear();
|
||||
|
||||
service.completeInstanceRefreshIfSettled(REGION, "test-asg");
|
||||
@@ -671,7 +674,7 @@ class AutoScalingServiceTest {
|
||||
|
||||
createWithMixedInstancesPolicy("mixed-with-lt", policy);
|
||||
|
||||
var group = service.describeAutoScalingGroups(REGION, List.of("mixed-with-lt")).getFirst();
|
||||
AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of("mixed-with-lt")).getFirst();
|
||||
assertEquals("lt-mixed",
|
||||
group.getMixedInstancesPolicy().getLaunchTemplate()
|
||||
.getLaunchTemplateSpecification().getLaunchTemplateId());
|
||||
@@ -809,7 +812,7 @@ class AutoScalingServiceTest {
|
||||
dup2.setInstanceId("i-dup");
|
||||
dup2.setLifecycleState("InService");
|
||||
dup2.setHealthStatus("Healthy");
|
||||
var instances = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst().getInstances();
|
||||
List<AsgInstance> instances = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst().getInstances();
|
||||
instances.add(dup1);
|
||||
instances.add(dup2);
|
||||
|
||||
@@ -854,7 +857,7 @@ class AutoScalingServiceTest {
|
||||
void suspendProcessesRecordsNamedProcessesAndResumeClearsThem() {
|
||||
service.suspendProcesses(REGION, "test-asg", List.of("Launch", "Terminate"));
|
||||
|
||||
var group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
|
||||
AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
|
||||
assertEquals(List.of("Launch", "Terminate"), group.getSuspendedProcesses());
|
||||
|
||||
service.resumeProcesses(REGION, "test-asg", List.of("Launch"));
|
||||
@@ -870,7 +873,7 @@ class AutoScalingServiceTest {
|
||||
void suspendProcessesWithNoNamesSuspendsEveryScalingProcess() {
|
||||
service.suspendProcesses(REGION, "test-asg", List.of());
|
||||
|
||||
var group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
|
||||
AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
|
||||
assertTrue(group.getSuspendedProcesses().contains("Launch"));
|
||||
assertTrue(group.getSuspendedProcesses().contains("Terminate"));
|
||||
assertTrue(group.getSuspendedProcesses().contains("HealthCheck"));
|
||||
@@ -905,7 +908,7 @@ class AutoScalingServiceTest {
|
||||
service.putScheduledUpdateGroupAction(REGION, "test-asg", "morning",
|
||||
null, null, "0 7 * * 1-5", "Europe/Rome", 0, 1, 1);
|
||||
|
||||
var actions = service.describeScheduledActions(REGION, "test-asg", List.of());
|
||||
List<ScheduledAction> actions = service.describeScheduledActions(REGION, "test-asg", List.of());
|
||||
assertEquals(1, actions.size());
|
||||
assertEquals("morning", actions.getFirst().getScheduledActionName());
|
||||
assertEquals("0 7 * * 1-5", actions.getFirst().getRecurrence());
|
||||
@@ -923,7 +926,7 @@ class AutoScalingServiceTest {
|
||||
void putWarmPoolReplacesConfigurationAndMapsTheClearSentinel() {
|
||||
service.putWarmPool(REGION, "test-asg", 2, 1, "Running", true);
|
||||
|
||||
var pool = service.describeWarmPool(REGION, "test-asg");
|
||||
WarmPoolConfiguration pool = service.describeWarmPool(REGION, "test-asg");
|
||||
assertEquals(2, pool.getMaxGroupPreparedCapacity());
|
||||
assertEquals(1, pool.getMinSize());
|
||||
assertEquals("Running", pool.getPoolState());
|
||||
|
||||
+3
-1
@@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.bedrock;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ExtractableResponse;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
@@ -31,7 +33,7 @@ class BedrockIntegrationTest {
|
||||
@Test
|
||||
@Order(1)
|
||||
void createGuardrail() {
|
||||
var response = given()
|
||||
ExtractableResponse<Response> response = given()
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{
|
||||
|
||||
+2
-1
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.bedrockagentcorecontrol;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ExtractableResponse;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
@@ -42,7 +43,7 @@ class BedrockAgentCorePaginationIntegrationTest {
|
||||
String token = null;
|
||||
int pages = 0;
|
||||
do {
|
||||
var req = given().contentType("application/json").queryParam("maxResults", 2);
|
||||
RequestSpecification req = given().contentType("application/json").queryParam("maxResults", 2);
|
||||
if (token != null) {
|
||||
req = req.queryParam("nextToken", token);
|
||||
}
|
||||
|
||||
+3
-1
@@ -1,6 +1,8 @@
|
||||
package io.github.hectorvent.floci.services.bedrockagentcorecontrol;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ExtractableResponse;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -30,7 +32,7 @@ class BedrockAgentCoreTaggingIdentityIntegrationTest {
|
||||
@Test
|
||||
@Order(1)
|
||||
void createRuntimeCapturesArns() {
|
||||
var resp = given().contentType("application/json").body(CREATE_RUNTIME)
|
||||
ExtractableResponse<Response> resp = given().contentType("application/json").body(CREATE_RUNTIME)
|
||||
.when().put("/runtimes/")
|
||||
.then().statusCode(202)
|
||||
.body("workloadIdentityDetails.workloadIdentityArn", notNullValue())
|
||||
|
||||
+2
-1
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation;
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -77,7 +78,7 @@ class ApiGatewayCfnMockCorsIntegrationTest {
|
||||
|
||||
for (String path : new String[]{"/execute-api/" + apiId + "/dev/items",
|
||||
"/restapis/" + apiId + "/dev/_user_request_/items"}) {
|
||||
var response = given().header("Origin", "https://example.com")
|
||||
Response response = given().header("Origin", "https://example.com")
|
||||
.header("Access-Control-Request-Method", "GET")
|
||||
.when().options(path).then().statusCode(200)
|
||||
.header("Access-Control-Allow-Origin", equalTo("*"))
|
||||
|
||||
+2
-1
@@ -17,6 +17,7 @@ import java.nio.file.Path;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
@@ -106,7 +107,7 @@ class CfnProvisionerFixtureTest {
|
||||
Path provisioners = Path.of(
|
||||
"src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners");
|
||||
Set<String> onDisk;
|
||||
try (var files = Files.list(provisioners)) {
|
||||
try (Stream<Path> files = Files.list(provisioners)) {
|
||||
onDisk = files.map(f -> f.getFileName().toString())
|
||||
.filter(n -> n.endsWith("CfnProvisioner.java"))
|
||||
.map(n -> n.replace(".java", ""))
|
||||
|
||||
+2
-1
@@ -22,6 +22,7 @@ import java.util.TreeMap;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Pins which {@code Fn::GetAtt} attributes declared by the CloudFormation registry schemas Floci
|
||||
@@ -183,7 +184,7 @@ class CfnSchemaCoverageTest {
|
||||
|
||||
private static Map<String, ProvisionerScan> scanProvisioners() {
|
||||
Map<String, ProvisionerScan> scans = new TreeMap<>();
|
||||
try (var files = Files.list(PROVISIONERS)) {
|
||||
try (Stream<Path> files = Files.list(PROVISIONERS)) {
|
||||
for (Path file : files.filter(f -> f.getFileName().toString().endsWith("CfnProvisioner.java"))
|
||||
.sorted()
|
||||
.toList()) {
|
||||
|
||||
+3
-2
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation;
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -225,7 +226,7 @@ class CloudFormationEc2NetworkingIntegrationTest {
|
||||
}
|
||||
|
||||
private static void cloudFormation(String stack, String action, String templateBody) {
|
||||
var request = given()
|
||||
RequestSpecification request = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", action)
|
||||
@@ -256,7 +257,7 @@ class CloudFormationEc2NetworkingIntegrationTest {
|
||||
}
|
||||
|
||||
private static String ec2(String action, Map<String, String> params) {
|
||||
var request = given()
|
||||
RequestSpecification request = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", EC2_AUTH)
|
||||
.formParam("Action", action)
|
||||
|
||||
+2
-1
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation;
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
@@ -469,7 +470,7 @@ class CloudFormationIamUserIntegrationTest {
|
||||
}
|
||||
|
||||
private static Response cfnQuery(String action, String stackName, String template) {
|
||||
var req = given()
|
||||
RequestSpecification req = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", action)
|
||||
|
||||
+4
-2
@@ -3,8 +3,10 @@ package io.github.hectorvent.floci.services.cloudformation;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.Stack;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.mockito.InjectSpy;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -41,7 +43,7 @@ class CloudFormationManagedPolicyUpdateIntegrationTest {
|
||||
IamService iamService;
|
||||
|
||||
private String iam(String action, String... kv) {
|
||||
var req = given()
|
||||
RequestSpecification req = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", action);
|
||||
@@ -77,7 +79,7 @@ class CloudFormationManagedPolicyUpdateIntegrationTest {
|
||||
io.github.hectorvent.floci.services.iam.model.IamRole> roles =
|
||||
(io.github.hectorvent.floci.core.storage.StorageBackend<String,
|
||||
io.github.hectorvent.floci.services.iam.model.IamRole>) rolesField.get(target);
|
||||
var role = roles.get(roleName).orElseThrow();
|
||||
IamRole role = roles.get(roleName).orElseThrow();
|
||||
// isServiceLinkedRole() alone triggers the guard; the path must also look like a real
|
||||
// service-linked path since the guard's error message parses the principal back out of it.
|
||||
role.setPath("/aws-service-role/example.amazonaws.com/");
|
||||
|
||||
+1
-1
@@ -72,7 +72,7 @@ class CloudFormationPersistenceIntegrationTest {
|
||||
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
|
||||
|
||||
// Read the on-disk file the way a fresh Floci process would on the next boot.
|
||||
var store = new PersistentStorage<String, Stack>(
|
||||
PersistentStorage<String, Stack> store = new PersistentStorage<>(
|
||||
STACKS_FILE, new TypeReference<Map<String, Stack>>() {});
|
||||
store.load();
|
||||
|
||||
|
||||
+3
-3
@@ -64,12 +64,12 @@ class CloudFormationStackPersistenceTest {
|
||||
changeSet.setStatus("CREATE_COMPLETE");
|
||||
stack.getChangeSets().put("initial-create", changeSet);
|
||||
|
||||
var writer = new PersistentStorage<String, Stack>(
|
||||
PersistentStorage<String, Stack> writer = new PersistentStorage<>(
|
||||
filePath, new TypeReference<Map<String, Stack>>() {});
|
||||
writer.put(KEY, stack);
|
||||
|
||||
// Fresh instance + load() simulates a Floci restart reading the same file
|
||||
var reader = new PersistentStorage<String, Stack>(
|
||||
PersistentStorage<String, Stack> reader = new PersistentStorage<>(
|
||||
filePath, new TypeReference<Map<String, Stack>>() {});
|
||||
reader.load();
|
||||
|
||||
@@ -117,7 +117,7 @@ class CloudFormationStackPersistenceTest {
|
||||
""".formatted(KEY);
|
||||
Files.writeString(filePath, legacyJson);
|
||||
|
||||
var store = new PersistentStorage<String, Stack>(
|
||||
PersistentStorage<String, Stack> store = new PersistentStorage<>(
|
||||
filePath, new TypeReference<Map<String, Stack>>() {});
|
||||
store.load();
|
||||
|
||||
|
||||
+1
-1
@@ -195,7 +195,7 @@ class EventBusProvisionOwnershipTest {
|
||||
}
|
||||
|
||||
private JsonNode props(boolean withPolicy) {
|
||||
var node = MAPPER.createObjectNode();
|
||||
ObjectNode node = MAPPER.createObjectNode();
|
||||
node.put("Name", BUS);
|
||||
if (withPolicy) {
|
||||
node.set("Policy", MAPPER.createObjectNode().put("Version", "2012-10-17"));
|
||||
|
||||
+2
-2
@@ -30,11 +30,11 @@ class InlineZipPackagerTest {
|
||||
|
||||
private static String readZipEntry(String zipBase64, String entryName) throws Exception {
|
||||
byte[] zipBytes = Base64.getDecoder().decode(zipBase64);
|
||||
try (var zis = new ZipInputStream(new ByteArrayInputStream(zipBytes))) {
|
||||
try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(zipBytes))) {
|
||||
ZipEntry entry;
|
||||
while ((entry = zis.getNextEntry()) != null) {
|
||||
if (entry.getName().equals(entryName)) {
|
||||
var out = new ByteArrayOutputStream();
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
zis.transferTo(out);
|
||||
return out.toString(java.nio.charset.StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
+2
-1
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
@@ -144,7 +145,7 @@ class OrganizationsCfnIntegrationTest {
|
||||
}
|
||||
|
||||
private static Response cloudFormation(String action, String... formParams) {
|
||||
var request = given()
|
||||
RequestSpecification request = given()
|
||||
.header("Authorization", "AWS4-HMAC-SHA256 Credential=" + MANAGEMENT_ACCOUNT
|
||||
+ "/20260823/us-east-1/cloudformation/aws4_request, SignedHeaders=host, Signature=abc")
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
|
||||
+2
-1
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestInstance;
|
||||
@@ -67,7 +68,7 @@ class OrganizationsCfnRollbackIntegrationTest {
|
||||
}
|
||||
|
||||
private static Response cloudFormation(String action, String... formParams) {
|
||||
var request = given()
|
||||
RequestSpecification request = given()
|
||||
.header("Authorization", "AWS4-HMAC-SHA256 Credential=" + MANAGEMENT_ACCOUNT
|
||||
+ "/20260823/us-east-1/cloudformation/aws4_request, SignedHeaders=host, Signature=abc")
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
|
||||
+4
-2
@@ -6,8 +6,10 @@ import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
@@ -1665,8 +1667,8 @@ class SamTransformIntegrationTest {
|
||||
|
||||
private static byte[] buildHandlerZip() {
|
||||
try {
|
||||
var baos = new java.io.ByteArrayOutputStream();
|
||||
try (var zos = new java.util.zip.ZipOutputStream(baos)) {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
|
||||
zos.putNextEntry(new java.util.zip.ZipEntry("index.js"));
|
||||
zos.write("exports.handler=async(e)=>({statusCode:200})".getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
zos.closeEntry();
|
||||
|
||||
+8
-6
@@ -2,6 +2,8 @@ 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.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.ecr.EcrService;
|
||||
@@ -83,10 +85,10 @@ class CfnStableNameUpdatePathTest {
|
||||
.thenReturn("arn:aws:firehose:us-east-1:000000000000:deliverystream/created");
|
||||
FirehoseCfnProvisioner provisioner = new FirehoseCfnProvisioner(firehose);
|
||||
|
||||
var props = mapper.createObjectNode();
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.set("S3DestinationConfiguration",
|
||||
mapper.createObjectNode().put("BucketARN", "arn:aws:s3:::bucket"));
|
||||
var createTags = props.putArray("Tags");
|
||||
ArrayNode createTags = props.putArray("Tags");
|
||||
createTags.addObject().put("Key", "env").put("Value", "dev");
|
||||
createTags.addObject().put("Key", "team").put("Value", "a");
|
||||
|
||||
@@ -101,7 +103,7 @@ class CfnStableNameUpdatePathTest {
|
||||
existing.getTags().add(new DeliveryStreamDescription.Tag("team", "a"));
|
||||
when(firehose.describeDeliveryStream(generatedName)).thenReturn(existing);
|
||||
|
||||
var updateProps = mapper.createObjectNode();
|
||||
ObjectNode updateProps = mapper.createObjectNode();
|
||||
updateProps.set("S3DestinationConfiguration",
|
||||
mapper.createObjectNode().put("BucketARN", "arn:aws:s3:::bucket"));
|
||||
updateProps.putArray("Tags").addObject().put("Key", "env").put("Value", "prod");
|
||||
@@ -137,7 +139,7 @@ class CfnStableNameUpdatePathTest {
|
||||
anyString())).thenReturn(updatedPipe);
|
||||
PipesCfnProvisioner provisioner = new PipesCfnProvisioner(pipes, mapper);
|
||||
|
||||
var props = mapper.createObjectNode()
|
||||
ObjectNode props = mapper.createObjectNode()
|
||||
.put("Source", "arn:aws:sqs:us-east-1:000000000000:src")
|
||||
.put("Target", "arn:aws:sqs:us-east-1:000000000000:dst")
|
||||
.put("RoleArn", "arn:aws:iam::000000000000:role/r");
|
||||
@@ -325,7 +327,7 @@ class CfnStableNameUpdatePathTest {
|
||||
.thenReturn(existingRepo);
|
||||
EcrCfnProvisioner provisioner = new EcrCfnProvisioner(ecr);
|
||||
|
||||
var createProps = mapper.createObjectNode().put("ImageTagMutability", "MUTABLE");
|
||||
ObjectNode createProps = mapper.createObjectNode().put("ImageTagMutability", "MUTABLE");
|
||||
createProps.set("LifecyclePolicy", mapper.createObjectNode().put("LifecyclePolicyText", "{}"));
|
||||
createProps.put("RepositoryPolicyText", "{}");
|
||||
StackResource created = resource("AWS::ECR::Repository", "Repo");
|
||||
@@ -335,7 +337,7 @@ class CfnStableNameUpdatePathTest {
|
||||
.thenReturn(Map.of("env", "dev", "team", "a"));
|
||||
|
||||
// The update changes mutability and one tag, drops the other tag and both policies.
|
||||
var updateProps = mapper.createObjectNode().put("ImageTagMutability", "IMMUTABLE");
|
||||
ObjectNode updateProps = mapper.createObjectNode().put("ImageTagMutability", "IMMUTABLE");
|
||||
updateProps.putArray("Tags").addObject().put("Key", "env").put("Value", "prod");
|
||||
StackResource updated = resource("AWS::ECR::Repository", "Repo");
|
||||
provisioner.provision(updated, updateProps, ctx(generatedName));
|
||||
|
||||
+2
-1
@@ -4,6 +4,7 @@ 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.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.codebuild.CodeBuildJsonHandler;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
@@ -28,7 +29,7 @@ class CodeBuildCfnProvisionerTest {
|
||||
new CodeBuildCfnProvisioner(handler, mock(RegionResolver.class), mapper);
|
||||
|
||||
private ProvisionContext ctx() {
|
||||
var engine = mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine.class);
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
return new ProvisionContext(engine, "us-east-1", "000000000000", "cfn-stack");
|
||||
}
|
||||
|
||||
+3
-2
@@ -4,6 +4,7 @@ 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.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.codepipeline.CodePipelineService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -30,7 +31,7 @@ class CodePipelineCfnProvisionerTest {
|
||||
new CodePipelineCfnProvisioner(service, mock(RegionResolver.class), mapper);
|
||||
|
||||
private ProvisionContext ctx() {
|
||||
var engine = mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine.class);
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
return new ProvisionContext(engine, "us-east-1", "000000000000", "cfn-stack");
|
||||
}
|
||||
@@ -219,7 +220,7 @@ class CodePipelineCfnProvisionerTest {
|
||||
// raw props must never be consulted directly for this boolean.
|
||||
props.putObject("RegisterWithThirdParty").put("Fn::If", "SomeCondition");
|
||||
StackResource r = resource("AWS::CodePipeline::Webhook");
|
||||
var engine = mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine.class);
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolveNode(any())).thenAnswer(inv -> {
|
||||
ObjectNode resolved = ((ObjectNode) inv.getArgument(0)).deepCopy();
|
||||
resolved.put("RegisterWithThirdParty", true);
|
||||
|
||||
+3
-2
@@ -2,6 +2,7 @@ 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.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
@@ -478,7 +479,7 @@ class Ec2NetworkCfnProvisionerTest {
|
||||
}
|
||||
|
||||
private static ObjectNode withTags(ObjectNode props, String... keyValues) {
|
||||
var tags = props.putArray("Tags");
|
||||
ArrayNode tags = props.putArray("Tags");
|
||||
for (int i = 0; i + 1 < keyValues.length; i += 2) {
|
||||
tags.addObject().put("Key", keyValues[i]).put("Value", keyValues[i + 1]);
|
||||
}
|
||||
@@ -714,7 +715,7 @@ class Ec2NetworkCfnProvisionerTest {
|
||||
when(ec2.allocateAddress(REGION)).thenReturn(addr);
|
||||
doThrow(new AwsException("TagLimitExceeded", "too many tags", 400)).when(ec2).createTags(any(), any(), any());
|
||||
|
||||
for (var attempt : List.of(
|
||||
for (Map.Entry<String, ObjectNode> attempt : List.of(
|
||||
Map.entry("AWS::EC2::Subnet", withTags(mapper.createObjectNode().put("VpcId", VPC_ID).put("CidrBlock", "10.0.1.0/24"), "k", "v")),
|
||||
Map.entry("AWS::EC2::RouteTable", withTags(mapper.createObjectNode().put("VpcId", VPC_ID), "k", "v")),
|
||||
Map.entry("AWS::EC2::InternetGateway", withTags(mapper.createObjectNode(), "k", "v")),
|
||||
|
||||
+2
-1
@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;
|
||||
import io.github.hectorvent.floci.services.ec2.model.SecurityGroupRule;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
@@ -238,7 +239,7 @@ class Ec2SecurityGroupRuleCfnProvisionerTest {
|
||||
|
||||
provisioner.provision(r, props, ctx());
|
||||
|
||||
var order = inOrder(ec2);
|
||||
InOrder order = inOrder(ec2);
|
||||
order.verify(ec2).authorizeSecurityGroupIngress(eq("us-east-1"), eq("sg-123"), anyList());
|
||||
order.verify(ec2).deleteSecurityGroupRule("us-east-1", "sgr-old");
|
||||
assertEquals("sgr-new", r.getPhysicalId());
|
||||
|
||||
+2
-1
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplate
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
@@ -98,7 +99,7 @@ class Ec2VpcGatewayAttachmentCfnProvisionerTest {
|
||||
provisioner.provision(r, props("vpc-new", "igw-new", null), ctx());
|
||||
|
||||
// Order matters: a failed attach must leave the previous attachment alone.
|
||||
var order = inOrder(ec2);
|
||||
InOrder order = inOrder(ec2);
|
||||
order.verify(ec2).attachInternetGateway(REGION, "igw-new", "vpc-new");
|
||||
order.verify(ec2).detachInternetGateway(REGION, "igw-old", "vpc-old");
|
||||
assertEquals("igw|vpc-new|igw-new", r.getPhysicalId());
|
||||
|
||||
+5
-4
@@ -2,6 +2,7 @@ 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.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
@@ -191,7 +192,7 @@ class EcsCapacityCfnProvisionerTest {
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.put("Name", "the-provider");
|
||||
props.putObject("AutoScalingGroupProvider").put("AutoScalingGroupArn", ASG_ARN);
|
||||
var tags = props.putArray("Tags");
|
||||
ArrayNode tags = props.putArray("Tags");
|
||||
tags.addObject().put("Key", "keep").put("Value", "1");
|
||||
|
||||
provisioner.provision(r, props, ctx());
|
||||
@@ -243,7 +244,7 @@ class EcsCapacityCfnProvisionerTest {
|
||||
StackResource r = resource(PROVIDER_TYPE, "Provider");
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.put("Name", "the-provider");
|
||||
var tags = props.putArray("Tags");
|
||||
ArrayNode tags = props.putArray("Tags");
|
||||
tags.addObject().put("Key", "env").put("Value", "prod");
|
||||
tags.addObject().put("Key", "team").put("Value", "platform");
|
||||
|
||||
@@ -260,10 +261,10 @@ class EcsCapacityCfnProvisionerTest {
|
||||
StackResource r = resource(ASSOCIATIONS_TYPE, "Assoc");
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.put("Cluster", "the-cluster");
|
||||
var providers = props.putArray("CapacityProviders");
|
||||
ArrayNode providers = props.putArray("CapacityProviders");
|
||||
providers.add("the-provider");
|
||||
providers.add("FARGATE");
|
||||
var strategy = props.putArray("DefaultCapacityProviderStrategy");
|
||||
ArrayNode strategy = props.putArray("DefaultCapacityProviderStrategy");
|
||||
strategy.addObject().put("CapacityProvider", "the-provider").put("Weight", 2).put("Base", 1);
|
||||
|
||||
provisioner.provision(r, props, ctx());
|
||||
|
||||
+2
-1
@@ -2,6 +2,7 @@ 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.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
@@ -286,7 +287,7 @@ class ElbV2CfnProvisionerTest {
|
||||
when(elb.createRule(eq(REGION), eq(LISTENER_ARN), anyList(), eq(10), anyList(), eq(Map.of())))
|
||||
.thenReturn(rule(LISTENER_ARN));
|
||||
ObjectNode props = mapper.createObjectNode().put("ListenerArn", LISTENER_ARN).put("Priority", "10");
|
||||
var conditions = props.putArray("Conditions");
|
||||
ArrayNode conditions = props.putArray("Conditions");
|
||||
conditions.addObject().put("Field", "path-pattern").putObject("PathPatternConfig").putArray("Values").add("/api/*");
|
||||
ObjectNode header = conditions.addObject().put("Field", "http-header");
|
||||
header.putObject("HttpHeaderConfig").put("HttpHeaderName", "X-Env").putArray("Values").add("prod");
|
||||
|
||||
+2
-1
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.eventbridge.model.Rule;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.Target;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.stubbing.OngoingStubbing;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
@@ -343,7 +344,7 @@ class EventsCfnProvisionerTest {
|
||||
/** Successive answers from ListTargetsByRule, in the order the run asks for them. */
|
||||
@SafeVarargs
|
||||
private void stubTargetSequence(List<Target> first, List<Target>... rest) {
|
||||
var stub = when(events.listTargetsByRule(anyString(), any(), anyString())).thenReturn(first);
|
||||
OngoingStubbing<List<Target>> stub = when(events.listTargetsByRule(anyString(), any(), anyString())).thenReturn(first);
|
||||
for (List<Target> answer : rest) {
|
||||
stub = stub.thenReturn(answer);
|
||||
}
|
||||
|
||||
+1
-1
@@ -120,7 +120,7 @@ class LambdaEventSourceMappingCfnProvisionerTest {
|
||||
return resolved;
|
||||
}
|
||||
if (node.isArray()) {
|
||||
var arr = mapper.createArrayNode();
|
||||
ArrayNode arr = mapper.createArrayNode();
|
||||
for (JsonNode item : node) {
|
||||
arr.add(resolveMockNode(item, engine));
|
||||
}
|
||||
|
||||
+2
-2
@@ -183,7 +183,7 @@ class CloudFrontCustomOriginServingTest {
|
||||
distribution.setConfig(config);
|
||||
Distribution created = cloudFrontService.createDistribution(distribution, Map.of());
|
||||
|
||||
var response = given()
|
||||
Response response = given()
|
||||
.header("Host", created.getDomainName())
|
||||
.header("Origin", "https://viewer.example")
|
||||
.when().get("/resource")
|
||||
@@ -228,7 +228,7 @@ class CloudFrontCustomOriginServingTest {
|
||||
Distribution removeOnlyCreated =
|
||||
cloudFrontService.createDistribution(removeOnlyDistribution, Map.of());
|
||||
|
||||
var removeOnlyResponse = given()
|
||||
Response removeOnlyResponse = given()
|
||||
.header("Host", removeOnlyCreated.getDomainName())
|
||||
.when().get("/resource")
|
||||
.then().statusCode(200)
|
||||
|
||||
+5
-4
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.s3.model.PutObjectOptions;
|
||||
import io.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -431,7 +432,7 @@ class CloudFrontDistributionServingTest {
|
||||
defaultSigner.keyGroupId(),
|
||||
privateSigner.keyGroupId()));
|
||||
|
||||
var created = given()
|
||||
Response created = given()
|
||||
.contentType("application/xml")
|
||||
.body(body)
|
||||
.when()
|
||||
@@ -450,7 +451,7 @@ class CloudFrontDistributionServingTest {
|
||||
.extract().response();
|
||||
|
||||
String configPath = created.header("Location") + "/config";
|
||||
var config = given()
|
||||
Response config = given()
|
||||
.when()
|
||||
.get(configPath)
|
||||
.then()
|
||||
@@ -518,7 +519,7 @@ class CloudFrontDistributionServingTest {
|
||||
defaultSigner.keyGroupId(),
|
||||
privateSigner.keyGroupId()));
|
||||
|
||||
var created = given()
|
||||
Response created = given()
|
||||
.contentType("application/xml")
|
||||
.body(body)
|
||||
.when()
|
||||
@@ -532,7 +533,7 @@ class CloudFrontDistributionServingTest {
|
||||
.extract().response();
|
||||
|
||||
String configPath = created.header("Location") + "/config";
|
||||
var config = given()
|
||||
Response config = given()
|
||||
.when()
|
||||
.get(configPath)
|
||||
.then()
|
||||
|
||||
+2
-2
@@ -134,8 +134,8 @@ class CloudFrontServiceTest {
|
||||
|
||||
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
|
||||
EmulatorConfig.DnsConfig dnsConfig = Mockito.mock(EmulatorConfig.DnsConfig.class);
|
||||
var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
var cloudFrontConfig = Mockito.mock(EmulatorConfig.CloudFrontServiceConfig.class);
|
||||
EmulatorConfig.ServicesConfig servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.CloudFrontServiceConfig cloudFrontConfig = Mockito.mock(EmulatorConfig.CloudFrontServiceConfig.class);
|
||||
|
||||
when(config.defaultAccountId()).thenReturn(ACCOUNT);
|
||||
when(config.hostname()).thenReturn(Optional.empty());
|
||||
|
||||
+9
-9
@@ -80,7 +80,7 @@ class CloudFrontSignatureVerifierTest {
|
||||
"Signature", signCfBase64(policy, "SHA1withRSA"),
|
||||
"Key-Pair-Id", KEY_ID);
|
||||
|
||||
var result = CloudFrontSignatureVerifier.verify(RESOURCE, query, Map.of(), null, trusted(), now);
|
||||
CloudFrontSignatureVerifier.Result result = CloudFrontSignatureVerifier.verify(RESOURCE, query, Map.of(), null, trusted(), now);
|
||||
assertTrue(result.allowed(), result.reason());
|
||||
}
|
||||
|
||||
@@ -94,7 +94,7 @@ class CloudFrontSignatureVerifierTest {
|
||||
"Signature", signCfBase64(policy, "SHA1withRSA"),
|
||||
"Key-Pair-Id", KEY_ID);
|
||||
|
||||
var result = CloudFrontSignatureVerifier.verify(
|
||||
CloudFrontSignatureVerifier.Result result = CloudFrontSignatureVerifier.verify(
|
||||
resource, query, Map.of(), null, trusted(), now);
|
||||
assertTrue(result.allowed(), result.reason());
|
||||
}
|
||||
@@ -109,7 +109,7 @@ class CloudFrontSignatureVerifierTest {
|
||||
"Signature", signCfBase64(policyJson, "SHA1withRSA"),
|
||||
"Key-Pair-Id", KEY_ID);
|
||||
|
||||
var result = CloudFrontSignatureVerifier.verify(
|
||||
CloudFrontSignatureVerifier.Result result = CloudFrontSignatureVerifier.verify(
|
||||
resource, query, Map.of(), null, trusted(), now);
|
||||
assertTrue(result.allowed(), result.reason());
|
||||
}
|
||||
@@ -169,7 +169,7 @@ class CloudFrontSignatureVerifierTest {
|
||||
signCfBase64(policy, "SHA1withRSA"),
|
||||
"CloudFront-Key-Pair-Id", KEY_ID);
|
||||
|
||||
var result = CloudFrontSignatureVerifier.verify(
|
||||
CloudFrontSignatureVerifier.Result result = CloudFrontSignatureVerifier.verify(
|
||||
RESOURCE,
|
||||
Map.of("Expires", Long.toString(soon())),
|
||||
cookies,
|
||||
@@ -237,7 +237,7 @@ class CloudFrontSignatureVerifierTest {
|
||||
"Signature", signCfBase64(policy, "SHA1withRSA"),
|
||||
"Key-Pair-Id", KEY_ID);
|
||||
|
||||
var result = CloudFrontSignatureVerifier.verify(RESOURCE, query, Map.of(), null, trusted(), now);
|
||||
CloudFrontSignatureVerifier.Result result = CloudFrontSignatureVerifier.verify(RESOURCE, query, Map.of(), null, trusted(), now);
|
||||
assertFalse(result.allowed());
|
||||
assertTrue(result.reason().contains("expired"), result.reason());
|
||||
}
|
||||
@@ -251,7 +251,7 @@ class CloudFrontSignatureVerifierTest {
|
||||
"Signature", signCfBase64(policy, "SHA1withRSA"),
|
||||
"Key-Pair-Id", KEY_ID);
|
||||
|
||||
var result = CloudFrontSignatureVerifier.verify(
|
||||
CloudFrontSignatureVerifier.Result result = CloudFrontSignatureVerifier.verify(
|
||||
"https://d123.cloudfront.net/private/OTHER.jpg", query, Map.of(), null, trusted(), now);
|
||||
assertFalse(result.allowed());
|
||||
}
|
||||
@@ -264,14 +264,14 @@ class CloudFrontSignatureVerifierTest {
|
||||
"Signature", signCfBase64(policy, "SHA1withRSA"),
|
||||
"Key-Pair-Id", "SOME-OTHER-KEY");
|
||||
|
||||
var result = CloudFrontSignatureVerifier.verify(RESOURCE, query, Map.of(), null, trusted(), now);
|
||||
CloudFrontSignatureVerifier.Result result = CloudFrontSignatureVerifier.verify(RESOURCE, query, Map.of(), null, trusted(), now);
|
||||
assertFalse(result.allowed());
|
||||
assertTrue(result.reason().contains("trusted signer"), result.reason());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingSignatureIsRejected() {
|
||||
var result = CloudFrontSignatureVerifier.verify(RESOURCE, Map.of(), Map.of(), null, trusted(), now);
|
||||
CloudFrontSignatureVerifier.Result result = CloudFrontSignatureVerifier.verify(RESOURCE, Map.of(), Map.of(), null, trusted(), now);
|
||||
assertFalse(result.allowed());
|
||||
assertEquals("Missing CloudFront signature", result.reason());
|
||||
}
|
||||
@@ -285,7 +285,7 @@ class CloudFrontSignatureVerifierTest {
|
||||
"Signature", "AAAA",
|
||||
"Key-Pair-Id", KEY_ID);
|
||||
|
||||
var result = CloudFrontSignatureVerifier.verify(RESOURCE, query, Map.of(), null, trusted(), now);
|
||||
CloudFrontSignatureVerifier.Result result = CloudFrontSignatureVerifier.verify(RESOURCE, query, Map.of(), null, trusted(), now);
|
||||
assertFalse(result.allowed());
|
||||
assertTrue(result.reason().contains("base64"), result.reason());
|
||||
}
|
||||
|
||||
+3
-3
@@ -84,7 +84,7 @@ class ResponseHeadersPolicyConfigCodecTest {
|
||||
|
||||
@Test
|
||||
void removeHeadersConfigIsCaptured() {
|
||||
var directives = ResponseHeadersPolicyConfigCodec.directives(
|
||||
ResponseHeadersPolicyConfigCodec.Directives directives = ResponseHeadersPolicyConfigCodec.directives(
|
||||
ResponseHeadersPolicyConfigCodec.parse(XML));
|
||||
assertEquals(List.of("Server"), directives.remove());
|
||||
}
|
||||
@@ -163,7 +163,7 @@ class ResponseHeadersPolicyConfigCodecTest {
|
||||
cors.put("OriginOverride", "false");
|
||||
Map<String, Object> config = Map.of("CorsConfig", cors);
|
||||
|
||||
var simple = ResponseHeadersPolicyConfigCodec.directives(
|
||||
ResponseHeadersPolicyConfigCodec.Directives simple = ResponseHeadersPolicyConfigCodec.directives(
|
||||
config, "https://viewer.example", false, true, null);
|
||||
Map<String, String> simpleHeaders = simple.add().stream().collect(
|
||||
java.util.stream.Collectors.toMap(
|
||||
@@ -171,7 +171,7 @@ class ResponseHeadersPolicyConfigCodecTest {
|
||||
ResponseHeadersPolicyConfigCodec.PolicyHeader::value));
|
||||
assertEquals(Map.of("Access-Control-Allow-Origin", "*"), simpleHeaders);
|
||||
|
||||
var preflight = ResponseHeadersPolicyConfigCodec.directives(
|
||||
ResponseHeadersPolicyConfigCodec.Directives preflight = ResponseHeadersPolicyConfigCodec.directives(
|
||||
config, "https://viewer.example", true, true, null);
|
||||
Map<String, String> preflightHeaders = preflight.add().stream().collect(
|
||||
java.util.stream.Collectors.toMap(
|
||||
|
||||
+3
-1
@@ -6,7 +6,9 @@ import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.util.UUID;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
@@ -184,7 +186,7 @@ class CloudTrailAdvancedSelectorsIntegrationTest {
|
||||
}
|
||||
|
||||
private static String gunzip(byte[] gz) throws Exception {
|
||||
try (var gzin = new java.util.zip.GZIPInputStream(new java.io.ByteArrayInputStream(gz))) {
|
||||
try (GZIPInputStream gzin = new GZIPInputStream(new ByteArrayInputStream(gz))) {
|
||||
return new String(gzin.readAllBytes());
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -368,7 +368,7 @@ class CloudWatchLogsHandlerTest {
|
||||
Response response = handler.handle("PutLogEvents", request, REGION);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
var stored = service.getLogEvents(GROUP, STREAM, null, null, 100, true, null, REGION);
|
||||
CloudWatchLogsService.LogEventsResult stored = service.getLogEvents(GROUP, STREAM, null, null, 100, true, null, REGION);
|
||||
assertEquals(1, stored.events().size());
|
||||
assertEquals("hello via ARN", stored.events().getFirst().getMessage());
|
||||
}
|
||||
|
||||
+11
-11
@@ -428,7 +428,7 @@ class CloudWatchLogsServiceTest {
|
||||
service.putLogEvents("/app/logs", "b-newest", List.of(Map.of("timestamp", 3000L, "message", "new")), REGION);
|
||||
service.putLogEvents("/app/logs", "c-middle", List.of(Map.of("timestamp", 2000L, "message", "mid")), REGION);
|
||||
|
||||
var result = service.describeLogStreams("/app/logs", null, "LastEventTime", true, 1, null, REGION);
|
||||
CloudWatchLogsService.DescribeLogStreamsResult result = service.describeLogStreams("/app/logs", null, "LastEventTime", true, 1, null, REGION);
|
||||
|
||||
assertEquals(1, result.logStreams().size());
|
||||
assertEquals("b-newest", result.logStreams().getFirst().getLogStreamName());
|
||||
@@ -442,11 +442,11 @@ class CloudWatchLogsServiceTest {
|
||||
service.createLogStream("/app/logs", "a-active", REGION);
|
||||
service.putLogEvents("/app/logs", "a-active", List.of(Map.of("timestamp", 1000L, "message", "x")), REGION);
|
||||
|
||||
var descending = service.describeLogStreams("/app/logs", null, "LastEventTime", true, 0, null, REGION);
|
||||
CloudWatchLogsService.DescribeLogStreamsResult descending = service.describeLogStreams("/app/logs", null, "LastEventTime", true, 0, null, REGION);
|
||||
assertEquals(List.of("a-active", "z-empty"),
|
||||
descending.logStreams().stream().map(LogStream::getLogStreamName).toList());
|
||||
|
||||
var ascending = service.describeLogStreams("/app/logs", null, "LastEventTime", false, 0, null, REGION);
|
||||
CloudWatchLogsService.DescribeLogStreamsResult ascending = service.describeLogStreams("/app/logs", null, "LastEventTime", false, 0, null, REGION);
|
||||
assertEquals(List.of("z-empty", "a-active"),
|
||||
ascending.logStreams().stream().map(LogStream::getLogStreamName).toList());
|
||||
}
|
||||
@@ -458,12 +458,12 @@ class CloudWatchLogsServiceTest {
|
||||
service.createLogStream("/app/logs", "stream-2", REGION);
|
||||
service.createLogStream("/app/logs", "stream-3", REGION);
|
||||
|
||||
var page1 = service.describeLogStreams("/app/logs", null, null, false, 2, null, REGION);
|
||||
CloudWatchLogsService.DescribeLogStreamsResult page1 = service.describeLogStreams("/app/logs", null, null, false, 2, null, REGION);
|
||||
assertEquals(List.of("stream-1", "stream-2"),
|
||||
page1.logStreams().stream().map(LogStream::getLogStreamName).toList());
|
||||
assertNotNull(page1.nextToken());
|
||||
|
||||
var page2 = service.describeLogStreams("/app/logs", null, null, false, 2, page1.nextToken(), REGION);
|
||||
CloudWatchLogsService.DescribeLogStreamsResult page2 = service.describeLogStreams("/app/logs", null, null, false, 2, page1.nextToken(), REGION);
|
||||
assertEquals(List.of("stream-3"),
|
||||
page2.logStreams().stream().map(LogStream::getLogStreamName).toList());
|
||||
assertNull(page2.nextToken());
|
||||
@@ -507,13 +507,13 @@ class CloudWatchLogsServiceTest {
|
||||
service.createLogStream("/app/logs", "stream-" + i, REGION);
|
||||
}
|
||||
|
||||
var page1 = service.describeLogStreams("/app/logs", null, null, false, 2, null, REGION);
|
||||
CloudWatchLogsService.DescribeLogStreamsResult page1 = service.describeLogStreams("/app/logs", null, null, false, 2, null, REGION);
|
||||
assertEquals(List.of("stream-1", "stream-2"),
|
||||
page1.logStreams().stream().map(LogStream::getLogStreamName).toList());
|
||||
|
||||
service.deleteLogStream("/app/logs", "stream-1", REGION);
|
||||
|
||||
var page2 = service.describeLogStreams("/app/logs", null, null, false, 2, page1.nextToken(), REGION);
|
||||
CloudWatchLogsService.DescribeLogStreamsResult page2 = service.describeLogStreams("/app/logs", null, null, false, 2, page1.nextToken(), REGION);
|
||||
assertEquals(List.of("stream-3", "stream-4"),
|
||||
page2.logStreams().stream().map(LogStream::getLogStreamName).toList());
|
||||
assertNull(page2.nextToken());
|
||||
@@ -534,13 +534,13 @@ class CloudWatchLogsServiceTest {
|
||||
service.putLogEvents("/app/logs", "c", List.of(Map.of("timestamp", 3000L, "message", "x")), REGION);
|
||||
service.putLogEvents("/app/logs", "d", List.of(Map.of("timestamp", 4000L, "message", "x")), REGION);
|
||||
|
||||
var page1 = service.describeLogStreams("/app/logs", null, "LastEventTime", true, 2, null, REGION);
|
||||
CloudWatchLogsService.DescribeLogStreamsResult page1 = service.describeLogStreams("/app/logs", null, "LastEventTime", true, 2, null, REGION);
|
||||
assertEquals(List.of("d", "c"),
|
||||
page1.logStreams().stream().map(LogStream::getLogStreamName).toList());
|
||||
|
||||
service.putLogEvents("/app/logs", "d", List.of(Map.of("timestamp", 5000L, "message", "x")), REGION);
|
||||
|
||||
var page2 = service.describeLogStreams("/app/logs", null, "LastEventTime", true, 2, page1.nextToken(), REGION);
|
||||
CloudWatchLogsService.DescribeLogStreamsResult page2 = service.describeLogStreams("/app/logs", null, "LastEventTime", true, 2, page1.nextToken(), REGION);
|
||||
assertEquals(List.of("b", "a"),
|
||||
page2.logStreams().stream().map(LogStream::getLogStreamName).toList());
|
||||
assertNull(page2.nextToken());
|
||||
@@ -562,14 +562,14 @@ class CloudWatchLogsServiceTest {
|
||||
service.putLogEvents("/app/logs", "c", List.of(Map.of("timestamp", 3000L, "message", "x")), REGION);
|
||||
service.putLogEvents("/app/logs", "d", List.of(Map.of("timestamp", 4000L, "message", "x")), REGION);
|
||||
|
||||
var page1 = service.describeLogStreams("/app/logs", null, "LastEventTime", true, 2, null, REGION);
|
||||
CloudWatchLogsService.DescribeLogStreamsResult page1 = service.describeLogStreams("/app/logs", null, "LastEventTime", true, 2, null, REGION);
|
||||
assertEquals(List.of("d", "c"),
|
||||
page1.logStreams().stream().map(LogStream::getLogStreamName).toList());
|
||||
|
||||
// b was not returned yet; this would now sort it ahead of c, the last returned stream.
|
||||
service.putLogEvents("/app/logs", "b", List.of(Map.of("timestamp", 9000L, "message", "x")), REGION);
|
||||
|
||||
var page2 = service.describeLogStreams("/app/logs", null, "LastEventTime", true, 2, page1.nextToken(), REGION);
|
||||
CloudWatchLogsService.DescribeLogStreamsResult page2 = service.describeLogStreams("/app/logs", null, "LastEventTime", true, 2, page1.nextToken(), REGION);
|
||||
assertEquals(List.of("b", "a"),
|
||||
page2.logStreams().stream().map(LogStream::getLogStreamName).toList());
|
||||
assertNull(page2.nextToken());
|
||||
|
||||
+3
-1
@@ -1,6 +1,8 @@
|
||||
package io.github.hectorvent.floci.services.connect;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ExtractableResponse;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -24,7 +26,7 @@ class ConnectIntegrationTest {
|
||||
@Test
|
||||
@Order(1)
|
||||
void createInstance() {
|
||||
var response = given()
|
||||
ExtractableResponse<Response> response = given()
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{
|
||||
|
||||
+4
-3
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.controlcatalog;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -111,7 +112,7 @@ class ControlCatalogControllerIntegrationTest {
|
||||
@Test
|
||||
void listControlsSupportsImplementationFilterAndPagination() {
|
||||
String filter = "{\"Filter\":{\"Implementations\":{\"Types\":[\"AWS::Organizations::Policy::RESOURCE_CONTROL_POLICY\"]}}}";
|
||||
var firstPage = given()
|
||||
Response firstPage = given()
|
||||
.contentType("application/json")
|
||||
.header("Authorization", auth("us-east-1"))
|
||||
.body(filter)
|
||||
@@ -125,7 +126,7 @@ class ControlCatalogControllerIntegrationTest {
|
||||
.extract().response();
|
||||
|
||||
List<String> allArns = new ArrayList<>(firstPage.path("Controls.Arn"));
|
||||
var secondPage = given()
|
||||
Response secondPage = given()
|
||||
.contentType("application/json")
|
||||
.header("Authorization", auth("us-east-1"))
|
||||
.body(filter)
|
||||
@@ -138,7 +139,7 @@ class ControlCatalogControllerIntegrationTest {
|
||||
.extract().response();
|
||||
allArns.addAll(secondPage.path("Controls.Arn"));
|
||||
|
||||
var finalPage = given()
|
||||
Response finalPage = given()
|
||||
.contentType("application/json")
|
||||
.header("Authorization", auth("us-east-1"))
|
||||
.body(filter)
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.controlcatalog;
|
||||
|
||||
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.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.services.controlcatalog.model.ControlDefinition;
|
||||
@@ -19,7 +20,7 @@ class ControlCatalogServiceTest {
|
||||
|
||||
@Test
|
||||
void listControlsFiltersByImplementationIdentifierAndProvider() throws Exception {
|
||||
var response = service.listControls(objectMapper.readTree("""
|
||||
ObjectNode response = service.listControls(objectMapper.readTree("""
|
||||
{"Filter":{"Implementations":{"Identifiers":["CT.S3.PV.5"]},"GovernedProviders":["AWS"]}}
|
||||
"""), null, null, "aws");
|
||||
|
||||
@@ -45,7 +46,7 @@ class ControlCatalogServiceTest {
|
||||
service.clear();
|
||||
assertTrue(controls.keysForAccount("000000000000").isEmpty());
|
||||
|
||||
var response = service.listControls(objectMapper.createObjectNode(), null, null, "aws");
|
||||
ObjectNode response = service.listControls(objectMapper.createObjectNode(), null, null, "aws");
|
||||
assertEquals(6, response.path("Controls").size());
|
||||
assertFalse(controls.keysForAccount("000000000000").isEmpty());
|
||||
}
|
||||
|
||||
+2
-1
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cur;
|
||||
|
||||
import io.github.hectorvent.floci.services.floci.duck.FlociDuckClient;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.github.hectorvent.floci.testing.SynchronousBillingEmissionProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
@@ -80,7 +81,7 @@ class CurEmissionIntegrationTest {
|
||||
.then().statusCode(200);
|
||||
|
||||
// Find the freshly written Parquet object by listing the destination prefix.
|
||||
var listing = s3Service.listObjects(destBucket, "billing/sync-emit/", null, Integer.MAX_VALUE);
|
||||
List<S3Object> listing = s3Service.listObjects(destBucket, "billing/sync-emit/", null, Integer.MAX_VALUE);
|
||||
assertThat(listing.size(), greaterThanOrEqualTo(1));
|
||||
String parquetKey = listing.get(0).getKey();
|
||||
assertThat(parquetKey, startsWith("billing/sync-emit/"));
|
||||
|
||||
+3
-2
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cur;
|
||||
import io.github.hectorvent.floci.core.common.UsageLine;
|
||||
import io.github.hectorvent.floci.services.floci.duck.FlociDuckClient;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
import io.github.hectorvent.floci.testing.SidecarContainersProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
@@ -87,7 +88,7 @@ class ParquetEmitterIntegrationTest {
|
||||
assertThat(result.rowCount(), equalTo(2));
|
||||
|
||||
// Confirm the Parquet object actually landed in S3.
|
||||
var parquetObject = s3Service.getObject(destBucket, result.key());
|
||||
S3Object parquetObject = s3Service.getObject(destBucket, result.key());
|
||||
assertNotNull(parquetObject);
|
||||
assertThat(parquetObject.getSize(), greaterThanOrEqualTo(1L));
|
||||
|
||||
@@ -126,7 +127,7 @@ class ParquetEmitterIntegrationTest {
|
||||
ParquetEmitter.Result result = emitter.emit("cleanup-report", destBucket, null, lines);
|
||||
|
||||
// Staging bucket exists, but no staging objects should remain for this run.
|
||||
var staging = s3Service.listObjects("floci-cur-staging",
|
||||
List<S3Object> staging = s3Service.listObjects("floci-cur-staging",
|
||||
"cur-staging/cleanup-report/" + result.runId(), null, Integer.MAX_VALUE);
|
||||
assertTrue(staging.isEmpty(),
|
||||
"Expected no leftover staging objects, found: " + staging);
|
||||
|
||||
@@ -376,7 +376,7 @@ class DataSyncServiceTest {
|
||||
"S3Config": {"BucketAccessRoleArn": "arn:aws:iam::000000000000:role/datasync"}}
|
||||
""");
|
||||
|
||||
var page = service.listLocations(
|
||||
DataSyncService.Page<DataSyncLocation> page = service.listLocations(
|
||||
json("[{\"Name\": \"LocationType\", \"Values\": [\"Nfs\"], \"Operator\": \"Equals\"}]"), null, 0);
|
||||
|
||||
assertEquals(List.of(nfs.getLocationArn()),
|
||||
@@ -403,11 +403,11 @@ class DataSyncServiceTest {
|
||||
service.createAgent(json("{\"ActivationKey\": \"AAAAA-1AAAA-BB1CC-DDDDD-EEEEE\"}"), REGION);
|
||||
}
|
||||
|
||||
var first = service.listAgents(null, 2);
|
||||
DataSyncService.Page<DataSyncAgent> first = service.listAgents(null, 2);
|
||||
assertEquals(2, first.items().size());
|
||||
assertEquals(first.items().get(1).getAgentArn(), first.nextToken());
|
||||
|
||||
var second = service.listAgents(first.nextToken(), 2);
|
||||
DataSyncService.Page<DataSyncAgent> second = service.listAgents(first.nextToken(), 2);
|
||||
assertEquals(1, second.items().size());
|
||||
assertNull(second.nextToken());
|
||||
}
|
||||
|
||||
+2
-1
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.detective;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.services.detective.model.DetectiveMember;
|
||||
import io.github.hectorvent.floci.services.detective.model.DetectiveState;
|
||||
import io.github.hectorvent.floci.services.organizations.OrganizationsService;
|
||||
import io.github.hectorvent.floci.services.organizations.model.Organization;
|
||||
@@ -62,7 +63,7 @@ class DetectiveServiceTest {
|
||||
when(regionResolver.getAccountId()).thenReturn(ADMIN_ACCOUNT);
|
||||
String graphArn = service.graphArn(REGION);
|
||||
|
||||
var member = service.createMember(REGION, graphArn, MEMBER_ACCOUNT, null);
|
||||
DetectiveMember member = service.createMember(REGION, graphArn, MEMBER_ACCOUNT, null);
|
||||
|
||||
assertEquals(MEMBER_ACCOUNT, member.getAccountId());
|
||||
assertNull(member.getEmailAddress());
|
||||
|
||||
+4
-4
@@ -48,8 +48,8 @@ class DocDbLegacyMigrationRaceTest {
|
||||
"docdb-clusters.json".equals(inv.getArgument(1)) ? clusterStore : instanceStore);
|
||||
|
||||
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
|
||||
var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
var docdbConfig = Mockito.mock(EmulatorConfig.DocDbServiceConfig.class);
|
||||
EmulatorConfig.ServicesConfig servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.DocDbServiceConfig docdbConfig = Mockito.mock(EmulatorConfig.DocDbServiceConfig.class);
|
||||
when(config.services()).thenReturn(servicesConfig);
|
||||
when(servicesConfig.docdb()).thenReturn(docdbConfig);
|
||||
when(docdbConfig.mock()).thenReturn(true);
|
||||
@@ -67,8 +67,8 @@ class DocDbLegacyMigrationRaceTest {
|
||||
"docdb-clusters.json".equals(inv.getArgument(1)) ? clusterStore : instanceStore);
|
||||
|
||||
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
|
||||
var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
var docdbConfig = Mockito.mock(EmulatorConfig.DocDbServiceConfig.class);
|
||||
EmulatorConfig.ServicesConfig servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.DocDbServiceConfig docdbConfig = Mockito.mock(EmulatorConfig.DocDbServiceConfig.class);
|
||||
when(config.services()).thenReturn(servicesConfig);
|
||||
when(servicesConfig.docdb()).thenReturn(docdbConfig);
|
||||
when(docdbConfig.mock()).thenReturn(true);
|
||||
|
||||
@@ -54,8 +54,8 @@ class DocDbServiceTest {
|
||||
.thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
|
||||
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
|
||||
var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
var docdbConfig = Mockito.mock(EmulatorConfig.DocDbServiceConfig.class);
|
||||
EmulatorConfig.ServicesConfig servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.DocDbServiceConfig docdbConfig = Mockito.mock(EmulatorConfig.DocDbServiceConfig.class);
|
||||
when(config.services()).thenReturn(servicesConfig);
|
||||
when(servicesConfig.docdb()).thenReturn(docdbConfig);
|
||||
when(docdbConfig.mock()).thenReturn(true);
|
||||
@@ -157,8 +157,8 @@ class DocDbServiceTest {
|
||||
when(storageFactory.create(anyString(), anyString(), any()))
|
||||
.thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
|
||||
var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
var docdbConfig = Mockito.mock(EmulatorConfig.DocDbServiceConfig.class);
|
||||
EmulatorConfig.ServicesConfig servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.DocDbServiceConfig docdbConfig = Mockito.mock(EmulatorConfig.DocDbServiceConfig.class);
|
||||
when(config.services()).thenReturn(servicesConfig);
|
||||
when(servicesConfig.docdb()).thenReturn(docdbConfig);
|
||||
when(docdbConfig.mock()).thenReturn(false);
|
||||
@@ -227,8 +227,8 @@ class DocDbServiceTest {
|
||||
"docdb-clusters.json".equals(inv.getArgument(1)) ? clusterStore : instanceStore);
|
||||
|
||||
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
|
||||
var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
var docdbConfig = Mockito.mock(EmulatorConfig.DocDbServiceConfig.class);
|
||||
EmulatorConfig.ServicesConfig servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.DocDbServiceConfig docdbConfig = Mockito.mock(EmulatorConfig.DocDbServiceConfig.class);
|
||||
when(config.services()).thenReturn(servicesConfig);
|
||||
when(servicesConfig.docdb()).thenReturn(docdbConfig);
|
||||
when(docdbConfig.mock()).thenReturn(true);
|
||||
@@ -321,8 +321,8 @@ class DocDbServiceTest {
|
||||
when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv ->
|
||||
"docdb-clusters.json".equals(inv.getArgument(1)) ? clusterStore : instanceStore);
|
||||
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
|
||||
var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
var docdbConfig = Mockito.mock(EmulatorConfig.DocDbServiceConfig.class);
|
||||
EmulatorConfig.ServicesConfig servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.DocDbServiceConfig docdbConfig = Mockito.mock(EmulatorConfig.DocDbServiceConfig.class);
|
||||
when(config.services()).thenReturn(servicesConfig);
|
||||
when(servicesConfig.docdb()).thenReturn(docdbConfig);
|
||||
when(docdbConfig.mock()).thenReturn(true);
|
||||
|
||||
+5
-5
@@ -358,11 +358,11 @@ class DynamoDbAccessPathValidatorTest {
|
||||
|
||||
@Test
|
||||
void rejectsANestedPathOnAKeyAttribute() {
|
||||
var names = mapper.createObjectNode();
|
||||
ObjectNode names = mapper.createObjectNode();
|
||||
names.put("#sk", "sk");
|
||||
var values = expressionValues(":pk", ":v");
|
||||
ObjectNode values = expressionValues(":pk", ":v");
|
||||
|
||||
var error = assertThrows(AwsException.class,
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> DynamoDbAccessPathValidator.validateQuery(
|
||||
table, tablePath, null, "pk = :pk AND #sk.foo = :v",
|
||||
null, null, names, values));
|
||||
@@ -373,7 +373,7 @@ class DynamoDbAccessPathValidatorTest {
|
||||
|
||||
@Test
|
||||
void reportsTheMissingKeySchemaElementForANonKeyAttribute() {
|
||||
var error = assertThrows(AwsException.class,
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> validateExpression(tablePath, "attr1 = :v"));
|
||||
|
||||
assertEquals("Query condition missed key schema element: pk", error.getMessage());
|
||||
@@ -381,7 +381,7 @@ class DynamoDbAccessPathValidatorTest {
|
||||
|
||||
@Test
|
||||
void stillRejectsANonKeyAttributeAlongsideTheFullKey() {
|
||||
var error = assertThrows(AwsException.class,
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> validateExpression(tablePath, "pk = :pk AND attr1 = :v"));
|
||||
|
||||
assertEquals("Query key condition not supported", error.getMessage());
|
||||
|
||||
+2
-1
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.ConditionalCheckFailedException;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.DynamoDbStreamRecord;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.KinesisStreamingDestination;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.StreamDescription;
|
||||
@@ -481,7 +482,7 @@ class DynamoDbConcurrencyIntegrationTest {
|
||||
|
||||
// The NEW_IMAGE.cnt values, read in stream order, must be strictly increasing.
|
||||
int previous = 0;
|
||||
for (var record : pulled.records()) {
|
||||
for (DynamoDbStreamRecord record : pulled.records()) {
|
||||
JsonNode newImage = record.getNewImage();
|
||||
assertNotNull(newImage, "NEW_IMAGE view type must populate newImage");
|
||||
int current = Integer.parseInt(newImage.get("cnt").get("N").asText());
|
||||
|
||||
+1
-1
@@ -151,7 +151,7 @@ class DynamoDbConsumedCapacityIntegrationTest {
|
||||
@Test
|
||||
@Order(5)
|
||||
void scanWithFilterCostsWhatTheUnfilteredScanCosts() {
|
||||
for (var i = 0; i < 6; i++) {
|
||||
for (int i = 0; i < 6; i++) {
|
||||
putItem("""
|
||||
{"pk": {"S": "cc-scan-%d"}, "keep": {"S": "no"}, "filler": {"S": "%s"}}
|
||||
""".formatted(i, "x".repeat(1000)));
|
||||
|
||||
+1
-1
@@ -367,7 +367,7 @@ class DynamoDbFilterExpressionIntegrationTest {
|
||||
|
||||
private void scanWithFilter(String filterExpression, String exprAttrValuesJson,
|
||||
String exprAttrNamesJson, int expectedCount) {
|
||||
var body = new StringBuilder();
|
||||
StringBuilder body = new StringBuilder();
|
||||
body.append("{");
|
||||
body.append("\"TableName\": \"").append(TABLE_NAME).append("\",");
|
||||
body.append("\"FilterExpression\": \"").append(filterExpression).append("\",");
|
||||
|
||||
+3
-2
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.PersistentStorage;
|
||||
@@ -52,14 +53,14 @@ class DynamoDbGsiSortKeyRestartTest {
|
||||
ObjectNode req = mapper.createObjectNode();
|
||||
req.put("TableName", TABLE);
|
||||
req.putArray("KeySchema").addObject().put("AttributeName", "PK").put("KeyType", "HASH");
|
||||
var attrDefs = req.putArray("AttributeDefinitions");
|
||||
ArrayNode attrDefs = req.putArray("AttributeDefinitions");
|
||||
attrDefs.addObject().put("AttributeName", "PK").put("AttributeType", "S");
|
||||
attrDefs.addObject().put("AttributeName", "GSI1PK").put("AttributeType", "S");
|
||||
attrDefs.addObject().put("AttributeName", "GSI1SK").put("AttributeType", "S");
|
||||
req.put("BillingMode", "PAY_PER_REQUEST");
|
||||
ObjectNode gsi = req.putArray("GlobalSecondaryIndexes").addObject();
|
||||
gsi.put("IndexName", "GSI1");
|
||||
var gsiKeySchema = gsi.putArray("KeySchema");
|
||||
ArrayNode gsiKeySchema = gsi.putArray("KeySchema");
|
||||
gsiKeySchema.addObject().put("AttributeName", "GSI1PK").put("KeyType", "HASH");
|
||||
gsiKeySchema.addObject().put("AttributeName", "GSI1SK").put("KeyType", "RANGE");
|
||||
gsi.putObject("Projection").put("ProjectionType", "ALL");
|
||||
|
||||
+24
-23
@@ -10,6 +10,7 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
@@ -49,7 +50,7 @@ class DynamoDbImportIntegrationTest {
|
||||
putObject("plain/data.json",
|
||||
"{\"Item\":{\"pk\":{\"S\":\"imported1\"}}}\n{\"Item\":{\"pk\":{\"S\":\"imported2\"}}}\n");
|
||||
|
||||
var importArn = dynamo("ImportTable", importRequest("ImportPlain", BUCKET_NAME, "plain/", "DYNAMODB_JSON", "NONE"))
|
||||
String importArn = dynamo("ImportTable", importRequest("ImportPlain", BUCKET_NAME, "plain/", "DYNAMODB_JSON", "NONE"))
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("ImportTableDescription.ImportArn", containsString("/import/"))
|
||||
@@ -108,13 +109,13 @@ class DynamoDbImportIntegrationTest {
|
||||
@Test
|
||||
void importTable_gzip_roundTripsAnExport() {
|
||||
createCompositeTable("RoundTripSource");
|
||||
for (var i = 1; i <= 3; i++) {
|
||||
for (int i = 1; i <= 3; i++) {
|
||||
dynamo("PutItem", "{\"TableName\": \"RoundTripSource\", \"Item\": {\"pk\": {\"S\": \"user-" + i
|
||||
+ "\"}, \"sk\": {\"S\": \"order-" + i + "\"}, \"total\": {\"N\": \"" + (i * 10) + "\"}}}")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
var exportArn = dynamo("ExportTableToPointInTime", """
|
||||
String exportArn = dynamo("ExportTableToPointInTime", """
|
||||
{
|
||||
"TableArn": "%s",
|
||||
"S3Bucket": "%s",
|
||||
@@ -125,10 +126,10 @@ class DynamoDbImportIntegrationTest {
|
||||
.extract().jsonPath().getString("ExportDescription.ExportArn");
|
||||
assertEquals("COMPLETED", pollExport(exportArn));
|
||||
|
||||
var exportId = exportArn.substring(exportArn.lastIndexOf('/') + 1);
|
||||
var dataPrefix = "roundtrip/AWSDynamoDB/" + exportId + "/data/";
|
||||
String exportId = exportArn.substring(exportArn.lastIndexOf('/') + 1);
|
||||
String dataPrefix = "roundtrip/AWSDynamoDB/" + exportId + "/data/";
|
||||
|
||||
var importArn = dynamo("ImportTable", """
|
||||
String importArn = dynamo("ImportTable", """
|
||||
{
|
||||
"S3BucketSource": {"S3Bucket": "%s", "S3KeyPrefix": "%s"},
|
||||
"InputFormat": "DYNAMODB_JSON",
|
||||
@@ -171,7 +172,7 @@ class DynamoDbImportIntegrationTest {
|
||||
putObject("bad/data.json",
|
||||
"{\"Item\":{\"pk\":{\"S\":\"good\"}}}\nnot json at all\n{\"NoItem\":1}\n\n{\"Item\":{\"other\":{\"S\":\"missing key\"}}}\n");
|
||||
|
||||
var importArn = dynamo("ImportTable", importRequest("ImportBadLines", BUCKET_NAME, "bad/", "DYNAMODB_JSON", "NONE"))
|
||||
String importArn = dynamo("ImportTable", importRequest("ImportBadLines", BUCKET_NAME, "bad/", "DYNAMODB_JSON", "NONE"))
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("ImportTableDescription.ImportArn");
|
||||
|
||||
@@ -187,7 +188,7 @@ class DynamoDbImportIntegrationTest {
|
||||
|
||||
@Test
|
||||
void importTable_missingBucket_failsWithS3NoSuchBucket() {
|
||||
var importArn = dynamo("ImportTable", importRequest("ImportNoBucket", "no-such-import-bucket", "imp/", "DYNAMODB_JSON", "NONE"))
|
||||
String importArn = dynamo("ImportTable", importRequest("ImportNoBucket", "no-such-import-bucket", "imp/", "DYNAMODB_JSON", "NONE"))
|
||||
.then().statusCode(200)
|
||||
.body("ImportTableDescription.ImportStatus", equalTo("IN_PROGRESS"))
|
||||
.extract().jsonPath().getString("ImportTableDescription.ImportArn");
|
||||
@@ -210,7 +211,7 @@ class DynamoDbImportIntegrationTest {
|
||||
|
||||
@Test
|
||||
void importTable_bucketOfAnotherAccount_failsWithS3AccessDenied() {
|
||||
var importArn = dynamo("ImportTable", """
|
||||
String importArn = dynamo("ImportTable", """
|
||||
{
|
||||
"S3BucketSource": {"S3Bucket": "%s", "S3KeyPrefix": "plain/", "S3BucketOwner": "111111111111"},
|
||||
"InputFormat": "DYNAMODB_JSON",
|
||||
@@ -238,7 +239,7 @@ class DynamoDbImportIntegrationTest {
|
||||
|
||||
@Test
|
||||
void importTable_emptyPrefix_fails() {
|
||||
var importArn = dynamo("ImportTable", importRequest("ImportEmptyPrefix", BUCKET_NAME, "nothing-here/", "DYNAMODB_JSON", "NONE"))
|
||||
String importArn = dynamo("ImportTable", importRequest("ImportEmptyPrefix", BUCKET_NAME, "nothing-here/", "DYNAMODB_JSON", "NONE"))
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("ImportTableDescription.ImportArn");
|
||||
|
||||
@@ -253,7 +254,7 @@ class DynamoDbImportIntegrationTest {
|
||||
@Test
|
||||
void importTable_sameClientToken_returnsTheSameImport() {
|
||||
putObject("token/data.json", "{\"Item\":{\"pk\":{\"S\":\"one\"}}}\n");
|
||||
var body = """
|
||||
String body = """
|
||||
{
|
||||
"ClientToken": "import-token-1",
|
||||
"S3BucketSource": {"S3Bucket": "%s", "S3KeyPrefix": "token/"},
|
||||
@@ -267,12 +268,12 @@ class DynamoDbImportIntegrationTest {
|
||||
}
|
||||
""".formatted(BUCKET_NAME);
|
||||
|
||||
var first = dynamo("ImportTable", body)
|
||||
String first = dynamo("ImportTable", body)
|
||||
.then().statusCode(200)
|
||||
.body("ImportTableDescription.ClientToken", equalTo("import-token-1"))
|
||||
.extract().jsonPath().getString("ImportTableDescription.ImportArn");
|
||||
|
||||
var second = dynamo("ImportTable", body)
|
||||
String second = dynamo("ImportTable", body)
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath().getString("ImportTableDescription.ImportArn");
|
||||
|
||||
@@ -283,7 +284,7 @@ class DynamoDbImportIntegrationTest {
|
||||
@Test
|
||||
void importTable_concurrentSameClientToken_startsOneImport() throws Exception {
|
||||
putObject("race/data.json", "{\"Item\":{\"pk\":{\"S\":\"one\"}}}\n");
|
||||
var body = """
|
||||
String body = """
|
||||
{
|
||||
"ClientToken": "import-token-race",
|
||||
"S3BucketSource": {"S3Bucket": "%s", "S3KeyPrefix": "race/"},
|
||||
@@ -296,12 +297,12 @@ class DynamoDbImportIntegrationTest {
|
||||
}
|
||||
}
|
||||
""".formatted(BUCKET_NAME);
|
||||
var threads = 8;
|
||||
var startGate = new CountDownLatch(1);
|
||||
var pool = Executors.newFixedThreadPool(threads);
|
||||
int threads = 8;
|
||||
CountDownLatch startGate = new CountDownLatch(1);
|
||||
ExecutorService pool = Executors.newFixedThreadPool(threads);
|
||||
try {
|
||||
var futures = new ArrayList<Future<String>>();
|
||||
for (var i = 0; i < threads; i++) {
|
||||
ArrayList<Future<String>> futures = new ArrayList<>();
|
||||
for (int i = 0; i < threads; i++) {
|
||||
futures.add(pool.submit(() -> {
|
||||
startGate.await();
|
||||
return dynamo("ImportTable", body)
|
||||
@@ -310,8 +311,8 @@ class DynamoDbImportIntegrationTest {
|
||||
}));
|
||||
}
|
||||
startGate.countDown();
|
||||
var importArns = new HashSet<String>();
|
||||
for (var future : futures) {
|
||||
HashSet<String> importArns = new HashSet<>();
|
||||
for (Future<String> future : futures) {
|
||||
importArns.add(future.get(30, TimeUnit.SECONDS));
|
||||
}
|
||||
assertEquals(1, importArns.size(), importArns.toString());
|
||||
@@ -486,9 +487,9 @@ class DynamoDbImportIntegrationTest {
|
||||
}
|
||||
|
||||
private String pollStatus(Supplier<io.restassured.response.Response> call, String statusPath) {
|
||||
var deadline = System.currentTimeMillis() + 10_000;
|
||||
long deadline = System.currentTimeMillis() + 10_000;
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
var status = call.get().then().statusCode(200).extract().jsonPath().getString(statusPath);
|
||||
String status = call.get().then().statusCode(200).extract().jsonPath().getString(statusPath);
|
||||
if (!"IN_PROGRESS".equals(status)) {
|
||||
return status;
|
||||
}
|
||||
|
||||
+12
-12
@@ -41,7 +41,7 @@ class DynamoDbPartiQLParserTest {
|
||||
}
|
||||
|
||||
private Cond firstCond(String statement, String... params) {
|
||||
var stmt = DynamoDbPartiQLParser.parse(statement, Arrays.stream(params).map(this::json).toList());
|
||||
Stmt stmt = DynamoDbPartiQLParser.parse(statement, Arrays.stream(params).map(this::json).toList());
|
||||
return assertInstanceOf(Stmt.Select.class, stmt).where().get(0);
|
||||
}
|
||||
|
||||
@@ -55,9 +55,9 @@ class DynamoDbPartiQLParserTest {
|
||||
"{\"M\":{\"a\":{\"S\":\"b\"}}}"
|
||||
})
|
||||
void bindsAParameterOfATypeWithNoLiteralSyntax(String param) {
|
||||
var cond = firstCond(SELECT + "= ?", param);
|
||||
Cond cond = firstCond(SELECT + "= ?", param);
|
||||
|
||||
var val = assertInstanceOf(Cond.Eq.class, cond).val();
|
||||
PVal val = assertInstanceOf(Cond.Eq.class, cond).val();
|
||||
assertEquals(json(param), assertInstanceOf(PVal.Av.class, val).node());
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ class DynamoDbPartiQLParserTest {
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"{\"Q\":\"x\"}", "{}"})
|
||||
void rejectsAParameterCarryingNoRecognisedType(String param) {
|
||||
var e = assertThrows(AwsException.class, () -> firstCond(SELECT + "= ?", param));
|
||||
AwsException e = assertThrows(AwsException.class, () -> firstCond(SELECT + "= ?", param));
|
||||
|
||||
assertEquals("ValidationException", e.getErrorCode());
|
||||
assertEquals("Supplied AttributeValue is empty, must contain exactly one of the supported datatypes",
|
||||
@@ -81,7 +81,7 @@ class DynamoDbPartiQLParserTest {
|
||||
"{\"M\":{\"k\":{\"S\":\"a\",\"N\":\"1\"}}}"
|
||||
})
|
||||
void rejectsAParameterCarryingMoreThanOneType(String param) {
|
||||
var e = assertThrows(AwsException.class, () -> firstCond(SELECT + "= ?", param));
|
||||
AwsException e = assertThrows(AwsException.class, () -> firstCond(SELECT + "= ?", param));
|
||||
|
||||
assertEquals("ValidationException", e.getErrorCode());
|
||||
assertEquals("Supplied AttributeValue has more than one datatypes set, "
|
||||
@@ -97,7 +97,7 @@ class DynamoDbPartiQLParserTest {
|
||||
"{\"B\":123}"
|
||||
})
|
||||
void rejectsABinaryParameterThatIsNotBase64(String param) {
|
||||
var e = assertThrows(AwsException.class, () -> firstCond(SELECT + "= ?", param));
|
||||
AwsException e = assertThrows(AwsException.class, () -> firstCond(SELECT + "= ?", param));
|
||||
|
||||
assertEquals("SerializationException", e.getErrorCode());
|
||||
assertEquals(400, e.getHttpStatus());
|
||||
@@ -105,7 +105,7 @@ class DynamoDbPartiQLParserTest {
|
||||
|
||||
@Test
|
||||
void namesTheLengthOfBase64ThatIsNotAMultipleOfFour() {
|
||||
var e = assertThrows(AwsException.class, () -> firstCond(SELECT + "= ?", "{\"B\":\"AQI\"}"));
|
||||
AwsException e = assertThrows(AwsException.class, () -> firstCond(SELECT + "= ?", "{\"B\":\"AQI\"}"));
|
||||
|
||||
assertEquals("SerializationException", e.getErrorCode());
|
||||
assertEquals("Base64 encoded length is expected a multiple of 4 bytes but found: 3", e.getMessage());
|
||||
@@ -113,7 +113,7 @@ class DynamoDbPartiQLParserTest {
|
||||
|
||||
@Test
|
||||
void acceptsAnEmptyBinaryParameter() {
|
||||
var cond = firstCond(SELECT + "= ?", "{\"B\":\"\"}");
|
||||
Cond cond = firstCond(SELECT + "= ?", "{\"B\":\"\"}");
|
||||
|
||||
assertInstanceOf(PVal.Av.class, assertInstanceOf(Cond.Eq.class, cond).val());
|
||||
}
|
||||
@@ -122,7 +122,7 @@ class DynamoDbPartiQLParserTest {
|
||||
// last placeholder still fails the request.
|
||||
@Test
|
||||
void rejectsAMalformedParameterBeyondThePlaceholders() {
|
||||
var e = assertThrows(AwsException.class,
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> firstCond(SELECT + "= ?", "{\"S\":\"a\"}", "{\"B\":\"not base64!!\"}"));
|
||||
|
||||
assertEquals("SerializationException", e.getErrorCode());
|
||||
@@ -139,7 +139,7 @@ class DynamoDbPartiQLParserTest {
|
||||
"'<', {\"BS\":[\"AQID\"]}, BS"
|
||||
})
|
||||
void rejectsAnOrderingOperatorOnATypeWithNoOrdering(String op, String param, String type) {
|
||||
var e = assertThrows(AwsException.class, () -> firstCond(SELECT + op + " ?", param));
|
||||
AwsException e = assertThrows(AwsException.class, () -> firstCond(SELECT + op + " ?", param));
|
||||
|
||||
assertEquals("ValidationException", e.getErrorCode());
|
||||
assertEquals("Incorrect operand type for operator or function; "
|
||||
@@ -148,7 +148,7 @@ class DynamoDbPartiQLParserTest {
|
||||
|
||||
@Test
|
||||
void namesBetweenAsTheOperatorWhenItsBoundIsUnordered() {
|
||||
var e = assertThrows(AwsException.class,
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> firstCond(SELECT + "BETWEEN ? AND ?", "{\"BOOL\":true}", "{\"BOOL\":false}"));
|
||||
|
||||
assertEquals("Incorrect operand type for operator or function; "
|
||||
@@ -164,7 +164,7 @@ class DynamoDbPartiQLParserTest {
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"{\"S\":\"a\"}", "{\"N\":\"1\"}", "{\"B\":\"AQID\"}"})
|
||||
void acceptsAnOrderingOperatorOnAnOrderedType(String param) {
|
||||
var cond = firstCond(SELECT + "< ?", param);
|
||||
Cond cond = firstCond(SELECT + "< ?", param);
|
||||
|
||||
assertEquals("<", assertInstanceOf(Cond.Cmp.class, cond).op());
|
||||
}
|
||||
|
||||
+117
-116
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
@@ -627,7 +628,7 @@ class DynamoDbServiceTest {
|
||||
ObjectNode keyConditions = mapper.createObjectNode();
|
||||
ObjectNode pkCondition = mapper.createObjectNode();
|
||||
pkCondition.put("ComparisonOperator", "EQ");
|
||||
var attrList = mapper.createArrayNode();
|
||||
ArrayNode attrList = mapper.createArrayNode();
|
||||
ObjectNode pkVal = mapper.createObjectNode();
|
||||
pkVal.put("S", "c1");
|
||||
attrList.add(pkVal);
|
||||
@@ -658,12 +659,12 @@ class DynamoDbServiceTest {
|
||||
|
||||
@Test
|
||||
void queryWithTheSortKeyValueOnTheLeft() {
|
||||
var region = "eu-west-1";
|
||||
String region = "eu-west-1";
|
||||
createOrdersTable(region);
|
||||
service.putItem("Orders", item("customerId", "c1", "orderId", "o1"), region);
|
||||
service.putItem("Orders", item("customerId", "c1", "orderId", "o3"), region);
|
||||
|
||||
var exprValues = mapper.createObjectNode();
|
||||
ObjectNode exprValues = mapper.createObjectNode();
|
||||
exprValues.set(":pk", mapper.createObjectNode().put("S", "c1"));
|
||||
exprValues.set(":lo", mapper.createObjectNode().put("S", "o2"));
|
||||
|
||||
@@ -890,7 +891,7 @@ class DynamoDbServiceTest {
|
||||
private ObjectNode legacyEqCondition(String value) {
|
||||
ObjectNode condition = mapper.createObjectNode();
|
||||
condition.put("ComparisonOperator", "EQ");
|
||||
var attrList = mapper.createArrayNode();
|
||||
ArrayNode attrList = mapper.createArrayNode();
|
||||
attrList.add(attributeValue("S", value));
|
||||
condition.set("AttributeValueList", attrList);
|
||||
return condition;
|
||||
@@ -989,7 +990,7 @@ class DynamoDbServiceTest {
|
||||
ObjectNode scanFilter = mapper.createObjectNode();
|
||||
ObjectNode condition = mapper.createObjectNode();
|
||||
condition.put("ComparisonOperator", "EQ");
|
||||
var attrList = mapper.createArrayNode();
|
||||
ArrayNode attrList = mapper.createArrayNode();
|
||||
ObjectNode val = mapper.createObjectNode();
|
||||
val.put("S", "Alice");
|
||||
attrList.add(val);
|
||||
@@ -1012,7 +1013,7 @@ class DynamoDbServiceTest {
|
||||
ObjectNode scanFilter = mapper.createObjectNode();
|
||||
ObjectNode condition = mapper.createObjectNode();
|
||||
condition.put("ComparisonOperator", "GE");
|
||||
var attrList = mapper.createArrayNode();
|
||||
ArrayNode attrList = mapper.createArrayNode();
|
||||
ObjectNode val = mapper.createObjectNode();
|
||||
val.put("S", "Bob");
|
||||
attrList.add(val);
|
||||
@@ -1503,7 +1504,7 @@ class DynamoDbServiceTest {
|
||||
|
||||
private ObjectNode listAttributeValue(String... values) {
|
||||
ObjectNode node = mapper.createObjectNode();
|
||||
var arrayNode = mapper.createArrayNode();
|
||||
ArrayNode arrayNode = mapper.createArrayNode();
|
||||
for (String v : values) {
|
||||
arrayNode.add(attributeValue("S", v));
|
||||
}
|
||||
@@ -1513,7 +1514,7 @@ class DynamoDbServiceTest {
|
||||
|
||||
private ObjectNode stringSetAttributeValue(String... values) {
|
||||
ObjectNode node = mapper.createObjectNode();
|
||||
var arrayNode = mapper.createArrayNode();
|
||||
ArrayNode arrayNode = mapper.createArrayNode();
|
||||
for (String v : values) {
|
||||
arrayNode.add(v);
|
||||
}
|
||||
@@ -1535,7 +1536,7 @@ class DynamoDbServiceTest {
|
||||
|
||||
private ObjectNode numberSetAttributeValue(String... values) {
|
||||
ObjectNode node = mapper.createObjectNode();
|
||||
var arrayNode = mapper.createArrayNode();
|
||||
ArrayNode arrayNode = mapper.createArrayNode();
|
||||
for (String v : values) {
|
||||
arrayNode.add(v);
|
||||
}
|
||||
@@ -1545,7 +1546,7 @@ class DynamoDbServiceTest {
|
||||
|
||||
private ObjectNode binarySetAttributeValue(String... base64Values) {
|
||||
ObjectNode node = mapper.createObjectNode();
|
||||
var arrayNode = mapper.createArrayNode();
|
||||
ArrayNode arrayNode = mapper.createArrayNode();
|
||||
for (String v : base64Values) {
|
||||
arrayNode.add(v);
|
||||
}
|
||||
@@ -1699,7 +1700,7 @@ class DynamoDbServiceTest {
|
||||
String region = "eu-west-1";
|
||||
createUsersTable(region);
|
||||
ObjectNode u1 = item("userId", "u1");
|
||||
var list = mapper.createArrayNode();
|
||||
ArrayNode list = mapper.createArrayNode();
|
||||
list.add(attributeValue("N", "10"));
|
||||
list.add(attributeValue("N", "20"));
|
||||
ObjectNode listNode = mapper.createObjectNode();
|
||||
@@ -1708,7 +1709,7 @@ class DynamoDbServiceTest {
|
||||
service.putItem("Users", u1, region);
|
||||
|
||||
ObjectNode u2 = item("userId", "u2");
|
||||
var list2 = mapper.createArrayNode();
|
||||
ArrayNode list2 = mapper.createArrayNode();
|
||||
list2.add(attributeValue("N", "30"));
|
||||
ObjectNode listNode2 = mapper.createObjectNode();
|
||||
listNode2.set("L", list2);
|
||||
@@ -1739,7 +1740,7 @@ class DynamoDbServiceTest {
|
||||
|
||||
// Use SS (String Set) type for ADD operation
|
||||
ObjectNode tagVal = mapper.createObjectNode();
|
||||
var tagArray = tagVal.putArray("SS");
|
||||
ArrayNode tagArray = tagVal.putArray("SS");
|
||||
tagArray.add("a");
|
||||
exprValues.set(":val", priceVal);
|
||||
exprValues.set(":newTag", tagVal);
|
||||
@@ -1750,7 +1751,7 @@ class DynamoDbServiceTest {
|
||||
|
||||
// And add another tag to the same item, to verify that the ADD works on existing items as well
|
||||
ObjectNode tagVal2 = mapper.createObjectNode();
|
||||
var tagArray2 = tagVal2.putArray("SS");
|
||||
ArrayNode tagArray2 = tagVal2.putArray("SS");
|
||||
tagArray2.add("b");
|
||||
exprValues.set(":newTag", tagVal2);
|
||||
DynamoDbService.UpdateResult updateResult = service.updateItem("Orders", key, null,
|
||||
@@ -1847,7 +1848,7 @@ class DynamoDbServiceTest {
|
||||
|
||||
ObjectNode initialItem = item("userId", "list-test");
|
||||
ObjectNode listValue = mapper.createObjectNode();
|
||||
var list = listValue.putArray("L");
|
||||
ArrayNode list = listValue.putArray("L");
|
||||
|
||||
list.add(attributeValue("S", "a"));
|
||||
list.add(attributeValue("S", "b"));
|
||||
@@ -1884,7 +1885,7 @@ class DynamoDbServiceTest {
|
||||
|
||||
ObjectNode initialItem = item("userId", "huge-index-test");
|
||||
ObjectNode listValue = mapper.createObjectNode();
|
||||
var list = listValue.putArray("L");
|
||||
ArrayNode list = listValue.putArray("L");
|
||||
|
||||
list.add(attributeValue("S", "a"));
|
||||
list.add(attributeValue("S", "b"));
|
||||
@@ -1919,7 +1920,7 @@ class DynamoDbServiceTest {
|
||||
|
||||
ObjectNode initialItem = item("userId", "max-index-test");
|
||||
ObjectNode listValue = mapper.createObjectNode();
|
||||
var list = listValue.putArray("L");
|
||||
ArrayNode list = listValue.putArray("L");
|
||||
|
||||
list.add(attributeValue("S", "a"));
|
||||
list.add(attributeValue("S", "b"));
|
||||
@@ -1954,7 +1955,7 @@ class DynamoDbServiceTest {
|
||||
|
||||
ObjectNode initialItem = item("userId", "invalid-index-test");
|
||||
ObjectNode listValue = mapper.createObjectNode();
|
||||
var list = listValue.putArray("L");
|
||||
ArrayNode list = listValue.putArray("L");
|
||||
|
||||
list.add(attributeValue("S", "a"));
|
||||
list.add(attributeValue("S", "b"));
|
||||
@@ -2658,7 +2659,7 @@ class DynamoDbServiceTest {
|
||||
}
|
||||
|
||||
private void createBinaryIndexedTable(String region) {
|
||||
var gsi = new GlobalSecondaryIndex("gsib",
|
||||
GlobalSecondaryIndex gsi = new GlobalSecondaryIndex("gsib",
|
||||
List.of(new KeySchemaElement("bidx", "HASH")), null, "ALL", null);
|
||||
service.createTable("BinaryIndexed",
|
||||
List.of(new KeySchemaElement("pk", "HASH")),
|
||||
@@ -2670,13 +2671,13 @@ class DynamoDbServiceTest {
|
||||
|
||||
@Test
|
||||
void putItemEmptyBinaryGsiKeyThrowsValidationException() {
|
||||
var region = "eu-west-1";
|
||||
String region = "eu-west-1";
|
||||
createBinaryIndexedTable(region);
|
||||
|
||||
var item = item("pk", "p1");
|
||||
ObjectNode item = item("pk", "p1");
|
||||
item.set("bidx", attributeValue("B", ""));
|
||||
|
||||
var ex = assertThrows(AwsException.class, () ->
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
service.putItem("BinaryIndexed", item, region));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertEquals("One or more parameter values are not valid. A value specified for a secondary "
|
||||
@@ -2686,13 +2687,13 @@ class DynamoDbServiceTest {
|
||||
|
||||
@Test
|
||||
void updateItemSettingEmptyBinaryGsiKeyThrowsValidationException() {
|
||||
var region = "eu-west-1";
|
||||
String region = "eu-west-1";
|
||||
createBinaryIndexedTable(region);
|
||||
|
||||
var exprValues = mapper.createObjectNode();
|
||||
ObjectNode exprValues = mapper.createObjectNode();
|
||||
exprValues.set(":v", attributeValue("B", ""));
|
||||
|
||||
var ex = assertThrows(AwsException.class, () ->
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
service.updateItem("BinaryIndexed", item("pk", "p1"), null,
|
||||
"SET bidx = :v", null, exprValues, null, region));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
@@ -3085,7 +3086,7 @@ class DynamoDbServiceTest {
|
||||
exprValues.set(":start", attributeValue("S", "2026-01-01Z#"));
|
||||
exprValues.set(":end", attributeValue("S", "2026-12-31Z#z"));
|
||||
|
||||
var result = service.query("Orders", null, exprValues,
|
||||
DynamoDbService.QueryResult result = service.query("Orders", null, exprValues,
|
||||
"customerId = :pk AND (orderId BETWEEN :start AND :end)", null, null, region);
|
||||
assertEquals(3, result.items().size(), "parenthesized BETWEEN should work");
|
||||
}
|
||||
@@ -3104,7 +3105,7 @@ class DynamoDbServiceTest {
|
||||
exprValues.set(":v1", attributeValue("S", "2026-01-01Z#"));
|
||||
exprValues.set(":v2", attributeValue("S", "2026-12-31Z#z"));
|
||||
|
||||
var result = service.query("Orders", null, exprValues,
|
||||
DynamoDbService.QueryResult result = service.query("Orders", null, exprValues,
|
||||
"(#f0 = :v0)AND(#f1 BETWEEN :v1 AND :v2)", null, null, null, null, null, exprNames, "us-east-1");
|
||||
assertEquals(2, result.items().size(), "compact AND with BETWEEN should work");
|
||||
}
|
||||
@@ -3112,10 +3113,10 @@ class DynamoDbServiceTest {
|
||||
@Test
|
||||
void batchWriteItemReportsAKeySchemaMismatchTheWayAwsDoes() {
|
||||
createUsersTable("us-east-1");
|
||||
var wrongType = mapper.createObjectNode();
|
||||
ObjectNode wrongType = mapper.createObjectNode();
|
||||
wrongType.set("userId", attributeValue("N", "5"));
|
||||
|
||||
var error = assertThrows(AwsException.class, () -> service.batchWriteItem(
|
||||
AwsException error = assertThrows(AwsException.class, () -> service.batchWriteItem(
|
||||
Map.of("Users", List.of(putRequest(wrongType))), "us-east-1"));
|
||||
assertEquals("The provided key element does not match the schema", error.getMessage());
|
||||
}
|
||||
@@ -3123,14 +3124,14 @@ class DynamoDbServiceTest {
|
||||
@Test
|
||||
void batchWriteItemReportsAMissingKeyAsASchemaMismatch() {
|
||||
createUsersTable("us-east-1");
|
||||
var noKey = mapper.createObjectNode();
|
||||
ObjectNode noKey = mapper.createObjectNode();
|
||||
noKey.set("name", attributeValue("S", "x"));
|
||||
|
||||
var putError = assertThrows(AwsException.class, () -> service.batchWriteItem(
|
||||
AwsException putError = assertThrows(AwsException.class, () -> service.batchWriteItem(
|
||||
Map.of("Users", List.of(putRequest(noKey))), "us-east-1"));
|
||||
assertEquals("The provided key element does not match the schema", putError.getMessage());
|
||||
|
||||
var deleteError = assertThrows(AwsException.class, () -> service.batchWriteItem(
|
||||
AwsException deleteError = assertThrows(AwsException.class, () -> service.batchWriteItem(
|
||||
Map.of("Users", List.of(deleteRequest(noKey))), "us-east-1"));
|
||||
assertEquals("The provided key element does not match the schema", deleteError.getMessage());
|
||||
}
|
||||
@@ -3138,10 +3139,10 @@ class DynamoDbServiceTest {
|
||||
@Test
|
||||
void putItemStillNamesTheMismatchedKeyTypes() {
|
||||
createUsersTable("us-east-1");
|
||||
var wrongType = mapper.createObjectNode();
|
||||
ObjectNode wrongType = mapper.createObjectNode();
|
||||
wrongType.set("userId", attributeValue("N", "5"));
|
||||
|
||||
var error = assertThrows(AwsException.class,
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> service.putItem("Users", wrongType, "us-east-1"));
|
||||
assertEquals("One or more parameter values were invalid: Type mismatch for key userId "
|
||||
+ "expected: S actual: N", error.getMessage());
|
||||
@@ -3209,7 +3210,7 @@ class DynamoDbServiceTest {
|
||||
key.set("customerId", attributeValue("S", "c9"));
|
||||
key.set("orderId", attributeValue("S", "o9"));
|
||||
|
||||
var ex = assertThrows(AwsException.class, () -> service.updateItem("Orders", key, null,
|
||||
AwsException ex = assertThrows(AwsException.class, () -> service.updateItem("Orders", key, null,
|
||||
"SET #missing.subkey = :val", exprNames, exprValues, "NONE", null, "us-east-1", "NONE"));
|
||||
assertEquals("The document path provided in the update expression is invalid for update", ex.getMessage());
|
||||
}
|
||||
@@ -3236,7 +3237,7 @@ class DynamoDbServiceTest {
|
||||
key.set("customerId", attributeValue("S", "c1"));
|
||||
key.set("orderId", attributeValue("S", "o1"));
|
||||
|
||||
var result = service.updateItem("Orders", key, null,
|
||||
DynamoDbService.UpdateResult result = service.updateItem("Orders", key, null,
|
||||
"SET #details.subkey = :val, #status = :s", exprNames, exprValues, "ALL_NEW", null, "us-east-1", "NONE");
|
||||
|
||||
JsonNode updated = result.newItem();
|
||||
@@ -3285,7 +3286,7 @@ class DynamoDbServiceTest {
|
||||
"SET #a = :v1, #b = :v1, #c = :v1, #d = :v1", exprNames, exprValues, "NONE", null, "us-east-1", "NONE");
|
||||
|
||||
// SET last two assignments, then REMOVE two fields (comma-separated)
|
||||
var result = service.updateItem("Orders", key, null,
|
||||
DynamoDbService.UpdateResult result = service.updateItem("Orders", key, null,
|
||||
"SET #a = :v1, #b = :v2 REMOVE #c, #d", exprNames, exprValues, "ALL_NEW", null, "us-east-1", "NONE");
|
||||
|
||||
JsonNode updated = result.newItem();
|
||||
@@ -3529,13 +3530,13 @@ class DynamoDbServiceTest {
|
||||
|
||||
@Test
|
||||
void updateItemSetArithmeticOverflowThrowsValidationException() {
|
||||
var region = "eu-west-1";
|
||||
String region = "eu-west-1";
|
||||
createUsersTable(region);
|
||||
var exprValues = mapper.createObjectNode();
|
||||
ObjectNode exprValues = mapper.createObjectNode();
|
||||
exprValues.set(":a", attributeValue("N", "9.9e125"));
|
||||
exprValues.set(":b", attributeValue("N", "9.9e125"));
|
||||
|
||||
var ex = assertThrows(AwsException.class, () ->
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
service.updateItem("Users", item("userId", "u1"), null,
|
||||
"SET n = :a + :b", null, exprValues, null, region));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
@@ -3546,15 +3547,15 @@ class DynamoDbServiceTest {
|
||||
|
||||
@Test
|
||||
void updateItemAddOverflowThrowsValidationException() {
|
||||
var region = "eu-west-1";
|
||||
String region = "eu-west-1";
|
||||
createUsersTable(region);
|
||||
var existing = item("userId", "u1");
|
||||
ObjectNode existing = item("userId", "u1");
|
||||
existing.set("n", attributeValue("N", "9.9e125"));
|
||||
service.putItem("Users", existing, region);
|
||||
var exprValues = mapper.createObjectNode();
|
||||
ObjectNode exprValues = mapper.createObjectNode();
|
||||
exprValues.set(":a", attributeValue("N", "9.9e125"));
|
||||
|
||||
var ex = assertThrows(AwsException.class, () ->
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
service.updateItem("Users", item("userId", "u1"), null,
|
||||
"ADD n :a", null, exprValues, null, region));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
@@ -4081,9 +4082,9 @@ class DynamoDbServiceTest {
|
||||
}
|
||||
|
||||
private ImportTableDescription importDescription(String bucket, String prefix, String compression) {
|
||||
var desc = new ImportTableDescription();
|
||||
ImportTableDescription desc = new ImportTableDescription();
|
||||
desc.setImportArn("arn:aws:dynamodb:us-east-1:000000000000:table/Users/import/1-abc");
|
||||
var source = mapper.createObjectNode();
|
||||
ObjectNode source = mapper.createObjectNode();
|
||||
source.put("S3Bucket", bucket);
|
||||
source.put("S3KeyPrefix", prefix);
|
||||
desc.setS3BucketSource(source);
|
||||
@@ -4092,7 +4093,7 @@ class DynamoDbServiceTest {
|
||||
}
|
||||
|
||||
private ObjectNode importRequest(String tableName, String inputFormat) {
|
||||
var request = mapper.createObjectNode();
|
||||
ObjectNode request = mapper.createObjectNode();
|
||||
request.putObject("S3BucketSource").put("S3Bucket", "bucket").put("S3KeyPrefix", "imp/");
|
||||
request.put("InputFormat", inputFormat);
|
||||
request.putObject("TableCreationParameters").put("TableName", tableName);
|
||||
@@ -4100,8 +4101,8 @@ class DynamoDbServiceTest {
|
||||
}
|
||||
|
||||
private static byte[] gzip(String text) throws Exception {
|
||||
var out = new ByteArrayOutputStream();
|
||||
try (var gz = new GZIPOutputStream(out)) {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try (GZIPOutputStream gz = new GZIPOutputStream(out)) {
|
||||
gz.write(text.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
return out.toByteArray();
|
||||
@@ -4112,9 +4113,9 @@ class DynamoDbServiceTest {
|
||||
}
|
||||
|
||||
private static S3Service s3With(S3Object... objects) {
|
||||
var s3 = mock(S3Service.class);
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
when(s3.listObjects("bucket", "imp/", null, Integer.MAX_VALUE)).thenReturn(List.of(objects));
|
||||
for (var object : objects) {
|
||||
for (S3Object object : objects) {
|
||||
when(s3.getObjectMetadata("bucket", object.getKey(), null)).thenReturn(object);
|
||||
when(s3.openObjectStream("bucket", object.getKey(), null))
|
||||
.thenAnswer(invocation -> new ByteArrayInputStream(object.getData()));
|
||||
@@ -4161,17 +4162,17 @@ class DynamoDbServiceTest {
|
||||
/** Checked against real DynamoDB: every item call on a CREATING table fails this way, DescribeTable still works. */
|
||||
@Test
|
||||
void itemCalls_creatingTable_returnResourceNotFoundWithoutTableName() {
|
||||
var svc = serviceWithS3(mock(S3Service.class), new InMemoryStorage<>());
|
||||
DynamoDbService svc = serviceWithS3(mock(S3Service.class), new InMemoryStorage<>());
|
||||
createUsersTableInCreating(svc);
|
||||
var region = "us-east-1";
|
||||
var key = item("userId", "u1");
|
||||
var keys = mapper.createObjectNode();
|
||||
String region = "us-east-1";
|
||||
ObjectNode key = item("userId", "u1");
|
||||
ObjectNode keys = mapper.createObjectNode();
|
||||
keys.set("Keys", mapper.createArrayNode().add(key));
|
||||
var putRequest = mapper.createObjectNode();
|
||||
ObjectNode putRequest = mapper.createObjectNode();
|
||||
putRequest.putObject("PutRequest").set("Item", key);
|
||||
var transactPut = mapper.createObjectNode();
|
||||
ObjectNode transactPut = mapper.createObjectNode();
|
||||
transactPut.putObject("Put").put("TableName", "Users").set("Item", key);
|
||||
var transactGet = mapper.createObjectNode();
|
||||
ObjectNode transactGet = mapper.createObjectNode();
|
||||
transactGet.putObject("Get").put("TableName", "Users").set("Key", key);
|
||||
|
||||
List<org.junit.jupiter.api.function.Executable> itemCalls = List.of(
|
||||
@@ -4185,8 +4186,8 @@ class DynamoDbServiceTest {
|
||||
() -> svc.batchWriteItem(Map.of("Users", List.of(putRequest)), region),
|
||||
() -> svc.transactWriteItems(List.of(transactPut), region, null, null),
|
||||
() -> svc.transactGetItems(List.of(transactGet), region));
|
||||
for (var call : itemCalls) {
|
||||
var e = assertThrows(AwsException.class, call);
|
||||
for (Executable call : itemCalls) {
|
||||
AwsException e = assertThrows(AwsException.class, call);
|
||||
assertEquals("ResourceNotFoundException", e.getErrorCode());
|
||||
assertEquals("Requested resource not found", e.getMessage());
|
||||
}
|
||||
@@ -4195,12 +4196,12 @@ class DynamoDbServiceTest {
|
||||
|
||||
@Test
|
||||
void runImport_loadsGzipLinesAndCountsBadOnes() throws Exception {
|
||||
var object = s3Object("imp/part-0.json.gz",
|
||||
S3Object object = s3Object("imp/part-0.json.gz",
|
||||
gzip("{\"Item\":{\"userId\":{\"S\":\"u1\"}}}\nnot json\n{\"Item\":{\"userId\":{\"S\":\"u2\"}}}\n"));
|
||||
var importStore = new InMemoryStorage<String, ImportTableDescription>();
|
||||
var svc = serviceWithS3(s3With(object), importStore);
|
||||
InMemoryStorage<String, ImportTableDescription> importStore = new InMemoryStorage<>();
|
||||
DynamoDbService svc = serviceWithS3(s3With(object), importStore);
|
||||
createUsersTableInCreating(svc);
|
||||
var desc = importDescription("bucket", "imp/", "GZIP");
|
||||
ImportTableDescription desc = importDescription("bucket", "imp/", "GZIP");
|
||||
|
||||
svc.runImport(desc, "Users", "us-east-1");
|
||||
|
||||
@@ -4218,10 +4219,10 @@ class DynamoDbServiceTest {
|
||||
/** Checked against real DynamoDB: another account's bucket fails this way when no policy grants access. */
|
||||
@Test
|
||||
void runImport_bucketOfAnotherAccount_failsWithS3AccessDeniedWithoutReadingS3() {
|
||||
var s3 = mock(S3Service.class);
|
||||
var svc = serviceWithS3(s3, new InMemoryStorage<>());
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
DynamoDbService svc = serviceWithS3(s3, new InMemoryStorage<>());
|
||||
createUsersTableInCreating(svc);
|
||||
var desc = importDescription("bucket", "imp/", "NONE");
|
||||
ImportTableDescription desc = importDescription("bucket", "imp/", "NONE");
|
||||
((ObjectNode) desc.getS3BucketSource()).put("S3BucketOwner", "111111111111");
|
||||
|
||||
svc.runImport(desc, "Users", "us-east-1");
|
||||
@@ -4235,10 +4236,10 @@ class DynamoDbServiceTest {
|
||||
|
||||
@Test
|
||||
void runImport_bucketOwnerIsTheCaller_readsTheBucket() {
|
||||
var object = s3Object("imp/data.json", "{\"Item\":{\"userId\":{\"S\":\"u1\"}}}\n".getBytes(StandardCharsets.UTF_8));
|
||||
var svc = serviceWithS3(s3With(object), new InMemoryStorage<>());
|
||||
S3Object object = s3Object("imp/data.json", "{\"Item\":{\"userId\":{\"S\":\"u1\"}}}\n".getBytes(StandardCharsets.UTF_8));
|
||||
DynamoDbService svc = serviceWithS3(s3With(object), new InMemoryStorage<>());
|
||||
createUsersTableInCreating(svc);
|
||||
var desc = importDescription("bucket", "imp/", "NONE");
|
||||
ImportTableDescription desc = importDescription("bucket", "imp/", "NONE");
|
||||
((ObjectNode) desc.getS3BucketSource()).put("S3BucketOwner", "000000000000");
|
||||
|
||||
svc.runImport(desc, "Users", "us-east-1");
|
||||
@@ -4249,10 +4250,10 @@ class DynamoDbServiceTest {
|
||||
|
||||
@Test
|
||||
void runImport_persistsLoadedItems() {
|
||||
var object = s3Object("imp/data.json",
|
||||
S3Object object = s3Object("imp/data.json",
|
||||
"{\"Item\":{\"userId\":{\"S\":\"u1\"}}}\n{\"Item\":{\"userId\":{\"S\":\"u2\"}}}\n".getBytes(StandardCharsets.UTF_8));
|
||||
var itemStore = new InMemoryStorage<String, Map<String, JsonNode>>();
|
||||
var svc = new DynamoDbService(new InMemoryStorage<>(), itemStore, null, new InMemoryStorage<>(),
|
||||
InMemoryStorage<String, Map<String, JsonNode>> itemStore = new InMemoryStorage<>();
|
||||
DynamoDbService svc = new DynamoDbService(new InMemoryStorage<>(), itemStore, null, new InMemoryStorage<>(),
|
||||
new RegionResolver("us-east-1", "000000000000"), null, null, s3With(object), mapper);
|
||||
createUsersTableInCreating(svc);
|
||||
|
||||
@@ -4264,11 +4265,11 @@ class DynamoDbServiceTest {
|
||||
|
||||
@Test
|
||||
void runImport_unreadableObject_isCountedAndTheRestIsLoaded() throws Exception {
|
||||
var data = s3Object("imp/data.json.gz", gzip("{\"Item\":{\"userId\":{\"S\":\"u1\"}}}\n"));
|
||||
var manifest = s3Object("imp/manifest-summary.json", "{}".getBytes(StandardCharsets.UTF_8));
|
||||
var svc = serviceWithS3(s3With(data, manifest), new InMemoryStorage<>());
|
||||
S3Object data = s3Object("imp/data.json.gz", gzip("{\"Item\":{\"userId\":{\"S\":\"u1\"}}}\n"));
|
||||
S3Object manifest = s3Object("imp/manifest-summary.json", "{}".getBytes(StandardCharsets.UTF_8));
|
||||
DynamoDbService svc = serviceWithS3(s3With(data, manifest), new InMemoryStorage<>());
|
||||
createUsersTableInCreating(svc);
|
||||
var desc = importDescription("bucket", "imp/", "GZIP");
|
||||
ImportTableDescription desc = importDescription("bucket", "imp/", "GZIP");
|
||||
|
||||
svc.runImport(desc, "Users", "us-east-1");
|
||||
|
||||
@@ -4280,12 +4281,12 @@ class DynamoDbServiceTest {
|
||||
|
||||
@Test
|
||||
void runImport_malformedAttributeValue_isCountedNotFatal() {
|
||||
var object = s3Object("imp/data.json",
|
||||
S3Object object = s3Object("imp/data.json",
|
||||
("{\"Item\":{\"userId\":{\"S\":\"u1\"},\"m\":{\"M\":\"not a map\"}}}\n"
|
||||
+ "{\"Item\":{\"userId\":{\"S\":\"u2\"}}}\n").getBytes(StandardCharsets.UTF_8));
|
||||
var svc = serviceWithS3(s3With(object), new InMemoryStorage<>());
|
||||
DynamoDbService svc = serviceWithS3(s3With(object), new InMemoryStorage<>());
|
||||
createUsersTableInCreating(svc);
|
||||
var desc = importDescription("bucket", "imp/", "NONE");
|
||||
ImportTableDescription desc = importDescription("bucket", "imp/", "NONE");
|
||||
|
||||
svc.runImport(desc, "Users", "us-east-1");
|
||||
|
||||
@@ -4296,12 +4297,12 @@ class DynamoDbServiceTest {
|
||||
|
||||
@Test
|
||||
void runImport_missingBucket_failsWithS3NoSuchBucket() {
|
||||
var s3 = mock(S3Service.class);
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
when(s3.listObjects("missing", "imp/", null, Integer.MAX_VALUE))
|
||||
.thenThrow(new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
|
||||
var svc = serviceWithS3(s3, new InMemoryStorage<>());
|
||||
DynamoDbService svc = serviceWithS3(s3, new InMemoryStorage<>());
|
||||
createUsersTableInCreating(svc);
|
||||
var desc = importDescription("missing", "imp/", "NONE");
|
||||
ImportTableDescription desc = importDescription("missing", "imp/", "NONE");
|
||||
|
||||
svc.runImport(desc, "Users", "us-east-1");
|
||||
|
||||
@@ -4313,12 +4314,12 @@ class DynamoDbServiceTest {
|
||||
|
||||
@Test
|
||||
void runImport_otherS3Error_reportsAnS3FailureCode() {
|
||||
var s3 = mock(S3Service.class);
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
when(s3.listObjects("bucket", "imp/", null, Integer.MAX_VALUE))
|
||||
.thenThrow(new AwsException("AccessDenied", "Access Denied", 403));
|
||||
var svc = serviceWithS3(s3, new InMemoryStorage<>());
|
||||
DynamoDbService svc = serviceWithS3(s3, new InMemoryStorage<>());
|
||||
createUsersTableInCreating(svc);
|
||||
var desc = importDescription("bucket", "imp/", "NONE");
|
||||
ImportTableDescription desc = importDescription("bucket", "imp/", "NONE");
|
||||
|
||||
svc.runImport(desc, "Users", "us-east-1");
|
||||
|
||||
@@ -4330,7 +4331,7 @@ class DynamoDbServiceTest {
|
||||
void deleteTable_whileCreating_returnsResourceInUseException() {
|
||||
createUsersTableInCreating(service);
|
||||
|
||||
var e = assertThrows(AwsException.class, () -> service.deleteTable("Users", "us-east-1"));
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.deleteTable("Users", "us-east-1"));
|
||||
|
||||
assertEquals("ResourceInUseException", e.getErrorCode());
|
||||
assertEquals("CREATING", service.describeTable("Users", "us-east-1").getTableStatus());
|
||||
@@ -4340,14 +4341,14 @@ class DynamoDbServiceTest {
|
||||
void updateTable_whileCreating_returnsResourceInUseException() {
|
||||
createUsersTableInCreating(service);
|
||||
|
||||
var e = assertThrows(AwsException.class, () -> service.updateTable("Users", 10L, 10L, "us-east-1"));
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.updateTable("Users", 10L, 10L, "us-east-1"));
|
||||
|
||||
assertEquals("ResourceInUseException", e.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateImportRequest_rejectsUnsupportedFormatWithoutUnsupportedOperationWording() {
|
||||
var e = assertThrows(AwsException.class,
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> service.validateImportRequest(importRequest("Users", "CSV")));
|
||||
|
||||
assertEquals("ValidationException", e.getErrorCode());
|
||||
@@ -4357,67 +4358,67 @@ class DynamoDbServiceTest {
|
||||
|
||||
@Test
|
||||
void validateImportRequest_blankClientToken_returnsValidationException() {
|
||||
var request = importRequest("Users", "DYNAMODB_JSON");
|
||||
ObjectNode request = importRequest("Users", "DYNAMODB_JSON");
|
||||
request.put("ClientToken", "");
|
||||
|
||||
var e = assertThrows(AwsException.class, () -> service.validateImportRequest(request));
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.validateImportRequest(request));
|
||||
|
||||
assertEquals("ValidationException", e.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateImportRequest_sameClientToken_returnsExistingImport() {
|
||||
var importStore = new InMemoryStorage<String, ImportTableDescription>();
|
||||
var request = importRequest("Users", "DYNAMODB_JSON");
|
||||
InMemoryStorage<String, ImportTableDescription> importStore = new InMemoryStorage<>();
|
||||
ObjectNode request = importRequest("Users", "DYNAMODB_JSON");
|
||||
request.put("ClientToken", "token-1");
|
||||
var existing = importDescription("bucket", "imp/", "NONE");
|
||||
ImportTableDescription existing = importDescription("bucket", "imp/", "NONE");
|
||||
existing.setClientToken("token-1");
|
||||
existing.setInputFormat("DYNAMODB_JSON");
|
||||
existing.setTableCreationParameters(request.get("TableCreationParameters"));
|
||||
importStore.put(existing.getImportArn(), existing);
|
||||
var svc = serviceWithS3(mock(S3Service.class), importStore);
|
||||
DynamoDbService svc = serviceWithS3(mock(S3Service.class), importStore);
|
||||
|
||||
assertSame(existing, svc.validateImportRequest(request));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateImportRequest_sameClientTokenDifferentParameters_returnsImportConflictException() {
|
||||
var importStore = new InMemoryStorage<String, ImportTableDescription>();
|
||||
var existing = importDescription("bucket", "imp/", "NONE");
|
||||
InMemoryStorage<String, ImportTableDescription> importStore = new InMemoryStorage<>();
|
||||
ImportTableDescription existing = importDescription("bucket", "imp/", "NONE");
|
||||
existing.setClientToken("token-1");
|
||||
existing.setInputFormat("DYNAMODB_JSON");
|
||||
existing.setTableCreationParameters(mapper.createObjectNode().put("TableName", "Users"));
|
||||
importStore.put(existing.getImportArn(), existing);
|
||||
var svc = serviceWithS3(mock(S3Service.class), importStore);
|
||||
var request = importRequest("Other", "DYNAMODB_JSON");
|
||||
DynamoDbService svc = serviceWithS3(mock(S3Service.class), importStore);
|
||||
ObjectNode request = importRequest("Other", "DYNAMODB_JSON");
|
||||
request.put("ClientToken", "token-1");
|
||||
|
||||
var e = assertThrows(AwsException.class, () -> svc.validateImportRequest(request));
|
||||
AwsException e = assertThrows(AwsException.class, () -> svc.validateImportRequest(request));
|
||||
|
||||
assertEquals("ImportConflictException", e.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listImports_pageSizeBelowOne_returnsValidationException() {
|
||||
var svc = serviceWithS3(mock(S3Service.class), new InMemoryStorage<>());
|
||||
DynamoDbService svc = serviceWithS3(mock(S3Service.class), new InMemoryStorage<>());
|
||||
|
||||
var e = assertThrows(AwsException.class, () -> svc.listImports(null, 0, null));
|
||||
AwsException e = assertThrows(AwsException.class, () -> svc.listImports(null, 0, null));
|
||||
|
||||
assertEquals("ValidationException", e.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listImports_walksPagesByNextToken() {
|
||||
var importStore = new InMemoryStorage<String, ImportTableDescription>();
|
||||
for (var i = 1; i <= 3; i++) {
|
||||
var desc = importDescription("bucket", "imp/", "NONE");
|
||||
InMemoryStorage<String, ImportTableDescription> importStore = new InMemoryStorage<>();
|
||||
for (int i = 1; i <= 3; i++) {
|
||||
ImportTableDescription desc = importDescription("bucket", "imp/", "NONE");
|
||||
desc.setImportArn("arn:aws:dynamodb:us-east-1:000000000000:table/Users/import/" + i + "-abc");
|
||||
importStore.put(desc.getImportArn(), desc);
|
||||
}
|
||||
var svc = serviceWithS3(mock(S3Service.class), importStore);
|
||||
DynamoDbService svc = serviceWithS3(mock(S3Service.class), importStore);
|
||||
|
||||
var first = svc.listImports(null, 2, null);
|
||||
var second = svc.listImports(null, 2, first.nextToken());
|
||||
DynamoDbService.ListImportsResult first = svc.listImports(null, 2, null);
|
||||
DynamoDbService.ListImportsResult second = svc.listImports(null, 2, first.nextToken());
|
||||
|
||||
assertEquals(2, first.importSummaryList().size());
|
||||
assertNotNull(first.nextToken());
|
||||
@@ -4427,22 +4428,22 @@ class DynamoDbServiceTest {
|
||||
|
||||
@Test
|
||||
void constructor_failsInterruptedJobsAndActivatesCreatingTables() {
|
||||
var resolver = new RegionResolver("us-east-1", "000000000000");
|
||||
var tables = new AccountAwareStorageBackend<TableDefinition>(new InMemoryStorage<>(), null, "000000000000");
|
||||
var exports = new AccountAwareStorageBackend<ExportDescription>(new InMemoryStorage<>(), null, "000000000000");
|
||||
var imports = new AccountAwareStorageBackend<ImportTableDescription>(new InMemoryStorage<>(), null, "000000000000");
|
||||
var before = new DynamoDbService(tables, new InMemoryStorage<>(), exports, imports,
|
||||
RegionResolver resolver = new RegionResolver("us-east-1", "000000000000");
|
||||
AccountAwareStorageBackend<TableDefinition> tables = new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, "000000000000");
|
||||
AccountAwareStorageBackend<ExportDescription> exports = new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, "000000000000");
|
||||
AccountAwareStorageBackend<ImportTableDescription> imports = new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, "000000000000");
|
||||
DynamoDbService before = new DynamoDbService(tables, new InMemoryStorage<>(), exports, imports,
|
||||
resolver, null, null, mock(S3Service.class), mapper);
|
||||
createUsersTableInCreating(before);
|
||||
var importDesc = importDescription("bucket", "imp/", "NONE");
|
||||
ImportTableDescription importDesc = importDescription("bucket", "imp/", "NONE");
|
||||
importDesc.setImportStatus("IN_PROGRESS");
|
||||
imports.put(importDesc.getImportArn(), importDesc);
|
||||
var exportDesc = new ExportDescription();
|
||||
ExportDescription exportDesc = new ExportDescription();
|
||||
exportDesc.setExportArn("arn:aws:dynamodb:us-east-1:000000000000:table/Users/export/1-abc");
|
||||
exportDesc.setExportStatus("IN_PROGRESS");
|
||||
exports.put(exportDesc.getExportArn(), exportDesc);
|
||||
|
||||
var restarted = new DynamoDbService(tables, new InMemoryStorage<>(), exports, imports,
|
||||
DynamoDbService restarted = new DynamoDbService(tables, new InMemoryStorage<>(), exports, imports,
|
||||
resolver, null, null, mock(S3Service.class), mapper);
|
||||
|
||||
assertEquals("ACTIVE", restarted.describeTable("Users", "us-east-1").getTableStatus());
|
||||
|
||||
+2
-1
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -459,7 +460,7 @@ class DynamoDbTableArnIntegrationTest {
|
||||
}
|
||||
|
||||
private static String createTable(String tableName, String authorization) {
|
||||
var request = given()
|
||||
RequestSpecification request = given()
|
||||
.header("X-Amz-Target", "DynamoDB_20120810.CreateTable")
|
||||
.contentType(DYNAMODB_CONTENT_TYPE);
|
||||
if (authorization != null) {
|
||||
|
||||
+21
-21
@@ -65,7 +65,7 @@ class DynamoDbWriteCapacityTest {
|
||||
|
||||
@Test
|
||||
void insertChargesTableAndEveryIndexTheItemEnters() {
|
||||
var cost = DynamoDbWriteCapacity.forWrite(table, null, fullItem());
|
||||
DynamoDbWriteCapacity.Cost cost = DynamoDbWriteCapacity.forWrite(table, null, fullItem());
|
||||
assertEquals(1.0, cost.table());
|
||||
assertEquals(Map.of("gsi-inc", 1.0), cost.gsi());
|
||||
assertEquals(Map.of("lsi1", 1.0), cost.lsi());
|
||||
@@ -74,10 +74,10 @@ class DynamoDbWriteCapacityTest {
|
||||
|
||||
@Test
|
||||
void sparseInsertChargesNothingForTheIndexesItMisses() {
|
||||
var sparse = item("""
|
||||
ObjectNode sparse = item("""
|
||||
{"pk": {"S": "p1"}, "sk": {"S": "1"}, "other": {"S": "o"}}
|
||||
""");
|
||||
var cost = DynamoDbWriteCapacity.forWrite(table, null, sparse);
|
||||
DynamoDbWriteCapacity.Cost cost = DynamoDbWriteCapacity.forWrite(table, null, sparse);
|
||||
assertEquals(1.0, cost.total());
|
||||
assertTrue(cost.gsi().isEmpty(), "an item without gsiPk never enters the GSI");
|
||||
assertTrue(cost.lsi().isEmpty(), "an item without lsiSk never enters the LSI");
|
||||
@@ -85,7 +85,7 @@ class DynamoDbWriteCapacityTest {
|
||||
|
||||
@Test
|
||||
void identicalOverwriteChargesNoIndexWritesAtAll() {
|
||||
var cost = DynamoDbWriteCapacity.forWrite(table, fullItem(), fullItem());
|
||||
DynamoDbWriteCapacity.Cost cost = DynamoDbWriteCapacity.forWrite(table, fullItem(), fullItem());
|
||||
assertEquals(1.0, cost.table(), "the table write is still charged");
|
||||
assertTrue(cost.gsi().isEmpty());
|
||||
assertTrue(cost.lsi().isEmpty());
|
||||
@@ -93,11 +93,11 @@ class DynamoDbWriteCapacityTest {
|
||||
|
||||
@Test
|
||||
void nonProjectedAttributeChangeChargesNothingOnTheIncludeIndex() {
|
||||
var updated = fullItem();
|
||||
ObjectNode updated = fullItem();
|
||||
updated.set("other", item("""
|
||||
{"S": "o2"}
|
||||
"""));
|
||||
var cost = DynamoDbWriteCapacity.forWrite(table, fullItem(), updated);
|
||||
DynamoDbWriteCapacity.Cost cost = DynamoDbWriteCapacity.forWrite(table, fullItem(), updated);
|
||||
assertTrue(cost.gsi().isEmpty(), "other is outside the INCLUDE projection");
|
||||
assertEquals(Map.of("lsi1", 1.0), cost.lsi());
|
||||
assertEquals(2.0, cost.total());
|
||||
@@ -105,11 +105,11 @@ class DynamoDbWriteCapacityTest {
|
||||
|
||||
@Test
|
||||
void projectedAttributeChangeChargesOneIndexWrite() {
|
||||
var updated = fullItem();
|
||||
ObjectNode updated = fullItem();
|
||||
updated.set("proj", item("""
|
||||
{"S": "p2"}
|
||||
"""));
|
||||
var cost = DynamoDbWriteCapacity.forWrite(table, fullItem(), updated);
|
||||
DynamoDbWriteCapacity.Cost cost = DynamoDbWriteCapacity.forWrite(table, fullItem(), updated);
|
||||
assertEquals(Map.of("gsi-inc", 1.0), cost.gsi());
|
||||
assertEquals(Map.of("lsi1", 1.0), cost.lsi());
|
||||
assertEquals(3.0, cost.total());
|
||||
@@ -117,11 +117,11 @@ class DynamoDbWriteCapacityTest {
|
||||
|
||||
@Test
|
||||
void indexKeyChangeChargesDeletePlusInsert() {
|
||||
var moved = fullItem();
|
||||
ObjectNode moved = fullItem();
|
||||
moved.set("gsiPk", item("""
|
||||
{"S": "g-moved"}
|
||||
"""));
|
||||
var cost = DynamoDbWriteCapacity.forWrite(table, fullItem(), moved);
|
||||
DynamoDbWriteCapacity.Cost cost = DynamoDbWriteCapacity.forWrite(table, fullItem(), moved);
|
||||
assertEquals(Map.of("gsi-inc", 2.0), cost.gsi());
|
||||
assertEquals(Map.of("lsi1", 1.0), cost.lsi());
|
||||
assertEquals(4.0, cost.total());
|
||||
@@ -129,9 +129,9 @@ class DynamoDbWriteCapacityTest {
|
||||
|
||||
@Test
|
||||
void removingTheIndexKeyChargesDeleteOnly() {
|
||||
var removed = fullItem();
|
||||
ObjectNode removed = fullItem();
|
||||
removed.remove("gsiPk");
|
||||
var cost = DynamoDbWriteCapacity.forWrite(table, fullItem(), removed);
|
||||
DynamoDbWriteCapacity.Cost cost = DynamoDbWriteCapacity.forWrite(table, fullItem(), removed);
|
||||
assertEquals(Map.of("gsi-inc", 1.0), cost.gsi());
|
||||
assertEquals(Map.of("lsi1", 1.0), cost.lsi());
|
||||
assertEquals(3.0, cost.total());
|
||||
@@ -139,11 +139,11 @@ class DynamoDbWriteCapacityTest {
|
||||
|
||||
@Test
|
||||
void lsiKeyChangeWalksTheSameLadder() {
|
||||
var moved = fullItem();
|
||||
ObjectNode moved = fullItem();
|
||||
moved.set("lsiSk", item("""
|
||||
{"S": "L2"}
|
||||
"""));
|
||||
var cost = DynamoDbWriteCapacity.forWrite(table, fullItem(), moved);
|
||||
DynamoDbWriteCapacity.Cost cost = DynamoDbWriteCapacity.forWrite(table, fullItem(), moved);
|
||||
assertTrue(cost.gsi().isEmpty(), "lsiSk is outside the GSI projection, its view never changed");
|
||||
assertEquals(Map.of("lsi1", 2.0), cost.lsi());
|
||||
assertEquals(3.0, cost.total());
|
||||
@@ -151,7 +151,7 @@ class DynamoDbWriteCapacityTest {
|
||||
|
||||
@Test
|
||||
void deleteChargesOneWritePerIndexTheItemOccupied() {
|
||||
var cost = DynamoDbWriteCapacity.forWrite(table, fullItem(), null);
|
||||
DynamoDbWriteCapacity.Cost cost = DynamoDbWriteCapacity.forWrite(table, fullItem(), null);
|
||||
assertEquals(1.0, cost.table());
|
||||
assertEquals(Map.of("gsi-inc", 1.0), cost.gsi());
|
||||
assertEquals(Map.of("lsi1", 1.0), cost.lsi());
|
||||
@@ -160,17 +160,17 @@ class DynamoDbWriteCapacityTest {
|
||||
|
||||
@Test
|
||||
void deleteOfAMissingItemStillChargesOneTableUnit() {
|
||||
var cost = DynamoDbWriteCapacity.forWrite(table, null, null);
|
||||
DynamoDbWriteCapacity.Cost cost = DynamoDbWriteCapacity.forWrite(table, null, null);
|
||||
assertEquals(1.0, cost.total());
|
||||
}
|
||||
|
||||
@Test
|
||||
void costPlusSumsTheTableAndMergesIndexArms() {
|
||||
var indexed = DynamoDbWriteCapacity.forWrite(table, null, fullItem());
|
||||
var sparse = DynamoDbWriteCapacity.forWrite(table, null, item("""
|
||||
DynamoDbWriteCapacity.Cost indexed = DynamoDbWriteCapacity.forWrite(table, null, fullItem());
|
||||
DynamoDbWriteCapacity.Cost sparse = DynamoDbWriteCapacity.forWrite(table, null, item("""
|
||||
{"pk": {"S": "p2"}, "sk": {"S": "1"}, "other": {"S": "o"}}
|
||||
"""));
|
||||
var sum = DynamoDbWriteCapacity.Cost.zero().plus(indexed).plus(sparse);
|
||||
DynamoDbWriteCapacity.Cost sum = DynamoDbWriteCapacity.Cost.zero().plus(indexed).plus(sparse);
|
||||
assertEquals(2.0, sum.table());
|
||||
assertEquals(Map.of("gsi-inc", 1.0), sum.gsi());
|
||||
assertEquals(Map.of("lsi1", 1.0), sum.lsi());
|
||||
@@ -179,13 +179,13 @@ class DynamoDbWriteCapacityTest {
|
||||
|
||||
@Test
|
||||
void tableUnitsFollowTheLargerImagePerKilobyte() {
|
||||
var big = item("""
|
||||
ObjectNode big = item("""
|
||||
{"pk": {"S": "p1"}, "sk": {"S": "1"}}
|
||||
""");
|
||||
big.set("filler", item("""
|
||||
{"S": "%s"}
|
||||
""".formatted("x".repeat(2500))));
|
||||
var cost = DynamoDbWriteCapacity.forWrite(table, big, fullItem());
|
||||
DynamoDbWriteCapacity.Cost cost = DynamoDbWriteCapacity.forWrite(table, big, fullItem());
|
||||
assertEquals(3.0, cost.table(), "the larger of the two images rounds up per 1KB");
|
||||
}
|
||||
|
||||
|
||||
+128
-127
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -22,8 +23,8 @@ class ExpressionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void standardExpression() {
|
||||
var tokens = ExpressionEvaluator.tokenize("pk = :pk AND sk BETWEEN :a AND :b");
|
||||
var types = tokens.stream().map(ExpressionEvaluator.Token::type).toList();
|
||||
List<ExpressionEvaluator.Token> tokens = ExpressionEvaluator.tokenize("pk = :pk AND sk BETWEEN :a AND :b");
|
||||
List<ExpressionEvaluator.TokenType> types = tokens.stream().map(ExpressionEvaluator.Token::type).toList();
|
||||
assertEquals(List.of(
|
||||
ExpressionEvaluator.TokenType.IDENTIFIER, // pk
|
||||
ExpressionEvaluator.TokenType.EQ, // =
|
||||
@@ -40,8 +41,8 @@ class ExpressionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void compactFormat() {
|
||||
var tokens = ExpressionEvaluator.tokenize("(#f0 = :v0)AND(#f1 BETWEEN :v1 AND :v2)");
|
||||
var types = tokens.stream().map(ExpressionEvaluator.Token::type).toList();
|
||||
List<ExpressionEvaluator.Token> tokens = ExpressionEvaluator.tokenize("(#f0 = :v0)AND(#f1 BETWEEN :v1 AND :v2)");
|
||||
List<ExpressionEvaluator.TokenType> types = tokens.stream().map(ExpressionEvaluator.Token::type).toList();
|
||||
assertEquals(List.of(
|
||||
ExpressionEvaluator.TokenType.LPAREN,
|
||||
ExpressionEvaluator.TokenType.NAME_REF, // #f0
|
||||
@@ -62,8 +63,8 @@ class ExpressionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void allComparators() {
|
||||
var tokens = ExpressionEvaluator.tokenize("a = b a <> b a < b a <= b a > b a >= b");
|
||||
var comparators = tokens.stream()
|
||||
List<ExpressionEvaluator.Token> tokens = ExpressionEvaluator.tokenize("a = b a <> b a < b a <= b a > b a >= b");
|
||||
List<ExpressionEvaluator.TokenType> comparators = tokens.stream()
|
||||
.map(ExpressionEvaluator.Token::type)
|
||||
.filter(t -> t != ExpressionEvaluator.TokenType.IDENTIFIER && t != ExpressionEvaluator.TokenType.EOF)
|
||||
.toList();
|
||||
@@ -79,8 +80,8 @@ class ExpressionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void functionTokens() {
|
||||
var tokens = ExpressionEvaluator.tokenize("attribute_exists(a) AND begins_with(b, :v) AND contains(c, :w) AND size(d) > :x AND attribute_not_exists(e)");
|
||||
var functions = tokens.stream()
|
||||
List<ExpressionEvaluator.Token> tokens = ExpressionEvaluator.tokenize("attribute_exists(a) AND begins_with(b, :v) AND contains(c, :w) AND size(d) > :x AND attribute_not_exists(e)");
|
||||
List<String> functions = tokens.stream()
|
||||
.filter(t -> t.type() == ExpressionEvaluator.TokenType.FUNCTION)
|
||||
.map(ExpressionEvaluator.Token::value)
|
||||
.toList();
|
||||
@@ -89,15 +90,15 @@ class ExpressionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void inAndBetweenKeywords() {
|
||||
var tokens = ExpressionEvaluator.tokenize("x IN (:a, :b) AND y BETWEEN :c AND :d");
|
||||
List<ExpressionEvaluator.Token> tokens = ExpressionEvaluator.tokenize("x IN (:a, :b) AND y BETWEEN :c AND :d");
|
||||
assertTrue(tokens.stream().anyMatch(t -> t.type() == ExpressionEvaluator.TokenType.IN));
|
||||
assertTrue(tokens.stream().anyMatch(t -> t.type() == ExpressionEvaluator.TokenType.BETWEEN));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dottedPath() {
|
||||
var tokens = ExpressionEvaluator.tokenize("info.nested = :v");
|
||||
var types = tokens.stream().map(ExpressionEvaluator.Token::type).toList();
|
||||
List<ExpressionEvaluator.Token> tokens = ExpressionEvaluator.tokenize("info.nested = :v");
|
||||
List<ExpressionEvaluator.TokenType> types = tokens.stream().map(ExpressionEvaluator.Token::type).toList();
|
||||
assertEquals(List.of(
|
||||
ExpressionEvaluator.TokenType.IDENTIFIER, // info
|
||||
ExpressionEvaluator.TokenType.DOT,
|
||||
@@ -116,87 +117,87 @@ class ExpressionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void simpleComparison() {
|
||||
var expr = ExpressionEvaluator.parse("pk = :pk");
|
||||
ExpressionEvaluator.Expr expr = ExpressionEvaluator.parse("pk = :pk");
|
||||
assertInstanceOf(ExpressionEvaluator.CompareExpr.class, expr);
|
||||
}
|
||||
|
||||
@Test
|
||||
void andExpression() {
|
||||
var expr = ExpressionEvaluator.parse("a = :a AND b = :b");
|
||||
ExpressionEvaluator.Expr expr = ExpressionEvaluator.parse("a = :a AND b = :b");
|
||||
assertInstanceOf(ExpressionEvaluator.AndExpr.class, expr);
|
||||
assertEquals(2, ((ExpressionEvaluator.AndExpr) expr).operands().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void orExpression() {
|
||||
var expr = ExpressionEvaluator.parse("a = :a OR b = :b");
|
||||
ExpressionEvaluator.Expr expr = ExpressionEvaluator.parse("a = :a OR b = :b");
|
||||
assertInstanceOf(ExpressionEvaluator.OrExpr.class, expr);
|
||||
assertEquals(2, ((ExpressionEvaluator.OrExpr) expr).operands().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void notExpression() {
|
||||
var expr = ExpressionEvaluator.parse("NOT a = :a");
|
||||
ExpressionEvaluator.Expr expr = ExpressionEvaluator.parse("NOT a = :a");
|
||||
assertInstanceOf(ExpressionEvaluator.NotExpr.class, expr);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nestedParens() {
|
||||
var expr = ExpressionEvaluator.parse("(a = :a OR b = :b) AND c = :c");
|
||||
ExpressionEvaluator.Expr expr = ExpressionEvaluator.parse("(a = :a OR b = :b) AND c = :c");
|
||||
assertInstanceOf(ExpressionEvaluator.AndExpr.class, expr);
|
||||
var and = (ExpressionEvaluator.AndExpr) expr;
|
||||
ExpressionEvaluator.AndExpr and = (ExpressionEvaluator.AndExpr) expr;
|
||||
assertInstanceOf(ExpressionEvaluator.OrExpr.class, and.operands().get(0));
|
||||
assertInstanceOf(ExpressionEvaluator.CompareExpr.class, and.operands().get(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void betweenAndNotConfusedWithLogicalAnd() {
|
||||
var expr = ExpressionEvaluator.parse("sk BETWEEN :a AND :b");
|
||||
ExpressionEvaluator.Expr expr = ExpressionEvaluator.parse("sk BETWEEN :a AND :b");
|
||||
assertInstanceOf(ExpressionEvaluator.BetweenExpr.class, expr);
|
||||
}
|
||||
|
||||
@Test
|
||||
void betweenInsideAnd() {
|
||||
var expr = ExpressionEvaluator.parse("pk = :pk AND sk BETWEEN :a AND :b");
|
||||
ExpressionEvaluator.Expr expr = ExpressionEvaluator.parse("pk = :pk AND sk BETWEEN :a AND :b");
|
||||
assertInstanceOf(ExpressionEvaluator.AndExpr.class, expr);
|
||||
var and = (ExpressionEvaluator.AndExpr) expr;
|
||||
ExpressionEvaluator.AndExpr and = (ExpressionEvaluator.AndExpr) expr;
|
||||
assertInstanceOf(ExpressionEvaluator.CompareExpr.class, and.operands().get(0));
|
||||
assertInstanceOf(ExpressionEvaluator.BetweenExpr.class, and.operands().get(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void inOperator() {
|
||||
var expr = ExpressionEvaluator.parse("status IN (:a, :b, :c)");
|
||||
ExpressionEvaluator.Expr expr = ExpressionEvaluator.parse("status IN (:a, :b, :c)");
|
||||
assertInstanceOf(ExpressionEvaluator.InExpr.class, expr);
|
||||
assertEquals(3, ((ExpressionEvaluator.InExpr) expr).candidates().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void inOperatorSingleValue() {
|
||||
var expr = ExpressionEvaluator.parse("status IN (:a)");
|
||||
ExpressionEvaluator.Expr expr = ExpressionEvaluator.parse("status IN (:a)");
|
||||
assertInstanceOf(ExpressionEvaluator.InExpr.class, expr);
|
||||
assertEquals(1, ((ExpressionEvaluator.InExpr) expr).candidates().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void functionCallCondition() {
|
||||
var expr = ExpressionEvaluator.parse("attribute_exists(myAttr)");
|
||||
ExpressionEvaluator.Expr expr = ExpressionEvaluator.parse("attribute_exists(myAttr)");
|
||||
assertInstanceOf(ExpressionEvaluator.FunctionCallExpr.class, expr);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sizeComparison() {
|
||||
var expr = ExpressionEvaluator.parse("size(myList) > :val");
|
||||
ExpressionEvaluator.Expr expr = ExpressionEvaluator.parse("size(myList) > :val");
|
||||
assertInstanceOf(ExpressionEvaluator.CompareExpr.class, expr);
|
||||
var cmp = (ExpressionEvaluator.CompareExpr) expr;
|
||||
ExpressionEvaluator.CompareExpr cmp = (ExpressionEvaluator.CompareExpr) expr;
|
||||
assertInstanceOf(ExpressionEvaluator.FunctionOperand.class, cmp.left());
|
||||
}
|
||||
|
||||
@Test
|
||||
void compactFormatParsesCorrectly() {
|
||||
var expr = ExpressionEvaluator.parse("(#f0 = :v0)AND(#f1 BETWEEN :v1 AND :v2)");
|
||||
ExpressionEvaluator.Expr expr = ExpressionEvaluator.parse("(#f0 = :v0)AND(#f1 BETWEEN :v1 AND :v2)");
|
||||
assertInstanceOf(ExpressionEvaluator.AndExpr.class, expr);
|
||||
var and = (ExpressionEvaluator.AndExpr) expr;
|
||||
ExpressionEvaluator.AndExpr and = (ExpressionEvaluator.AndExpr) expr;
|
||||
assertInstanceOf(ExpressionEvaluator.CompareExpr.class, and.operands().get(0));
|
||||
assertInstanceOf(ExpressionEvaluator.BetweenExpr.class, and.operands().get(1));
|
||||
}
|
||||
@@ -209,42 +210,42 @@ class ExpressionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void pkAndSkEquals() {
|
||||
var result = ExpressionEvaluator.splitKeyCondition("pk = :pk AND sk = :sk");
|
||||
String[] result = ExpressionEvaluator.splitKeyCondition("pk = :pk AND sk = :sk");
|
||||
assertEquals("pk = :pk", result[0]);
|
||||
assertEquals("sk = :sk", result[1]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void pkAndSkBetweenParenthesized() {
|
||||
var result = ExpressionEvaluator.splitKeyCondition("pk = :pk AND (sk BETWEEN :a AND :b)");
|
||||
String[] result = ExpressionEvaluator.splitKeyCondition("pk = :pk AND (sk BETWEEN :a AND :b)");
|
||||
assertEquals("pk = :pk", result[0]);
|
||||
assertEquals("(sk BETWEEN :a AND :b)", result[1]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void compactFormat() {
|
||||
var result = ExpressionEvaluator.splitKeyCondition("(#f0 = :v0)AND(#f1 BETWEEN :v1 AND :v2)");
|
||||
String[] result = ExpressionEvaluator.splitKeyCondition("(#f0 = :v0)AND(#f1 BETWEEN :v1 AND :v2)");
|
||||
assertEquals("(#f0 = :v0)", result[0]);
|
||||
assertEquals("(#f1 BETWEEN :v1 AND :v2)", result[1]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void pkOnly() {
|
||||
var result = ExpressionEvaluator.splitKeyCondition("pk = :pk");
|
||||
String[] result = ExpressionEvaluator.splitKeyCondition("pk = :pk");
|
||||
assertEquals("pk = :pk", result[0]);
|
||||
assertNull(result[1]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void pkAndSkBeginsWith() {
|
||||
var result = ExpressionEvaluator.splitKeyCondition("pk = :pk AND begins_with(sk, :prefix)");
|
||||
String[] result = ExpressionEvaluator.splitKeyCondition("pk = :pk AND begins_with(sk, :prefix)");
|
||||
assertEquals("pk = :pk", result[0]);
|
||||
assertEquals("begins_with(sk, :prefix)", result[1]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void pkAndSkBetweenNoParen() {
|
||||
var result = ExpressionEvaluator.splitKeyCondition("pk = :pk AND sk BETWEEN :a AND :b");
|
||||
String[] result = ExpressionEvaluator.splitKeyCondition("pk = :pk AND sk BETWEEN :a AND :b");
|
||||
assertEquals("pk = :pk", result[0]);
|
||||
assertEquals("sk BETWEEN :a AND :b", result[1]);
|
||||
}
|
||||
@@ -279,43 +280,43 @@ class ExpressionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void andBothTrue() throws Exception {
|
||||
var i = item("{\"a\": {\"S\": \"1\"}, \"b\": {\"S\": \"2\"}}");
|
||||
var v = values("{\n\":a\": {\"S\": \"1\"},\n\":b\": {\"S\": \"2\"}}");
|
||||
JsonNode i = item("{\"a\": {\"S\": \"1\"}, \"b\": {\"S\": \"2\"}}");
|
||||
JsonNode v = values("{\n\":a\": {\"S\": \"1\"},\n\":b\": {\"S\": \"2\"}}");
|
||||
assertTrue(ExpressionEvaluator.matches("a = :a AND b = :b", i, null, v));
|
||||
}
|
||||
|
||||
@Test
|
||||
void andOneFalse() throws Exception {
|
||||
var i = item("{\"a\": {\"S\": \"1\"}, \"b\": {\"S\": \"3\"}}");
|
||||
var v = values("{\n\":a\": {\"S\": \"1\"},\n\":b\": {\"S\": \"2\"}}");
|
||||
JsonNode i = item("{\"a\": {\"S\": \"1\"}, \"b\": {\"S\": \"3\"}}");
|
||||
JsonNode v = values("{\n\":a\": {\"S\": \"1\"},\n\":b\": {\"S\": \"2\"}}");
|
||||
assertFalse(ExpressionEvaluator.matches("a = :a AND b = :b", i, null, v));
|
||||
}
|
||||
|
||||
@Test
|
||||
void orOneTrue() throws Exception {
|
||||
var i = item("{\"a\": {\"S\": \"1\"}, \"b\": {\"S\": \"3\"}}");
|
||||
var v = values("{\n\":a\": {\"S\": \"1\"},\n\":b\": {\"S\": \"2\"}}");
|
||||
JsonNode i = item("{\"a\": {\"S\": \"1\"}, \"b\": {\"S\": \"3\"}}");
|
||||
JsonNode v = values("{\n\":a\": {\"S\": \"1\"},\n\":b\": {\"S\": \"2\"}}");
|
||||
assertTrue(ExpressionEvaluator.matches("a = :a OR b = :b", i, null, v));
|
||||
}
|
||||
|
||||
@Test
|
||||
void orBothFalse() throws Exception {
|
||||
var i = item("{\"a\": {\"S\": \"X\"}, \"b\": {\"S\": \"Y\"}}");
|
||||
var v = values("{\n\":a\": {\"S\": \"1\"},\n\":b\": {\"S\": \"2\"}}");
|
||||
JsonNode i = item("{\"a\": {\"S\": \"X\"}, \"b\": {\"S\": \"Y\"}}");
|
||||
JsonNode v = values("{\n\":a\": {\"S\": \"1\"},\n\":b\": {\"S\": \"2\"}}");
|
||||
assertFalse(ExpressionEvaluator.matches("a = :a OR b = :b", i, null, v));
|
||||
}
|
||||
|
||||
@Test
|
||||
void notTrue() throws Exception {
|
||||
var i = item("{\"a\": {\"S\": \"X\"}}");
|
||||
var v = values("{\n\":a\": {\"S\": \"1\"}}");
|
||||
JsonNode i = item("{\"a\": {\"S\": \"X\"}}");
|
||||
JsonNode v = values("{\n\":a\": {\"S\": \"1\"}}");
|
||||
assertTrue(ExpressionEvaluator.matches("NOT a = :a", i, null, v));
|
||||
}
|
||||
|
||||
@Test
|
||||
void notFalse() throws Exception {
|
||||
var i = item("{\"a\": {\"S\": \"1\"}}");
|
||||
var v = values("{\n\":a\": {\"S\": \"1\"}}");
|
||||
JsonNode i = item("{\"a\": {\"S\": \"1\"}}");
|
||||
JsonNode v = values("{\n\":a\": {\"S\": \"1\"}}");
|
||||
assertFalse(ExpressionEvaluator.matches("NOT a = :a", i, null, v));
|
||||
}
|
||||
|
||||
@@ -323,22 +324,22 @@ class ExpressionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void stringEquals() throws Exception {
|
||||
var i = item("{\"name\": {\"S\": \"Alice\"}}");
|
||||
var v = values("{\n\":v\": {\"S\": \"Alice\"}}");
|
||||
JsonNode i = item("{\"name\": {\"S\": \"Alice\"}}");
|
||||
JsonNode v = values("{\n\":v\": {\"S\": \"Alice\"}}");
|
||||
assertTrue(ExpressionEvaluator.matches("name = :v", i, null, v));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stringNotEquals() throws Exception {
|
||||
var i = item("{\"name\": {\"S\": \"Alice\"}}");
|
||||
var v = values("{\n\":v\": {\"S\": \"Bob\"}}");
|
||||
JsonNode i = item("{\"name\": {\"S\": \"Alice\"}}");
|
||||
JsonNode v = values("{\n\":v\": {\"S\": \"Bob\"}}");
|
||||
assertTrue(ExpressionEvaluator.matches("name <> :v", i, null, v));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stringLessThan() throws Exception {
|
||||
var i = item("{\"name\": {\"S\": \"Alice\"}}");
|
||||
var v = values("{\n\":v\": {\"S\": \"Bob\"}}");
|
||||
JsonNode i = item("{\"name\": {\"S\": \"Alice\"}}");
|
||||
JsonNode v = values("{\n\":v\": {\"S\": \"Bob\"}}");
|
||||
assertTrue(ExpressionEvaluator.matches("name < :v", i, null, v));
|
||||
}
|
||||
|
||||
@@ -346,22 +347,22 @@ class ExpressionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void numberEquals() throws Exception {
|
||||
var i = item("{\"age\": {\"N\": \"25\"}}");
|
||||
var v = values("{\n\":v\": {\"N\": \"25\"}}");
|
||||
JsonNode i = item("{\"age\": {\"N\": \"25\"}}");
|
||||
JsonNode v = values("{\n\":v\": {\"N\": \"25\"}}");
|
||||
assertTrue(ExpressionEvaluator.matches("age = :v", i, null, v));
|
||||
}
|
||||
|
||||
@Test
|
||||
void numberGreaterThan() throws Exception {
|
||||
var i = item("{\"age\": {\"N\": \"30\"}}");
|
||||
var v = values("{\n\":v\": {\"N\": \"25\"}}");
|
||||
JsonNode i = item("{\"age\": {\"N\": \"30\"}}");
|
||||
JsonNode v = values("{\n\":v\": {\"N\": \"25\"}}");
|
||||
assertTrue(ExpressionEvaluator.matches("age > :v", i, null, v));
|
||||
}
|
||||
|
||||
@Test
|
||||
void numberLessThanOrEqual() throws Exception {
|
||||
var i = item("{\"age\": {\"N\": \"25\"}}");
|
||||
var v = values("{\n\":v\": {\"N\": \"25\"}}");
|
||||
JsonNode i = item("{\"age\": {\"N\": \"25\"}}");
|
||||
JsonNode v = values("{\n\":v\": {\"N\": \"25\"}}");
|
||||
assertTrue(ExpressionEvaluator.matches("age <= :v", i, null, v));
|
||||
}
|
||||
|
||||
@@ -369,31 +370,31 @@ class ExpressionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void boolNotEqualFalse() throws Exception {
|
||||
var i = item("{\"active\": {\"BOOL\": \"false\"}}");
|
||||
var v = values("{\n\":v\": {\"BOOL\": \"true\"}}");
|
||||
JsonNode i = item("{\"active\": {\"BOOL\": \"false\"}}");
|
||||
JsonNode v = values("{\n\":v\": {\"BOOL\": \"true\"}}");
|
||||
assertTrue(ExpressionEvaluator.matches("active <> :v", i, null, v));
|
||||
}
|
||||
|
||||
@Test
|
||||
void boolNotEqualTrue() throws Exception {
|
||||
var i = item("{\"active\": {\"BOOL\": \"true\"}}");
|
||||
var v = values("{\n\":v\": {\"BOOL\": \"true\"}}");
|
||||
JsonNode i = item("{\"active\": {\"BOOL\": \"true\"}}");
|
||||
JsonNode v = values("{\n\":v\": {\"BOOL\": \"true\"}}");
|
||||
assertFalse(ExpressionEvaluator.matches("active <> :v", i, null, v));
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingAttributeNotEqual() throws Exception {
|
||||
// DynamoDB: missing <> val → true
|
||||
var i = item("{\"other\": {\"S\": \"x\"}}");
|
||||
var v = values("{\n\":v\": {\"BOOL\": \"true\"}}");
|
||||
JsonNode i = item("{\"other\": {\"S\": \"x\"}}");
|
||||
JsonNode v = values("{\n\":v\": {\"BOOL\": \"true\"}}");
|
||||
assertTrue(ExpressionEvaluator.matches("active <> :v", i, null, v));
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingAttributeEquals() throws Exception {
|
||||
// DynamoDB: missing = val → false
|
||||
var i = item("{\"other\": {\"S\": \"x\"}}");
|
||||
var v = values("{\n\":v\": {\"S\": \"hello\"}}");
|
||||
JsonNode i = item("{\"other\": {\"S\": \"x\"}}");
|
||||
JsonNode v = values("{\n\":v\": {\"S\": \"hello\"}}");
|
||||
assertFalse(ExpressionEvaluator.matches("name = :v", i, null, v));
|
||||
}
|
||||
|
||||
@@ -401,29 +402,29 @@ class ExpressionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void inWithNumbers() throws Exception {
|
||||
var i = item("{\"status\": {\"N\": \"2\"}}");
|
||||
var v = values("{\n\":a\": {\"N\": \"1\"},\n\":b\": {\"N\": \"2\"},\n\":c\": {\"N\": \"3\"}}");
|
||||
JsonNode i = item("{\"status\": {\"N\": \"2\"}}");
|
||||
JsonNode v = values("{\n\":a\": {\"N\": \"1\"},\n\":b\": {\"N\": \"2\"},\n\":c\": {\"N\": \"3\"}}");
|
||||
assertTrue(ExpressionEvaluator.matches("status IN (:a, :b, :c)", i, null, v));
|
||||
}
|
||||
|
||||
@Test
|
||||
void inWithStrings() throws Exception {
|
||||
var i = item("{\"color\": {\"S\": \"red\"}}");
|
||||
var v = values("{\n\":a\": {\"S\": \"red\"},\n\":b\": {\"S\": \"blue\"}}");
|
||||
JsonNode i = item("{\"color\": {\"S\": \"red\"}}");
|
||||
JsonNode v = values("{\n\":a\": {\"S\": \"red\"},\n\":b\": {\"S\": \"blue\"}}");
|
||||
assertTrue(ExpressionEvaluator.matches("color IN (:a, :b)", i, null, v));
|
||||
}
|
||||
|
||||
@Test
|
||||
void inNotMatching() throws Exception {
|
||||
var i = item("{\"color\": {\"S\": \"green\"}}");
|
||||
var v = values("{\n\":a\": {\"S\": \"red\"},\n\":b\": {\"S\": \"blue\"}}");
|
||||
JsonNode i = item("{\"color\": {\"S\": \"green\"}}");
|
||||
JsonNode v = values("{\n\":a\": {\"S\": \"red\"},\n\":b\": {\"S\": \"blue\"}}");
|
||||
assertFalse(ExpressionEvaluator.matches("color IN (:a, :b)", i, null, v));
|
||||
}
|
||||
|
||||
@Test
|
||||
void inSingleValue() throws Exception {
|
||||
var i = item("{\"status\": {\"S\": \"active\"}}");
|
||||
var v = values("{\n\":a\": {\"S\": \"active\"}}");
|
||||
JsonNode i = item("{\"status\": {\"S\": \"active\"}}");
|
||||
JsonNode v = values("{\n\":a\": {\"S\": \"active\"}}");
|
||||
assertTrue(ExpressionEvaluator.matches("status IN (:a)", i, null, v));
|
||||
}
|
||||
|
||||
@@ -431,15 +432,15 @@ class ExpressionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void betweenStrings() throws Exception {
|
||||
var i = item("{\"sk\": {\"S\": \"B\"}}");
|
||||
var v = values("{\n\":low\": {\"S\": \"A\"},\n\":high\": {\"S\": \"C\"}}");
|
||||
JsonNode i = item("{\"sk\": {\"S\": \"B\"}}");
|
||||
JsonNode v = values("{\n\":low\": {\"S\": \"A\"},\n\":high\": {\"S\": \"C\"}}");
|
||||
assertTrue(ExpressionEvaluator.matches("sk BETWEEN :low AND :high", i, null, v));
|
||||
}
|
||||
|
||||
@Test
|
||||
void betweenOutOfRange() throws Exception {
|
||||
var i = item("{\"sk\": {\"S\": \"D\"}}");
|
||||
var v = values("{\n\":low\": {\"S\": \"A\"},\n\":high\": {\"S\": \"C\"}}");
|
||||
JsonNode i = item("{\"sk\": {\"S\": \"D\"}}");
|
||||
JsonNode v = values("{\n\":low\": {\"S\": \"A\"},\n\":high\": {\"S\": \"C\"}}");
|
||||
assertFalse(ExpressionEvaluator.matches("sk BETWEEN :low AND :high", i, null, v));
|
||||
}
|
||||
|
||||
@@ -447,37 +448,37 @@ class ExpressionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void attributeExistsPresent() throws Exception {
|
||||
var i = item("{\"name\": {\"S\": \"Alice\"}}");
|
||||
JsonNode i = item("{\"name\": {\"S\": \"Alice\"}}");
|
||||
assertTrue(ExpressionEvaluator.matches("attribute_exists(name)", i, null, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void attributeExistsMissing() throws Exception {
|
||||
var i = item("{\"other\": {\"S\": \"x\"}}");
|
||||
JsonNode i = item("{\"other\": {\"S\": \"x\"}}");
|
||||
assertFalse(ExpressionEvaluator.matches("attribute_exists(name)", i, null, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void attributeNotExistsPresent() throws Exception {
|
||||
var i = item("{\"name\": {\"S\": \"Alice\"}}");
|
||||
JsonNode i = item("{\"name\": {\"S\": \"Alice\"}}");
|
||||
assertFalse(ExpressionEvaluator.matches("attribute_not_exists(name)", i, null, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void attributeNotExistsMissing() throws Exception {
|
||||
var i = item("{\"other\": {\"S\": \"x\"}}");
|
||||
JsonNode i = item("{\"other\": {\"S\": \"x\"}}");
|
||||
assertTrue(ExpressionEvaluator.matches("attribute_not_exists(name)", i, null, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void attributeExistsNested() throws Exception {
|
||||
var i = item("{\"info\": {\"M\": {\"email\": {\"S\": \"a@b.com\"}}}}");
|
||||
JsonNode i = item("{\"info\": {\"M\": {\"email\": {\"S\": \"a@b.com\"}}}}");
|
||||
assertTrue(ExpressionEvaluator.matches("attribute_exists(info.email)", i, null, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void attributeExistsNestedMissing() throws Exception {
|
||||
var i = item("{\"info\": {\"M\": {\"name\": {\"S\": \"Alice\"}}}}");
|
||||
JsonNode i = item("{\"info\": {\"M\": {\"name\": {\"S\": \"Alice\"}}}}");
|
||||
assertFalse(ExpressionEvaluator.matches("attribute_exists(info.email)", i, null, null));
|
||||
}
|
||||
|
||||
@@ -485,15 +486,15 @@ class ExpressionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void beginsWithMatch() throws Exception {
|
||||
var i = item("{\"sk\": {\"S\": \"USER#123\"}}");
|
||||
var v = values("{\n\":prefix\": {\"S\": \"USER#\"}}");
|
||||
JsonNode i = item("{\"sk\": {\"S\": \"USER#123\"}}");
|
||||
JsonNode v = values("{\n\":prefix\": {\"S\": \"USER#\"}}");
|
||||
assertTrue(ExpressionEvaluator.matches("begins_with(sk, :prefix)", i, null, v));
|
||||
}
|
||||
|
||||
@Test
|
||||
void beginsWithNoMatch() throws Exception {
|
||||
var i = item("{\"sk\": {\"S\": \"ORDER#123\"}}");
|
||||
var v = values("{\n\":prefix\": {\"S\": \"USER#\"}}");
|
||||
JsonNode i = item("{\"sk\": {\"S\": \"ORDER#123\"}}");
|
||||
JsonNode v = values("{\n\":prefix\": {\"S\": \"USER#\"}}");
|
||||
assertFalse(ExpressionEvaluator.matches("begins_with(sk, :prefix)", i, null, v));
|
||||
}
|
||||
|
||||
@@ -501,29 +502,29 @@ class ExpressionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void containsString() throws Exception {
|
||||
var i = item("{\"desc\": {\"S\": \"hello world\"}}");
|
||||
var v = values("{\n\":sub\": {\"S\": \"world\"}}");
|
||||
JsonNode i = item("{\"desc\": {\"S\": \"hello world\"}}");
|
||||
JsonNode v = values("{\n\":sub\": {\"S\": \"world\"}}");
|
||||
assertTrue(ExpressionEvaluator.matches("contains(desc, :sub)", i, null, v));
|
||||
}
|
||||
|
||||
@Test
|
||||
void containsList() throws Exception {
|
||||
var i = item("{\"tags\": {\"L\": [{\"S\": \"a\"}, {\"S\": \"b\"}, {\"S\": \"c\"}]}}");
|
||||
var v = values("{\n\":val\": {\"S\": \"b\"}}");
|
||||
JsonNode i = item("{\"tags\": {\"L\": [{\"S\": \"a\"}, {\"S\": \"b\"}, {\"S\": \"c\"}]}}");
|
||||
JsonNode v = values("{\n\":val\": {\"S\": \"b\"}}");
|
||||
assertTrue(ExpressionEvaluator.matches("contains(tags, :val)", i, null, v));
|
||||
}
|
||||
|
||||
@Test
|
||||
void containsStringSet() throws Exception {
|
||||
var i = item("{\"tags\": {\"SS\": [\"a\", \"b\", \"c\"]}}");
|
||||
var v = values("{\n\":val\": {\"S\": \"b\"}}");
|
||||
JsonNode i = item("{\"tags\": {\"SS\": [\"a\", \"b\", \"c\"]}}");
|
||||
JsonNode v = values("{\n\":val\": {\"S\": \"b\"}}");
|
||||
assertTrue(ExpressionEvaluator.matches("contains(tags, :val)", i, null, v));
|
||||
}
|
||||
|
||||
@Test
|
||||
void containsNumberSet() throws Exception {
|
||||
var i = item("{\"nums\": {\"NS\": [\"1\", \"2\", \"3\"]}}");
|
||||
var v = values("{\n\":val\": {\"N\": \"2\"}}");
|
||||
JsonNode i = item("{\"nums\": {\"NS\": [\"1\", \"2\", \"3\"]}}");
|
||||
JsonNode v = values("{\n\":val\": {\"N\": \"2\"}}");
|
||||
assertTrue(ExpressionEvaluator.matches("contains(nums, :val)", i, null, v));
|
||||
}
|
||||
|
||||
@@ -531,9 +532,9 @@ class ExpressionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void expressionAttributeNames() throws Exception {
|
||||
var i = item("{\"status\": {\"S\": \"active\"}}");
|
||||
var v = values("{\n\":v\": {\"S\": \"active\"}}");
|
||||
var n = names("{\"#s\": \"status\"}");
|
||||
JsonNode i = item("{\"status\": {\"S\": \"active\"}}");
|
||||
JsonNode v = values("{\n\":v\": {\"S\": \"active\"}}");
|
||||
JsonNode n = names("{\"#s\": \"status\"}");
|
||||
assertTrue(ExpressionEvaluator.matches("#s = :v", i, n, v));
|
||||
}
|
||||
|
||||
@@ -542,8 +543,8 @@ class ExpressionEvaluatorTest {
|
||||
@Test
|
||||
void nestedParentheses() throws Exception {
|
||||
// ((a = :1 OR b = :2) AND c = :3) OR d = :4
|
||||
var i = item("{\"a\": {\"S\": \"X\"}, \"b\": {\"S\": \"Y\"}, \"c\": {\"S\": \"3\"}, \"d\": {\"S\": \"4\"}}");
|
||||
var v = values("{\n\":1\": {\"S\": \"1\"},\n\":2\": {\"S\": \"2\"},\n\":3\": {\"S\": \"3\"},\n\":4\": {\"S\": \"4\"}}");
|
||||
JsonNode i = item("{\"a\": {\"S\": \"X\"}, \"b\": {\"S\": \"Y\"}, \"c\": {\"S\": \"3\"}, \"d\": {\"S\": \"4\"}}");
|
||||
JsonNode v = values("{\n\":1\": {\"S\": \"1\"},\n\":2\": {\"S\": \"2\"},\n\":3\": {\"S\": \"3\"},\n\":4\": {\"S\": \"4\"}}");
|
||||
// a!=1, b!=2 so inner OR is false, AND c=3 doesn't matter (false AND true = false)
|
||||
// d=4 so outer OR is true
|
||||
assertTrue(ExpressionEvaluator.matches("((a = :1 OR b = :2) AND c = :3) OR d = :4", i, null, v));
|
||||
@@ -551,8 +552,8 @@ class ExpressionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void nestedParenthesesAllFalse() throws Exception {
|
||||
var i = item("{\"a\": {\"S\": \"X\"}, \"b\": {\"S\": \"Y\"}, \"c\": {\"S\": \"3\"}, \"d\": {\"S\": \"Z\"}}");
|
||||
var v = values("{\n\":1\": {\"S\": \"1\"},\n\":2\": {\"S\": \"2\"},\n\":3\": {\"S\": \"3\"},\n\":4\": {\"S\": \"4\"}}");
|
||||
JsonNode i = item("{\"a\": {\"S\": \"X\"}, \"b\": {\"S\": \"Y\"}, \"c\": {\"S\": \"3\"}, \"d\": {\"S\": \"Z\"}}");
|
||||
JsonNode v = values("{\n\":1\": {\"S\": \"1\"},\n\":2\": {\"S\": \"2\"},\n\":3\": {\"S\": \"3\"},\n\":4\": {\"S\": \"4\"}}");
|
||||
assertFalse(ExpressionEvaluator.matches("((a = :1 OR b = :2) AND c = :3) OR d = :4", i, null, v));
|
||||
}
|
||||
|
||||
@@ -560,9 +561,9 @@ class ExpressionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void compactFormatEvaluation() throws Exception {
|
||||
var i = item("{\"pk\": {\"S\": \"USER#1\"}, \"sk\": {\"S\": \"B\"}}");
|
||||
var v = values("{\n\":v0\": {\"S\": \"USER#1\"},\n\":v1\": {\"S\": \"A\"},\n\":v2\": {\"S\": \"C\"}}");
|
||||
var n = names("{\"#f0\": \"pk\", \"#f1\": \"sk\"}");
|
||||
JsonNode i = item("{\"pk\": {\"S\": \"USER#1\"}, \"sk\": {\"S\": \"B\"}}");
|
||||
JsonNode v = values("{\n\":v0\": {\"S\": \"USER#1\"},\n\":v1\": {\"S\": \"A\"},\n\":v2\": {\"S\": \"C\"}}");
|
||||
JsonNode n = names("{\"#f0\": \"pk\", \"#f1\": \"sk\"}");
|
||||
assertTrue(ExpressionEvaluator.matches("(#f0 = :v0)AND(#f1 BETWEEN :v1 AND :v2)", i, n, v));
|
||||
}
|
||||
|
||||
@@ -570,13 +571,13 @@ class ExpressionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void nullExpressionMatchesAll() throws Exception {
|
||||
var i = item("{\"a\": {\"S\": \"1\"}}");
|
||||
JsonNode i = item("{\"a\": {\"S\": \"1\"}}");
|
||||
assertTrue(ExpressionEvaluator.matches(null, i, null, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankExpressionMatchesAll() throws Exception {
|
||||
var i = item("{\"a\": {\"S\": \"1\"}}");
|
||||
JsonNode i = item("{\"a\": {\"S\": \"1\"}}");
|
||||
assertTrue(ExpressionEvaluator.matches(" ", i, null, null));
|
||||
}
|
||||
}
|
||||
@@ -605,12 +606,12 @@ class ExpressionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void reversedBetweenBoundsAreRejectedAtParseTime() {
|
||||
var mapper = new ObjectMapper();
|
||||
var values = mapper.createObjectNode();
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
ObjectNode values = mapper.createObjectNode();
|
||||
values.set(":hi", mapper.createObjectNode().put("N", "10"));
|
||||
values.set(":lo", mapper.createObjectNode().put("N", "1"));
|
||||
|
||||
var e = assertThrows(AwsException.class, () ->
|
||||
AwsException e = assertThrows(AwsException.class, () ->
|
||||
ExpressionEvaluator.validateExpression("n BETWEEN :hi AND :lo",
|
||||
"ConditionExpression", null, values));
|
||||
assertEquals("ValidationException", e.getErrorCode());
|
||||
@@ -624,19 +625,19 @@ class ExpressionEvaluatorTest {
|
||||
// their UTF-8 bytes. Java's UTF-16 ordering puts them the other way round.
|
||||
@Test
|
||||
void stringBoundsAreOrderedByUtf8Bytes() {
|
||||
var mapper = new ObjectMapper();
|
||||
var values = mapper.createObjectNode();
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
ObjectNode values = mapper.createObjectNode();
|
||||
values.set(":lo", mapper.createObjectNode().put("S", "\uE000"));
|
||||
values.set(":hi", mapper.createObjectNode().put("S", "\uD800\uDC00"));
|
||||
|
||||
assertDoesNotThrow(() -> ExpressionEvaluator.validateExpression("n BETWEEN :lo AND :hi",
|
||||
"ConditionExpression", null, values));
|
||||
|
||||
var reversed = mapper.createObjectNode();
|
||||
ObjectNode reversed = mapper.createObjectNode();
|
||||
reversed.set(":lo", mapper.createObjectNode().put("S", "\uD800\uDC00"));
|
||||
reversed.set(":hi", mapper.createObjectNode().put("S", "\uE000"));
|
||||
|
||||
var e = assertThrows(AwsException.class, () ->
|
||||
AwsException e = assertThrows(AwsException.class, () ->
|
||||
ExpressionEvaluator.validateExpression("n BETWEEN :lo AND :hi",
|
||||
"ConditionExpression", null, reversed));
|
||||
assertEquals("ValidationException", e.getErrorCode());
|
||||
@@ -647,21 +648,21 @@ class ExpressionEvaluatorTest {
|
||||
// SerializationException before any comparison happens.
|
||||
@Test
|
||||
void binaryBoundsCompareByBytesAndRejectMalformedBase64() {
|
||||
var mapper = new ObjectMapper();
|
||||
var reversed = mapper.createObjectNode();
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
ObjectNode reversed = mapper.createObjectNode();
|
||||
reversed.set(":lo", mapper.createObjectNode().put("B", "/w=="));
|
||||
reversed.set(":hi", mapper.createObjectNode().put("B", "AA=="));
|
||||
|
||||
var e = assertThrows(AwsException.class, () ->
|
||||
AwsException e = assertThrows(AwsException.class, () ->
|
||||
ExpressionEvaluator.validateExpression("n BETWEEN :lo AND :hi",
|
||||
"ConditionExpression", null, reversed));
|
||||
assertEquals("ValidationException", e.getErrorCode());
|
||||
|
||||
var malformed = mapper.createObjectNode();
|
||||
ObjectNode malformed = mapper.createObjectNode();
|
||||
malformed.set(":lo", mapper.createObjectNode().put("B", "!!!not-base64!!!"));
|
||||
malformed.set(":hi", mapper.createObjectNode().put("B", "@@@@"));
|
||||
|
||||
var serialization = assertThrows(AwsException.class, () ->
|
||||
AwsException serialization = assertThrows(AwsException.class, () ->
|
||||
ExpressionEvaluator.validateExpression("n BETWEEN :lo AND :hi",
|
||||
"ConditionExpression", null, malformed));
|
||||
assertEquals("SerializationException", serialization.getErrorCode());
|
||||
@@ -673,10 +674,10 @@ class ExpressionEvaluatorTest {
|
||||
// SerializationException, so the comparison itself must never decode blindly.
|
||||
@Test
|
||||
void binaryComparisonRejectsMalformedBase64() {
|
||||
var valid = mapper.createObjectNode().put("B", "AQID");
|
||||
var malformed = mapper.createObjectNode().put("B", "not base64!!");
|
||||
ObjectNode valid = mapper.createObjectNode().put("B", "AQID");
|
||||
ObjectNode malformed = mapper.createObjectNode().put("B", "not base64!!");
|
||||
|
||||
var e = assertThrows(AwsException.class,
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> ExpressionEvaluator.compareAttributeValues(valid, malformed));
|
||||
assertEquals("SerializationException", e.getErrorCode());
|
||||
assertEquals(400, e.getHttpStatus());
|
||||
@@ -685,12 +686,12 @@ class ExpressionEvaluatorTest {
|
||||
// A FilterExpression carries the same text without the envelope on AWS.
|
||||
@Test
|
||||
void filterExpressionReportsTheReversedBoundsWithoutTheEnvelope() {
|
||||
var mapper = new ObjectMapper();
|
||||
var values = mapper.createObjectNode();
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
ObjectNode values = mapper.createObjectNode();
|
||||
values.set(":hi", mapper.createObjectNode().put("N", "10"));
|
||||
values.set(":lo", mapper.createObjectNode().put("N", "1"));
|
||||
|
||||
var e = assertThrows(AwsException.class, () ->
|
||||
AwsException e = assertThrows(AwsException.class, () ->
|
||||
ExpressionEvaluator.validateExpression("n BETWEEN :hi AND :lo",
|
||||
"FilterExpression", null, values));
|
||||
assertEquals("Invalid FilterExpression: The BETWEEN operator requires upper bound to be "
|
||||
@@ -700,8 +701,8 @@ class ExpressionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void orderedBetweenBoundsAreAccepted() {
|
||||
var mapper = new ObjectMapper();
|
||||
var values = mapper.createObjectNode();
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
ObjectNode values = mapper.createObjectNode();
|
||||
values.set(":lo", mapper.createObjectNode().put("N", "1"));
|
||||
values.set(":hi", mapper.createObjectNode().put("N", "10"));
|
||||
|
||||
|
||||
+145
-145
@@ -631,14 +631,14 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
}
|
||||
|
||||
private AwsException expectValidationException(String action, JsonNode request) {
|
||||
var ex = assertThrows(AwsException.class, () -> handler.handle(action, request, "eu-west-1"));
|
||||
AwsException ex = assertThrows(AwsException.class, () -> handler.handle(action, request, "eu-west-1"));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
return ex;
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTableRejectsProvisionedThroughputWithPayPerRequest() {
|
||||
var ex = expectValidationException("CreateTable", json("""
|
||||
AwsException ex = expectValidationException("CreateTable", json("""
|
||||
{
|
||||
"TableName": "PprTable",
|
||||
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
|
||||
@@ -653,7 +653,7 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
|
||||
@Test
|
||||
void createTableRejectsGsiIncludeProjectionWithoutNonKeyAttributes() {
|
||||
var ex = expectValidationException("CreateTable", json("""
|
||||
AwsException ex = expectValidationException("CreateTable", json("""
|
||||
{
|
||||
"TableName": "GsiIncTable",
|
||||
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
|
||||
@@ -675,7 +675,7 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
|
||||
@Test
|
||||
void createTableRejectsLsiIncludeProjectionWithoutNonKeyAttributes() {
|
||||
var ex = expectValidationException("CreateTable", json("""
|
||||
AwsException ex = expectValidationException("CreateTable", json("""
|
||||
{
|
||||
"TableName": "LsiIncTable",
|
||||
"KeySchema": [
|
||||
@@ -704,7 +704,7 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
|
||||
@Test
|
||||
void createTableRejectsKeysOnlyProjectionCarryingNonKeyAttributes() {
|
||||
var ex = expectValidationException("CreateTable", json("""
|
||||
AwsException ex = expectValidationException("CreateTable", json("""
|
||||
{
|
||||
"TableName": "KeysOnlyTable",
|
||||
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
|
||||
@@ -727,7 +727,7 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
@Test
|
||||
void updateTableRejectsGsiIncludeProjectionWithoutNonKeyAttributes() {
|
||||
createUsersTable("eu-west-1");
|
||||
var ex = expectValidationException("UpdateTable", json("""
|
||||
AwsException ex = expectValidationException("UpdateTable", json("""
|
||||
{
|
||||
"TableName": "Users",
|
||||
"AttributeDefinitions": [{"AttributeName": "g", "AttributeType": "S"}],
|
||||
@@ -746,7 +746,7 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
@Test
|
||||
void updateTableRejectsAllProjectionCarryingNonKeyAttributes() {
|
||||
createUsersTable("eu-west-1");
|
||||
var ex = expectValidationException("UpdateTable", json("""
|
||||
AwsException ex = expectValidationException("UpdateTable", json("""
|
||||
{
|
||||
"TableName": "Users",
|
||||
"AttributeDefinitions": [{"AttributeName": "g", "AttributeType": "S"}],
|
||||
@@ -905,7 +905,7 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
// Checked against real DynamoDB: the projection is validated before the table lookup.
|
||||
@Test
|
||||
void updateTableValidatesGsiProjectionBeforeTableLookup() {
|
||||
var ex = expectValidationException("UpdateTable", json("""
|
||||
AwsException ex = expectValidationException("UpdateTable", json("""
|
||||
{
|
||||
"TableName": "NoSuchTable",
|
||||
"AttributeDefinitions": [{"AttributeName": "g", "AttributeType": "S"}],
|
||||
@@ -923,7 +923,7 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
// The empty-list, null, and index-position cases below were checked against real DynamoDB.
|
||||
@Test
|
||||
void createTableRejectsEmptyGsiNonKeyAttributesWithItsPosition() {
|
||||
var ex = expectValidationException("CreateTable", json("""
|
||||
AwsException ex = expectValidationException("CreateTable", json("""
|
||||
{
|
||||
"TableName": "EmptyGsiNonKey",
|
||||
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
|
||||
@@ -953,7 +953,7 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
|
||||
@Test
|
||||
void createTableRejectsEmptyLsiNonKeyAttributes() {
|
||||
var ex = expectValidationException("CreateTable", json("""
|
||||
AwsException ex = expectValidationException("CreateTable", json("""
|
||||
{
|
||||
"TableName": "EmptyLsiNonKey",
|
||||
"KeySchema": [
|
||||
@@ -984,7 +984,7 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
@Test
|
||||
void updateTableRejectsEmptyGsiNonKeyAttributesBeforeProjectionTypeCheck() {
|
||||
createUsersTable("eu-west-1");
|
||||
var ex = expectValidationException("UpdateTable", json("""
|
||||
AwsException ex = expectValidationException("UpdateTable", json("""
|
||||
{
|
||||
"TableName": "Users",
|
||||
"AttributeDefinitions": [{"AttributeName": "g", "AttributeType": "S"}],
|
||||
@@ -1019,13 +1019,13 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
}
|
||||
"""), "eu-west-1");
|
||||
assertEquals(200, response.getStatus());
|
||||
var gsi = service.describeTable("NullNonKey", "eu-west-1").findGsi("gsi1").orElseThrow();
|
||||
GlobalSecondaryIndex gsi = service.describeTable("NullNonKey", "eu-west-1").findGsi("gsi1").orElseThrow();
|
||||
assertEquals("KEYS_ONLY", gsi.getProjectionType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTableRejectsStreamViewTypeWithStreamEnabledFalse() {
|
||||
var ex = expectValidationException("CreateTable", json("""
|
||||
AwsException ex = expectValidationException("CreateTable", json("""
|
||||
{
|
||||
"TableName": "StreamFalseTable",
|
||||
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
|
||||
@@ -1040,7 +1040,7 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
|
||||
@Test
|
||||
void scanRejectsTotalSegmentsAboveTheMaximum() {
|
||||
var ex = expectValidationException("Scan", json("""
|
||||
AwsException ex = expectValidationException("Scan", json("""
|
||||
{"TableName": "Users", "Segment": 0, "TotalSegments": 1000001}
|
||||
"""));
|
||||
assertEquals("1 validation error detected: Value '1000001' at 'totalSegments' failed to "
|
||||
@@ -1050,7 +1050,7 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
@Test
|
||||
void updateItemRejectsExpressionAttributeNamesWithNoExpression() {
|
||||
createUsersTable("eu-west-1");
|
||||
var ex = expectValidationException("UpdateItem", json("""
|
||||
AwsException ex = expectValidationException("UpdateItem", json("""
|
||||
{
|
||||
"TableName": "Users",
|
||||
"Key": {"userId": {"S": "u1"}},
|
||||
@@ -1063,7 +1063,7 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
|
||||
@Test
|
||||
void scanRejectsANegativeSegment() {
|
||||
var ex = expectValidationException("Scan", json("""
|
||||
AwsException ex = expectValidationException("Scan", json("""
|
||||
{"TableName": "Users", "Segment": -1, "TotalSegments": 4}
|
||||
"""));
|
||||
assertEquals("1 validation error detected: Value '-1' at 'segment' failed to satisfy constraint: "
|
||||
@@ -1072,7 +1072,7 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
|
||||
@Test
|
||||
void scanRejectsTotalSegmentsBelowOne() {
|
||||
var ex = expectValidationException("Scan", json("""
|
||||
AwsException ex = expectValidationException("Scan", json("""
|
||||
{"TableName": "Users", "Segment": 0, "TotalSegments": 0}
|
||||
"""));
|
||||
assertEquals("1 validation error detected: Value '0' at 'totalSegments' failed to satisfy constraint: "
|
||||
@@ -1081,7 +1081,7 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
|
||||
@Test
|
||||
void scanReportsTotalSegmentsBeforeSegmentWhenBothAreOutOfRange() {
|
||||
var ex = expectValidationException("Scan", json("""
|
||||
AwsException ex = expectValidationException("Scan", json("""
|
||||
{"TableName": "Users", "Segment": -1, "TotalSegments": 0}
|
||||
"""));
|
||||
assertEquals("2 validation errors detected: "
|
||||
@@ -1095,7 +1095,7 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
void scanAcceptsSegmentsAtTheBounds() throws Exception {
|
||||
createUsersTable("eu-west-1");
|
||||
|
||||
var response = handler.handle("Scan", json("""
|
||||
Response response = handler.handle("Scan", json("""
|
||||
{"TableName": "Users", "Segment": 0, "TotalSegments": 1000000}
|
||||
"""), "eu-west-1");
|
||||
assertEquals(200, response.getStatus());
|
||||
@@ -1113,16 +1113,16 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
int totalSegments = 10;
|
||||
int totalDeleted = 0;
|
||||
for (int segment = 0; segment < totalSegments; segment++) {
|
||||
var scanReq = mapper.createObjectNode();
|
||||
ObjectNode scanReq = mapper.createObjectNode();
|
||||
scanReq.put("TableName", "Users");
|
||||
scanReq.put("Segment", segment);
|
||||
scanReq.put("TotalSegments", totalSegments);
|
||||
|
||||
var response = handler.handle("Scan", scanReq, region);
|
||||
Response response = handler.handle("Scan", scanReq, region);
|
||||
assertEquals(200, response.getStatus());
|
||||
var entity = mapper.readTree(response.getEntity().toString());
|
||||
var items = entity.get("Items");
|
||||
for (var item : items) {
|
||||
JsonNode entity = mapper.readTree(response.getEntity().toString());
|
||||
JsonNode items = entity.get("Items");
|
||||
for (JsonNode item : items) {
|
||||
totalDeleted++;
|
||||
String key = item.get("userId").get("S").asText();
|
||||
service.deleteItem("Users", item("userId", key), region);
|
||||
@@ -1131,10 +1131,10 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
|
||||
assertEquals(10, totalDeleted, "All 10 items should have been returned and deleted across segments");
|
||||
|
||||
var checkResponse = handler.handle("Scan", json("""
|
||||
Response checkResponse = handler.handle("Scan", json("""
|
||||
{"TableName": "Users", "Select": "COUNT"}
|
||||
"""), region);
|
||||
var checkEntity = mapper.readTree(checkResponse.getEntity().toString());
|
||||
JsonNode checkEntity = mapper.readTree(checkResponse.getEntity().toString());
|
||||
assertEquals(0, checkEntity.get("Count").asInt(), "No remaining items should be in the table");
|
||||
}
|
||||
|
||||
@@ -1152,7 +1152,7 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
for (int segment = 0; segment < totalSegments; segment++) {
|
||||
JsonNode exclusiveStartKey = null;
|
||||
do {
|
||||
var scanReq = mapper.createObjectNode();
|
||||
ObjectNode scanReq = mapper.createObjectNode();
|
||||
scanReq.put("TableName", "Users");
|
||||
scanReq.put("Segment", segment);
|
||||
scanReq.put("TotalSegments", totalSegments);
|
||||
@@ -1161,12 +1161,12 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
scanReq.set("ExclusiveStartKey", exclusiveStartKey);
|
||||
}
|
||||
|
||||
var response = handler.handle("Scan", scanReq, region);
|
||||
Response response = handler.handle("Scan", scanReq, region);
|
||||
assertEquals(200, response.getStatus());
|
||||
var entity = mapper.readTree(response.getEntity().toString());
|
||||
var items = entity.get("Items");
|
||||
JsonNode entity = mapper.readTree(response.getEntity().toString());
|
||||
JsonNode items = entity.get("Items");
|
||||
assertTrue(items.size() <= 2, "Page size must not exceed limit");
|
||||
for (var item : items) {
|
||||
for (JsonNode item : items) {
|
||||
String key = item.get("userId").get("S").asText();
|
||||
assertTrue(collectedKeys.add(key), "Item must not be returned multiple times: " + key);
|
||||
}
|
||||
@@ -1190,15 +1190,15 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
int sumCount = 0;
|
||||
int sumScannedCount = 0;
|
||||
for (int segment = 0; segment < totalSegments; segment++) {
|
||||
var scanReq = mapper.createObjectNode();
|
||||
ObjectNode scanReq = mapper.createObjectNode();
|
||||
scanReq.put("TableName", "Users");
|
||||
scanReq.put("Segment", segment);
|
||||
scanReq.put("TotalSegments", totalSegments);
|
||||
scanReq.put("Select", "COUNT");
|
||||
|
||||
var response = handler.handle("Scan", scanReq, region);
|
||||
Response response = handler.handle("Scan", scanReq, region);
|
||||
assertEquals(200, response.getStatus());
|
||||
var entity = mapper.readTree(response.getEntity().toString());
|
||||
JsonNode entity = mapper.readTree(response.getEntity().toString());
|
||||
sumCount += entity.get("Count").asInt();
|
||||
sumScannedCount += entity.get("ScannedCount").asInt();
|
||||
}
|
||||
@@ -1230,16 +1230,16 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
userSegments.put("bob", new HashSet<>());
|
||||
|
||||
for (int segment = 0; segment < totalSegments; segment++) {
|
||||
var scanReq = mapper.createObjectNode();
|
||||
ObjectNode scanReq = mapper.createObjectNode();
|
||||
scanReq.put("TableName", "Orders");
|
||||
scanReq.put("Segment", segment);
|
||||
scanReq.put("TotalSegments", totalSegments);
|
||||
|
||||
var response = handler.handle("Scan", scanReq, region);
|
||||
Response response = handler.handle("Scan", scanReq, region);
|
||||
assertEquals(200, response.getStatus());
|
||||
var entity = mapper.readTree(response.getEntity().toString());
|
||||
var items = entity.get("Items");
|
||||
for (var item : items) {
|
||||
JsonNode entity = mapper.readTree(response.getEntity().toString());
|
||||
JsonNode items = entity.get("Items");
|
||||
for (JsonNode item : items) {
|
||||
String userId = item.get("userId").get("S").asText();
|
||||
userSegments.get(userId).add(segment);
|
||||
}
|
||||
@@ -1250,7 +1250,7 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
}
|
||||
|
||||
private ObjectNode updateUserRequest() {
|
||||
var request = mapper.createObjectNode();
|
||||
ObjectNode request = mapper.createObjectNode();
|
||||
request.put("TableName", "Users");
|
||||
request.set("Key", mapper.createObjectNode().set("userId", attributeValue("S", "u1")));
|
||||
return request;
|
||||
@@ -1259,26 +1259,26 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
@Test
|
||||
void updateItemUpdatedNewReturnsOnlyTheChangedMapFragment() throws Exception {
|
||||
createUsersTable("eu-west-1");
|
||||
var parent = mapper.createObjectNode();
|
||||
ObjectNode parent = mapper.createObjectNode();
|
||||
parent.set("keep", attributeValue("S", "k"));
|
||||
parent.set("child", attributeValue("S", "old"));
|
||||
var putRequest = mapper.createObjectNode();
|
||||
ObjectNode putRequest = mapper.createObjectNode();
|
||||
putRequest.put("TableName", "Users");
|
||||
var item = mapper.createObjectNode();
|
||||
ObjectNode item = mapper.createObjectNode();
|
||||
item.set("userId", attributeValue("S", "u1"));
|
||||
item.set("parent", mapper.createObjectNode().set("M", parent));
|
||||
putRequest.set("Item", item);
|
||||
handler.handle("PutItem", putRequest, "eu-west-1");
|
||||
|
||||
var request = updateUserRequest();
|
||||
ObjectNode request = updateUserRequest();
|
||||
request.put("UpdateExpression", "SET parent.child = :v");
|
||||
request.set("ExpressionAttributeValues",
|
||||
mapper.createObjectNode().set(":v", attributeValue("S", "new")));
|
||||
request.put("ReturnValues", "UPDATED_NEW");
|
||||
|
||||
var response = handler.handle("UpdateItem", request, "eu-west-1");
|
||||
var body = mapper.convertValue(response.getEntity(), JsonNode.class);
|
||||
var attributes = body.get("Attributes");
|
||||
Response response = handler.handle("UpdateItem", request, "eu-west-1");
|
||||
JsonNode body = mapper.convertValue(response.getEntity(), JsonNode.class);
|
||||
JsonNode attributes = body.get("Attributes");
|
||||
assertEquals("new", attributes.get("parent").get("M").get("child").get("S").asText());
|
||||
assertFalse(attributes.get("parent").get("M").has("keep"));
|
||||
}
|
||||
@@ -1286,31 +1286,31 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
@Test
|
||||
void updateItemRemoveWithUpdatedNewOmitsAttributes() throws Exception {
|
||||
createUsersTable("eu-west-1");
|
||||
var putRequest = mapper.createObjectNode();
|
||||
ObjectNode putRequest = mapper.createObjectNode();
|
||||
putRequest.put("TableName", "Users");
|
||||
var item = mapper.createObjectNode();
|
||||
ObjectNode item = mapper.createObjectNode();
|
||||
item.set("userId", attributeValue("S", "u1"));
|
||||
item.set("y", attributeValue("S", "drop"));
|
||||
putRequest.set("Item", item);
|
||||
handler.handle("PutItem", putRequest, "eu-west-1");
|
||||
|
||||
var request = updateUserRequest();
|
||||
ObjectNode request = updateUserRequest();
|
||||
request.put("UpdateExpression", "REMOVE y");
|
||||
request.put("ReturnValues", "UPDATED_NEW");
|
||||
|
||||
var response = handler.handle("UpdateItem", request, "eu-west-1");
|
||||
var body = mapper.convertValue(response.getEntity(), JsonNode.class);
|
||||
Response response = handler.handle("UpdateItem", request, "eu-west-1");
|
||||
JsonNode body = mapper.convertValue(response.getEntity(), JsonNode.class);
|
||||
assertFalse(body.has("Attributes"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateItemReportsOnlyTheFirstInvalidEnum() {
|
||||
createUsersTable("eu-west-1");
|
||||
var request = updateUserRequest();
|
||||
ObjectNode request = updateUserRequest();
|
||||
request.put("ReturnValues", "INVALID");
|
||||
request.put("ReturnConsumedCapacity", "INVALID");
|
||||
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("UpdateItem", request, "eu-west-1"));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertTrue(ex.getMessage().startsWith("1 validation error detected:"), ex.getMessage());
|
||||
@@ -1327,12 +1327,12 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
|
||||
@Test
|
||||
void updateItemRejectsAnUpdateExpressionOver4096BytesBeforeTheTableLookup() {
|
||||
var request = updateUserRequest();
|
||||
ObjectNode request = updateUserRequest();
|
||||
request.put("TableName", "Missing");
|
||||
request.put("UpdateExpression", "SET " + nameOfBytes(4088) + " = :v");
|
||||
request.set("ExpressionAttributeValues", singleValue(":v"));
|
||||
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("UpdateItem", request, "eu-west-1"));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertEquals("1 validation error detected: Invalid UpdateExpression: "
|
||||
@@ -1342,11 +1342,11 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
@Test
|
||||
void updateItemAcceptsAnUpdateExpressionOfExactly4096Bytes() throws Exception {
|
||||
createUsersTable("eu-west-1");
|
||||
var request = updateUserRequest();
|
||||
ObjectNode request = updateUserRequest();
|
||||
request.put("UpdateExpression", "SET " + nameOfBytes(4087) + " = :v");
|
||||
request.set("ExpressionAttributeValues", singleValue(":v"));
|
||||
|
||||
var response = handler.handle("UpdateItem", request, "eu-west-1");
|
||||
Response response = handler.handle("UpdateItem", request, "eu-west-1");
|
||||
assertEquals(200, response.getStatus());
|
||||
}
|
||||
|
||||
@@ -1370,12 +1370,12 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
@Test
|
||||
void putItemRejectsAConditionExpressionOver4096Bytes() {
|
||||
createUsersTable("eu-west-1");
|
||||
var request = mapper.createObjectNode();
|
||||
ObjectNode request = mapper.createObjectNode();
|
||||
request.put("TableName", "Users");
|
||||
request.set("Item", item("userId", "u1"));
|
||||
request.put("ConditionExpression", "attribute_not_exists(" + nameOfBytes(4075) + ")");
|
||||
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("PutItem", request, "eu-west-1"));
|
||||
assertEquals("1 validation error detected: Invalid ConditionExpression: "
|
||||
+ "Expression size has exceeded the maximum allowed size;", ex.getMessage());
|
||||
@@ -1384,15 +1384,15 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
@Test
|
||||
void queryRejectsAFilterExpressionOver4096Bytes() {
|
||||
createUsersTable("eu-west-1");
|
||||
var request = mapper.createObjectNode();
|
||||
ObjectNode request = mapper.createObjectNode();
|
||||
request.put("TableName", "Users");
|
||||
request.put("KeyConditionExpression", "userId = :pk");
|
||||
request.put("FilterExpression", nameOfBytes(4092) + " = :v");
|
||||
var values = singleValue(":pk");
|
||||
ObjectNode values = singleValue(":pk");
|
||||
values.set(":v", attributeValue("S", "x"));
|
||||
request.set("ExpressionAttributeValues", values);
|
||||
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("Query", request, "eu-west-1"));
|
||||
assertEquals("Invalid FilterExpression: Expression size has exceeded the maximum allowed size;",
|
||||
ex.getMessage());
|
||||
@@ -1401,12 +1401,12 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
@Test
|
||||
void scanRejectsAFilterExpressionOver4096BytesAndReportsTheSize() {
|
||||
createUsersTable("eu-west-1");
|
||||
var request = mapper.createObjectNode();
|
||||
ObjectNode request = mapper.createObjectNode();
|
||||
request.put("TableName", "Users");
|
||||
request.put("FilterExpression", nameOfBytes(4092) + " = :v");
|
||||
request.set("ExpressionAttributeValues", singleValue(":v"));
|
||||
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("Scan", request, "eu-west-1"));
|
||||
assertEquals("Invalid FilterExpression: Expression size has exceeded the maximum allowed size; "
|
||||
+ "expression size: 4097", ex.getMessage());
|
||||
@@ -1415,10 +1415,10 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
@Test
|
||||
void getItemRejectsAProjectionExpressionOver4096Bytes() {
|
||||
createUsersTable("eu-west-1");
|
||||
var request = updateUserRequest();
|
||||
ObjectNode request = updateUserRequest();
|
||||
request.put("ProjectionExpression", nameOfBytes(4097));
|
||||
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("GetItem", request, "eu-west-1"));
|
||||
assertEquals("Invalid ProjectionExpression: Expression size has exceeded the maximum allowed size;",
|
||||
ex.getMessage());
|
||||
@@ -1426,8 +1426,8 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
|
||||
private ObjectNode nestedMaps(int levels) {
|
||||
ObjectNode value = attributeValue("S", "leaf");
|
||||
for (var i = 0; i < levels; i++) {
|
||||
var map = mapper.createObjectNode();
|
||||
for (int i = 0; i < levels; i++) {
|
||||
ObjectNode map = mapper.createObjectNode();
|
||||
map.set("n", value);
|
||||
value = mapper.createObjectNode();
|
||||
value.set("M", map);
|
||||
@@ -1436,9 +1436,9 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
}
|
||||
|
||||
private ObjectNode putRequest(JsonNode value) {
|
||||
var request = mapper.createObjectNode();
|
||||
ObjectNode request = mapper.createObjectNode();
|
||||
request.put("TableName", "Users");
|
||||
var item = item("userId", "u1");
|
||||
ObjectNode item = item("userId", "u1");
|
||||
item.set("data", value);
|
||||
request.set("Item", item);
|
||||
return request;
|
||||
@@ -1451,16 +1451,16 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
void putItemAcceptsAnAttributeWithALeafAtLevel32() throws Exception {
|
||||
createUsersTable("eu-west-1");
|
||||
|
||||
var response = handler.handle("PutItem", putRequest(nestedMaps(31)), "eu-west-1");
|
||||
Response response = handler.handle("PutItem", putRequest(nestedMaps(31)), "eu-west-1");
|
||||
assertEquals(200, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putItemRejectsAnAttributeWithALeafAtLevel33BeforeTheTableLookup() {
|
||||
var request = putRequest(nestedMaps(32));
|
||||
ObjectNode request = putRequest(nestedMaps(32));
|
||||
request.put("TableName", "Missing");
|
||||
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("PutItem", request, "eu-west-1"));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertEquals(NESTING_MESSAGE, ex.getMessage());
|
||||
@@ -1469,15 +1469,15 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
@Test
|
||||
void updateItemRejectsAnExpressionAttributeValueWithALeafAtLevel33() {
|
||||
createUsersTable("eu-west-1");
|
||||
var request = updateUserRequest();
|
||||
ObjectNode request = updateUserRequest();
|
||||
request.put("UpdateExpression", "SET touched = :t");
|
||||
request.put("ConditionExpression", "#d = :deep");
|
||||
request.set("ExpressionAttributeNames", mapper.createObjectNode().put("#d", "data"));
|
||||
var values = singleValue(":t");
|
||||
ObjectNode values = singleValue(":t");
|
||||
values.set(":deep", nestedMaps(32));
|
||||
request.set("ExpressionAttributeValues", values);
|
||||
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("UpdateItem", request, "eu-west-1"));
|
||||
assertEquals(NESTING_MESSAGE, ex.getMessage());
|
||||
}
|
||||
@@ -1502,22 +1502,22 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
|
||||
private ObjectNode transactWrite(String action, ObjectNode op) {
|
||||
op.put("TableName", "Users");
|
||||
var member = mapper.createObjectNode();
|
||||
ObjectNode member = mapper.createObjectNode();
|
||||
member.set(action, op);
|
||||
var request = mapper.createObjectNode();
|
||||
ObjectNode request = mapper.createObjectNode();
|
||||
request.set("TransactItems", mapper.createArrayNode().add(member));
|
||||
return request;
|
||||
}
|
||||
|
||||
@Test
|
||||
void transactWriteItemsRejectsAConditionExpressionOver4096BytesWithTheSizeBeforeTheTableLookup() {
|
||||
var put = mapper.createObjectNode();
|
||||
ObjectNode put = mapper.createObjectNode();
|
||||
put.set("Item", item("userId", "u1"));
|
||||
put.put("ConditionExpression", "attribute_not_exists(" + nameOfBytes(4075) + ")");
|
||||
var request = transactWrite("Put", put);
|
||||
ObjectNode request = transactWrite("Put", put);
|
||||
((ObjectNode) request.get("TransactItems").get(0).get("Put")).put("TableName", "Missing");
|
||||
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("TransactWriteItems", request, "eu-west-1"));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertEquals("Invalid ConditionExpression: Expression size has exceeded the maximum allowed size; "
|
||||
@@ -1540,12 +1540,12 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
@Test
|
||||
void transactWriteItemsRejectsAnUpdateExpressionOver4096Bytes() {
|
||||
createUsersTable("eu-west-1");
|
||||
var update = mapper.createObjectNode();
|
||||
ObjectNode update = mapper.createObjectNode();
|
||||
update.set("Key", item("userId", "u1"));
|
||||
update.put("UpdateExpression", "SET " + nameOfBytes(4088) + " = :v");
|
||||
update.set("ExpressionAttributeValues", singleValue(":v"));
|
||||
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("TransactWriteItems", transactWrite("Update", update), "eu-west-1"));
|
||||
assertEquals("Invalid UpdateExpression: Expression size has exceeded the maximum allowed size;",
|
||||
ex.getMessage());
|
||||
@@ -1554,12 +1554,12 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
@Test
|
||||
void transactWriteItemsRejectsAPutItemWithALeafAtLevel33() {
|
||||
createUsersTable("eu-west-1");
|
||||
var put = mapper.createObjectNode();
|
||||
var item = item("userId", "u1");
|
||||
ObjectNode put = mapper.createObjectNode();
|
||||
ObjectNode item = item("userId", "u1");
|
||||
item.set("data", nestedMaps(32));
|
||||
put.set("Item", item);
|
||||
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("TransactWriteItems", transactWrite("Put", put), "eu-west-1"));
|
||||
assertEquals("Nesting Levels have exceeded supported limits: "
|
||||
+ "Attributes in the item have nested levels beyond supported limit", ex.getMessage());
|
||||
@@ -1567,14 +1567,14 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
|
||||
@Test
|
||||
void batchWriteItemRejectsAPutItemWithALeafAtLevel33BeforeTheTableLookup() {
|
||||
var item = item("userId", "u1");
|
||||
ObjectNode item = item("userId", "u1");
|
||||
item.set("data", nestedMaps(32));
|
||||
var putRequest = mapper.createObjectNode();
|
||||
ObjectNode putRequest = mapper.createObjectNode();
|
||||
putRequest.set("PutRequest", mapper.createObjectNode().set("Item", item));
|
||||
var request = mapper.createObjectNode();
|
||||
ObjectNode request = mapper.createObjectNode();
|
||||
request.set("RequestItems", mapper.createObjectNode().set("Missing", mapper.createArrayNode().add(putRequest)));
|
||||
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("BatchWriteItem", request, "eu-west-1"));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertEquals("Nesting Levels have exceeded supported limits: "
|
||||
@@ -1584,16 +1584,16 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
@Test
|
||||
void transactWriteItemsCancelsOnAnUpdateValueWithALeafAtLevel33() throws Exception {
|
||||
createUsersTable("eu-west-1");
|
||||
var update = mapper.createObjectNode();
|
||||
ObjectNode update = mapper.createObjectNode();
|
||||
update.set("Key", item("userId", "u1"));
|
||||
update.put("UpdateExpression", "SET deep = :deep");
|
||||
update.set("ExpressionAttributeValues", mapper.createObjectNode().set(":deep", nestedMaps(32)));
|
||||
|
||||
var response = handler.handle("TransactWriteItems", transactWrite("Update", update), "eu-west-1");
|
||||
Response response = handler.handle("TransactWriteItems", transactWrite("Update", update), "eu-west-1");
|
||||
assertEquals(400, response.getStatus());
|
||||
var body = mapper.convertValue(response.getEntity(), JsonNode.class);
|
||||
JsonNode body = mapper.convertValue(response.getEntity(), JsonNode.class);
|
||||
assertEquals("TransactionCanceledException", body.get("__type").asText());
|
||||
var reason = body.get("CancellationReasons").get(0);
|
||||
JsonNode reason = body.get("CancellationReasons").get(0);
|
||||
assertEquals("ValidationError", reason.get("Code").asText());
|
||||
assertEquals("Nesting Levels have exceeded supported limits", reason.get("Message").asText());
|
||||
assertNull(service.getItem("Users", item("userId", "u1"), "eu-west-1"));
|
||||
@@ -1602,31 +1602,31 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
@Test
|
||||
void transactWriteItemsDoesNotCheckTheDepthOfAConditionCheckValue() throws Exception {
|
||||
createUsersTable("eu-west-1");
|
||||
var putRequest = mapper.createObjectNode();
|
||||
ObjectNode putRequest = mapper.createObjectNode();
|
||||
putRequest.put("TableName", "Users");
|
||||
putRequest.set("Item", item("userId", "u1", "marker", "x"));
|
||||
handler.handle("PutItem", putRequest, "eu-west-1");
|
||||
var check = mapper.createObjectNode();
|
||||
ObjectNode check = mapper.createObjectNode();
|
||||
check.set("Key", item("userId", "u1"));
|
||||
check.put("ConditionExpression", "#d = :deep");
|
||||
check.set("ExpressionAttributeNames", mapper.createObjectNode().put("#d", "data"));
|
||||
check.set("ExpressionAttributeValues", mapper.createObjectNode().set(":deep", nestedMaps(32)));
|
||||
|
||||
var response = handler.handle("TransactWriteItems", transactWrite("ConditionCheck", check), "eu-west-1");
|
||||
Response response = handler.handle("TransactWriteItems", transactWrite("ConditionCheck", check), "eu-west-1");
|
||||
assertEquals(400, response.getStatus());
|
||||
var reason = mapper.convertValue(response.getEntity(), JsonNode.class).get("CancellationReasons").get(0);
|
||||
JsonNode reason = mapper.convertValue(response.getEntity(), JsonNode.class).get("CancellationReasons").get(0);
|
||||
assertEquals("ConditionalCheckFailed", reason.get("Code").asText());
|
||||
assertEquals("The conditional request failed", reason.get("Message").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateItemRejectsAnOutOfRangeAddOperandBeforeTheTableLookup() {
|
||||
var request = updateUserRequest();
|
||||
ObjectNode request = updateUserRequest();
|
||||
request.put("TableName", "Missing");
|
||||
request.put("UpdateExpression", "ADD n :a");
|
||||
request.set("ExpressionAttributeValues", mapper.createObjectNode().set(":a", attributeValue("N", "1e126")));
|
||||
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("UpdateItem", request, "eu-west-1"));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertEquals("1 validation error detected: Number overflow. "
|
||||
@@ -1636,11 +1636,11 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
@Test
|
||||
void updateItemRejectsATooSmallExpressionAttributeValue() {
|
||||
createUsersTable("eu-west-1");
|
||||
var request = updateUserRequest();
|
||||
ObjectNode request = updateUserRequest();
|
||||
request.put("UpdateExpression", "SET x = :a");
|
||||
request.set("ExpressionAttributeValues", mapper.createObjectNode().set(":a", attributeValue("N", "1e-131")));
|
||||
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("UpdateItem", request, "eu-west-1"));
|
||||
assertEquals("1 validation error detected: Number underflow. "
|
||||
+ "Attempting to store a number with magnitude smaller than supported range", ex.getMessage());
|
||||
@@ -1649,13 +1649,13 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
@Test
|
||||
void updateItemRejectsAnAttributeUpdatesValueWithTooManyDigits() {
|
||||
createUsersTable("eu-west-1");
|
||||
var request = updateUserRequest();
|
||||
var update = mapper.createObjectNode();
|
||||
ObjectNode request = updateUserRequest();
|
||||
ObjectNode update = mapper.createObjectNode();
|
||||
update.put("Action", "ADD");
|
||||
update.set("Value", attributeValue("N", "123456789012345678901234567890123456789"));
|
||||
request.set("AttributeUpdates", mapper.createObjectNode().set("n", update));
|
||||
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("UpdateItem", request, "eu-west-1"));
|
||||
assertEquals("1 validation error detected: Attempting to store more than 38 significant digits in a Number",
|
||||
ex.getMessage());
|
||||
@@ -1664,15 +1664,15 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
@Test
|
||||
void queryRejectsAnOutOfRangeExpressionAttributeValueWithoutTheEnvelope() {
|
||||
createUsersTable("eu-west-1");
|
||||
var request = mapper.createObjectNode();
|
||||
ObjectNode request = mapper.createObjectNode();
|
||||
request.put("TableName", "Users");
|
||||
request.put("KeyConditionExpression", "userId = :p");
|
||||
request.put("FilterExpression", "n = :a");
|
||||
var values = singleValue(":p");
|
||||
ObjectNode values = singleValue(":p");
|
||||
values.set(":a", attributeValue("N", "1e126"));
|
||||
request.set("ExpressionAttributeValues", values);
|
||||
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("Query", request, "eu-west-1"));
|
||||
assertEquals("Number overflow. Attempting to store a number with magnitude larger than supported range",
|
||||
ex.getMessage());
|
||||
@@ -1680,14 +1680,14 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
|
||||
@Test
|
||||
void updateItemRejectsAnAttributeUpdatesValueWithALeafAtLevel33BeforeTheTableLookup() {
|
||||
var request = updateUserRequest();
|
||||
ObjectNode request = updateUserRequest();
|
||||
request.put("TableName", "Missing");
|
||||
var update = mapper.createObjectNode();
|
||||
ObjectNode update = mapper.createObjectNode();
|
||||
update.put("Action", "PUT");
|
||||
update.set("Value", nestedMaps(32));
|
||||
request.set("AttributeUpdates", mapper.createObjectNode().set("data", update));
|
||||
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("UpdateItem", request, "eu-west-1"));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertEquals(NESTING_MESSAGE, ex.getMessage());
|
||||
@@ -1696,11 +1696,11 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
@Test
|
||||
void putItemRejectsAnExpectedValueWithALeafAtLevel33() {
|
||||
createUsersTable("eu-west-1");
|
||||
var request = putRequest(attributeValue("S", "x"));
|
||||
ObjectNode request = putRequest(attributeValue("S", "x"));
|
||||
request.set("Expected", mapper.createObjectNode().set("data",
|
||||
mapper.createObjectNode().set("Value", nestedMaps(32))));
|
||||
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("PutItem", request, "eu-west-1"));
|
||||
assertEquals(NESTING_MESSAGE, ex.getMessage());
|
||||
}
|
||||
@@ -1708,18 +1708,18 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
@Test
|
||||
void queryRejectsAQueryFilterValueWithALeafAtLevel33WithoutTheEnvelope() {
|
||||
createUsersTable("eu-west-1");
|
||||
var request = mapper.createObjectNode();
|
||||
ObjectNode request = mapper.createObjectNode();
|
||||
request.put("TableName", "Users");
|
||||
var keyCondition = mapper.createObjectNode();
|
||||
ObjectNode keyCondition = mapper.createObjectNode();
|
||||
keyCondition.put("ComparisonOperator", "EQ");
|
||||
keyCondition.set("AttributeValueList", mapper.createArrayNode().add(attributeValue("S", "u1")));
|
||||
request.set("KeyConditions", mapper.createObjectNode().set("userId", keyCondition));
|
||||
var filter = mapper.createObjectNode();
|
||||
ObjectNode filter = mapper.createObjectNode();
|
||||
filter.put("ComparisonOperator", "EQ");
|
||||
filter.set("AttributeValueList", mapper.createArrayNode().add(nestedMaps(32)));
|
||||
request.set("QueryFilter", mapper.createObjectNode().set("data", filter));
|
||||
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("Query", request, "eu-west-1"));
|
||||
assertEquals("Nesting Levels have exceeded supported limits: "
|
||||
+ "Attributes in the item have nested levels beyond supported limit", ex.getMessage());
|
||||
@@ -1727,41 +1727,41 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
|
||||
private void seedUpdateReturnValuesItem() throws Exception {
|
||||
createUsersTable("eu-west-1");
|
||||
var parent = mapper.createObjectNode();
|
||||
ObjectNode parent = mapper.createObjectNode();
|
||||
parent.set("keep", attributeValue("S", "k"));
|
||||
parent.set("child", attributeValue("S", "old"));
|
||||
var list = mapper.createArrayNode()
|
||||
ArrayNode list = mapper.createArrayNode()
|
||||
.add(attributeValue("S", "l0")).add(attributeValue("S", "l1")).add(attributeValue("S", "l2"));
|
||||
var item = item("userId", "u1");
|
||||
ObjectNode item = item("userId", "u1");
|
||||
item.set("parent", mapper.createObjectNode().set("M", parent));
|
||||
item.set("l", mapper.createObjectNode().set("L", list));
|
||||
var putRequest = mapper.createObjectNode();
|
||||
ObjectNode putRequest = mapper.createObjectNode();
|
||||
putRequest.put("TableName", "Users");
|
||||
putRequest.set("Item", item);
|
||||
handler.handle("PutItem", putRequest, "eu-west-1");
|
||||
}
|
||||
|
||||
private JsonNode updateAttributes(String expression, ObjectNode values, String returnValues) throws Exception {
|
||||
var request = updateUserRequest();
|
||||
ObjectNode request = updateUserRequest();
|
||||
request.put("UpdateExpression", expression);
|
||||
if (values != null) {
|
||||
request.set("ExpressionAttributeValues", values);
|
||||
}
|
||||
request.put("ReturnValues", returnValues);
|
||||
var body = mapper.convertValue(handler.handle("UpdateItem", request, "eu-west-1").getEntity(), JsonNode.class);
|
||||
JsonNode body = mapper.convertValue(handler.handle("UpdateItem", request, "eu-west-1").getEntity(), JsonNode.class);
|
||||
return body.get("Attributes");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateItemUpdatedNewReturnsTheWholeMapWhenTheMapItselfIsSet() throws Exception {
|
||||
seedUpdateReturnValuesItem();
|
||||
var parent = mapper.createObjectNode();
|
||||
ObjectNode parent = mapper.createObjectNode();
|
||||
parent.set("keep", attributeValue("S", "k"));
|
||||
parent.set("child", attributeValue("S", "new"));
|
||||
var values = mapper.createObjectNode();
|
||||
ObjectNode values = mapper.createObjectNode();
|
||||
values.set(":v", mapper.createObjectNode().set("M", parent));
|
||||
|
||||
var attributes = updateAttributes("SET parent = :v", values, "UPDATED_NEW");
|
||||
JsonNode attributes = updateAttributes("SET parent = :v", values, "UPDATED_NEW");
|
||||
assertEquals("k", attributes.get("parent").get("M").get("keep").get("S").asText());
|
||||
assertEquals("new", attributes.get("parent").get("M").get("child").get("S").asText());
|
||||
}
|
||||
@@ -1769,10 +1769,10 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
@Test
|
||||
void updateItemUpdatedOldReturnsTheWholeOldMapWhenTheMapItselfIsSet() throws Exception {
|
||||
seedUpdateReturnValuesItem();
|
||||
var values = mapper.createObjectNode();
|
||||
ObjectNode values = mapper.createObjectNode();
|
||||
values.set(":v", mapper.createObjectNode().set("M", mapper.createObjectNode().set("child", attributeValue("S", "new"))));
|
||||
|
||||
var attributes = updateAttributes("SET parent = :v", values, "UPDATED_OLD");
|
||||
JsonNode attributes = updateAttributes("SET parent = :v", values, "UPDATED_OLD");
|
||||
assertEquals("k", attributes.get("parent").get("M").get("keep").get("S").asText());
|
||||
assertEquals("old", attributes.get("parent").get("M").get("child").get("S").asText());
|
||||
}
|
||||
@@ -1781,7 +1781,7 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
void updateItemUpdatedNewReturnsANestedSetEvenWhenTheValueDidNotChange() throws Exception {
|
||||
seedUpdateReturnValuesItem();
|
||||
|
||||
var attributes = updateAttributes("SET parent.child = :v", singleValueOf("old"), "UPDATED_NEW");
|
||||
JsonNode attributes = updateAttributes("SET parent.child = :v", singleValueOf("old"), "UPDATED_NEW");
|
||||
assertEquals("old", attributes.get("parent").get("M").get("child").get("S").asText());
|
||||
assertFalse(attributes.get("parent").get("M").has("keep"));
|
||||
}
|
||||
@@ -1789,12 +1789,12 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
@Test
|
||||
void updateItemUpdatedNewPacksTouchedListElementsInIndexOrder() throws Exception {
|
||||
seedUpdateReturnValuesItem();
|
||||
var values = mapper.createObjectNode();
|
||||
ObjectNode values = mapper.createObjectNode();
|
||||
values.set(":v", attributeValue("S", "L2"));
|
||||
values.set(":w", attributeValue("S", "L0"));
|
||||
|
||||
var attributes = updateAttributes("SET l[2] = :v, l[0] = :w", values, "UPDATED_NEW");
|
||||
var packed = attributes.get("l").get("L");
|
||||
JsonNode attributes = updateAttributes("SET l[2] = :v, l[0] = :w", values, "UPDATED_NEW");
|
||||
JsonNode packed = attributes.get("l").get("L");
|
||||
assertEquals(2, packed.size());
|
||||
assertEquals("L0", packed.get(0).get("S").asText());
|
||||
assertEquals("L2", packed.get(1).get("S").asText());
|
||||
@@ -1804,7 +1804,7 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
void updateItemUpdatedNewAfterRemovingAListElementReturnsTheElementNowAtThatIndex() throws Exception {
|
||||
seedUpdateReturnValuesItem();
|
||||
|
||||
var attributes = updateAttributes("REMOVE l[1]", null, "UPDATED_NEW");
|
||||
JsonNode attributes = updateAttributes("REMOVE l[1]", null, "UPDATED_NEW");
|
||||
assertEquals(1, attributes.get("l").get("L").size());
|
||||
assertEquals("l2", attributes.get("l").get("L").get(0).get("S").asText());
|
||||
}
|
||||
@@ -1822,14 +1822,14 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
|
||||
@Test
|
||||
void transactGetItemsRejectsAnOversizedProjectionBeforeTheTableLookup() {
|
||||
var get = mapper.createObjectNode();
|
||||
ObjectNode get = mapper.createObjectNode();
|
||||
get.put("TableName", "Missing");
|
||||
get.set("Key", item("userId", "u1"));
|
||||
get.put("ProjectionExpression", nameOfBytes(4097));
|
||||
var request = mapper.createObjectNode();
|
||||
ObjectNode request = mapper.createObjectNode();
|
||||
request.set("TransactItems", mapper.createArrayNode().add(mapper.createObjectNode().set("Get", get)));
|
||||
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("TransactGetItems", request, "eu-west-1"));
|
||||
assertEquals("Invalid ProjectionExpression: Expression size has exceeded the maximum allowed size;",
|
||||
ex.getMessage());
|
||||
@@ -1899,11 +1899,11 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
@Test
|
||||
void executeStatementRejectsATooDeepParameter() {
|
||||
createUsersTable("eu-west-1");
|
||||
var request = mapper.createObjectNode();
|
||||
ObjectNode request = mapper.createObjectNode();
|
||||
request.put("Statement", "UPDATE \"Users\" SET deep=? WHERE userId=?");
|
||||
request.set("Parameters", mapper.createArrayNode().add(nestedMaps(33)).add(attributeValue("S", "u1")));
|
||||
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("ExecuteStatement", request, "eu-west-1"));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertEquals("Nesting Levels have exceeded supported limits: "
|
||||
@@ -1925,20 +1925,20 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
void executeTransactionCancelsOnAnItemLeftTooDeepWithThatStatementsReason() throws Exception {
|
||||
createUsersTable("eu-west-1");
|
||||
service.putItem("Users", item("userId", "u1"), "eu-west-1");
|
||||
var fine = mapper.createObjectNode();
|
||||
ObjectNode fine = mapper.createObjectNode();
|
||||
fine.put("Statement", "UPDATE \"Users\" SET x=? WHERE userId=?");
|
||||
fine.set("Parameters", mapper.createArrayNode().add(attributeValue("S", "x")).add(attributeValue("S", "u1")));
|
||||
var deep = mapper.createObjectNode();
|
||||
ObjectNode deep = mapper.createObjectNode();
|
||||
deep.put("Statement", "INSERT INTO \"Users\" VALUE {'userId': ?, 'deep': ?}");
|
||||
deep.set("Parameters", mapper.createArrayNode().add(attributeValue("S", "u2")).add(nestedMaps(32)));
|
||||
var request = mapper.createObjectNode();
|
||||
ObjectNode request = mapper.createObjectNode();
|
||||
request.set("TransactStatements", mapper.createArrayNode().add(fine).add(deep));
|
||||
|
||||
var response = handler.handle("ExecuteTransaction", request, "eu-west-1");
|
||||
Response response = handler.handle("ExecuteTransaction", request, "eu-west-1");
|
||||
assertEquals(400, response.getStatus());
|
||||
var body = mapper.convertValue(response.getEntity(), JsonNode.class);
|
||||
JsonNode body = mapper.convertValue(response.getEntity(), JsonNode.class);
|
||||
assertEquals("TransactionCanceledException", body.get("__type").asText());
|
||||
var reasons = body.get("CancellationReasons");
|
||||
JsonNode reasons = body.get("CancellationReasons");
|
||||
assertEquals("None", reasons.get(0).get("Code").asText());
|
||||
assertEquals("ValidationError", reasons.get(1).get("Code").asText());
|
||||
assertEquals("Nesting Levels have exceeded supported limits", reasons.get(1).get("Message").asText());
|
||||
|
||||
+24
-23
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
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;
|
||||
@@ -42,16 +43,16 @@ class ProjectionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void projectsMultipleListIndicesCompactedAndIndexOrdered() {
|
||||
var item = readValue("""
|
||||
ObjectNode item = readValue("""
|
||||
{"mylist": {"L": [{"S": "zero"}, {"S": "one"}, {"S": "two"}]}}
|
||||
""");
|
||||
|
||||
var result = ProjectionEvaluator.project(item, "#l[2], #l[0]",
|
||||
ObjectNode result = ProjectionEvaluator.project(item, "#l[2], #l[0]",
|
||||
readValue("""
|
||||
{"#l": "mylist"}
|
||||
"""));
|
||||
|
||||
var list = result.get("mylist").get("L");
|
||||
JsonNode list = result.get("mylist").get("L");
|
||||
assertEquals(2, list.size(), "both requested elements must survive");
|
||||
assertEquals("zero", list.get(0).get("S").asText());
|
||||
assertEquals("two", list.get(1).get("S").asText());
|
||||
@@ -59,11 +60,11 @@ class ProjectionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void mergesTwoScalarPathsUnderOneListIndex() {
|
||||
var result = ProjectionEvaluator.project(listItem(), "l[0].a, l[0].b", null);
|
||||
ObjectNode result = ProjectionEvaluator.project(listItem(), "l[0].a, l[0].b", null);
|
||||
|
||||
var list = result.get("l").get("L");
|
||||
JsonNode list = result.get("l").get("L");
|
||||
assertEquals(1, list.size());
|
||||
var element = list.get(0).get("M");
|
||||
JsonNode element = list.get(0).get("M");
|
||||
assertEquals("a0", element.get("a").get("S").asText());
|
||||
assertEquals("b0", element.get("b").get("S").asText());
|
||||
assertNull(element.get("m"), "unprojected sibling must be dropped");
|
||||
@@ -71,9 +72,9 @@ class ProjectionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void mergesScalarSiblingAndNestedMapSiblingUnderOneListIndex() {
|
||||
var result = ProjectionEvaluator.project(listItem(), "l[0].a, l[0].m.x", null);
|
||||
ObjectNode result = ProjectionEvaluator.project(listItem(), "l[0].a, l[0].m.x", null);
|
||||
|
||||
var element = result.get("l").get("L").get(0).get("M");
|
||||
JsonNode element = result.get("l").get("L").get(0).get("M");
|
||||
assertEquals("a0", element.get("a").get("S").asText());
|
||||
assertEquals("x0", element.get("m").get("M").get("x").get("S").asText());
|
||||
assertNull(element.get("m").get("M").get("y"), "only x was projected inside m");
|
||||
@@ -82,11 +83,11 @@ class ProjectionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void mergesTwoPathsSharingAnElementOfANestedList() {
|
||||
var result = ProjectionEvaluator.project(listItem(), "l[0].n[0].p, l[0].n[0].q", null);
|
||||
ObjectNode result = ProjectionEvaluator.project(listItem(), "l[0].n[0].p, l[0].n[0].q", null);
|
||||
|
||||
var outer = result.get("l").get("L");
|
||||
JsonNode outer = result.get("l").get("L");
|
||||
assertEquals(1, outer.size());
|
||||
var inner = outer.get(0).get("M").get("n").get("L");
|
||||
JsonNode inner = outer.get(0).get("M").get("n").get("L");
|
||||
assertEquals(1, inner.size(), "both paths share inner index 0");
|
||||
assertEquals("p00", inner.get(0).get("M").get("p").get("S").asText());
|
||||
assertEquals("q00", inner.get(0).get("M").get("q").get("S").asText());
|
||||
@@ -94,9 +95,9 @@ class ProjectionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void keepsDistinctInnerListIndicesSeparateUnderOneSharedOuterIndex() {
|
||||
var result = ProjectionEvaluator.project(listItem(), "l[0].n[0].p, l[0].n[1].q", null);
|
||||
ObjectNode result = ProjectionEvaluator.project(listItem(), "l[0].n[0].p, l[0].n[1].q", null);
|
||||
|
||||
var inner = result.get("l").get("L").get(0).get("M").get("n").get("L");
|
||||
JsonNode inner = result.get("l").get("L").get(0).get("M").get("n").get("L");
|
||||
assertEquals(2, inner.size());
|
||||
assertEquals("p00", inner.get(0).get("M").get("p").get("S").asText());
|
||||
assertNull(inner.get(0).get("M").get("q"));
|
||||
@@ -106,9 +107,9 @@ class ProjectionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void mergesSharedIndexAndKeepsDistinctIndexSeparateCompacted() {
|
||||
var result = ProjectionEvaluator.project(listItem(), "l[0].a, l[0].b, l[2].c", null);
|
||||
ObjectNode result = ProjectionEvaluator.project(listItem(), "l[0].a, l[0].b, l[2].c", null);
|
||||
|
||||
var list = result.get("l").get("L");
|
||||
JsonNode list = result.get("l").get("L");
|
||||
assertEquals(2, list.size(), "index 0 (merged) and index 2 compact to two elements");
|
||||
assertEquals("a0", list.get(0).get("M").get("a").get("S").asText());
|
||||
assertEquals("b0", list.get(0).get("M").get("b").get("S").asText());
|
||||
@@ -118,7 +119,7 @@ class ProjectionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void rejectsNonNumericListIndexAsSyntaxError() {
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> ProjectionEvaluator.project(mapper.createObjectNode(), "l[a]", null));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertEquals("Invalid ProjectionExpression: Syntax error; token: \"a\", near: \"[a]\"",
|
||||
@@ -127,7 +128,7 @@ class ProjectionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void rejectsEmptyListIndexAsSyntaxError() {
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> ProjectionEvaluator.project(mapper.createObjectNode(), "l[]", null));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertEquals("Invalid ProjectionExpression: Syntax error; token: \"]\", near: \"[]\"",
|
||||
@@ -136,7 +137,7 @@ class ProjectionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void rejectsListIndexAboveTheAllowableRange() {
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> ProjectionEvaluator.project(mapper.createObjectNode(), "l[999999999999999999999]", null));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertEquals("Invalid ProjectionExpression: List index is not within the allowable range; "
|
||||
@@ -145,7 +146,7 @@ class ProjectionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void rejectsFirstListIndexPastTheAllowableRange() {
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> ProjectionEvaluator.project(mapper.createObjectNode(), "l[4294967295]", null));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertEquals("Invalid ProjectionExpression: List index is not within the allowable range; "
|
||||
@@ -154,7 +155,7 @@ class ProjectionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void rejectsUnicodeDigitListIndexAsSyntaxError() {
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> ProjectionEvaluator.project(mapper.createObjectNode(), "l[123]", null));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertEquals("Invalid ProjectionExpression: Syntax error; token: \"1\", near: \"[12\"",
|
||||
@@ -163,7 +164,7 @@ class ProjectionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void rejectsLeadingZeroListIndexAsSyntaxError() {
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> ProjectionEvaluator.project(mapper.createObjectNode(), "l[001]", null));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertEquals("Invalid ProjectionExpression: Syntax error; token: \"0\", near: \"001\"",
|
||||
@@ -172,7 +173,7 @@ class ProjectionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void rejectsLongZeroPaddedListIndexAsSyntaxError() {
|
||||
var ex = assertThrows(AwsException.class,
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> ProjectionEvaluator.project(mapper.createObjectNode(), "l[0000000000001]", null));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertEquals("Invalid ProjectionExpression: Syntax error; token: \"0\", near: \"000\"",
|
||||
@@ -181,7 +182,7 @@ class ProjectionEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void allowableIndexBeyondTheListJustDropsTheAttribute() {
|
||||
var result = ProjectionEvaluator.project(listItem(), "l[4294967294]", null);
|
||||
ObjectNode result = ProjectionEvaluator.project(listItem(), "l[4294967294]", null);
|
||||
assertNull(result.get("l"), "an in-range index past the list end matches nothing");
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.services.ec2.model.NetworkInterface;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Tag;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -61,7 +62,7 @@ class Ec2DeregisterAndCopyImageIntegrationTest {
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-west-2/ec2/aws4_request";
|
||||
|
||||
private String ec2(String auth, String action, String... formParams) {
|
||||
var req = given().formParam("Action", action).header("Authorization", auth);
|
||||
RequestSpecification req = given().formParam("Action", action).header("Authorization", auth);
|
||||
for (int i = 0; i < formParams.length; i += 2) {
|
||||
req = req.formParam(formParams[i], formParams[i + 1]);
|
||||
}
|
||||
|
||||
@@ -25,6 +25,8 @@ import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
import io.restassured.response.ExtractableResponse;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -304,7 +306,7 @@ class Ec2IntegrationTest {
|
||||
* absent from the body rather than compared as a value.
|
||||
*/
|
||||
private void assertSynthesizedOwnership(String ownerScope, String expectedId, String expectedAlias) {
|
||||
var response = given()
|
||||
ExtractableResponse<Response> response = given()
|
||||
.formParam("Action", "DescribeImages")
|
||||
.formParam("Owner.1", ownerScope)
|
||||
.formParam("Filter.1.Name", "name")
|
||||
@@ -346,7 +348,7 @@ class Ec2IntegrationTest {
|
||||
void anOwnerAliasFilterAloneStillAgreesWithTheOwnerId() {
|
||||
// The mirror of the above. Filtering on the alias with no Owner.N left the id at the
|
||||
// Amazon default, so the image reported aws-marketplace beside Amazon's account.
|
||||
var response = given()
|
||||
ExtractableResponse<Response> response = given()
|
||||
.formParam("Action", "DescribeImages")
|
||||
.formParam("Filter.1.Name", "name")
|
||||
.formParam("Filter.1.Value.1", "unmatched-alias-filter-only-*")
|
||||
|
||||
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Ipam;
|
||||
import io.github.hectorvent.floci.services.ec2.model.IpamPool;
|
||||
import io.github.hectorvent.floci.services.ec2.model.IpamPoolAllocation;
|
||||
import io.github.hectorvent.floci.services.ec2.model.IpamPoolCidr;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Tag;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -238,7 +239,7 @@ class Ec2IpamServiceTest {
|
||||
assertTrue(pool.getIpamPoolId().startsWith("ipam-pool-"));
|
||||
|
||||
service.provisionIpamPoolCidr(REGION, pool.getIpamPoolId(), "10.0.0.0/8");
|
||||
var cidrs = service.getIpamPoolCidrs(REGION, pool.getIpamPoolId());
|
||||
List<IpamPoolCidr> cidrs = service.getIpamPoolCidrs(REGION, pool.getIpamPoolId());
|
||||
assertEquals(1, cidrs.size());
|
||||
assertEquals("10.0.0.0/8", cidrs.get(0).getCidr());
|
||||
assertEquals("provisioned", cidrs.get(0).getState());
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
@@ -39,7 +40,7 @@ class Ec2ModifyVpcEndpointTest {
|
||||
+ "\"Principal\":\"*\",\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}";
|
||||
|
||||
private String ec2(String action, String... formParams) {
|
||||
var req = given().formParam("Action", action).header("Authorization", AUTH_HEADER);
|
||||
RequestSpecification req = given().formParam("Action", action).header("Authorization", AUTH_HEADER);
|
||||
for (int i = 0; i < formParams.length; i += 2) {
|
||||
req = req.formParam(formParams[i], formParams[i + 1]);
|
||||
}
|
||||
|
||||
+3
-2
@@ -22,6 +22,7 @@ import java.util.Set;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -242,7 +243,7 @@ class Ec2ServiceConcurrencyTest {
|
||||
}));
|
||||
}
|
||||
start.countDown();
|
||||
for (var f : futures) {
|
||||
for (Future<?> f : futures) {
|
||||
f.get(30, TimeUnit.SECONDS);
|
||||
}
|
||||
pool.shutdownNow();
|
||||
@@ -263,7 +264,7 @@ class Ec2ServiceConcurrencyTest {
|
||||
}
|
||||
start.countDown();
|
||||
Set<String> results = new java.util.HashSet<>();
|
||||
for (var f : futures) {
|
||||
for (Future<String> f : futures) {
|
||||
results.add(f.get(30, TimeUnit.SECONDS));
|
||||
}
|
||||
pool.shutdownNow();
|
||||
|
||||
Loaded 100 of 392 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user