208 lines
7.3 KiB
TypeScript
208 lines
7.3 KiB
TypeScript
import assert from "node:assert/strict";
|
|
import { generateKeyPairSync } from "node:crypto";
|
|
import { test } from "node:test";
|
|
import { BadGatewayException, BadRequestException, ConflictException } from "@nestjs/common";
|
|
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import { AdminMiniAppBuildService } from "../src/modules/admin/admin-miniapp-build.service.js";
|
|
import { AdminMiniAppUploadService } from "../src/modules/admin/admin-miniapp-upload.service.js";
|
|
import type { AdminMiniAppReleaseService } from "../src/modules/admin/admin-miniapp-release.service.js";
|
|
import { encryptMiniAppCredential } from "../src/modules/admin/miniapp-credential-crypto.js";
|
|
|
|
process.env.SESSION_SECRET = "upload-service-test-secret-1234567890";
|
|
|
|
const privateKey = generateKeyPairSync("rsa", {
|
|
modulusLength: 2048,
|
|
privateKeyEncoding: { type: "pkcs8", format: "pem" },
|
|
publicKeyEncoding: { type: "spki", format: "pem" },
|
|
}).privateKey;
|
|
process.env.MINIAPP_TEST_PRIVATE_KEY = privateKey;
|
|
|
|
const brandId = "brand-1";
|
|
const actorId = "admin-1";
|
|
|
|
function task(overrides: Record<string, unknown> = {}) {
|
|
return {
|
|
id: "task-1",
|
|
version: 7,
|
|
status: "built",
|
|
buildStatus: "idle",
|
|
updatedAt: new Date(),
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
function validBrandSettings() {
|
|
return {
|
|
appId: "wxtestsettings",
|
|
apiBaseUrl: "https://wechat.example.com/api",
|
|
};
|
|
}
|
|
|
|
function createHarness(
|
|
options: {
|
|
task?: Record<string, unknown>;
|
|
settings?: Record<string, unknown>;
|
|
exitCode?: number;
|
|
artifact?: boolean;
|
|
uploadError?: Error;
|
|
} = {},
|
|
) {
|
|
const artifactRoot =
|
|
options.artifact === false
|
|
? join(tmpdir(), "missing")
|
|
: mkdtempSync(join(tmpdir(), "miniapp-upload-"));
|
|
if (options.artifact !== false) writeFileSync(join(artifactRoot, "app.json"), "{}");
|
|
const updates: Record<string, unknown>[] = [];
|
|
const releases = {
|
|
uploadContext: async () => ({
|
|
task: task(options.task),
|
|
brand: {
|
|
templateKey: "food",
|
|
miniAppSettings: options.settings ?? validBrandSettings(),
|
|
},
|
|
}),
|
|
updateBuild: async (_brandId: string, _actorId: string, _taskId: string, input: object) => {
|
|
updates.push({ kind: "build", input });
|
|
return input;
|
|
},
|
|
updateStatus: async (_brandId: string, _actorId: string, _taskId: string, input: object) => {
|
|
updates.push({ kind: "status", input });
|
|
return input;
|
|
},
|
|
} as unknown as AdminMiniAppReleaseService;
|
|
const builds = {
|
|
run: async (
|
|
_templateKey: string,
|
|
_config: { apiBaseUrl: string; appId: string },
|
|
onLog: (message: string, stream: "stdout" | "stderr") => void,
|
|
) => {
|
|
onLog("build log", "stdout");
|
|
return { exitCode: options.exitCode ?? 0 };
|
|
},
|
|
} as unknown as AdminMiniAppBuildService;
|
|
const service = new AdminMiniAppUploadService(releases, builds);
|
|
return { service, updates, artifactRoot };
|
|
}
|
|
|
|
function createHarnessWithCredential(
|
|
options: {
|
|
task?: Record<string, unknown>;
|
|
exitCode?: number;
|
|
artifact?: boolean;
|
|
} = {},
|
|
) {
|
|
const artifactRoot =
|
|
options.artifact === false
|
|
? join(tmpdir(), "missing")
|
|
: mkdtempSync(join(tmpdir(), "miniapp-upload-"));
|
|
if (options.artifact !== false) writeFileSync(join(artifactRoot, "app.json"), "{}");
|
|
const updates: Record<string, unknown>[] = [];
|
|
const releases = {
|
|
uploadContext: async () => ({
|
|
task: task(options.task),
|
|
brand: {
|
|
templateKey: "food",
|
|
miniAppSettings: {
|
|
...validBrandSettings(),
|
|
credential: encryptMiniAppCredential(process.env.MINIAPP_TEST_PRIVATE_KEY ?? ""),
|
|
},
|
|
},
|
|
}),
|
|
updateBuild: async (_brandId: string, _actorId: string, _taskId: string, input: object) => {
|
|
updates.push({ kind: "build", input });
|
|
return input;
|
|
},
|
|
updateStatus: async (_brandId: string, _actorId: string, _taskId: string, input: object) => {
|
|
updates.push({ kind: "status", input });
|
|
return input;
|
|
},
|
|
} as unknown as AdminMiniAppReleaseService;
|
|
const builds = {
|
|
run: async (
|
|
_templateKey: string,
|
|
_config: { apiBaseUrl: string; appId: string },
|
|
onLog: (message: string, stream: "stdout" | "stderr") => void,
|
|
) => {
|
|
onLog("build log", "stdout");
|
|
return { exitCode: options.exitCode ?? 0 };
|
|
},
|
|
} as unknown as AdminMiniAppBuildService;
|
|
return { service: new AdminMiniAppUploadService(releases, builds), updates, artifactRoot };
|
|
}
|
|
|
|
test("upload blocks a currently building task before credentials are read", async () => {
|
|
const { service } = createHarness({
|
|
task: { buildStatus: "building", updatedAt: new Date() },
|
|
});
|
|
await assert.rejects(() => service.run(brandId, actorId, "task-1", {}), ConflictException);
|
|
});
|
|
|
|
test("upload rejects invalid app configuration before building", async () => {
|
|
const { service } = createHarness({
|
|
settings: { ...validBrandSettings(), appId: "touristappid" },
|
|
});
|
|
await assert.rejects(
|
|
() => service.run(brandId, actorId, "task-1", {}),
|
|
(error: unknown) => {
|
|
assert.ok(error instanceof Error);
|
|
assert.match(error.message, /AppID/);
|
|
return true;
|
|
},
|
|
);
|
|
});
|
|
|
|
test("failed build records logs and build failure state", async () => {
|
|
const { service, updates } = createHarnessWithCredential({ exitCode: 2 });
|
|
await assert.rejects(
|
|
() => service.run(brandId, actorId, "task-1", {}),
|
|
(error: unknown) => {
|
|
assert.ok(error instanceof BadRequestException);
|
|
const logs = (updates.at(-1)?.input as { buildLogs: Array<{ message: string }> }).buildLogs;
|
|
assert.ok(logs.some((entry) => entry.message.includes("build log")));
|
|
assert.ok(logs.some((entry) => entry.message.includes("退出码 2")));
|
|
return true;
|
|
},
|
|
);
|
|
assert.equal((updates.at(-1)?.input as { buildStatus: string }).buildStatus, "failed");
|
|
});
|
|
|
|
test("missing artifact records build failure without invoking upload", async () => {
|
|
const { service, updates } = createHarnessWithCredential({ artifact: false });
|
|
const previousProjectPath = process.env.MINIAPP_ARTIFACT_ROOT;
|
|
process.env.MINIAPP_ARTIFACT_ROOT = join(tmpdir(), "missing-miniapp-artifacts");
|
|
try {
|
|
await assert.rejects(
|
|
() => service.run(brandId, actorId, "task-1", {}),
|
|
(error: unknown) => {
|
|
assert.ok(error instanceof BadRequestException);
|
|
assert.match((error as BadRequestException).message, /app\.json/);
|
|
return true;
|
|
},
|
|
);
|
|
assert.equal((updates.at(-1)?.input as { buildStatus: string }).buildStatus, "failed");
|
|
} finally {
|
|
if (previousProjectPath === undefined) delete process.env.MINIAPP_ARTIFACT_ROOT;
|
|
else process.env.MINIAPP_ARTIFACT_ROOT = previousProjectPath;
|
|
}
|
|
});
|
|
|
|
test("upload rejects missing credentials before build", async () => {
|
|
const previous = process.env.WECHAT_UPLOAD_PRIVATE_KEY;
|
|
delete process.env.WECHAT_UPLOAD_PRIVATE_KEY;
|
|
try {
|
|
const { service } = createHarness();
|
|
await assert.rejects(
|
|
() => service.run(brandId, actorId, "task-1", {}),
|
|
(error: unknown) => {
|
|
assert.ok(error instanceof BadRequestException);
|
|
assert.match((error as BadRequestException).message, /WECHAT_UPLOAD_PRIVATE_KEY/);
|
|
return true;
|
|
},
|
|
);
|
|
} finally {
|
|
if (previous !== undefined) process.env.WECHAT_UPLOAD_PRIVATE_KEY = previous;
|
|
}
|
|
});
|