Light, fluffy, and always free - The AWS Local Emulator alternative
feat(comprehend): add Amazon Comprehend sync text-analysis actions (#2674)
Ahmed khaled5c1b69c45f7b
diff --git a/README.md b/README.mdindex b8ad2af06f..dd6f277f32 100644--- a/README.md+++ b/README.md@@ -178,7 +178,7 @@ LocalStack's community edition [sunset in March 2026](https://blog.localstack.cl| CodeBuild | Real Docker execution | No || Native binary | ~40 MB | No |-**82 AWS services. Broad coverage. Free forever.**+**83 AWS services. Broad coverage. Free forever.**## Architecture Overviewdiff --git a/docs/index.md b/docs/index.mdindex df9cbbf53c..5a82025717 100644--- a/docs/index.md+++ b/docs/index.md@@ -12,7 +12,7 @@ Floci is a fast, free, and open-source local AWS service emulator built for deve## Supported Services-Floci emulates 82 AWS services. See the [Services Overview](services/index.md) for per-service operation counts, endpoints, and full protocol details.+Floci emulates 83 AWS services. See the [Services Overview](services/index.md) for per-service operation counts, endpoints, and full protocol details.| Service | Protocol ||---|---|@@ -117,7 +117,7 @@ docker compose up -daws --endpoint-url http://localhost:4566 s3 mb s3://my-bucket```-All 82 AWS services are immediately available at `http://localhost:4566`.+All 83 AWS services are immediately available at `http://localhost:4566`.[Get started →](getting-started/quick-start.md){ .md-button .md-button--primary }[View services →](services/index.md){ .md-button }diff --git a/docs/services/comprehend.md b/docs/services/comprehend.mdnew file mode 100644index 0000000000..0778b2b9e0--- /dev/null+++ b/docs/services/comprehend.md@@ -0,0 +1,84 @@+# Comprehend++**Protocol:** JSON 1.1 (`X-Amz-Target: Comprehend_20171127.*`)+**Endpoint:** `POST http://localhost:4566/`++## Supported Actions++<!-- floci:actions:start -->+| Action | Description |+| --- | --- |+| `DetectSentiment` | Detect the overall sentiment of a text (POSITIVE/NEGATIVE/NEUTRAL/MIXED) |+| `DetectKeyPhrases` | Detect key noun-phrases in a text |+| `DetectDominantLanguage` | Detect the dominant language of a text |+| `DetectPiiEntities` | Detect personally identifiable information (PII) in a text |+| `ContainsPiiEntities` | Report whether a text contains PII, without locating it |+<!-- floci:actions:end -->++## Emulation Behavior++- **Stub responses:** every action returns a fixed, AWS-shaped response — no real NLP/ML+ is performed. `DetectSentiment` always returns `NEUTRAL`, `DetectKeyPhrases` always+ returns one stub phrase, `DetectDominantLanguage` always reports `en`, and+ `DetectPiiEntities`/`ContainsPiiEntities` always report no PII found.+- **Real input validation:** `Text` and `LanguageCode` (where applicable) are still+ required and `LanguageCode` is validated against Comprehend's supported set —+ this is protocol compatibility, not content analysis. `DetectSentiment` and+ `DetectKeyPhrases` accept the general set (`en`, `es`, `fr`, `de`, `it`, `pt`,+ `ar`, `hi`, `ja`, `ko`, `zh`, `zh-TW`); `DetectPiiEntities` and+ `ContainsPiiEntities` accept only `en`/`es`, matching AWS's narrower support+ for PII detection.+- **Out of scope:** the async job/model-training surface (`DocumentClassifier`,+ `EntityRecognizer`, `Flywheel`, `Dataset`, `Endpoint` operations), `DetectEntities`,+ and `DetectSyntax` are not implemented.+- **Intentional deviation:** real Comprehend enforces a maximum input size on `Text`+ and returns `TextSizeLimitExceededException` when exceeded. This is not enforced+ here — any non-empty `Text` is accepted regardless of length.++## Configuration++| Variable | Default | Description |+|---|---|---|+| `FLOCI_SERVICES_COMPREHEND_ENABLED` | `true` | Enable or disable the service |++## Examples++```bash+export AWS_ENDPOINT_URL=http://localhost:4566++aws comprehend detect-sentiment \+ --text "Floci makes local AWS testing painless" \+ --language-code en \+ --endpoint-url $AWS_ENDPOINT_URL++aws comprehend detect-key-phrases \+ --text "Floci makes local AWS testing painless" \+ --language-code en \+ --endpoint-url $AWS_ENDPOINT_URL++aws comprehend detect-dominant-language \+ --text "Floci makes local AWS testing painless" \+ --endpoint-url $AWS_ENDPOINT_URL++aws comprehend detect-pii-entities \+ --text "My SSN is 123-45-6789" \+ --language-code en \+ --endpoint-url $AWS_ENDPOINT_URL+```++## SDK Example (Java)++```java+ComprehendClient comprehend = ComprehendClient.builder()+ .endpointOverride(URI.create("http://localhost:4566"))+ .region(Region.US_EAST_1)+ .credentialsProvider(StaticCredentialsProvider.create(+ AwsBasicCredentials.create("test", "test")))+ .build();++DetectSentimentResponse response = comprehend.detectSentiment(req -> req+ .text("Floci makes local AWS testing painless")+ .languageCode("en"));++System.out.println("Sentiment: " + response.sentiment());+```diff --git a/docs/services/index.md b/docs/services/index.mdindex 51ecfb1cc5..d6d602d3a6 100644--- a/docs/services/index.md+++ b/docs/services/index.md@@ -1,6 +1,6 @@# Services Overview-Floci emulates 82 AWS services on a single port (`4566`). All services use the real AWS wire protocol, your existing AWS CLI commands and SDK clients work without modification.+Floci emulates 83 AWS services on a single port (`4566`). All services use the real AWS wire protocol, your existing AWS CLI commands and SDK clients work without modification.This page is the canonical reference for supported service and operation counts. Some services expose separate control-plane and data-plane rows below. Other docs (and the README) should link here rather than duplicating the table.@@ -100,6 +100,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac| [AWS Config](config.md) | `POST /` + `X-Amz-Target: StarlingDoveService.*` | JSON 1.1 | 33 || [CloudTrail](cloudtrail.md) | `POST /` + `X-Amz-Target: com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101.*` | JSON 1.1 | 9 || [Textract](textract.md) | `POST /` + `X-Amz-Target: Textract.*` | JSON 1.1 | 6 |+| [Comprehend](comprehend.md) | `POST /` + `X-Amz-Target: Comprehend_20171127.*` | JSON 1.1 | 5 || [Transcribe](transcribe.md) | `POST /` + `X-Amz-Target: Transcribe.*` | JSON 1.1 | 8 || [Pricing](pricing.md) | `POST /` + `X-Amz-Target: AWSPriceListService.*` | JSON 1.1 | 5 || [Cost Explorer](ce.md) | `POST /` + `X-Amz-Target: AWSInsightsIndexService.*` | JSON 1.1 | 9 |diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex 8fc9f4941b..2697b54758 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -657,6 +657,7 @@ public interface EmulatorConfig {Route53ServiceConfig route53();TransferServiceConfig transfer();TextractServiceConfig textract();+ ComprehendServiceConfig comprehend();PricingServiceConfig pricing();DuckConfig duck();TranscribeServiceConfig transcribe();@@ -1543,6 +1544,11 @@ public interface EmulatorConfig {boolean enabled();}+ interface ComprehendServiceConfig {+ @WithDefault("true")+ boolean enabled();+ }+interface PricingServiceConfig {@WithDefault("true")boolean enabled();diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.javaindex 9d6f2a838b..ee92fda1c3 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java@@ -28,6 +28,7 @@ import io.github.hectorvent.floci.services.configservice.ConfigServiceJsonHandleimport io.github.hectorvent.floci.services.cur.CurJsonHandler;import io.github.hectorvent.floci.services.pricing.PricingJsonHandler;import io.github.hectorvent.floci.services.textract.TextractJsonHandler;+import io.github.hectorvent.floci.services.comprehend.ComprehendJsonHandler;import io.github.hectorvent.floci.services.transcribe.TranscribeJsonHandler;import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2JsonHandler;import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsHandler;@@ -100,6 +101,7 @@ public class AwsJson11Controller {private final Ec2MessagesJsonHandler ec2MessagesJsonHandler;private final TransferHandler transferHandler;private final TextractJsonHandler textractJsonHandler;+ private final ComprehendJsonHandler comprehendJsonHandler;private final PricingJsonHandler pricingJsonHandler;private final TranscribeJsonHandler transcribeJsonHandler;private final CostExplorerJsonHandler costExplorerJsonHandler;@@ -143,6 +145,7 @@ public class AwsJson11Controller {Ec2MessagesJsonHandler ec2MessagesJsonHandler,TransferHandler transferHandler,TextractJsonHandler textractJsonHandler,+ ComprehendJsonHandler comprehendJsonHandler,PricingJsonHandler pricingJsonHandler,TranscribeJsonHandler transcribeJsonHandler,CostExplorerJsonHandler costExplorerJsonHandler,@@ -190,6 +193,7 @@ public class AwsJson11Controller {this.ec2MessagesJsonHandler = ec2MessagesJsonHandler;this.transferHandler = transferHandler;this.textractJsonHandler = textractJsonHandler;+ this.comprehendJsonHandler = comprehendJsonHandler;this.pricingJsonHandler = pricingJsonHandler;this.transcribeJsonHandler = transcribeJsonHandler;this.costExplorerJsonHandler = costExplorerJsonHandler;@@ -268,6 +272,7 @@ public class AwsJson11Controller {case "ec2messages" -> ec2MessagesJsonHandler.handle(action, request, region);case "transfer" -> transferHandler.handle(action, request, region);case "textract" -> textractJsonHandler.handle(action, request, region);+ case "comprehend" -> comprehendJsonHandler.handle(action, request, region);case "pricing" -> pricingJsonHandler.handle(action, request, region);case "transcribe" -> transcribeJsonHandler.handle(action, request, region);case "ce" -> costExplorerJsonHandler.handle(action, request, region);diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.javaindex e3d9953f71..7a72cfd654 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java@@ -446,6 +446,10 @@ public class ResolvedServiceCatalog {null, null, 5000L, null, ServiceProtocol.JSON,protocols(ServiceProtocol.JSON),Set.of("Textract."), Set.of("textract"), Set.of(), Set.of()),+ descriptor("comprehend", "comprehend", config.services().comprehend().enabled(), true,+ null, null, 5000L, null, ServiceProtocol.JSON,+ protocols(ServiceProtocol.JSON),+ Set.of("Comprehend_20171127."), Set.of("comprehend"), Set.of(), Set.of()),descriptor("pricing", "pricing", config.services().pricing().enabled(), true,null, null, 5000L, null, ServiceProtocol.JSON,protocols(ServiceProtocol.JSON),diff --git a/src/main/java/io/github/hectorvent/floci/services/comprehend/ComprehendJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/comprehend/ComprehendJsonHandler.javanew file mode 100644index 0000000000..237ca176da--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/comprehend/ComprehendJsonHandler.java@@ -0,0 +1,68 @@+package io.github.hectorvent.floci.services.comprehend;+import com.fasterxml.jackson.databind.JsonNode;+import io.github.hectorvent.floci.core.common.AwsErrorResponse;+import io.github.hectorvent.floci.core.common.AwsException;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import jakarta.ws.rs.core.Response;+import org.jboss.logging.Logger;+/**+ * JSON 1.1 handler for Amazon Comprehend API operations.+ * Dispatches X-Amz-Target: Comprehend_20171127.* actions to {@link ComprehendService}.+ *+ * @see <a href="https://docs.aws.amazon.com/comprehend/latest/APIReference/Welcome.html">Comprehend API Reference</a>+ */+@ApplicationScoped+public class ComprehendJsonHandler {+ private static final Logger LOG = Logger.getLogger(ComprehendJsonHandler.class);+ private final ComprehendService comprehendService;+ @Inject+ public ComprehendJsonHandler(ComprehendService comprehendService) {+ this.comprehendService = comprehendService;+ }+ /**+ * Dispatches Comprehend actions received via the AwsJson11Controller.+ * Only the sync Detect and ContainsPiiEntities actions are implemented; the+ * async job and model-training surface (DocumentClassifier, EntityRecognizer,+ * Flywheel, Dataset, Endpoint) is out of scope.+ */+ public Response handle(String action, JsonNode request, String region) {+ LOG.debugv("Comprehend action: {0}", action);+ return switch (action) {+ case "DetectSentiment" -> comprehendService.detectSentiment(+ getStringField(request, "Text"), getStringField(request, "LanguageCode"));+ case "DetectKeyPhrases" -> comprehendService.detectKeyPhrases(+ getStringField(request, "Text"), getStringField(request, "LanguageCode"));+ case "DetectDominantLanguage" -> comprehendService.detectDominantLanguage(+ getStringField(request, "Text"));+ case "DetectPiiEntities" -> comprehendService.detectPiiEntities(+ getStringField(request, "Text"), getStringField(request, "LanguageCode"));+ case "ContainsPiiEntities" -> comprehendService.containsPiiEntities(+ getStringField(request, "Text"), getStringField(request, "LanguageCode"));+ default -> Response.status(400)+ .entity(new AwsErrorResponse("UnknownOperationException",+ "Unknown operation: Comprehend_20171127." + action))+ .build();+ };+ }+ /**+ * Extracts a string-typed field. A present-but-wrong-typed value (e.g. a number+ * or boolean where the modeled shape is a string) is a shape/marshalling+ * mismatch caught at the protocol layer, before any operation-specific business+ * validation runs — matching {@code JsonErrorResponseUtils.createSerializationErrorResponse()}'s+ * treatment of a malformed JSON body. It must not be silently coerced via+ * {@code asText()}, nor conflated with a missing field (a modeled business error+ * specific to each operation, handled downstream in {@link ComprehendService}).+ */+ private String getStringField(JsonNode node, String field) {+ JsonNode value = node == null ? null : node.get(field);+ if (value == null || value.isNull()) {+ return null;+ }+ if (!value.isTextual()) {+ throw new AwsException("SerializationException",+ "Unable to unmarshal request; the value for '" + field + "' is not a string.", 400);+ }+ return value.asText();+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/comprehend/ComprehendService.java b/src/main/java/io/github/hectorvent/floci/services/comprehend/ComprehendService.javanew file mode 100644index 0000000000..8b34a67f47--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/comprehend/ComprehendService.java@@ -0,0 +1,122 @@+package io.github.hectorvent.floci.services.comprehend;+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 jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import jakarta.ws.rs.core.Response;+import java.util.Set;+/**+ * Dummy response builder for Amazon Comprehend. Stateless — every sync Detect*+ * action ignores the actual Text content and returns a fixed but AWS-shaped+ * response. Input validation (Text/LanguageCode required, supported language+ * codes) still follows real Comprehend behavior, since that is protocol+ * compatibility rather than NLP logic.+ * <p>+ * Real detection logic (lexicon/regex based) is a planned follow-up; see the+ * tracking issue for scope.+ *+ * @see <a href="https://docs.aws.amazon.com/comprehend/latest/APIReference/Welcome.html">Comprehend API Reference</a>+ */+@ApplicationScoped+public class ComprehendService {+ /** Languages accepted by DetectSentiment/DetectKeyPhrases. */+ private static final Set<String> SUPPORTED_LANGUAGE_CODES = Set.of(+ "en", "es", "fr", "de", "it", "pt", "ar", "hi", "ja", "ko", "zh", "zh-TW");+ /**+ * Languages accepted by DetectPiiEntities/ContainsPiiEntities — a narrower set than the+ * general LanguageCode enum. AWS's own operation docs for DetectPiiEntitiesRequest.LanguageCode+ * state: "Enter the language code for English (en) or Spanish (es)."+ */+ private static final Set<String> PII_SUPPORTED_LANGUAGE_CODES = Set.of("en", "es");+ private final ObjectMapper objectMapper;+ @Inject+ public ComprehendService(ObjectMapper objectMapper) {+ this.objectMapper = objectMapper;+ }+ /**+ * DetectSentiment — always returns NEUTRAL with flat confidence scores.+ * Response shape: https://docs.aws.amazon.com/comprehend/latest/APIReference/API_DetectSentiment.html+ */+ public Response detectSentiment(String text, String languageCode) {+ requireText(text);+ requireLanguageCode(languageCode, SUPPORTED_LANGUAGE_CODES);+ ObjectNode root = objectMapper.createObjectNode();+ root.put("Sentiment", "NEUTRAL");+ ObjectNode score = root.putObject("SentimentScore");+ score.put("Positive", 0.1);+ score.put("Negative", 0.1);+ score.put("Neutral", 0.7);+ score.put("Mixed", 0.1);+ return Response.ok(root).build();+ }+ /**+ * DetectKeyPhrases — always returns a single stub key phrase.+ * Response shape: https://docs.aws.amazon.com/comprehend/latest/APIReference/API_DetectKeyPhrases.html+ */+ public Response detectKeyPhrases(String text, String languageCode) {+ requireText(text);+ requireLanguageCode(languageCode, SUPPORTED_LANGUAGE_CODES);+ ObjectNode root = objectMapper.createObjectNode();+ ArrayNode keyPhrases = root.putArray("KeyPhrases");+ ObjectNode phrase = keyPhrases.addObject();+ phrase.put("Score", 0.99);+ phrase.put("Text", "Floci");+ phrase.put("BeginOffset", 0);+ phrase.put("EndOffset", 5);+ return Response.ok(root).build();+ }+ /**+ * DetectDominantLanguage — always reports English. Takes no LanguageCode input.+ * Response shape: https://docs.aws.amazon.com/comprehend/latest/APIReference/API_DetectDominantLanguage.html+ */+ public Response detectDominantLanguage(String text) {+ requireText(text);+ ObjectNode root = objectMapper.createObjectNode();+ ArrayNode languages = root.putArray("Languages");+ ObjectNode language = languages.addObject();+ language.put("LanguageCode", "en");+ language.put("Score", 0.99);+ return Response.ok(root).build();+ }+ /**+ * DetectPiiEntities — always reports no PII found (an empty result is a+ * legitimate real response for PII-free text, unlike a fabricated match).+ * Response shape: https://docs.aws.amazon.com/comprehend/latest/APIReference/API_DetectPiiEntities.html+ */+ public Response detectPiiEntities(String text, String languageCode) {+ requireText(text);+ requireLanguageCode(languageCode, PII_SUPPORTED_LANGUAGE_CODES);+ ObjectNode root = objectMapper.createObjectNode();+ root.putArray("Entities");+ return Response.ok(root).build();+ }+ /**+ * ContainsPiiEntities — always reports no PII labels found.+ * Response shape: https://docs.aws.amazon.com/comprehend/latest/APIReference/API_ContainsPiiEntities.html+ */+ public Response containsPiiEntities(String text, String languageCode) {+ requireText(text);+ requireLanguageCode(languageCode, PII_SUPPORTED_LANGUAGE_CODES);+ ObjectNode root = objectMapper.createObjectNode();+ root.putArray("Labels");+ return Response.ok(root).build();+ }+ // Private helpers+ private void requireText(String text) {+ if (text == null || text.isEmpty()) {+ throw new AwsException("InvalidRequestException", "Text is a required field.", 400);+ }+ }+ private void requireLanguageCode(String languageCode, Set<String> allowedLanguageCodes) {+ if (languageCode == null || languageCode.isEmpty()) {+ throw new AwsException("InvalidRequestException", "LanguageCode is a required field.", 400);+ }+ if (!allowedLanguageCodes.contains(languageCode)) {+ throw new AwsException("UnsupportedLanguageException",+ "Confidence score for language code \"" + languageCode+ + "\" is not supported.", 400);+ }+ }+}diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex 7f050bcf27..9304d659e8 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -506,6 +506,8 @@ floci:enabled: truetextract:enabled: true+ comprehend:+ enabled: truepricing:enabled: truetranscribe:diff --git a/src/test/java/io/github/hectorvent/floci/services/comprehend/ComprehendIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/comprehend/ComprehendIntegrationTest.javanew file mode 100644index 0000000000..ee68cc0d5b--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/comprehend/ComprehendIntegrationTest.java@@ -0,0 +1,203 @@+package io.github.hectorvent.floci.services.comprehend;+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;+import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.*;+/**+ * Integration tests for the Amazon Comprehend stub.+ * Validates AWS-compatible wire format using RestAssured.+ * Protocol: JSON 1.1 — Content-Type: application/x-amz-json-1.1, X-Amz-Target: Comprehend_20171127.<Action>+ */+@QuarkusTest+class ComprehendIntegrationTest {+ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }+ private static final String CONTENT_TYPE = "application/x-amz-json-1.1";+ private static final String AUTH_HEADER =+ "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/comprehend/aws4_request";+ @Test+ void detectSentiment_returnsNeutralWithScores() {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Comprehend_20171127.DetectSentiment")+ .header("Authorization", AUTH_HEADER)+ .body("{\"Text\":\"Floci makes local AWS testing painless\",\"LanguageCode\":\"en\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("Sentiment", equalTo("NEUTRAL"))+ .body("SentimentScore.Positive", notNullValue())+ .body("SentimentScore.Negative", notNullValue())+ .body("SentimentScore.Neutral", notNullValue())+ .body("SentimentScore.Mixed", notNullValue());+ }+ @Test+ void detectSentiment_missingText_returns400() {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Comprehend_20171127.DetectSentiment")+ .header("Authorization", AUTH_HEADER)+ .body("{\"LanguageCode\":\"en\"}")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidRequestException"));+ }+ @Test+ void detectSentiment_unsupportedLanguage_returns400() {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Comprehend_20171127.DetectSentiment")+ .header("Authorization", AUTH_HEADER)+ .body("{\"Text\":\"hello\",\"LanguageCode\":\"xx\"}")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("UnsupportedLanguageException"));+ }+ @Test+ void detectSentiment_nonStringText_returnsSerializationException() {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Comprehend_20171127.DetectSentiment")+ .header("Authorization", AUTH_HEADER)+ .body("{\"Text\":12345,\"LanguageCode\":\"en\"}")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("SerializationException"));+ }+ @Test+ void detectSentiment_nonStringLanguageCode_returnsSerializationException() {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Comprehend_20171127.DetectSentiment")+ .header("Authorization", AUTH_HEADER)+ .body("{\"Text\":\"hello\",\"LanguageCode\":true}")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("SerializationException"));+ }+ @Test+ void detectKeyPhrases_returnsStubPhrase() {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Comprehend_20171127.DetectKeyPhrases")+ .header("Authorization", AUTH_HEADER)+ .body("{\"Text\":\"Floci makes local AWS testing painless\",\"LanguageCode\":\"en\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("KeyPhrases", hasSize(1))+ .body("KeyPhrases[0].Text", equalTo("Floci"))+ .body("KeyPhrases[0].Score", notNullValue())+ .body("KeyPhrases[0].BeginOffset", notNullValue())+ .body("KeyPhrases[0].EndOffset", notNullValue());+ }+ @Test+ void detectDominantLanguage_doesNotRequireLanguageCode() {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Comprehend_20171127.DetectDominantLanguage")+ .header("Authorization", AUTH_HEADER)+ .body("{\"Text\":\"Floci makes local AWS testing painless\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("Languages", hasSize(1))+ .body("Languages[0].LanguageCode", equalTo("en"))+ .body("Languages[0].Score", notNullValue());+ }+ @Test+ void detectDominantLanguage_missingText_returns400() {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Comprehend_20171127.DetectDominantLanguage")+ .header("Authorization", AUTH_HEADER)+ .body("{}")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidRequestException"));+ }+ @Test+ void detectPiiEntities_returnsEmptyEntities() {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Comprehend_20171127.DetectPiiEntities")+ .header("Authorization", AUTH_HEADER)+ .body("{\"Text\":\"My SSN is 123-45-6789\",\"LanguageCode\":\"en\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("Entities", hasSize(0));+ }+ @Test+ void detectPiiEntities_rejectsLanguageOutsideEnEs() {+ // DetectPiiEntities/ContainsPiiEntities support only en/es, unlike the general+ // 12-language set accepted by DetectSentiment/DetectKeyPhrases.+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Comprehend_20171127.DetectPiiEntities")+ .header("Authorization", AUTH_HEADER)+ .body("{\"Text\":\"My SSN is 123-45-6789\",\"LanguageCode\":\"fr\"}")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("UnsupportedLanguageException"));+ }+ @Test+ void containsPiiEntities_rejectsLanguageOutsideEnEs() {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Comprehend_20171127.ContainsPiiEntities")+ .header("Authorization", AUTH_HEADER)+ .body("{\"Text\":\"My SSN is 123-45-6789\",\"LanguageCode\":\"fr\"}")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("UnsupportedLanguageException"));+ }+ @Test+ void containsPiiEntities_returnsEmptyLabels() {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Comprehend_20171127.ContainsPiiEntities")+ .header("Authorization", AUTH_HEADER)+ .body("{\"Text\":\"My SSN is 123-45-6789\",\"LanguageCode\":\"en\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("Labels", hasSize(0));+ }+ @Test+ void unknownAction_returnsUnknownOperationError() {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Comprehend_20171127.DetectEntities")+ .header("Authorization", AUTH_HEADER)+ .body("{}")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("UnknownOperationException"));+ }+}diff --git a/src/test/resources/application.yml b/src/test/resources/application.ymlindex 18d0082723..7df748f452 100644--- a/src/test/resources/application.yml+++ b/src/test/resources/application.yml@@ -296,6 +296,8 @@ floci:enabled: truetextract:enabled: true+ comprehend:+ enabled: truepricing:enabled: truece:diff --git a/tools/docs/services.yaml b/tools/docs/services.yamlindex 84d8c317af..6940695a9b 100644--- a/tools/docs/services.yaml+++ b/tools/docs/services.yaml@@ -34,6 +34,10 @@ services:doc: docs/services/cloudtrail.mdsources:- { path: src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailJsonHandler.java, mode: switch }+ - service: comprehend+ doc: docs/services/comprehend.md+ sources:+ - { path: src/main/java/io/github/hectorvent/floci/services/comprehend/ComprehendJsonHandler.java, mode: switch }- service: docdbdoc: docs/services/docdb.mdsources: