// MUST be first — pins env before anything that reads it at module load. import "./setup_env"; import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { bitsDevTaskOpenApiBody, createBitsDevTask, type BitsDevTaskCreateInput, type BitsDevTaskPreparedBody, } from "../src/bits_dev_task"; const realFetch = globalThis.fetch; const APP = { projectName: "tiktok_im_business_page", scmName: "tiktok/im/business_page", projectUniqueId: "68d38ce6003b041ba643fcf3", }; const INPUT: BitsDevTaskCreateInput = { spaceId: "39151416834", teamFlowId: 424599259394, workflowId: 25538, applications: [APP], projectType: "HYBRID", controlPanel: "I18N", repoPath: "tiktok/tt_im_monorepo", sourceBranch: "feature/streamline-dev-task-test", targetBranch: "master", title: "(Streamline) development task test", mrType: "bug", meegoTaskId: "7034950124", }; const NODE_ID = "766087"; const PREPARED: BitsDevTaskPreparedBody = { applications: [{ ...APP, appName: "tiktok_im_business_page", nodeId: 10990000, scmId: 410000, gitRepoName: "tiktok/tt_im_monorepo", gitRepoId: 753114, }], memberEmail: "johnlee@bytedance.com", envSettingMap: { [NODE_ID]: { boe: { enabled: false, lanes: [] }, ppe: { enabled: true, lanes: [{ laneType: "ppe_i18n_env_", laneId: "feature_d_${random}", overwritePrefix: "ppe_", laneGcStrategy: 1, disableDeploy: false, envTypes: [2], stageId: NODE_ID, stageName: "自测流水线", }], }, }, }, envProjectData: { method: "CreateBizEnvConfig", data: JSON.stringify({ nodeConfigs: [{ nodeID: Number(NODE_ID) }], projectConfigs: [] }), }, }; function bitsDevTaskPrepareReply(url: string, requestBody: any, createReply: unknown = { code: 200, data: { devBasicId: 2709999 } }) { if (url.includes("/openapi/onesite/v1/user/me")) { return { code: 200, data: { jwtToken: "test-jwt", email: "johnlee@bytedance.com", username: "johnlee" } }; } if (url.includes("/api/v1/dev/app/components")) { const uid = requestBody?.queryProjects?.[0]?.projectUniqueId || APP.projectUniqueId; return { code: 200, data: { projects: [{ projectType: 5, projectUniqueId: uid, projectName: "tiktok_im_business_page", nodeId: "10990000", controlPlaneDetail: [{ controlPlane: 2, scmInfo: [{ id: "410000", name: "tiktok/im/business_page", isMain: true, gitRepoName: "tiktok/tt_im_monorepo", gitRepoId: "753114", }], }], }], }, }; } if (url.includes("/api/v1/dev/config/workflow/get")) { return { code: 200, data: { workflow: { orchestration: [{ id: Number(NODE_ID), name: "自测流水线", nodeType: 10, nodeConfig: { ciPipelineNodeConfig: { env: { ppe: { enabled: true, lanes: [{ laneType: "ppe_i18n_env_", laneId: "feature_d_${random}", overwritePrefix: "ppe_", laneGcStrategy: "LANE_GC_STRATEGY_TYPE_AFTER_RELEASE", envTypes: ["ENV_TYPE_LANE"], }], }, }, }, }, }], }, }, }; } if (url.includes("/api/v5/env/env_manager/get_project_env_config")) { const nodeConfigs = requestBody?.nodeConfigs ?? []; return { BaseResp: { StatusCode: 0 }, nodeConfigs: nodeConfigs.length ? nodeConfigs : [{ nodeID: Number(NODE_ID), nodeName: "自测流水线", ppe: { enabled: true, lanes: [{ laneType: "ppe_i18n_env_", laneId: "feature_d_${random}", overwritePrefix: "ppe_", laneGcStrategy: 1, envTypes: [2], }], }, }], projectConfigs: [{ projectUniqueId: APP.projectUniqueId }], }; } if (url.includes("/api/v1/dev/task/checks/mr")) { return { code: 200, data: { hasExisted: false } }; } return createReply; } beforeEach(() => { globalThis.fetch = realFetch; }); afterEach(() => { globalThis.fetch = realFetch; }); function stubPrepareThenCreate(createReply: unknown = { code: 200, data: { devBasicId: 2709999 } }, createStatus = 200) { const calls: { url: string; init?: RequestInit; body: any }[] = []; globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { const url = String(input); const body = init?.body ? JSON.parse(String(init.body)) : null; calls.push({ url, init, body }); const payload = bitsDevTaskPrepareReply(url, body, createReply); const status = url.includes("/openapi/onesite/v1/dev/create") ? createStatus : 200; return new Response(JSON.stringify(payload), { status }); }) as typeof fetch; return calls; } describe("tt_im_monorepo Bits 开发任务创建器", () => { test("OpenAPI create 请求体钉死在需求研发流程,不携带 legacy host group", () => { const body = bitsDevTaskOpenApiBody(INPUT, PREPARED); expect(body.task).toMatchObject({ title: "(Streamline) development task test", name: "(Streamline) development task test", space_id: 39151416834, team_flow_id: 424599259394, dev_task_template_id: 25538, }); expect((body as any).projects[0].project_info).toMatchObject({ type: "PROJECT_TYPE_HYBRID", project_unique_id: "68d38ce6003b041ba643fcf3", }); expect((body as any).projects[0].build_configs[0].scm_dependencies[0].id).toBe(410000); expect((body as any).members).toEqual([{ email: "johnlee@bytedance.com", role: 0 }]); expect((body as any).env_setting_map[NODE_ID].ppe.lanes[0].lane_id).toBe("feature_d_${random}"); expect((body as any).env_project_data.method).toBe("CreateBizEnvConfig"); expect(JSON.stringify(body)).not.toContain("ppe_test_123"); expect((body as any).changes[0].manifest.code_element).toMatchObject({ repo_path: "tiktok/tt_im_monorepo", source_branch: "feature/streamline-dev-task-test", target_branch: "master", iid: 0, repo_id: 753114, }); expect(JSON.stringify(body)).not.toContain("host_group_name"); expect(JSON.stringify(body)).not.toContain("TikTok-IM-FE"); }); test("create 前只读补齐,只发一次 create,覆盖目标分支并立即返回开发任务链接", async () => { const calls = stubPrepareThenCreate(); const result = await createBitsDevTask( { ...INPUT, targetBranch: "feature/acceptance-baseline" }, { token: "personal-test-token" }, ); expect(result).toMatchObject({ ok: true, devTaskId: 2709999 }); expect(result.url).toBe("https://bits.bytedance.net/devops/39151416834/develop/detail/2709999?devops_space_type=server_fe"); const createCalls = calls.filter((c) => c.url.includes("/openapi/onesite/v1/dev/create")); expect(createCalls).toHaveLength(1); expect(calls.some((c) => c.url.includes("/user/me"))).toBe(true); expect(calls.some((c) => c.url.includes("/app/components"))).toBe(true); expect(calls.some((c) => c.url.includes("/config/workflow/get"))).toBe(true); expect(calls.some((c) => c.url.includes("/get_project_env_config"))).toBe(true); const create = createCalls[0]; expect(create.body.changes[0].manifest.code_element.target_branch).toBe("feature/acceptance-baseline"); expect(create.body.work_items[0]).toMatchObject({ id: "7034950124", type: "issue", url: "https://meego.larkoffice.com/tiktok/issue/detail/7034950124", }); expect(Number.isFinite(create.body.work_items[0].timestamp)).toBe(true); expect(create.body.task).toMatchObject({ title: "(Streamline) development task test", space_id: 39151416834, team_flow_id: 424599259394, dev_task_template_id: 25538, }); expect(create.body.env_setting_map[NODE_ID].ppe.lanes[0].lane_id).toContain("feature_d_"); expect(JSON.stringify(create.body)).not.toContain("ppe_test_123"); const headers = new Headers(create.init?.headers); expect(headers.get("authorization")).toBe("Bearer personal-test-token"); expect(headers.has("x-jwt-token")).toBe(false); expect(headers.has("x-onesite")).toBe(false); expect(headers.has("x-bits-user")).toBe(false); const envHeaders = new Headers(calls.find((c) => c.url.includes("/get_project_env_config"))?.init?.headers); expect(envHeaders.get("x-jwt-token")).toBe("test-jwt"); }); test("work_items 按工单类型走:Feature 带的需求单和缺陷单各指向自己的链接", () => { const item = (over: Partial) => bitsDevTaskOpenApiBody({ ...INPUT, mrType: "feature", ...over }, PREPARED).work_items as Record[]; expect(item({ meegoTaskId: "7382040553", meegoTaskType: "issue", meegoProjectKey: "tiktok" })[0]).toMatchObject({ type: "feature", url: "https://meego.larkoffice.com/tiktok/story/detail/7382040553", }); expect(item({ meegoTaskId: "7365664146", meegoTaskType: "bug", meegoProjectKey: "tiktok" })[0]).toMatchObject({ type: "issue", url: "https://meego.larkoffice.com/tiktok/issue/detail/7365664146", }); }); test("create 返回对象型 message 时同样保留业务原因", async () => { stubPrepareThenCreate({ code: 400, message: { reason: "应用信息缺少 SCM 权限", log_id: "fixture-log-id" }, }, 400); const result = await createBitsDevTask(INPUT, { token: "personal-test-token" }); expect(result.ok).toBe(false); expect(result.error).toContain("应用信息缺少 SCM 权限"); expect(result.error).toContain("fixture-log-id"); expect(result.error).not.toContain("[object Object]"); }); test("user/me 换不到 JWT 时停止,不发 create", async () => { let creates = 0; globalThis.fetch = (async (input: RequestInfo | URL) => { const url = String(input); if (url.includes("/dev/create")) creates++; return new Response(JSON.stringify({ code: 200, data: { username: "johnlee" } }), { status: 200 }); }) as typeof fetch; const result = await createBitsDevTask(INPUT, { token: "personal-test-token" }); expect(result.ok).toBe(false); expect(result.error).toContain("换 JWT"); expect(creates).toBe(0); }); test("缺少 projectUniqueId 时停止,不发写请求", async () => { let fetches = 0; globalThis.fetch = (async () => { fetches++; throw new Error("must not create"); }) as typeof fetch; const result = await createBitsDevTask({ ...INPUT, applications: [{ projectName: "tiktok_im_business_page", scmName: "tiktok/im/business_page" }], }, { token: "personal-test-token" }); expect(result.ok).toBe(false); expect(result.error).toContain("缺少 projectUniqueId"); expect(fetches).toBe(0); }); test("未从仓库元数据解析出应用时停止", async () => { let fetches = 0; globalThis.fetch = (async () => { fetches++; throw new Error("must not create"); }) as typeof fetch; const result = await createBitsDevTask({ ...INPUT, applications: [] }, { token: "personal-test-token" }); expect(result.ok).toBe(false); expect(result.error).toContain("未识别到 tt_im_monorepo"); expect(fetches).toBe(0); }); });