mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(translate): add Amazon Translate mock service (#2879)
* feat(translate): add Amazon Translate mock service JSON 1.1 stub for Amazon Translate covering the three self-contained sync operations: TranslateText, TranslateDocument, ListLanguages. Follows the existing Comprehend/Textract stub pattern (stateless, echoes input, AI_MOCK_CONFIG override for TranslateText). - TranslateText echoes Text, enforces the 10,000-byte limit, allows any language pair; an auto source is reported back as en. - TranslateDocument echoes the base64 Content and enforces the English-pivot rule, the ContentType allow-list, valid base64, and the 100 KB cap (InvalidRequestException, matching the operation's error model). The encoded length is checked before decoding so an oversized payload cannot force a large allocation. - ListLanguages returns a fixed ~35-language catalog; DisplayLanguageCode is validated, pagination inputs are accepted but ignored. Untrusted request values are truncated before being echoed into error messages. * chore(translate): remove em-dashes per AGENTS.md style guide Replace em-dashes in the Translate doc page and Java comments with colons, commas, or periods, and the ellipsis in the error-message preview helper with "...". Addresses the Greptile review note on PR #2879.
This commit is contained in:
1 parent
c32f8b5a24
commit
10192f05d5
15 files changed
+842
-9
No files matched your search
@@ -190,7 +190,7 @@ LocalStack's community edition [sunset in March 2026](https://blog.localstack.cl
|
||||
| CodeBuild | Real Docker execution | No |
|
||||
| Native binary | ~40 MB | No |
|
||||
|
||||
**84 AWS services. Broad coverage. Free forever.**
|
||||
**85 AWS services. Broad coverage. Free forever.**
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
|
||||
+2
-2
@@ -12,7 +12,7 @@ Floci is a fast, free, and open-source local AWS service emulator built for deve
|
||||
|
||||
## Supported Services
|
||||
|
||||
Floci emulates 84 AWS services. See the [Services Overview](services/index.md) for per-service operation counts, endpoints, and full protocol details.
|
||||
Floci emulates 85 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 84 AWS services are immediately available at `http://localhost:4566`.
|
||||
All 85 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 }
|
||||
@@ -1,6 +1,6 @@
|
||||
# Services Overview
|
||||
|
||||
Floci emulates 84 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 85 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.
|
||||
|
||||
@@ -105,6 +105,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
|
||||
| [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 |
|
||||
| [Rekognition](rekognition.md) | `POST /` + `X-Amz-Target: RekognitionService.*` | JSON 1.1 | 5 |
|
||||
| [Translate](translate.md) | `POST /` + `X-Amz-Target: AWSShineFrontendService_20170701.*` | JSON 1.1 | 3 |
|
||||
| [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 |
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
# Translate
|
||||
|
||||
**Protocol:** JSON 1.1 (`X-Amz-Target: AWSShineFrontendService_20170701.*`)
|
||||
**Endpoint:** `POST http://localhost:4566/`
|
||||
|
||||
## Supported Actions
|
||||
|
||||
<!-- floci:actions:start -->
|
||||
| Action | Description |
|
||||
| --- | --- |
|
||||
| `TranslateText` | Translate a UTF-8 text string between two languages |
|
||||
| `TranslateDocument` | Translate a document (≤100 KB) supplied as a base64 blob |
|
||||
| `ListLanguages` | List the language codes and names Floci recognizes |
|
||||
<!-- floci:actions:end -->
|
||||
|
||||
## Emulation Behavior
|
||||
|
||||
- **No machine translation:** `TranslateText` returns the request `Text` verbatim as
|
||||
`TranslatedText`, and `TranslateDocument` returns the request `Document.Content` bytes
|
||||
unchanged as `TranslatedDocument.Content`. To exercise logic that branches on a specific
|
||||
translation, use the mock config below.
|
||||
- **Language detection:** a `SourceLanguageCode` of `auto` is accepted and reported back
|
||||
as `en` (the stub's fixed "detected" language); no Comprehend call is made.
|
||||
- **Real input validation:** `Text` / `Document.Content` / `Document.ContentType` and both
|
||||
language codes are required. `SourceLanguageCode` must be `auto` or a code from the
|
||||
catalog returned by `ListLanguages`; `TargetLanguageCode` must be a catalog code. An
|
||||
unknown code returns `UnsupportedLanguagePairException`.
|
||||
- `TranslateText` rejects a `Text` longer than 10,000 UTF-8 bytes with
|
||||
`TextSizeLimitExceededException`, matching AWS. Any language pair is allowed
|
||||
(`TranslateText` is any-to-any).
|
||||
- `TranslateDocument` requires an **English pivot**: either the source or the target
|
||||
language must resolve to `en`, otherwise it returns `UnsupportedLanguagePairException`.
|
||||
It also rejects a `ContentType` other than `text/plain`, `text/html`, or the
|
||||
Word (`.docx`) MIME type, a `Content` that is not valid base64, and a decoded
|
||||
document over 100 KB, all with `InvalidRequestException` (`TranslateDocument` does
|
||||
not model `TextSizeLimitExceededException`).
|
||||
- **Fixed catalog:** `ListLanguages` returns a curated ~35-language subset of Translate's
|
||||
full list, enough to drive an i18n pipeline. `MaxResults` / `NextToken` are accepted
|
||||
but ignored (the whole catalog fits in one page, so no `NextToken` is returned).
|
||||
`DisplayLanguageCode` is validated against the AWS enum
|
||||
(`de`, `en`, `es`, `fr`, `it`, `ja`, `ko`, `pt`, `zh`, `zh-TW`) but every `LanguageName`
|
||||
is returned in English regardless.
|
||||
- **Out of scope:** custom terminology, parallel data, asynchronous batch translation jobs
|
||||
(`StartTextTranslationJob` and friends), and tagging, all needing persistent state.
|
||||
- **Deviation:** `ListLanguages` always returns `LanguageName`s in English regardless of
|
||||
`DisplayLanguageCode` (real Translate localizes them), and the `Formality` /
|
||||
`Profanity` / `Brevity` translation settings are accepted but ignored.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Variable | Default | Description |
|
||||
|---|---|---|
|
||||
| `FLOCI_SERVICES_TRANSLATE_ENABLED` | `true` | Enable or disable the service |
|
||||
| `AI_MOCK_CONFIG` | unset | Path to a shared mock-response config file; see "Mock Responses" below |
|
||||
|
||||
## Mock Responses
|
||||
|
||||
To return a real translated string instead of the echoed input, point `AI_MOCK_CONFIG` at a
|
||||
JSON file shared across Translate, Comprehend, Textract, and Rekognition:
|
||||
|
||||
```json
|
||||
{
|
||||
"translate": {
|
||||
"Hello world": {
|
||||
"TranslateText": { "TranslatedText": "Hola mundo", "SourceLanguageCode": "en", "TargetLanguageCode": "es" }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The lookup key is the **exact `Text` value** sent in the request, so only `TranslateText`
|
||||
can be mocked; `TranslateDocument` carries a binary payload with no stable key. The file is
|
||||
re-read when its modification time changes, so it can be edited without restarting the
|
||||
emulator. A missing file, an unset `AI_MOCK_CONFIG`, or no matching entry all fall back to
|
||||
the echoed-input default. Mocking is opt-in and never breaks a call that isn't using it.
|
||||
|
||||
## Examples
|
||||
|
||||
```bash
|
||||
export AWS_ENDPOINT_URL=http://localhost:4566
|
||||
|
||||
aws translate translate-text \
|
||||
--text "Floci makes local AWS testing painless" \
|
||||
--source-language-code en \
|
||||
--target-language-code fr \
|
||||
--endpoint-url $AWS_ENDPOINT_URL
|
||||
|
||||
aws translate list-languages \
|
||||
--endpoint-url $AWS_ENDPOINT_URL
|
||||
```
|
||||
|
||||
## SDK Example (Java)
|
||||
|
||||
```java
|
||||
TranslateClient translate = TranslateClient.builder()
|
||||
.endpointOverride(URI.create("http://localhost:4566"))
|
||||
.region(Region.US_EAST_1)
|
||||
.credentialsProvider(StaticCredentialsProvider.create(
|
||||
AwsBasicCredentials.create("test", "test")))
|
||||
.build();
|
||||
|
||||
TranslateTextResponse response = translate.translateText(req -> req
|
||||
.text("Floci makes local AWS testing painless")
|
||||
.sourceLanguageCode("en")
|
||||
.targetLanguageCode("fr"));
|
||||
|
||||
System.out.println("Translated: " + response.translatedText());
|
||||
```
|
||||
@@ -679,6 +679,7 @@ public interface EmulatorConfig {
|
||||
PricingServiceConfig pricing();
|
||||
DuckConfig duck();
|
||||
TranscribeServiceConfig transcribe();
|
||||
TranslateServiceConfig translate();
|
||||
CostExplorerServiceConfig ce();
|
||||
CurServiceConfig cur();
|
||||
BcmDataExportsServiceConfig bcmDataExports();
|
||||
@@ -1607,6 +1608,11 @@ public interface EmulatorConfig {
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface TranslateServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface PricingServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
@@ -15,8 +15,8 @@ import java.util.Optional;
|
||||
/**
|
||||
* Loads the shared mock-response configuration file referenced by {@code AI_MOCK_CONFIG}
|
||||
* or {@code floci.ai-mock-config-file}, used by the fixed-stub AI services (Textract,
|
||||
* Comprehend, Rekognition) to return a caller-configured response instead of their default
|
||||
* canned stub. The file is re-read when its modification time changes, so it can be edited
|
||||
* Comprehend, Rekognition, Translate) to return a caller-configured response instead of their
|
||||
* default canned stub. The file is re-read when its modification time changes, so it can be edited
|
||||
* without restarting the emulator — same mechanism as {@code SfnMockLoader}.
|
||||
* <p>
|
||||
* Unlike {@code SfnMockLoader} (where the mock configuration is the only way to run a
|
||||
@@ -27,8 +27,8 @@ import java.util.Optional;
|
||||
* default response.
|
||||
* <p>
|
||||
* Config file shape: {@code {"<serviceKey>": {"<lookupKey>": {"<Action>": <response>}}}}.
|
||||
* See {@code docs/services/textract.md} / {@code comprehend.md} / {@code rekognition.md}
|
||||
* "Mock Responses" sections for each service's lookup-key convention.
|
||||
* See {@code docs/services/textract.md} / {@code comprehend.md} / {@code rekognition.md} /
|
||||
* {@code translate.md} "Mock Responses" sections for each service's lookup-key convention.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class AiMockConfigLoader {
|
||||
|
||||
@@ -31,6 +31,7 @@ import io.github.hectorvent.floci.services.textract.TextractJsonHandler;
|
||||
import io.github.hectorvent.floci.services.comprehend.ComprehendJsonHandler;
|
||||
import io.github.hectorvent.floci.services.rekognition.RekognitionJsonHandler;
|
||||
import io.github.hectorvent.floci.services.transcribe.TranscribeJsonHandler;
|
||||
import io.github.hectorvent.floci.services.translate.TranslateJsonHandler;
|
||||
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;
|
||||
@@ -106,6 +107,7 @@ public class AwsJson11Controller {
|
||||
private final RekognitionJsonHandler rekognitionJsonHandler;
|
||||
private final PricingJsonHandler pricingJsonHandler;
|
||||
private final TranscribeJsonHandler transcribeJsonHandler;
|
||||
private final TranslateJsonHandler translateJsonHandler;
|
||||
private final CostExplorerJsonHandler costExplorerJsonHandler;
|
||||
private final CurJsonHandler curJsonHandler;
|
||||
private final BcmDataExportsJsonHandler bcmDataExportsJsonHandler;
|
||||
@@ -151,6 +153,7 @@ public class AwsJson11Controller {
|
||||
RekognitionJsonHandler rekognitionJsonHandler,
|
||||
PricingJsonHandler pricingJsonHandler,
|
||||
TranscribeJsonHandler transcribeJsonHandler,
|
||||
TranslateJsonHandler translateJsonHandler,
|
||||
CostExplorerJsonHandler costExplorerJsonHandler,
|
||||
CurJsonHandler curJsonHandler,
|
||||
BcmDataExportsJsonHandler bcmDataExportsJsonHandler,
|
||||
@@ -200,6 +203,7 @@ public class AwsJson11Controller {
|
||||
this.rekognitionJsonHandler = rekognitionJsonHandler;
|
||||
this.pricingJsonHandler = pricingJsonHandler;
|
||||
this.transcribeJsonHandler = transcribeJsonHandler;
|
||||
this.translateJsonHandler = translateJsonHandler;
|
||||
this.costExplorerJsonHandler = costExplorerJsonHandler;
|
||||
this.curJsonHandler = curJsonHandler;
|
||||
this.bcmDataExportsJsonHandler = bcmDataExportsJsonHandler;
|
||||
@@ -280,6 +284,7 @@ public class AwsJson11Controller {
|
||||
case "rekognition" -> rekognitionJsonHandler.handle(action, request, region);
|
||||
case "pricing" -> pricingJsonHandler.handle(action, request, region);
|
||||
case "transcribe" -> transcribeJsonHandler.handle(action, request, region);
|
||||
case "translate" -> translateJsonHandler.handle(action, request, region);
|
||||
case "ce" -> costExplorerJsonHandler.handle(action, request, region);
|
||||
case "cur" -> curJsonHandler.handle(action, request, region);
|
||||
case "bcm-data-exports" -> bcmDataExportsJsonHandler.handle(action, request, region);
|
||||
|
||||
@@ -476,6 +476,10 @@ public class ResolvedServiceCatalog {
|
||||
config.storage().services().transcribe().flushIntervalMs(), null, ServiceProtocol.JSON,
|
||||
protocols(ServiceProtocol.JSON),
|
||||
Set.of("Transcribe."), Set.of("transcribe"), Set.of(), Set.of()),
|
||||
descriptor("translate", "translate", config.services().translate().enabled(), true,
|
||||
null, null, 5000L, null, ServiceProtocol.JSON,
|
||||
protocols(ServiceProtocol.JSON),
|
||||
Set.of("AWSShineFrontendService_20170701."), Set.of("translate"), Set.of(), Set.of()),
|
||||
descriptor("ce", "ce", config.services().ce().enabled(), true,
|
||||
null, null, 5000L, null, ServiceProtocol.JSON,
|
||||
protocols(ServiceProtocol.JSON),
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package io.github.hectorvent.floci.services.translate;
|
||||
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 Translate API operations.
|
||||
* Dispatches X-Amz-Target: AWSShineFrontendService_20170701.* actions to {@link TranslateService}.
|
||||
*
|
||||
* @see <a href="https://docs.aws.amazon.com/translate/latest/APIReference/welcome.html">Translate API Reference</a>
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class TranslateJsonHandler {
|
||||
private static final Logger LOG = Logger.getLogger(TranslateJsonHandler.class);
|
||||
private final TranslateService translateService;
|
||||
@Inject
|
||||
public TranslateJsonHandler(TranslateService translateService) {
|
||||
this.translateService = translateService;
|
||||
}
|
||||
/**
|
||||
* Dispatches Translate actions received via the AwsJson11Controller. Only the three
|
||||
* self-contained sync actions are implemented; the terminology, parallel-data, async
|
||||
* batch-job, and tagging surface (all of which need persistent state) is out of scope.
|
||||
*/
|
||||
public Response handle(String action, JsonNode request, String region) {
|
||||
LOG.debugv("Translate action: {0}", action);
|
||||
return switch (action) {
|
||||
case "TranslateText" -> translateService.translateText(
|
||||
getStringField(request, "Text"),
|
||||
getStringField(request, "SourceLanguageCode"),
|
||||
getStringField(request, "TargetLanguageCode"));
|
||||
case "TranslateDocument" -> translateService.translateDocument(
|
||||
getNestedStringField(request, "Document", "Content"),
|
||||
getNestedStringField(request, "Document", "ContentType"),
|
||||
getStringField(request, "SourceLanguageCode"),
|
||||
getStringField(request, "TargetLanguageCode"));
|
||||
case "ListLanguages" -> translateService.listLanguages(
|
||||
getStringField(request, "DisplayLanguageCode"));
|
||||
default -> Response.status(400)
|
||||
.entity(new AwsErrorResponse("UnknownOperationException",
|
||||
"Unknown operation: AWSShineFrontendService_20170701." + action))
|
||||
.build();
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Extracts a string-typed field. A present-but-wrong-typed value is a shape/marshalling
|
||||
* mismatch caught at the protocol layer before operation-specific validation, matching
|
||||
* {@link ComprehendJsonHandler}. It must not be silently coerced, nor conflated with a
|
||||
* missing field (a modeled business error handled in {@link TranslateService}).
|
||||
*/
|
||||
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();
|
||||
}
|
||||
/** {@link #getStringField} for a field nested one level under {@code parent} (e.g. Document.Content). */
|
||||
private String getNestedStringField(JsonNode node, String parent, String field) {
|
||||
JsonNode parentNode = node == null ? null : node.get(parent);
|
||||
if (parentNode == null || parentNode.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!parentNode.isObject()) {
|
||||
throw new AwsException("SerializationException",
|
||||
"Unable to unmarshal request; the value for '" + parent + "' is not a structure.", 400);
|
||||
}
|
||||
return getStringField(parentNode, field);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package io.github.hectorvent.floci.services.translate;
|
||||
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.AiMockConfigLoader;
|
||||
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.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
/**
|
||||
* Dummy response builder for Amazon Translate. Stateless: no machine translation is
|
||||
* performed. {@code TranslateText} and {@code TranslateDocument} echo their input back
|
||||
* as the "translated" payload; {@code ListLanguages} returns a fixed catalog. Input
|
||||
* validation (required fields, known language codes, Text/document size limits, and the
|
||||
* English-pivot rule for documents) still follows real Translate behavior, since that is
|
||||
* protocol compatibility rather than translation logic.
|
||||
* <p>
|
||||
* Callers can override the {@code TranslateText} default per exact {@code Text} value via
|
||||
* {@link AiMockConfigLoader}; see {@code docs/services/translate.md} "Mock Responses".
|
||||
* {@code TranslateDocument} carries a binary payload with no stable lookup key, so mock
|
||||
* lookup is skipped for it (same treatment as a Bytes-backed Textract document).
|
||||
*
|
||||
* @see <a href="https://docs.aws.amazon.com/translate/latest/APIReference/welcome.html">Translate API Reference</a>
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class TranslateService {
|
||||
private static final String SERVICE_KEY = "translate";
|
||||
/** TranslateText input cap: real Translate rejects Text longer than 10,000 UTF-8 bytes. */
|
||||
private static final int MAX_TEXT_BYTES = 10_000;
|
||||
/** TranslateDocument input cap: real Translate rejects a document larger than 100 KB. */
|
||||
private static final int MAX_DOCUMENT_BYTES = 100 * 1024;
|
||||
/**
|
||||
* Longest base64 string that can decode to {@link #MAX_DOCUMENT_BYTES} (4 chars per 3
|
||||
* bytes, rounded up). Checked before {@link Base64.Decoder#decode} so an oversized
|
||||
* payload is rejected without allocating the decoded {@code byte[]}.
|
||||
*/
|
||||
private static final int MAX_DOCUMENT_CONTENT_CHARS = ((MAX_DOCUMENT_BYTES + 2) / 3) * 4;
|
||||
/** Longest request value echoed verbatim into an error message. */
|
||||
private static final int ERROR_VALUE_PREVIEW_CHARS = 64;
|
||||
/** ContentType values real Translate accepts for TranslateDocument. */
|
||||
private static final Set<String> SUPPORTED_CONTENT_TYPES = Set.of(
|
||||
"text/plain", "text/html",
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document");
|
||||
/**
|
||||
* DisplayLanguageCode enum accepted by ListLanguages. Matches the AWS API model; the
|
||||
* returned {@code LanguageName}s are always English here regardless of this value
|
||||
* (documented deviation: real Translate localizes the names).
|
||||
*/
|
||||
private static final Set<String> SUPPORTED_DISPLAY_LANGUAGE_CODES = Set.of(
|
||||
"de", "en", "es", "fr", "it", "ja", "ko", "pt", "zh", "zh-TW");
|
||||
/**
|
||||
* Curated subset of Translate's supported languages, enough to exercise an i18n
|
||||
* pipeline without tracking AWS's full ~75-language list. Also the allow-list for
|
||||
* Source/TargetLanguageCode validation. Insertion order is preserved for ListLanguages.
|
||||
*/
|
||||
private static final Map<String, String> SUPPORTED_LANGUAGES = buildSupportedLanguages();
|
||||
private final ObjectMapper objectMapper;
|
||||
private final AiMockConfigLoader mockConfigLoader;
|
||||
@Inject
|
||||
public TranslateService(ObjectMapper objectMapper, AiMockConfigLoader mockConfigLoader) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.mockConfigLoader = mockConfigLoader;
|
||||
}
|
||||
/**
|
||||
* TranslateText: echoes {@code Text} back as {@code TranslatedText}. A source code of
|
||||
* {@code auto} is reported back as {@code en} (the stub's fixed "detected" language).
|
||||
* Response shape: https://docs.aws.amazon.com/translate/latest/APIReference/API_TranslateText.html
|
||||
*/
|
||||
public Response translateText(String text, String sourceLanguageCode, String targetLanguageCode) {
|
||||
requireField(text, "Text");
|
||||
// length() (chars) is a lower bound on UTF-8 byte count, so the cheap check
|
||||
// short-circuits before getBytes() allocates for a pathologically large Text.
|
||||
if (text.length() > MAX_TEXT_BYTES
|
||||
|| text.getBytes(StandardCharsets.UTF_8).length > MAX_TEXT_BYTES) {
|
||||
throw new AwsException("TextSizeLimitExceededException",
|
||||
"The text is longer than the maximum supported size of "
|
||||
+ MAX_TEXT_BYTES + " bytes.", 400);
|
||||
}
|
||||
String resolvedSource = validateSourceLanguage(sourceLanguageCode);
|
||||
validateTargetLanguage(targetLanguageCode);
|
||||
Optional<JsonNode> mock = mockConfigLoader.lookup(SERVICE_KEY, text, "TranslateText");
|
||||
if (mock.isPresent()) {
|
||||
return Response.ok(mock.get()).build();
|
||||
}
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
root.put("TranslatedText", text);
|
||||
root.put("SourceLanguageCode", resolvedSource);
|
||||
root.put("TargetLanguageCode", targetLanguageCode);
|
||||
return Response.ok(root).build();
|
||||
}
|
||||
/**
|
||||
* TranslateDocument: echoes the document bytes back unchanged as the translated
|
||||
* document. Content is validated as base64 and size-checked, but never decoded for
|
||||
* translation. Real Translate only translates between English and another language, so
|
||||
* one of the two language codes must resolve to {@code en}.
|
||||
* Response shape: https://docs.aws.amazon.com/translate/latest/APIReference/API_TranslateDocument.html
|
||||
*/
|
||||
public Response translateDocument(String content, String contentType,
|
||||
String sourceLanguageCode, String targetLanguageCode) {
|
||||
requireField(content, "Document.Content");
|
||||
requireField(contentType, "Document.ContentType");
|
||||
if (!SUPPORTED_CONTENT_TYPES.contains(contentType)) {
|
||||
throw new AwsException("InvalidRequestException",
|
||||
"Unsupported document content type: \"" + preview(contentType) + "\". Supported "
|
||||
+ "types are text/plain, text/html, and the Word (.docx) MIME type.", 400);
|
||||
}
|
||||
// Validate the cheap fields before touching the (potentially large) base64 blob.
|
||||
String resolvedSource = validateSourceLanguage(sourceLanguageCode);
|
||||
validateTargetLanguage(targetLanguageCode);
|
||||
if (!"en".equals(resolvedSource) && !"en".equals(targetLanguageCode)) {
|
||||
throw new AwsException("UnsupportedLanguagePairException",
|
||||
"Amazon Translate can only translate documents between English and another "
|
||||
+ "language. Set either the source or the target language to \"en\".", 400);
|
||||
}
|
||||
if (content.length() > MAX_DOCUMENT_CONTENT_CHARS) {
|
||||
throw new AwsException("InvalidRequestException",
|
||||
"The document exceeds the maximum supported size of "
|
||||
+ MAX_DOCUMENT_BYTES + " bytes.", 400);
|
||||
}
|
||||
byte[] decoded;
|
||||
try {
|
||||
decoded = Base64.getDecoder().decode(content);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new AwsException("InvalidRequestException",
|
||||
"Document.Content is not valid base64-encoded data.", 400);
|
||||
}
|
||||
if (decoded.length > MAX_DOCUMENT_BYTES) {
|
||||
throw new AwsException("InvalidRequestException",
|
||||
"The document size (" + decoded.length + " bytes) exceeds the maximum "
|
||||
+ "supported size of " + MAX_DOCUMENT_BYTES + " bytes.", 400);
|
||||
}
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
// json-1.1 marshals a blob as its base64 string; echo the caller's bytes verbatim.
|
||||
root.putObject("TranslatedDocument").put("Content", content);
|
||||
root.put("SourceLanguageCode", resolvedSource);
|
||||
root.put("TargetLanguageCode", targetLanguageCode);
|
||||
return Response.ok(root).build();
|
||||
}
|
||||
/**
|
||||
* ListLanguages: returns the full fixed catalog. Pagination inputs are accepted but
|
||||
* ignored (the catalog is small and static), so no {@code NextToken} is returned.
|
||||
* Response shape: https://docs.aws.amazon.com/translate/latest/APIReference/API_ListLanguages.html
|
||||
*/
|
||||
public Response listLanguages(String displayLanguageCode) {
|
||||
String display = (displayLanguageCode == null || displayLanguageCode.isEmpty())
|
||||
? "en" : displayLanguageCode;
|
||||
if (!SUPPORTED_DISPLAY_LANGUAGE_CODES.contains(display)) {
|
||||
throw new AwsException("UnsupportedDisplayLanguageCodeException",
|
||||
"Unsupported display language code: \"" + preview(display) + "\".", 400);
|
||||
}
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode languages = root.putArray("Languages");
|
||||
for (Map.Entry<String, String> entry : SUPPORTED_LANGUAGES.entrySet()) {
|
||||
ObjectNode language = languages.addObject();
|
||||
language.put("LanguageCode", entry.getKey());
|
||||
language.put("LanguageName", entry.getValue());
|
||||
}
|
||||
root.put("DisplayLanguageCode", display);
|
||||
return Response.ok(root).build();
|
||||
}
|
||||
// Private helpers
|
||||
private void requireField(String value, String fieldName) {
|
||||
if (value == null || value.isEmpty()) {
|
||||
throw new AwsException("InvalidRequestException",
|
||||
fieldName + " is a required field.", 400);
|
||||
}
|
||||
}
|
||||
/** Returns the code to report back; {@code auto} resolves to {@code en}. */
|
||||
private String validateSourceLanguage(String code) {
|
||||
requireField(code, "SourceLanguageCode");
|
||||
if ("auto".equals(code)) {
|
||||
return "en";
|
||||
}
|
||||
requireKnownLanguage(code);
|
||||
return code;
|
||||
}
|
||||
private void validateTargetLanguage(String code) {
|
||||
requireField(code, "TargetLanguageCode");
|
||||
requireKnownLanguage(code);
|
||||
}
|
||||
private void requireKnownLanguage(String code) {
|
||||
if (!SUPPORTED_LANGUAGES.containsKey(code)) {
|
||||
throw new AwsException("UnsupportedLanguagePairException",
|
||||
"Unsupported language code: \"" + preview(code) + "\".", 400);
|
||||
}
|
||||
}
|
||||
/** Caps an untrusted request value before it goes into a client-visible error message. */
|
||||
private static String preview(String value) {
|
||||
if (value.length() <= ERROR_VALUE_PREVIEW_CHARS) {
|
||||
return value;
|
||||
}
|
||||
return value.substring(0, ERROR_VALUE_PREVIEW_CHARS) + "...";
|
||||
}
|
||||
private static Map<String, String> buildSupportedLanguages() {
|
||||
Map<String, String> languages = new LinkedHashMap<>();
|
||||
languages.put("af", "Afrikaans");
|
||||
languages.put("ar", "Arabic");
|
||||
languages.put("bn", "Bengali");
|
||||
languages.put("zh", "Chinese (Simplified)");
|
||||
languages.put("zh-TW", "Chinese (Traditional)");
|
||||
languages.put("cs", "Czech");
|
||||
languages.put("da", "Danish");
|
||||
languages.put("nl", "Dutch");
|
||||
languages.put("en", "English");
|
||||
languages.put("fi", "Finnish");
|
||||
languages.put("fr", "French");
|
||||
languages.put("de", "German");
|
||||
languages.put("el", "Greek");
|
||||
languages.put("he", "Hebrew");
|
||||
languages.put("hi", "Hindi");
|
||||
languages.put("hu", "Hungarian");
|
||||
languages.put("id", "Indonesian");
|
||||
languages.put("it", "Italian");
|
||||
languages.put("ja", "Japanese");
|
||||
languages.put("ko", "Korean");
|
||||
languages.put("ms", "Malay");
|
||||
languages.put("no", "Norwegian");
|
||||
languages.put("fa", "Persian");
|
||||
languages.put("pl", "Polish");
|
||||
languages.put("pt", "Portuguese (Brazil)");
|
||||
languages.put("pt-PT", "Portuguese (Portugal)");
|
||||
languages.put("ro", "Romanian");
|
||||
languages.put("ru", "Russian");
|
||||
languages.put("sk", "Slovak");
|
||||
languages.put("es", "Spanish");
|
||||
languages.put("sv", "Swedish");
|
||||
languages.put("th", "Thai");
|
||||
languages.put("tr", "Turkish");
|
||||
languages.put("uk", "Ukrainian");
|
||||
languages.put("vi", "Vietnamese");
|
||||
return Collections.unmodifiableMap(languages);
|
||||
}
|
||||
}
|
||||
@@ -84,7 +84,7 @@ floci:
|
||||
# Needed for multi-container Docker setups. Example: FLOCI_HOSTNAME=floci
|
||||
default-region: us-east-1
|
||||
default-account-id: "000000000000"
|
||||
# Shared mock-response config for Textract/Comprehend/Rekognition. See AiMockConfigLoader.
|
||||
# Shared mock-response config for Textract/Comprehend/Rekognition/Translate. See AiMockConfigLoader.
|
||||
ai-mock-config-file: ${AI_MOCK_CONFIG:}
|
||||
storage:
|
||||
# Supported modes: memory, persistent, hybrid, wal
|
||||
@@ -527,6 +527,8 @@ floci:
|
||||
enabled: true
|
||||
rekognition:
|
||||
enabled: true
|
||||
translate:
|
||||
enabled: true
|
||||
pricing:
|
||||
enabled: true
|
||||
transcribe:
|
||||
|
||||
+374
@@ -0,0 +1,374 @@
|
||||
package io.github.hectorvent.floci.services.translate;
|
||||
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 java.util.Base64;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
/**
|
||||
* Integration tests for the Amazon Translate stub.
|
||||
* Validates AWS-compatible wire format using RestAssured.
|
||||
* Protocol: JSON 1.1, Content-Type: application/x-amz-json-1.1,
|
||||
* X-Amz-Target: AWSShineFrontendService_20170701.<Action>
|
||||
*/
|
||||
@QuarkusTest
|
||||
class TranslateIntegrationTest {
|
||||
@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/translate/aws4_request";
|
||||
private static final String TARGET_TEXT = "AWSShineFrontendService_20170701.TranslateText";
|
||||
private static final String TARGET_DOCUMENT = "AWSShineFrontendService_20170701.TranslateDocument";
|
||||
private static final String TARGET_LIST = "AWSShineFrontendService_20170701.ListLanguages";
|
||||
private static String base64(String plain) {
|
||||
return Base64.getEncoder().encodeToString(plain.getBytes());
|
||||
}
|
||||
// --- TranslateText ---
|
||||
@Test
|
||||
void translateText_echoesInputAsTranslatedText() {
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_TEXT)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"Text\":\"Floci makes local AWS testing painless\","
|
||||
+ "\"SourceLanguageCode\":\"en\",\"TargetLanguageCode\":\"fr\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("TranslatedText", equalTo("Floci makes local AWS testing painless"))
|
||||
.body("SourceLanguageCode", equalTo("en"))
|
||||
.body("TargetLanguageCode", equalTo("fr"));
|
||||
}
|
||||
@Test
|
||||
void translateText_anyToAnyPairIsAllowed() {
|
||||
// Unlike TranslateDocument, TranslateText does not require an English pivot.
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_TEXT)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"Text\":\"bonjour\",\"SourceLanguageCode\":\"fr\",\"TargetLanguageCode\":\"de\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("TranslatedText", equalTo("bonjour"));
|
||||
}
|
||||
@Test
|
||||
void translateText_autoSourceIsReportedAsEn() {
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_TEXT)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"Text\":\"hello\",\"SourceLanguageCode\":\"auto\",\"TargetLanguageCode\":\"de\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("SourceLanguageCode", equalTo("en"))
|
||||
.body("TargetLanguageCode", equalTo("de"));
|
||||
}
|
||||
@Test
|
||||
void translateText_matchingMockConfig_returnsConfiguredResponse() {
|
||||
// src/test/resources/fixtures/ai-mock-config.json maps "Hello world" to "Hola mundo".
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_TEXT)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"Text\":\"Hello world\",\"SourceLanguageCode\":\"en\",\"TargetLanguageCode\":\"es\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("TranslatedText", equalTo("Hola mundo"));
|
||||
}
|
||||
@Test
|
||||
void translateText_missingText_returns400() {
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_TEXT)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"SourceLanguageCode\":\"en\",\"TargetLanguageCode\":\"fr\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidRequestException"));
|
||||
}
|
||||
@Test
|
||||
void translateText_oversizedText_returns400() {
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_TEXT)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"Text\":\"" + "a".repeat(10_001) + "\","
|
||||
+ "\"SourceLanguageCode\":\"en\",\"TargetLanguageCode\":\"fr\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("TextSizeLimitExceededException"));
|
||||
}
|
||||
@Test
|
||||
void translateText_missingSourceLanguage_returns400() {
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_TEXT)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"Text\":\"hello\",\"TargetLanguageCode\":\"fr\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidRequestException"));
|
||||
}
|
||||
@Test
|
||||
void translateText_unknownSourceLanguage_returns400() {
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_TEXT)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"Text\":\"hello\",\"SourceLanguageCode\":\"zz\",\"TargetLanguageCode\":\"fr\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("UnsupportedLanguagePairException"));
|
||||
}
|
||||
@Test
|
||||
void translateText_unknownTargetLanguage_returns400() {
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_TEXT)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"Text\":\"hello\",\"SourceLanguageCode\":\"en\",\"TargetLanguageCode\":\"xx\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("UnsupportedLanguagePairException"));
|
||||
}
|
||||
@Test
|
||||
void translateText_nonStringText_returnsSerializationException() {
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_TEXT)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"Text\":123,\"SourceLanguageCode\":\"en\",\"TargetLanguageCode\":\"fr\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("SerializationException"));
|
||||
}
|
||||
@Test
|
||||
void translateText_nonStringTargetLanguage_returnsSerializationException() {
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_TEXT)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"Text\":\"hello\",\"SourceLanguageCode\":\"en\",\"TargetLanguageCode\":true}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("SerializationException"));
|
||||
}
|
||||
// --- TranslateDocument ---
|
||||
@Test
|
||||
void translateDocument_echoesContentUnchanged() {
|
||||
String content = base64("<p>hello</p>");
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_DOCUMENT)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"Document\":{\"Content\":\"" + content + "\",\"ContentType\":\"text/html\"},"
|
||||
+ "\"SourceLanguageCode\":\"en\",\"TargetLanguageCode\":\"fr\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("TranslatedDocument.Content", equalTo(content))
|
||||
.body("SourceLanguageCode", equalTo("en"))
|
||||
.body("TargetLanguageCode", equalTo("fr"));
|
||||
}
|
||||
@Test
|
||||
void translateDocument_autoSourceWithEnglishTarget_isReportedAsEn() {
|
||||
String content = base64("bonjour");
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_DOCUMENT)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"Document\":{\"Content\":\"" + content + "\",\"ContentType\":\"text/plain\"},"
|
||||
+ "\"SourceLanguageCode\":\"auto\",\"TargetLanguageCode\":\"en\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("SourceLanguageCode", equalTo("en"));
|
||||
}
|
||||
@Test
|
||||
void translateDocument_nonEnglishPair_returns400() {
|
||||
String content = base64("hola");
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_DOCUMENT)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"Document\":{\"Content\":\"" + content + "\",\"ContentType\":\"text/plain\"},"
|
||||
+ "\"SourceLanguageCode\":\"es\",\"TargetLanguageCode\":\"fr\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("UnsupportedLanguagePairException"));
|
||||
}
|
||||
@Test
|
||||
void translateDocument_missingContentType_returns400() {
|
||||
String content = base64("hello");
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_DOCUMENT)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"Document\":{\"Content\":\"" + content + "\"},"
|
||||
+ "\"SourceLanguageCode\":\"en\",\"TargetLanguageCode\":\"fr\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidRequestException"));
|
||||
}
|
||||
@Test
|
||||
void translateDocument_unsupportedContentType_returns400() {
|
||||
String content = base64("hello");
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_DOCUMENT)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"Document\":{\"Content\":\"" + content + "\",\"ContentType\":\"application/pdf\"},"
|
||||
+ "\"SourceLanguageCode\":\"en\",\"TargetLanguageCode\":\"fr\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidRequestException"));
|
||||
}
|
||||
@Test
|
||||
void translateDocument_missingDocument_returns400() {
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_DOCUMENT)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"SourceLanguageCode\":\"en\",\"TargetLanguageCode\":\"fr\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidRequestException"));
|
||||
}
|
||||
@Test
|
||||
void translateDocument_documentNotObject_returnsSerializationException() {
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_DOCUMENT)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"Document\":\"not-a-structure\","
|
||||
+ "\"SourceLanguageCode\":\"en\",\"TargetLanguageCode\":\"fr\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("SerializationException"));
|
||||
}
|
||||
@Test
|
||||
void translateDocument_invalidBase64Content_returns400() {
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_DOCUMENT)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"Document\":{\"Content\":\"@@@not-base64@@@\",\"ContentType\":\"text/plain\"},"
|
||||
+ "\"SourceLanguageCode\":\"en\",\"TargetLanguageCode\":\"fr\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidRequestException"));
|
||||
}
|
||||
@Test
|
||||
void translateDocument_oversizedContent_returns400() {
|
||||
String content = Base64.getEncoder().encodeToString(new byte[100 * 1024 + 1]);
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_DOCUMENT)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"Document\":{\"Content\":\"" + content + "\",\"ContentType\":\"text/plain\"},"
|
||||
+ "\"SourceLanguageCode\":\"en\",\"TargetLanguageCode\":\"fr\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
// TranslateDocument does not model TextSizeLimitExceededException (that is TranslateText only).
|
||||
.body("__type", equalTo("InvalidRequestException"));
|
||||
}
|
||||
// --- ListLanguages ---
|
||||
@Test
|
||||
void listLanguages_returnsCatalogWithDefaultDisplayCode() {
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_LIST)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("DisplayLanguageCode", equalTo("en"))
|
||||
.body("Languages.size()", greaterThan(20))
|
||||
.body("Languages.LanguageCode", hasItems("en", "es", "fr", "vi"))
|
||||
.body("Languages.find { it.LanguageCode == 'en' }.LanguageName", equalTo("English"))
|
||||
.body("NextToken", nullValue());
|
||||
}
|
||||
@Test
|
||||
void listLanguages_explicitValidDisplayCode_isEchoed() {
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_LIST)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"DisplayLanguageCode\":\"ja\",\"MaxResults\":5}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("DisplayLanguageCode", equalTo("ja"))
|
||||
.body("Languages.find { it.LanguageCode == 'en' }.LanguageName", equalTo("English"));
|
||||
}
|
||||
@Test
|
||||
void listLanguages_unsupportedDisplayCode_returns400() {
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", TARGET_LIST)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"DisplayLanguageCode\":\"xx\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("UnsupportedDisplayLanguageCodeException"));
|
||||
}
|
||||
@Test
|
||||
void unknownAction_returnsUnknownOperationError() {
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", "AWSShineFrontendService_20170701.ImportTerminology")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("UnknownOperationException"));
|
||||
}
|
||||
}
|
||||
@@ -310,6 +310,8 @@ floci:
|
||||
enabled: true
|
||||
rekognition:
|
||||
enabled: true
|
||||
translate:
|
||||
enabled: true
|
||||
pricing:
|
||||
enabled: true
|
||||
ce:
|
||||
|
||||
@@ -38,5 +38,14 @@
|
||||
"LabelModelVersion": "1.0"
|
||||
}
|
||||
}
|
||||
},
|
||||
"translate": {
|
||||
"Hello world": {
|
||||
"TranslateText": {
|
||||
"TranslatedText": "Hola mundo",
|
||||
"SourceLanguageCode": "en",
|
||||
"TargetLanguageCode": "es"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -68,6 +68,10 @@ services:
|
||||
doc: docs/services/rekognition.md
|
||||
sources:
|
||||
- { path: src/main/java/io/github/hectorvent/floci/services/rekognition/RekognitionJsonHandler.java, mode: switch }
|
||||
- service: translate
|
||||
doc: docs/services/translate.md
|
||||
sources:
|
||||
- { path: src/main/java/io/github/hectorvent/floci/services/translate/TranslateJsonHandler.java, mode: switch }
|
||||
- service: docdb
|
||||
doc: docs/services/docdb.md
|
||||
sources:
|
||||
|
||||
Reference in new issue
Block a user