Files
SnapOtter/tests/integration/replace-color.test.ts
T
SnapOtter 733ebe8010 test: major coverage expansion — 18 new test files, ~830 new tests
Unit tests: 1354 → 1781 (+427)
- 11 new AI bridge module tests (packages/ai/ from 2/13 → 13/13 files)
- files-page-store (0% → full), pdf-to-image-store, features-store expanded
- saturation and edit-metadata image-engine operations
- analytics route, features route, web analytics lib, api-extended

Integration tests: ~2070 → 2320 (+250)
- 31 integration files expanded with branch-coverage-targeted tests
- progress.ts SSE endpoints (28% → comprehensive, +18 tests)
- gif-tools all modes (+18), pdf-to-image format variants (+13)
- Cross-format matrix expanded to 17 tools × 17 formats (467 tests)
- Adversarial: concurrent, memory pressure, unicode filenames, pipeline limits

E2E-Docker: +1020 lines across 6 spec files
- Info, colors, sharpening, base64, QR read, JXL/ICO/SVG formats
- Strip-metadata, image-enhancement, content-aware-resize expanded
- Batch pipelines, multi-format batches, HEIC input coverage
2026-04-26 12:03:08 +08:00

322 lines
11 KiB
TypeScript

/**
* Integration tests for the replace-color tool.
*
* Replaces a source color with a target color (or makes it transparent).
* Tests valid replacements, tolerance parameter, makeTransparent mode,
* and verifies pixel-level changes.
*/
import { readFileSync } from "node:fs";
import { join } from "node:path";
import sharp from "sharp";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { buildTestApp, createMultipartPayload, loginAsAdmin, type TestApp } from "./test-server.js";
const FIXTURES = join(__dirname, "..", "fixtures");
const PNG = readFileSync(join(FIXTURES, "test-200x150.png"));
const JPG = readFileSync(join(FIXTURES, "test-100x100.jpg"));
let testApp: TestApp;
let app: TestApp["app"];
let adminToken: string;
let solidRedBuffer: Buffer;
beforeAll(async () => {
testApp = await buildTestApp();
app = testApp.app;
adminToken = await loginAsAdmin(app);
// Create a solid red test image for predictable color replacement
solidRedBuffer = await sharp({
create: { width: 50, height: 50, channels: 3, background: { r: 255, g: 0, b: 0 } },
})
.png()
.toBuffer();
}, 30_000);
afterAll(async () => {
await testApp.cleanup();
}, 10_000);
function makePayload(
settings: Record<string, unknown>,
buffer: Buffer = PNG,
filename = "test.png",
contentType = "image/png",
) {
return createMultipartPayload([
{ name: "file", filename, contentType, content: buffer },
{ name: "settings", content: JSON.stringify(settings) },
]);
}
async function postTool(
settings: Record<string, unknown>,
buffer?: Buffer,
filename?: string,
ct?: string,
) {
const { body: payload, contentType } = makePayload(settings, buffer, filename, ct);
return app.inject({
method: "POST",
url: "/api/v1/tools/replace-color",
payload,
headers: {
"content-type": contentType,
authorization: `Bearer ${adminToken}`,
},
});
}
// ── Basic replacement ─────────────────────────────────────────────
describe("Basic color replacement", () => {
it("replaces red with blue in a solid red image", async () => {
const res = await postTool(
{ sourceColor: "#FF0000", targetColor: "#0000FF", tolerance: 30 },
solidRedBuffer,
);
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.downloadUrl).toBeDefined();
expect(result.processedSize).toBeGreaterThan(0);
// Download and verify color changed
const dlRes = await app.inject({
method: "GET",
url: result.downloadUrl,
headers: { authorization: `Bearer ${adminToken}` },
});
expect(dlRes.statusCode).toBe(200);
// Check that the output pixels are predominantly blue
const { data } = await sharp(dlRes.rawPayload)
.removeAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
// First pixel should be blue-ish (high B, low R)
expect(data[2]).toBeGreaterThan(data[0]); // blue > red
});
it("processes with default settings", async () => {
const res = await postTool({});
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.downloadUrl).toBeDefined();
});
});
// ── Tolerance ─────────────────────────────────────────────────────
describe("Tolerance parameter", () => {
it("with tolerance=0, only exact matches are replaced", async () => {
const res = await postTool(
{ sourceColor: "#FF0000", targetColor: "#00FF00", tolerance: 0 },
solidRedBuffer,
);
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.downloadUrl).toBeDefined();
});
it("with high tolerance, more colors are affected", async () => {
const res = await postTool(
{ sourceColor: "#FF0000", targetColor: "#00FF00", tolerance: 200 },
solidRedBuffer,
);
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.downloadUrl).toBeDefined();
});
it("with max tolerance=255, all pixels are affected", async () => {
const res = await postTool({
sourceColor: "#FF0000",
targetColor: "#00FF00",
tolerance: 255,
});
expect(res.statusCode).toBe(200);
});
});
// ── Make transparent ──────────────────────────────────────────────
describe("Make transparent mode", () => {
it("makes matching pixels transparent instead of replacing", async () => {
const res = await postTool(
{ sourceColor: "#FF0000", makeTransparent: true, tolerance: 30 },
solidRedBuffer,
);
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.downloadUrl).toBeDefined();
// Download and verify alpha channel
const dlRes = await app.inject({
method: "GET",
url: result.downloadUrl,
headers: { authorization: `Bearer ${adminToken}` },
});
const meta = await sharp(dlRes.rawPayload).metadata();
expect(meta.channels).toBe(4); // RGBA output
});
});
// ── Format support ────────────────────────────────────────────────
describe("Multiple input formats", () => {
it("processes JPEG input", async () => {
const res = await postTool(
{ sourceColor: "#808080", targetColor: "#FF0000", tolerance: 50 },
JPG,
"test.jpg",
"image/jpeg",
);
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.downloadUrl).toBeDefined();
});
});
// ── Error handling ────────────────────────────────────────────────
describe("Error handling", () => {
it("returns 400 when no file is provided", async () => {
const { body: payload, contentType } = createMultipartPayload([
{
name: "settings",
content: JSON.stringify({ sourceColor: "#FF0000", targetColor: "#00FF00" }),
},
]);
const res = await app.inject({
method: "POST",
url: "/api/v1/tools/replace-color",
payload,
headers: {
"content-type": contentType,
authorization: `Bearer ${adminToken}`,
},
});
expect(res.statusCode).toBe(400);
});
it("returns 400 for invalid hex color format", async () => {
const res = await postTool({ sourceColor: "red", targetColor: "#00FF00" });
expect(res.statusCode).toBe(400);
});
it("returns 400 for short hex color", async () => {
const res = await postTool({ sourceColor: "#F00", targetColor: "#00FF00" });
expect(res.statusCode).toBe(400);
});
it("returns 400 for tolerance out of range (negative)", async () => {
const res = await postTool({ tolerance: -1 });
expect(res.statusCode).toBe(400);
});
it("returns 400 for tolerance out of range (>255)", async () => {
const res = await postTool({ tolerance: 300 });
expect(res.statusCode).toBe(400);
});
});
// ── Branch coverage: line 82 (makeTransparent on non-alpha format → forced PNG) ──
describe("Alpha format fallback", () => {
it("forces PNG when makeTransparent is used on a JPEG input", async () => {
// Use solidRedBuffer with matching sourceColor to ensure transparency is applied
const res = await postTool(
{ sourceColor: "#FF0000", makeTransparent: true, tolerance: 30 },
solidRedBuffer,
"test.jpg",
"image/jpeg",
);
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
const dlRes = await app.inject({
method: "GET",
url: result.downloadUrl,
headers: { authorization: `Bearer ${adminToken}` },
});
const meta = await sharp(dlRes.rawPayload).metadata();
// JPEG doesn't support alpha, so output is forced to PNG
expect(meta.format).toBe("png");
});
it("keeps PNG when makeTransparent is used on a PNG input", async () => {
const res = await postTool(
{ sourceColor: "#FF0000", makeTransparent: true, tolerance: 30 },
solidRedBuffer,
"test.png",
"image/png",
);
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
const dlRes = await app.inject({
method: "GET",
url: result.downloadUrl,
headers: { authorization: `Bearer ${adminToken}` },
});
const meta = await sharp(dlRes.rawPayload).metadata();
expect(meta.format).toBe("png");
});
});
// ── HEIC input handling ─────────────────────────────────────────
describe("HEIC input", () => {
it("processes HEIC image", async () => {
const HEIC = readFileSync(join(FIXTURES, "test-200x150.heic"));
const res = await postTool(
{ sourceColor: "#808080", targetColor: "#FF0000", tolerance: 50 },
HEIC,
"photo.heic",
"image/heic",
);
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.downloadUrl).toBeDefined();
});
});
// ── WebP input ──────────────────────────────────────────────────
describe("WebP input", () => {
it("processes WebP image", async () => {
const WEBP = readFileSync(join(FIXTURES, "test-50x50.webp"));
const res = await postTool(
{ sourceColor: "#808080", targetColor: "#00FF00", tolerance: 40 },
WEBP,
"test.webp",
"image/webp",
);
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.downloadUrl).toBeDefined();
});
});
// ── Edge size inputs ────────────────────────────────────────────
describe("Edge size inputs", () => {
it("processes 1x1 pixel image", async () => {
const TINY = readFileSync(join(FIXTURES, "test-1x1.png"));
const res = await postTool(
{ sourceColor: "#000000", targetColor: "#FFFFFF", tolerance: 255 },
TINY,
"tiny.png",
"image/png",
);
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.processedSize).toBeGreaterThan(0);
});
it("processes stress-large.jpg", async () => {
const LARGE = readFileSync(join(FIXTURES, "content", "stress-large.jpg"));
const res = await postTool(
{ sourceColor: "#808080", targetColor: "#FF0000", tolerance: 30 },
LARGE,
"large.jpg",
"image/jpeg",
);
expect(res.statusCode).toBe(200);
const result = JSON.parse(res.body);
expect(result.processedSize).toBeGreaterThan(0);
});
});