Light, fluffy, and always free - The AWS Local Emulator alternative
feat(textract): add Textract service support and integration tests (#719)
Roméod7ec2b284f05
diff --git a/README.md b/README.mdindex 006c190812..7c6cba60d6 100644--- a/README.md+++ b/README.md@@ -255,12 +255,13 @@ All default images are configurable via environment variables, useful for pinnin| **AWS Backup** | In-process | Vaults, backup plans with rules, resource selections, on-demand jobs with simulated lifecycle (CREATED → RUNNING → COMPLETED), recovery points, tagging || **Route53** | In-process | Hosted zones with auto-created SOA + NS records, resource record sets (CREATE/UPSERT/DELETE with atomic validation), change tracking (always INSYNC), health checks, and per-resource tagging || **Transfer Family** | In-process | Server lifecycle (`CreateServer` / `DeleteServer` / `StartServer` / `StopServer` / `UpdateServer`), user management, SSH public key import, and tagging |+| **Textract** | In-process (stub) | API-compatible stubs for all operations; dummy block data with realistic shape and metadata; async job simulation with immediate SUCCEEDED status |> **Lambda, ElastiCache, RDS, MSK, ECS, EC2, EKS, OpenSearch, and CodeBuild** spin up real Docker containers and support IAM authentication and SigV4 request signing — the same auth flow as production AWS. **ECR** runs a shared `registry:2` container so the stock `docker` client can push and pull image bytes against repositories returned by the AWS-shaped control plane.>> For per-service operation counts and endpoint protocols, see the [Services Overview](https://floci.io/floci/services/) in the documentation site.-**45 AWS services supported.**+**46 AWS services supported.**## Persistence & Storage Modesdiff --git a/docs/services/textract.md b/docs/services/textract.mdnew file mode 100644index 0000000000..2ce3f124f9--- /dev/null+++ b/docs/services/textract.md@@ -0,0 +1,98 @@+# Textract++**Protocol:** JSON 1.1+**Header:** `X-Amz-Target: Textract.<Action>`++Floci emulates the AWS Textract API with a dummy response stub. The response shape matches the real AWS Textract contracts so AWS SDK and CLI clients accept the reply without error. No real OCR or document analysis is performed: every call returns a fixed set of `Block` objects with synthetic metadata.++## Supported Operations++| Operation | Notes |+|-----------|-------|+| `DetectDocumentText` | Returns stub PAGE + LINE + WORD blocks |+| `AnalyzeDocument` | Returns stub blocks; `FeatureTypes` accepted but ignored |+| `StartDocumentTextDetection` | Returns a `JobId`; job is immediately SUCCEEDED |+| `GetDocumentTextDetection` | Returns `SUCCEEDED` + stub blocks for a known `JobId` |+| `StartDocumentAnalysis` | Returns a `JobId`; job is immediately SUCCEEDED |+| `GetDocumentAnalysis` | Returns `SUCCEEDED` + stub blocks for a known `JobId` |++`Document` and `DocumentLocation` inputs (bytes or S3 references) are accepted but not parsed.++### Block shape++Each response includes a 3-block hierarchy matching the [AWS Block API shape](https://docs.aws.amazon.com/textract/latest/dg/API_Block.html):++| BlockType | Text | Relationships |+|-----------|------|---------------|+| `PAGE` | *(none)* | CHILD → LINE |+| `LINE` | `"Floci"` | CHILD → WORD |+| `WORD` | `"Floci"` | *(none)* |++Every block includes: `Id` (UUID), `Confidence` (99.9), `Page` (1), and a `Geometry` with `BoundingBox` + 4-point `Polygon`.++### Async job lifecycle++`Start*` operations store a job ID in memory and return it immediately. `Get*` calls with a valid job ID always return `JobStatus: SUCCEEDED`. Job IDs are not persisted across restarts. Using a `GetDocumentTextDetection` job ID in `GetDocumentAnalysis` (or vice-versa) returns `InvalidJobIdException`.++## Configuration++```yaml+floci:+ services:+ textract:+ enabled: true+```++## Examples++```bash+export AWS_ENDPOINT_URL=http://localhost:4566+export AWS_DEFAULT_REGION=us-east-1+export AWS_ACCESS_KEY_ID=test+export AWS_SECRET_ACCESS_KEY=test++# DetectDocumentText+aws textract detect-document-text \+ --document '{"S3Object":{"Bucket":"my-bucket","Name":"test.pdf"}}'++# AnalyzeDocument+aws textract analyze-document \+ --document '{"S3Object":{"Bucket":"my-bucket","Name":"test.pdf"}}' \+ --feature-types TABLES FORMS++# Async: start + poll+JOB_ID=$(aws textract start-document-text-detection \+ --document-location '{"S3Object":{"Bucket":"my-bucket","Name":"test.pdf"}}' \+ --query JobId --output text)++aws textract get-document-text-detection --job-id "$JOB_ID"+```++```python+import boto3++client = boto3.client("textract", endpoint_url="http://localhost:4566")++# Sync+resp = client.detect_document_text(+ Document={"S3Object": {"Bucket": "my-bucket", "Name": "test.pdf"}}+)+for block in resp["Blocks"]:+ print(block["BlockType"], block.get("Text", ""))++# Async+job = client.start_document_text_detection(+ DocumentLocation={"S3Object": {"Bucket": "my-bucket", "Name": "test.pdf"}}+)+result = client.get_document_text_detection(JobId=job["JobId"])+print(result["JobStatus"]) # SUCCEEDED+```++## Out of Scope++- Real OCR or document analysis (always returns a fixed stub block list).+- `AnalyzeExpense`, `AnalyzeID`, `AnalyzeLendingDocument` and other specialized analysis operations.+- `GetAdapterVersion`, `CreateAdapter`, `ListAdapters` (Adapter management API).+- `GetDocumentTextDetection` / `GetDocumentAnalysis` pagination via `NextToken`.+- Persistent job storage across restarts.+diff --git a/pom.xml b/pom.xmlindex b110e78289..d52e23e592 100644--- a/pom.xml+++ b/pom.xml@@ -231,6 +231,10 @@<artifactId>rds</artifactId><scope>test</scope></dependency>+ <dependency>+ <groupId>com.fasterxml.jackson.core</groupId>+ <artifactId>jackson-annotations</artifactId>+ </dependency></dependencies><build>diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex 450c13ef3e..130eda17e9 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -284,6 +284,7 @@ public interface EmulatorConfig {BackupServiceConfig backup();Route53ServiceConfig route53();TransferServiceConfig transfer();+ TextractServiceConfig textract();}interface TransferServiceConfig {@@ -619,6 +620,11 @@ public interface EmulatorConfig {boolean enabled();}+ interface TextractServiceConfig {+ @WithDefault("true")+ boolean enabled();+ }+interface EcrServiceConfig {@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 f27c2be0a3..30b69be19c 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@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.ecs.EcsJsonHandler;import io.github.hectorvent.floci.services.firehose.FirehoseJsonHandler;import io.github.hectorvent.floci.services.glue.GlueJsonHandler;import io.github.hectorvent.floci.services.resourcegroupstagging.ResourceGroupsTaggingJsonHandler;+import io.github.hectorvent.floci.services.textract.TextractJsonHandler;import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2JsonHandler;import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsHandler;import io.github.hectorvent.floci.services.cognito.CognitoJsonHandler;@@ -64,6 +65,7 @@ public class AwsJson11Controller {private final CodeDeployJsonHandler codeDeployJsonHandler;private final Ec2MessagesJsonHandler ec2MessagesJsonHandler;private final TransferHandler transferHandler;+ private final TextractJsonHandler textractJsonHandler;@Injectpublic AwsJson11Controller(ObjectMapper objectMapper, ResolvedServiceCatalog catalog,@@ -82,7 +84,8 @@ public class AwsJson11Controller {CodeBuildJsonHandler codeBuildJsonHandler,CodeDeployJsonHandler codeDeployJsonHandler,Ec2MessagesJsonHandler ec2MessagesJsonHandler,- TransferHandler transferHandler) {+ TransferHandler transferHandler,+ TextractJsonHandler textractJsonHandler) {this.objectMapper = objectMapper;this.catalog = catalog;this.regionResolver = regionResolver;@@ -105,6 +108,7 @@ public class AwsJson11Controller {this.codeDeployJsonHandler = codeDeployJsonHandler;this.ec2MessagesJsonHandler = ec2MessagesJsonHandler;this.transferHandler = transferHandler;+ this.textractJsonHandler = textractJsonHandler;}@POST@@ -152,6 +156,7 @@ public class AwsJson11Controller {case "codedeploy" -> codeDeployJsonHandler.handle(action, request, region);case "ec2messages" -> ec2MessagesJsonHandler.handle(action, request, region);case "transfer" -> transferHandler.handle(action, request, region);+ case "textract" -> textractJsonHandler.handle(action, request, region);default -> null;};// catalog.matchTarget is protocol-agnostic: a JSON 1.0 targetdiff --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 f928b5e3f2..3ea52c0401 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@@ -239,7 +239,11 @@ public class ResolvedServiceCatalog {descriptor("route53", "route53", config.services().route53().enabled(), true,"route53", config.storage().mode(), 5000L, null, ServiceProtocol.REST_XML,protocols(ServiceProtocol.REST_XML),- Set.of(), Set.of("route53"), Set.of(), Set.of(Route53Controller.class))+ Set.of(), Set.of("route53"), Set.of(), Set.of(Route53Controller.class)),+ descriptor("textract", "textract", config.services().textract().enabled(), true,+ null, null, 5000L, null, ServiceProtocol.JSON,+ protocols(ServiceProtocol.JSON),+ Set.of("Textract."), Set.of("textract"), Set.of(), Set.of())));}diff --git a/src/main/java/io/github/hectorvent/floci/services/textract/TextractJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/textract/TextractJsonHandler.javanew file mode 100644index 0000000000..a982c0de61--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/textract/TextractJsonHandler.java@@ -0,0 +1,47 @@+package io.github.hectorvent.floci.services.textract;+import com.fasterxml.jackson.databind.JsonNode;+import io.github.hectorvent.floci.core.common.AwsErrorResponse;+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 Textract API operations.+ * Dispatches X-Amz-Target: Textract.* actions to {@link TextractService}.+ *+ * @see <a href="https://docs.aws.amazon.com/textract/latest/dg/API_Operations.html">Textract API Reference</a>+ */+@ApplicationScoped+public class TextractJsonHandler {+ private static final Logger LOG = Logger.getLogger(TextractJsonHandler.class);+ private final TextractService textractService;+ @Inject+ public TextractJsonHandler(TextractService textractService) {+ this.textractService = textractService;+ }+ /**+ * Dispatches Textract actions received via the AwsJson11Controller.+ * The request body is accepted but not parsed — stub ignores document input.+ */+ public Response handle(String action, JsonNode request, String region) {+ LOG.debugv("Textract action: {0}", action);+ return switch (action) {+ case "DetectDocumentText" -> textractService.detectDocumentText();+ case "AnalyzeDocument" -> textractService.analyzeDocument();+ case "StartDocumentTextDetection" -> textractService.startDocumentTextDetection();+ case "GetDocumentTextDetection" -> textractService.getDocumentTextDetection(+ getStringField(request, "JobId"));+ case "StartDocumentAnalysis" -> textractService.startDocumentAnalysis();+ case "GetDocumentAnalysis" -> textractService.getDocumentAnalysis(+ getStringField(request, "JobId"));+ default -> Response.status(400)+ .entity(new AwsErrorResponse("UnknownOperationException",+ "Unknown operation: Textract." + action))+ .build();+ };+ }+ private String getStringField(JsonNode node, String field) {+ JsonNode value = node == null ? null : node.get(field);+ return (value != null && !value.isNull()) ? value.asText() : null;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/textract/TextractService.java b/src/main/java/io/github/hectorvent/floci/services/textract/TextractService.javanew file mode 100644index 0000000000..1f1841e83d--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/textract/TextractService.java@@ -0,0 +1,201 @@+package io.github.hectorvent.floci.services.textract;+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.UUID;+import java.util.concurrent.ConcurrentHashMap;+/**+ * Dummy response builder for Amazon Textract. Stateless for sync operations.+ * Async operations (Start* and Get*) use an in-memory job store.+ * No real OCR or document analysis is performed: every call returns a fixed+ * stub Block list matching the AWS Textract wire format.+ *+ * @see <a href="https://docs.aws.amazon.com/textract/latest/dg/API_Operations.html">Textract API Reference</a>+ */+@ApplicationScoped+public class TextractService {+ static final String MODEL_VERSION = "1.0";+ private final ObjectMapper objectMapper;+ /** In-memory async job store: jobId to jobType ("TEXT_DETECTION" or "DOCUMENT_ANALYSIS"). */+ private final ConcurrentHashMap<String, String> asyncJobs = new ConcurrentHashMap<>();+ @Inject+ public TextractService(ObjectMapper objectMapper) {+ this.objectMapper = objectMapper;+ }+ /**+ * DetectDocumentText — returns a stub PAGE + LINE + WORD block hierarchy.+ * Response shape: https://docs.aws.amazon.com/textract/latest/dg/API_DetectDocumentText.html+ */+ public Response detectDocumentText() {+ ObjectNode root = objectMapper.createObjectNode();+ root.set("DocumentMetadata", buildDocumentMetadata(1));+ root.set("Blocks", buildStubBlocks());+ root.put("DetectDocumentTextModelVersion", MODEL_VERSION);+ return Response.ok(root).build();+ }+ /**+ * AnalyzeDocument — returns the same stub blocks; FeatureTypes are accepted but ignored.+ * Response shape: https://docs.aws.amazon.com/textract/latest/dg/API_AnalyzeDocument.html+ */+ public Response analyzeDocument() {+ ObjectNode root = objectMapper.createObjectNode();+ root.set("DocumentMetadata", buildDocumentMetadata(1));+ root.set("Blocks", buildStubBlocks());+ root.put("AnalyzeDocumentModelVersion", MODEL_VERSION);+ return Response.ok(root).build();+ }+ /**+ * StartDocumentTextDetection — enqueues a fake async job and immediately marks it SUCCEEDED.+ * Response shape: https://docs.aws.amazon.com/textract/latest/dg/API_StartDocumentTextDetection.html+ */+ public Response startDocumentTextDetection() {+ String jobId = UUID.randomUUID().toString();+ asyncJobs.put(jobId, "TEXT_DETECTION");+ ObjectNode root = objectMapper.createObjectNode();+ root.put("JobId", jobId);+ return Response.ok(root).build();+ }+ /**+ * GetDocumentTextDetection — returns SUCCEEDED + stub blocks for any known JobId.+ * Response shape: https://docs.aws.amazon.com/textract/latest/dg/API_GetDocumentTextDetection.html+ */+ public Response getDocumentTextDetection(String jobId) {+ requireKnownJob(jobId, "TEXT_DETECTION");+ ObjectNode root = objectMapper.createObjectNode();+ root.put("JobStatus", "SUCCEEDED");+ root.set("DocumentMetadata", buildDocumentMetadata(1));+ root.set("Blocks", buildStubBlocks());+ root.put("DetectDocumentTextModelVersion", MODEL_VERSION);+ //after a successful job, we remove it to avoid memory growth+ asyncJobs.remove(jobId);+ return Response.ok(root).build();+ }+ /**+ * StartDocumentAnalysis — enqueues a fake async job and immediately marks it SUCCEEDED.+ * Response shape: https://docs.aws.amazon.com/textract/latest/dg/API_StartDocumentAnalysis.html+ */+ public Response startDocumentAnalysis() {+ String jobId = UUID.randomUUID().toString();+ asyncJobs.put(jobId, "DOCUMENT_ANALYSIS");+ ObjectNode root = objectMapper.createObjectNode();+ root.put("JobId", jobId);+ return Response.ok(root).build();+ }+ /**+ * GetDocumentAnalysis — returns SUCCEEDED + stub blocks for any known JobId.+ * Response shape: https://docs.aws.amazon.com/textract/latest/dg/API_GetDocumentAnalysis.html+ */+ public Response getDocumentAnalysis(String jobId) {+ requireKnownJob(jobId, "DOCUMENT_ANALYSIS");+ ObjectNode root = objectMapper.createObjectNode();+ root.put("JobStatus", "SUCCEEDED");+ root.set("DocumentMetadata", buildDocumentMetadata(1));+ root.set("Blocks", buildStubBlocks());+ root.put("AnalyzeDocumentModelVersion", MODEL_VERSION);++ //after a successful job, we remove it to avoid memory growth+ asyncJobs.remove(jobId);++ return Response.ok(root).build();+ }+ // Private helpers+ private void requireKnownJob(String jobId, String expectedType) {+ if (jobId == null || jobId.isBlank()) {+ throw new AwsException("ValidationException", "JobId is required.", 400);+ }+ String type = asyncJobs.get(jobId);+ if (type == null) {+ throw new AwsException("InvalidJobIdException",+ "An invalid job identifier was passed to an Amazon Textract operation.", 400);+ }+ if (!expectedType.equals(type)) {+ throw new AwsException("InvalidJobIdException",+ "Job was not started by the correct operation.", 400);+ }+ }+ private ObjectNode buildDocumentMetadata(int pages) {+ ObjectNode meta = objectMapper.createObjectNode();+ meta.put("Pages", pages);+ return meta;+ }+ /**+ * Builds a minimal AWS-shaped Block hierarchy: PAGE to LINE to WORD.+ * Each Block follows https://docs.aws.amazon.com/textract/latest/dg/API_Block.html+ */+ private ArrayNode buildStubBlocks() {+ ArrayNode blocks = objectMapper.createArrayNode();+ String wordId = UUID.randomUUID().toString();+ String lineId = UUID.randomUUID().toString();+ String pageId = UUID.randomUUID().toString();+ // WORD block+ ObjectNode word = objectMapper.createObjectNode();+ word.put("BlockType", "WORD");+ word.put("Id", wordId);+ word.put("Confidence", 99.9);+ word.put("Text", "Floci");+ word.set("Geometry", buildGeometry(0.1, 0.1, 0.15, 0.05));+ word.put("Page", 1);+ blocks.add(word);+ // LINE block (child: WORD)+ ObjectNode line = objectMapper.createObjectNode();+ line.put("BlockType", "LINE");+ line.put("Id", lineId);+ line.put("Confidence", 99.9);+ line.put("Text", "Floci");+ line.set("Geometry", buildGeometry(0.1, 0.1, 0.15, 0.05));+ line.set("Relationships", buildRelationships("CHILD", wordId));+ line.put("Page", 1);+ blocks.add(line);+ // PAGE block (child: LINE)+ ObjectNode page = objectMapper.createObjectNode();+ page.put("BlockType", "PAGE");+ page.put("Id", pageId);+ page.put("Confidence", 99.9);+ page.set("Geometry", buildGeometry(0.0, 0.0, 1.0, 1.0));+ page.set("Relationships", buildRelationships("CHILD", lineId));+ page.put("Page", 1);+ blocks.add(page);+ return blocks;+ }+ /**+ * Builds a Geometry object with BoundingBox and a 4-point Polygon.+ * @see <a href="https://docs.aws.amazon.com/textract/latest/dg/API_Geometry.html">Geometry</a>+ */+ private ObjectNode buildGeometry(double left, double top, double width, double height) {+ ObjectNode geometry = objectMapper.createObjectNode();+ ObjectNode bbox = geometry.putObject("BoundingBox");+ bbox.put("Width", width);+ bbox.put("Height", height);+ bbox.put("Left", left);+ bbox.put("Top", top);+ ArrayNode polygon = geometry.putArray("Polygon");+ addPoint(polygon, left, top);+ addPoint(polygon, left + width, top);+ addPoint(polygon, left + width, top + height);+ addPoint(polygon, left, top + height);+ return geometry;+ }+ private void addPoint(ArrayNode polygon, double x, double y) {+ ObjectNode point = polygon.addObject();+ point.put("X", x);+ point.put("Y", y);+ }+ /**+ * Builds a single Relationship entry.+ * @see <a href="https://docs.aws.amazon.com/textract/latest/dg/API_Relationship.html">Relationship</a>+ */+ private ArrayNode buildRelationships(String type, String... childIds) {+ ArrayNode relationships = objectMapper.createArrayNode();+ ObjectNode rel = relationships.addObject();+ rel.put("Type", type);+ ArrayNode ids = rel.putArray("Ids");+ for (String id : childIds) {+ ids.add(id);+ }+ return relationships;+ }+}diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex 4ea1567a17..1022d66127 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -248,3 +248,5 @@ floci:enabled: truetransfer:enabled: true+ textract:+ enabled: truediff --git a/src/test/java/io/github/hectorvent/floci/services/textract/TextractIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/textract/TextractIntegrationTest.javanew file mode 100644index 0000000000..a506d5fbfa--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/textract/TextractIntegrationTest.java@@ -0,0 +1,419 @@+package io.github.hectorvent.floci.services.textract;+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.*;+import static org.hamcrest.MatcherAssert.assertThat;+/**+ * Integration tests for the Amazon Textract stub.+ * Validates AWS-compatible wire format using RestAssured.+ * Protocol: JSON 1.1 — Content-Type: application/x-amz-json-1.1, X-Amz-Target: Textract.<Action>+ */+@QuarkusTest+class TextractIntegrationTest {+ @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/textract/aws4_request";+ @Test+ void detectDocumentText_returnsBlocksAndDocumentMetadata() {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.DetectDocumentText")+ .header("Authorization", AUTH_HEADER)+ .body("{\"Document\":{\"S3Object\":{\"Bucket\":\"my-bucket\",\"Name\":\"test.pdf\"}}}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("DocumentMetadata.Pages", equalTo(1))+ .body("DetectDocumentTextModelVersion", equalTo("1.0"))+ .body("Blocks", hasSize(3))+ .body("Blocks.BlockType", hasItems("PAGE", "LINE", "WORD"));+ }+ @Test+ void detectDocumentText_blockShapesAreAwsCompatible() {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.DetectDocumentText")+ .header("Authorization", AUTH_HEADER)+ .body("{}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("Blocks[0].Id", notNullValue())+ .body("Blocks[0].Confidence", notNullValue())+ .body("Blocks[0].Geometry.BoundingBox.Width", notNullValue())+ .body("Blocks[0].Geometry.BoundingBox.Height", notNullValue())+ .body("Blocks[0].Geometry.BoundingBox.Left", notNullValue())+ .body("Blocks[0].Geometry.BoundingBox.Top", notNullValue())+ .body("Blocks[0].Geometry.Polygon", hasSize(4));+ }+ @Test+ void analyzeDocument_returnsBlocksAndModelVersion() {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.AnalyzeDocument")+ .header("Authorization", AUTH_HEADER)+ .body("{\"Document\":{\"S3Object\":{\"Bucket\":\"my-bucket\",\"Name\":\"test.pdf\"}},\"FeatureTypes\":[\"TABLES\",\"FORMS\"]}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("DocumentMetadata.Pages", equalTo(1))+ .body("AnalyzeDocumentModelVersion", equalTo("1.0"))+ .body("Blocks", hasSize(3))+ .body("Blocks.BlockType", hasItems("PAGE", "LINE", "WORD"));+ }+ @Test+ void asyncTextDetection_startAndGetSucceeded() {+ String jobId = given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.StartDocumentTextDetection")+ .header("Authorization", AUTH_HEADER)+ .body("{\"DocumentLocation\":{\"S3Object\":{\"Bucket\":\"my-bucket\",\"Name\":\"test.pdf\"}}}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("JobId", notNullValue())+ .extract().path("JobId");+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.GetDocumentTextDetection")+ .header("Authorization", AUTH_HEADER)+ .body("{\"JobId\":\"" + jobId + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("JobStatus", equalTo("SUCCEEDED"))+ .body("DocumentMetadata.Pages", equalTo(1))+ .body("DetectDocumentTextModelVersion", equalTo("1.0"))+ .body("Blocks", hasSize(3));+ }+ @Test+ void getDocumentTextDetection_unknownJobId_returns400() {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.GetDocumentTextDetection")+ .header("Authorization", AUTH_HEADER)+ .body("{\"JobId\":\"non-existent-job-id\"}")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidJobIdException"));+ }+ @Test+ void getDocumentTextDetection_missingJobId_returns400() {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.GetDocumentTextDetection")+ .header("Authorization", AUTH_HEADER)+ .body("{}")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"));+ }+ @Test+ void asyncDocumentAnalysis_startAndGetSucceeded() {+ String jobId = given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.StartDocumentAnalysis")+ .header("Authorization", AUTH_HEADER)+ .body("{\"DocumentLocation\":{\"S3Object\":{\"Bucket\":\"my-bucket\",\"Name\":\"test.pdf\"}},\"FeatureTypes\":[\"TABLES\"]}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("JobId", notNullValue())+ .extract().path("JobId");+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.GetDocumentAnalysis")+ .header("Authorization", AUTH_HEADER)+ .body("{\"JobId\":\"" + jobId + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("JobStatus", equalTo("SUCCEEDED"))+ .body("DocumentMetadata.Pages", equalTo(1))+ .body("AnalyzeDocumentModelVersion", equalTo("1.0"))+ .body("Blocks", hasSize(3));+ }+ @Test+ void getDocumentAnalysis_wrongJobType_returns400() {+ String jobId = given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.StartDocumentTextDetection")+ .header("Authorization", AUTH_HEADER)+ .body("{}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().path("JobId");+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.GetDocumentAnalysis")+ .header("Authorization", AUTH_HEADER)+ .body("{\"JobId\":\"" + jobId + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidJobIdException"));+ }+ @Test+ void unknownAction_returnsUnknownOperationError() {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.DetectSentiment")+ .header("Authorization", AUTH_HEADER)+ .body("{}")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("UnknownOperationException"));+ }++ @Test+ void analyzeDocument_blockShapesAreAwsCompatible() {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.AnalyzeDocument")+ .header("Authorization", AUTH_HEADER)+ .body("{\"Document\":{\"S3Object\":{\"Bucket\":\"my-bucket\",\"Name\":\"test.pdf\"}},\"FeatureTypes\":[\"TABLES\"]}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("Blocks[0].Id", notNullValue())+ .body("Blocks[0].Geometry.BoundingBox.Width", notNullValue())+ .body("Blocks[0].Geometry.Polygon", hasSize(4));+ }++ @Test+ void analyzeDocument_featureTypesIsOptional() {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.AnalyzeDocument")+ .header("Authorization", AUTH_HEADER)+ .body("{}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("DocumentMetadata.Pages", equalTo(1))+ .body("AnalyzeDocumentModelVersion", equalTo("1.0"));+ }++ @Test+ void detectDocumentText_wordBlockHasText() {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.DetectDocumentText")+ .header("Authorization", AUTH_HEADER)+ .body("{}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("Blocks.findAll { it.BlockType == 'WORD' }.Text", hasItem("Floci"));+ }++ @Test+ void detectDocumentText_confidenceIsPresent() {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.DetectDocumentText")+ .header("Authorization", AUTH_HEADER)+ .body("{}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("Blocks.Confidence", everyItem(notNullValue()));+ }++ @Test+ void detectDocumentText_eachBlockHasPageNumber() {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.DetectDocumentText")+ .header("Authorization", AUTH_HEADER)+ .body("{}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("Blocks.Page", everyItem(equalTo(1)));+ }++ @Test+ void getDocumentAnalysis_unknownJobId_returns400() {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.GetDocumentAnalysis")+ .header("Authorization", AUTH_HEADER)+ .body("{\"JobId\":\"non-existent-job-id\"}")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidJobIdException"));+ }++ @Test+ void getDocumentAnalysis_missingJobId_returns400() {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.GetDocumentAnalysis")+ .header("Authorization", AUTH_HEADER)+ .body("{}")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"));+ }++ @Test+ void getDocumentTextDetection_wrongJobType_returns400() {+ // Start a DocumentAnalysis job, then try to get it as TextDetection+ String jobId = given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.StartDocumentAnalysis")+ .header("Authorization", AUTH_HEADER)+ .body("{\"FeatureTypes\":[\"TABLES\"]}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().path("JobId");++ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.GetDocumentTextDetection")+ .header("Authorization", AUTH_HEADER)+ .body("{\"JobId\":\"" + jobId + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidJobIdException"));+ }++ @Test+ void asyncTextDetection_jobIdIsUnique() {+ String jobId1 = given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.StartDocumentTextDetection")+ .header("Authorization", AUTH_HEADER)+ .body("{}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().path("JobId");++ String jobId2 = given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.StartDocumentTextDetection")+ .header("Authorization", AUTH_HEADER)+ .body("{}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().path("JobId");++ assertThat(jobId1, not(equalTo(jobId2)));+ }++ @Test+ void asyncDocumentAnalysis_jobIdIsUnique() {+ String jobId1 = given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.StartDocumentAnalysis")+ .header("Authorization", AUTH_HEADER)+ .body("{\"FeatureTypes\":[\"TABLES\"]}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().path("JobId");++ String jobId2 = given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.StartDocumentAnalysis")+ .header("Authorization", AUTH_HEADER)+ .body("{\"FeatureTypes\":[\"FORMS\"]}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().path("JobId");++ assertThat(jobId1, not(equalTo(jobId2)));+ }++ @Test+ void getDocumentTextDetection_returnsCorrectModelVersion() {+ String jobId = given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.StartDocumentTextDetection")+ .header("Authorization", AUTH_HEADER)+ .body("{}")+ .when()+ .post("/")+ .then()+ .extract().path("JobId");++ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.GetDocumentTextDetection")+ .header("Authorization", AUTH_HEADER)+ .body("{\"JobId\":\"" + jobId + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("DetectDocumentTextModelVersion", equalTo("1.0"));+ }++ @Test+ void getDocumentAnalysis_returnsCorrectModelVersion() {+ String jobId = given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.StartDocumentAnalysis")+ .header("Authorization", AUTH_HEADER)+ .body("{\"FeatureTypes\":[\"TABLES\"]}")+ .when()+ .post("/")+ .then()+ .extract().path("JobId");++ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "Textract.GetDocumentAnalysis")+ .header("Authorization", AUTH_HEADER)+ .body("{\"JobId\":\"" + jobId + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("AnalyzeDocumentModelVersion", equalTo("1.0"));+ }+}diff --git a/src/test/resources/application.yml b/src/test/resources/application.ymlindex 27398ce875..e4006591b4 100644--- a/src/test/resources/application.yml+++ b/src/test/resources/application.yml@@ -169,3 +169,5 @@ floci:job-completion-delay-seconds: 1route53:enabled: true+ textract:+ enabled: true