feat(moderation): normalize JSON response handling and enhance test coverage for moderation analysis

This commit is contained in:
MythEclipse
2026-05-21 03:52:51 +07:00
parent 419018ab0c
commit 5588ece6c7
3 changed files with 78 additions and 4 deletions
+36 -1
View File
@@ -481,7 +481,7 @@ describe("runModerationAnalysis", () => {
).rejects.toThrow(/500/);
});
it("parses first JSON object when provider appends extra JSON", async () => {
it("parses first JSON object when provider appends extra text to message content", async () => {
const moderationJson = JSON.stringify({
results: [
{
@@ -517,6 +517,41 @@ describe("runModerationAnalysis", () => {
expect(result.results[0].messageId).toBe("m1");
});
it("normalizes first JSON object when provider appends extra text to HTTP body", async () => {
const mockResponse = {
choices: [
{
message: {
content: JSON.stringify({
results: [
{
message_id: "m1",
status: "clean",
flags: [],
score: 0.1,
analysis: "OK",
},
],
}),
},
},
],
};
global.fetch = vi.fn().mockResolvedValue({
ok: true,
text: async () => `${JSON.stringify(mockResponse)}\nextra`,
});
const result = await runModerationAnalysis({
targets: [createMessageRecord()],
contextText: "test context",
});
expect(result.results).toHaveLength(1);
expect(result.results[0].messageId).toBe("m1");
});
it("throws on missing choices in response", async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: true,