244 lines
11 KiB
TypeScript
244 lines
11 KiB
TypeScript
// MUST be first — pins env before anything that reads it at module load.
|
||
import "./setup_env";
|
||
|
||
import { test, expect, describe, beforeEach, afterAll } from "bun:test";
|
||
|
||
/**
|
||
* code.byted.org 的 MR 通道(注册表里叫 `gitlab`,实现走 Codebase OpenAPI,见 gitlab_mr.ts)。
|
||
*
|
||
* 2026-11 起 tt_im_monorepo 走这条通道(生产 ce9bf567:改的是 bits-pipeline 应用,开发任务
|
||
* 那条路建不出任何东西)。所以除了通道本身,也端到端地钉住「tt-im-monorepo 被路由到这里、
|
||
* 提到 master」。
|
||
*
|
||
* 契约照抄官方 Codebase CLI 的 `mr create`:GetRepository{Path} 换 Id →
|
||
* ListRepoMergeRequests 找已有 → CreateMergeRequest。GitLab v4 那套已经下线,
|
||
* 这里断言**一次 /api/v4 都不打**。
|
||
*
|
||
* 注意 gitlab_mr.ts 按路径缓存仓库 Id(模块级),下面不同用例用不同的仓库路径来隔离。
|
||
*/
|
||
|
||
process.env.CODEBASE_MR_TOKEN = "test-token";
|
||
process.env.BITS_SKIP_USER_TOKEN = "1";
|
||
|
||
const { createGitlabMr, findGitlabMr, gitlabMrConfigured } = await import("../src/gitlab_mr");
|
||
const { submitMrForFix } = await import("../src/bits");
|
||
|
||
const BRANCH = "bugfix/streak-milestone-button-height";
|
||
const WEB_URL = "https://code.byted.org/tiktok/tt_im_monorepo/merge_requests/558";
|
||
|
||
const realFetch = globalThis.fetch;
|
||
type Call = { url: string; action: string | null; auth: string | null; body: any };
|
||
let calls: Call[] = [];
|
||
|
||
const ok = (result: unknown) => ({ status: 200, body: { ResponseMetadata: { RequestId: "r" }, Result: result } });
|
||
const cbErr = (code: string, message: string) => ({
|
||
status: 200,
|
||
body: { ResponseMetadata: { RequestId: "r", Error: { Code: code, Message: message } } },
|
||
});
|
||
|
||
/** 按 `?Action=` 分派;没写到的 action 当成调用了不该调的接口。 */
|
||
function stubCodebase(handlers: Record<string, (body: any) => { status: number; body: unknown }>) {
|
||
calls = [];
|
||
globalThis.fetch = (async (input: any, init?: RequestInit) => {
|
||
const url = typeof input === "string" ? input : input.url;
|
||
const action = new URL(url).searchParams.get("Action");
|
||
let body: any = null;
|
||
try { body = init?.body ? JSON.parse(String(init.body)) : null; } catch { /* keep null */ }
|
||
calls.push({ url, action, auth: new Headers(init?.headers as HeadersInit).get("Authorization"), body });
|
||
const h = action ? handlers[action] : undefined;
|
||
const r = h ? h(body) : { status: 599, body: { error: `unexpected call ${url}` } };
|
||
return new Response(JSON.stringify(r.body), { status: r.status, headers: { "content-type": "application/json" } });
|
||
}) as typeof fetch;
|
||
}
|
||
|
||
const repoReply = (id = 98765) => ok({
|
||
Repository: { Id: id, DefaultBranch: "master", MergeMethod: "squash_merge", RemoveSourceBranchAfterMerge: true },
|
||
});
|
||
const mr = (over: Record<string, unknown> = {}) => ({
|
||
Number: 558, URL: WEB_URL, Status: "open", SourceBranch: BRANCH, TargetBranch: "master", ...over,
|
||
});
|
||
|
||
beforeEach(() => { calls = []; });
|
||
afterAll(() => { globalThis.fetch = realFetch; });
|
||
|
||
describe("建 MR(Codebase OpenAPI)", () => {
|
||
test("有令牌才认为这条通道可用", () => {
|
||
expect(gitlabMrConfigured()).toBe(true);
|
||
});
|
||
|
||
test("按路径换仓库 Id,再照 CLI 的请求体建 MR,回填编号与链接", async () => {
|
||
stubCodebase({
|
||
GetRepository: () => repoReply(),
|
||
ListRepoMergeRequests: () => ok({ MergeRequests: [] }),
|
||
CreateMergeRequest: () => ok({ MergeRequest: mr() }),
|
||
});
|
||
const r = await createGitlabMr({
|
||
repoPath: "test/create-basic", sourceBranch: BRANCH, targetBranch: "master",
|
||
title: "[bug] 火花里程碑按钮高度", description: "streamline: …",
|
||
});
|
||
expect(r.ok).toBe(true);
|
||
expect(r.reused).toBeUndefined();
|
||
expect(r.mr?.iid).toBe(558);
|
||
expect(r.mr?.webUrl).toBe(WEB_URL);
|
||
expect(calls.map((c) => c.action)).toEqual(["GetRepository", "ListRepoMergeRequests", "CreateMergeRequest"]);
|
||
expect(calls[0].body).toEqual({ Path: "test/create-basic" });
|
||
expect(calls.find((c) => c.action === "CreateMergeRequest")!.body).toEqual({
|
||
SourceRepoId: "98765", SourceBranch: BRANCH,
|
||
TargetRepoId: "98765", TargetBranch: "master",
|
||
Title: "[bug] 火花里程碑按钮高度", Description: "streamline: …",
|
||
MergeMethod: "squash_merge", RemoveSourceBranchAfterMerge: true,
|
||
AutoInviteReviewers: true, AutoLinkWorkItems: false, Draft: false,
|
||
});
|
||
expect(calls.every((c) => c.auth === "Bearer test-token")).toBe(true);
|
||
// GitLab v4 已下线;这条通道也不碰 Bits。
|
||
expect(calls.some((c) => c.url.includes("/api/v4/") || c.url.includes("bits.bytedance.net"))).toBe(false);
|
||
});
|
||
|
||
test("仓库 Id 只换一次", async () => {
|
||
stubCodebase({
|
||
GetRepository: () => repoReply(),
|
||
ListRepoMergeRequests: () => ok({ MergeRequests: [] }),
|
||
CreateMergeRequest: () => ok({ MergeRequest: mr() }),
|
||
});
|
||
const input = { repoPath: "test/cache", sourceBranch: BRANCH, targetBranch: "master", title: "t" };
|
||
await createGitlabMr(input);
|
||
await createGitlabMr(input);
|
||
expect(calls.filter((c) => c.action === "GetRepository")).toHaveLength(1);
|
||
});
|
||
|
||
test("分支上已有打开的 MR ⇒ 认领它,不再建", async () => {
|
||
stubCodebase({
|
||
GetRepository: () => repoReply(),
|
||
ListRepoMergeRequests: () => ok({ MergeRequests: [mr({ Number: 557, URL: WEB_URL.replace("558", "557") })] }),
|
||
});
|
||
const r = await createGitlabMr({ repoPath: "test/existing", sourceBranch: BRANCH, targetBranch: "master", title: "t" });
|
||
expect(r.ok).toBe(true);
|
||
expect(r.reused).toBe(true);
|
||
expect(r.mr?.webUrl).toContain("/merge_requests/557");
|
||
expect(calls.some((c) => c.action === "CreateMergeRequest")).toBe(false);
|
||
});
|
||
|
||
test("create 报错但随后找得到 ⇒ 认领,并留着 create 的原话", async () => {
|
||
let listed = 0;
|
||
stubCodebase({
|
||
GetRepository: () => repoReply(),
|
||
ListRepoMergeRequests: () => ok({ MergeRequests: listed++ === 0 ? [] : [mr()] }),
|
||
CreateMergeRequest: () => cbErr("Timeout", "upstream timed out"),
|
||
});
|
||
const r = await createGitlabMr({ repoPath: "test/late", sourceBranch: BRANCH, targetBranch: "master", title: "t" });
|
||
expect(r.ok).toBe(true);
|
||
expect(r.reused).toBe(true);
|
||
expect(r.error).toContain("upstream timed out");
|
||
});
|
||
|
||
test("建不成也找不到 ⇒ 如实失败,带上 Codebase 的错误码和原话", async () => {
|
||
stubCodebase({
|
||
GetRepository: () => repoReply(),
|
||
ListRepoMergeRequests: () => ok({ MergeRequests: [] }),
|
||
CreateMergeRequest: () => cbErr("InvalidParameter", "source branch not found"),
|
||
});
|
||
const r = await createGitlabMr({ repoPath: "test/fail", sourceBranch: BRANCH, targetBranch: "master", title: "t" });
|
||
expect(r.ok).toBe(false);
|
||
expect(r.mr).toBeNull();
|
||
expect(r.error).toBe("InvalidParameter: source branch not found");
|
||
});
|
||
|
||
test("令牌过期 ⇒ 停在换仓库 Id 那一步,不发写请求", async () => {
|
||
stubCodebase({ GetRepository: () => cbErr("Unauthorized", "authenticated failed: personal access token expired") });
|
||
const r = await createGitlabMr({ repoPath: "test/expired", sourceBranch: BRANCH, targetBranch: "master", title: "t" });
|
||
expect(r.ok).toBe(false);
|
||
expect(r.error).toContain("personal access token expired");
|
||
expect(calls.map((c) => c.action)).toEqual(["GetRepository"]);
|
||
});
|
||
|
||
test("回包里没有链接 ⇒ 按 code.byted.org 的固定形态拼", async () => {
|
||
stubCodebase({
|
||
GetRepository: () => repoReply(),
|
||
ListRepoMergeRequests: () => ok({ MergeRequests: [] }),
|
||
CreateMergeRequest: () => ok({ MergeRequest: { Number: 12 } }),
|
||
});
|
||
const r = await createGitlabMr({ repoPath: "test/no-url", sourceBranch: BRANCH, targetBranch: "master", title: "t" });
|
||
expect(r.mr?.webUrl).toBe("https://code.byted.org/test/no-url/merge_requests/12");
|
||
});
|
||
|
||
test("源分支就是目标分支 ⇒ 不打任何接口", async () => {
|
||
stubCodebase({});
|
||
const r = await createGitlabMr({ repoPath: "test/same", sourceBranch: "master", targetBranch: "master", title: "t" });
|
||
expect(r.ok).toBe(false);
|
||
expect(calls).toHaveLength(0);
|
||
});
|
||
});
|
||
|
||
describe("按分支找已存在的 MR", () => {
|
||
test("分支名精确比对 —— 这条 MR 会被写进任务记录", async () => {
|
||
stubCodebase({
|
||
GetRepository: () => repoReply(),
|
||
ListRepoMergeRequests: () => ok({ MergeRequests: [mr({ SourceBranch: "feature/other" })] }),
|
||
});
|
||
expect(await findGitlabMr({ repoPath: "test/find", sourceBranch: BRANCH })).toBeNull();
|
||
});
|
||
});
|
||
|
||
describe("tt_im_monorepo 走这条通道", () => {
|
||
const happy = () => stubCodebase({
|
||
GetRepository: () => repoReply(),
|
||
ListRepoMergeRequests: () => ok({ MergeRequests: [] }),
|
||
CreateMergeRequest: () => ok({ MergeRequest: mr() }),
|
||
});
|
||
|
||
test("提到 master(哪怕 BASE_BRANCH=develop),回填 code.byted.org 链接,不碰 Bits", async () => {
|
||
const prev = process.env.BASE_BRANCH;
|
||
process.env.BASE_BRANCH = "develop";
|
||
try {
|
||
happy();
|
||
const r = await submitMrForFix({
|
||
platform: "ios", sourceBranch: BRANCH, repoKey: "tt-im-monorepo",
|
||
title: "[bug] 火花里程碑按钮高度", mrType: "bug", note: "streamline: …",
|
||
meegoWorkItems: [{ taskId: "123", taskType: "bug", projectKey: "x" } as any],
|
||
});
|
||
expect(r.ok).toBe(true);
|
||
expect(r.mrUrl).toBe(WEB_URL);
|
||
expect(calls.find((c) => c.action === "GetRepository")!.body).toEqual({ Path: "tiktok/tt_im_monorepo" });
|
||
expect(calls.find((c) => c.action === "CreateMergeRequest")!.body.TargetBranch).toBe("master");
|
||
expect(calls.some((c) => c.url.includes("bits.bytedance.net"))).toBe(false);
|
||
// 绑 Meego / 加 reviewer 不是这条通道的能力 —— 记成 ok 但说清楚,而不是悄悄跳过。
|
||
expect(r.steps.find((s) => s.step === "bind_meego")?.error).toContain("不支持自动绑定");
|
||
} finally {
|
||
if (prev === undefined) delete process.env.BASE_BRANCH; else process.env.BASE_BRANCH = prev;
|
||
}
|
||
});
|
||
|
||
test("任务自己的 baseRef 压过仓库主干", async () => {
|
||
happy();
|
||
await submitMrForFix({
|
||
platform: "android", sourceBranch: BRANCH, repoKey: "tt-im-monorepo",
|
||
title: "t", mrType: "bug", baseRef: "feature/streak-pet-baseline",
|
||
});
|
||
expect(calls.find((c) => c.action === "CreateMergeRequest")!.body.TargetBranch).toBe("feature/streak-pet-baseline");
|
||
});
|
||
|
||
test("自动路径不需要谁的 Bits Token —— 没有 tokenUser 也照建", async () => {
|
||
happy();
|
||
const r = await submitMrForFix({
|
||
platform: "ios", sourceBranch: BRANCH, repoKey: "tt-im-monorepo", trigger: "auto",
|
||
title: "t", mrType: "bug",
|
||
});
|
||
expect(r.ok).toBe(true);
|
||
});
|
||
|
||
test("建不成 ⇒ 失败原因里带上手动建 MR 的链接(面板据此出「去手动建 MR」)", async () => {
|
||
stubCodebase({
|
||
GetRepository: () => repoReply(),
|
||
ListRepoMergeRequests: () => ok({ MergeRequests: [] }),
|
||
CreateMergeRequest: () => cbErr("Forbidden", "no permission"),
|
||
});
|
||
const r = await submitMrForFix({
|
||
platform: "ios", sourceBranch: BRANCH, repoKey: "tt-im-monorepo", title: "t", mrType: "bug",
|
||
});
|
||
expect(r.ok).toBe(false);
|
||
const step = r.steps.find((s) => s.step === "create_mr")!;
|
||
expect(step.error).toContain("Forbidden: no permission");
|
||
expect(step.error).toContain("https://code.byted.org/tiktok/tt_im_monorepo/merge_requests/new?merge_request%5Bsource_branch%5D=");
|
||
});
|
||
});
|