feat(comprehend): add Amazon Comprehend sync text-analysis actions (#2674)

* feat(comprehend): add Amazon Comprehend sync text-analysis actions

Implements DetectSentiment, DetectKeyPhrases, DetectDominantLanguage,
DetectPiiEntities, and ContainsPiiEntities as fixed AWS-shaped stub
responses over the real JSON 1.1 wire protocol
(X-Amz-Target: Comprehend_20171127.*). Input validation (Text and
LanguageCode required, LanguageCode checked against Comprehend's
supported set) matches real API behavior and raises
InvalidRequestException/UnsupportedLanguageException per
botocore's declared error shapes.

The async job/model-training surface (DocumentClassifier,
EntityRecognizer, Flywheel, Dataset, Endpoint) and DetectEntities/
DetectSyntax are out of scope for this PR. Real (non-stub) detection
logic is planned as a follow-up once this lands.

Closes #2660

* fix(comprehend): restrict PII detection to en/es language codes

DetectPiiEntities and ContainsPiiEntities were validated against the
full 12-language set shared with DetectSentiment/DetectKeyPhrases, but
AWS's own operation docs for DetectPiiEntitiesRequest.LanguageCode
state PII detection only supports English (en) and Spanish (es).
Split the allowlist so the two PII operations reject other languages
with UnsupportedLanguageException, matching real Comprehend behavior.

Addresses review feedback on #2674.

* fix(comprehend): reject non-string Text/LanguageCode as SerializationException

getStringField() coerced any JSON value via asText() instead of
enforcing the modeled string type, so a numeric or boolean Text/
LanguageCode silently succeeded instead of being rejected. Reuses the
codebase's existing SerializationException convention (see
JsonErrorResponseUtils.createSerializationErrorResponse()) since a
wrong-typed field is a shape/marshalling mismatch caught before
business logic runs, distinct from a missing field (InvalidRequestException,
a modeled business error). Scoped to ComprehendJsonHandler only.

Addresses review feedback on #2674.
This commit is contained in:
Ahmed khaled authored and GitHub committed 2026-08-28 18:47:22 -04:00
1 parent 882992deb6
commit 5c1b69c45f
13 files changed
+505 -4

No files matched your search

+1 -1
View File
@@ -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 Overview
+2 -2
View File
@@ -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 -d
aws --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 }
+84
View File
@@ -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());
```
+2 -1
View File
@@ -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 |
@@ -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();
@@ -28,6 +28,7 @@ import io.github.hectorvent.floci.services.configservice.ConfigServiceJsonHandle
import 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);
@@ -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),
@@ -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();
}
}
@@ -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);
}
}
}
+2
View File
@@ -506,6 +506,8 @@ floci:
enabled: true
textract:
enabled: true
comprehend:
enabled: true
pricing:
enabled: true
transcribe:
@@ -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"));
}
}
+2
View File
@@ -296,6 +296,8 @@ floci:
enabled: true
textract:
enabled: true
comprehend:
enabled: true
pricing:
enabled: true
ce:
+4
View File
@@ -34,6 +34,10 @@ services:
doc: docs/services/cloudtrail.md
sources:
- { 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: docdb
doc: docs/services/docdb.md
sources: