mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(core): add configurable mock responses for stub AI services (#2765)
* feat(core): add configurable mock responses for stub AI services Adds AiMockConfigLoader, a shared mock-response config file (path via AI_MOCK_CONFIG env var or floci.ai-mock-config-file) that lets callers override Textract/Comprehend/Rekognition's fixed stub responses on a per-call basis, so application logic that branches on detection results (e.g. "escalate if sentiment is NEGATIVE") can be exercised end-to-end against floci. Mirrors Step Functions' SFN_MOCK_CONFIG mechanism (same mtime-cached reload without restart), but is shared across three services and never throws: a missing file, unset env var, or no matching entry all fall back to the existing default stub, since mocking here is opt-in on top of an always-available default, not the only way to invoke an action. Lookup keys: Comprehend keys on the exact Text value; Textract and Rekognition key on "<Bucket>/<Name>" from S3Object (a Bytes-backed image/document has no such key, so mocking only applies to S3Object-based calls). CompareFaces keys off SourceImage only. The Textract async Start*/Get* job flow does not support mocking. Closes #2764 * fix(core): catch unchecked exceptions when loading AI mock config Path.of(path) throws InvalidPathException (unchecked) for a malformed path string, and filesystem access can raise other unchecked exceptions IOException alone doesn't cover. load() only caught IOException, so a bad AI_MOCK_CONFIG value would propagate past the loader and turn a normal Comprehend/Textract/Rekognition request into a 500 — the exact opposite of this loader's contract (mocking is optional; it must never break the default stub). Wrapped the load logic in an outer catch (RuntimeException) that falls back the same way the existing IOException cases already do. Addresses review feedback on #2765.
This commit is contained in:
1 parent
0b46d804c0
commit
e2e69f65f5
18 files changed
+569
-37
No files matched your search
@@ -0,0 +1,120 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class AiMockConfigLoaderTest {
|
||||
|
||||
private static final String CONFIG = """
|
||||
{
|
||||
"comprehend": {
|
||||
"I love this": { "DetectSentiment": { "Sentiment": "POSITIVE" } }
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
private AiMockConfigLoader loader(String content) throws IOException {
|
||||
var file = tempDir.resolve("ai-mock-config.json");
|
||||
Files.writeString(file, content);
|
||||
return new AiMockConfigLoader(Optional.of(file.toString()), new ObjectMapper());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesMatchingEntry() throws IOException {
|
||||
var loader = loader(CONFIG);
|
||||
var result = loader.lookup("comprehend", "I love this", "DetectSentiment");
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals("POSITIVE", result.get().path("Sentiment").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackWhenServiceKeyUnmatched() throws IOException {
|
||||
var loader = loader(CONFIG);
|
||||
assertTrue(loader.lookup("rekognition", "I love this", "DetectSentiment").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackWhenLookupKeyUnmatched() throws IOException {
|
||||
var loader = loader(CONFIG);
|
||||
assertTrue(loader.lookup("comprehend", "I hate this", "DetectSentiment").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackWhenActionUnmatched() throws IOException {
|
||||
var loader = loader(CONFIG);
|
||||
assertTrue(loader.lookup("comprehend", "I love this", "DetectKeyPhrases").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackWhenLookupKeyIsNull() throws IOException {
|
||||
// Bytes-backed images/documents have no natural lookup key.
|
||||
var loader = loader(CONFIG);
|
||||
assertTrue(loader.lookup("comprehend", null, "DetectSentiment").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackWhenNoConfigConfigured() {
|
||||
var loader = new AiMockConfigLoader(Optional.empty(), new ObjectMapper());
|
||||
assertTrue(loader.lookup("comprehend", "I love this", "DetectSentiment").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackWhenFileMissing() {
|
||||
var loader = new AiMockConfigLoader(
|
||||
Optional.of(tempDir.resolve("absent.json").toString()), new ObjectMapper());
|
||||
assertTrue(loader.lookup("comprehend", "I love this", "DetectSentiment").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackWhenConfiguredPathIsUnparseable() {
|
||||
// An embedded NUL byte makes Path.of() throw InvalidPathException, an unchecked
|
||||
// exception that a plain "catch (IOException)" does not cover.
|
||||
var loader = new AiMockConfigLoader(Optional.of("bad\0path.json"), new ObjectMapper());
|
||||
assertTrue(loader.lookup("comprehend", "I love this", "DetectSentiment").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackWhenFileIsNotAJsonObject() throws IOException {
|
||||
var loader = loader("[1, 2, 3]");
|
||||
assertTrue(loader.lookup("comprehend", "I love this", "DetectSentiment").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackWhenFileIsMalformedJson() throws IOException {
|
||||
var loader = loader("{not valid json");
|
||||
assertTrue(loader.lookup("comprehend", "I love this", "DetectSentiment").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void treatsBlankConfiguredPathAsUnconfigured() {
|
||||
var loader = new AiMockConfigLoader(Optional.of(" "), new ObjectMapper());
|
||||
assertTrue(loader.lookup("comprehend", "I love this", "DetectSentiment").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void reloadsFileWhenModified() throws IOException, InterruptedException {
|
||||
var file = tempDir.resolve("ai-mock-config.json");
|
||||
Files.writeString(file, CONFIG);
|
||||
var loader = new AiMockConfigLoader(Optional.of(file.toString()), new ObjectMapper());
|
||||
assertTrue(loader.lookup("comprehend", "I love this", "DetectSentiment").isPresent());
|
||||
assertFalse(loader.lookup("comprehend", "I hate this", "DetectSentiment").isPresent());
|
||||
|
||||
Thread.sleep(1100);
|
||||
Files.writeString(file, CONFIG.replace("I love this", "I hate this"));
|
||||
assertTrue(loader.lookup("comprehend", "I hate this", "DetectSentiment").isPresent());
|
||||
assertFalse(loader.lookup("comprehend", "I love this", "DetectSentiment").isPresent());
|
||||
}
|
||||
}
|
||||
+15
@@ -37,6 +37,21 @@ class ComprehendIntegrationTest {
|
||||
.body("SentimentScore.Mixed", notNullValue());
|
||||
}
|
||||
@Test
|
||||
void detectSentiment_matchingMockConfig_returnsConfiguredResponse() {
|
||||
// src/test/resources/fixtures/ai-mock-config.json maps this exact Text to POSITIVE.
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", "Comprehend_20171127.DetectSentiment")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"Text\":\"I absolutely love this product!\",\"LanguageCode\":\"en\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Sentiment", equalTo("POSITIVE"))
|
||||
.body("SentimentScore.Positive", equalTo(0.98f));
|
||||
}
|
||||
@Test
|
||||
void detectSentiment_missingText_returns400() {
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
|
||||
+2
@@ -300,6 +300,8 @@ class EventBridgeSchedulerIntegrationTest {
|
||||
@Override
|
||||
public String ecrBaseUri() { return ""; }
|
||||
@Override
|
||||
public Optional<String> aiMockConfigFile() { return Optional.empty(); }
|
||||
@Override
|
||||
public StorageConfig storage() { return null; }
|
||||
@Override
|
||||
public DnsConfig dns() {
|
||||
|
||||
+15
@@ -38,6 +38,21 @@ class RekognitionIntegrationTest {
|
||||
.body("LabelModelVersion", equalTo("1.0"));
|
||||
}
|
||||
@Test
|
||||
void detectLabels_matchingMockConfig_returnsConfiguredResponse() {
|
||||
// src/test/resources/fixtures/ai-mock-config.json maps mock-bucket/cat.jpg.
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", "RekognitionService.DetectLabels")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"Image\":{\"S3Object\":{\"Bucket\":\"mock-bucket\",\"Name\":\"cat.jpg\"}}}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Labels", hasSize(2))
|
||||
.body("Labels.Name", hasItems("Cat", "Animal"));
|
||||
}
|
||||
@Test
|
||||
void detectLabels_missingImage_returns400() {
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
|
||||
+15
@@ -37,6 +37,21 @@ class TextractIntegrationTest {
|
||||
.body("Blocks.BlockType", hasItems("PAGE", "LINE", "WORD"));
|
||||
}
|
||||
@Test
|
||||
void detectDocumentText_matchingMockConfig_returnsConfiguredResponse() {
|
||||
// src/test/resources/fixtures/ai-mock-config.json maps mock-bucket/invoice.pdf.
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", "Textract.DetectDocumentText")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"Document\":{\"S3Object\":{\"Bucket\":\"mock-bucket\",\"Name\":\"invoice.pdf\"}}}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Blocks", hasSize(1))
|
||||
.body("Blocks[0].Text", equalTo("Invoice Total: $42.00"));
|
||||
}
|
||||
@Test
|
||||
void detectDocumentText_blockShapesAreAwsCompatible() {
|
||||
given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
|
||||
Reference in new issue
Block a user