-
-
Notifications
You must be signed in to change notification settings - Fork 97
test: mock create-pr git subprocess calls #756
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,20 +1,82 @@ | ||
| import { execSync } from "node:child_process"; | ||
| import { EventEmitter } from "node:events"; | ||
| import fs from "node:fs"; | ||
| import os from "node:os"; | ||
| import path from "node:path"; | ||
| import { | ||
| buildPullRequestBody, | ||
| buildPullRequestTitle, | ||
| collectAdvisoryIdsForPackage, | ||
| defaultFixBranchName, | ||
| findingsMeetFailOnThreshold, | ||
| selectAvailableBranchName, | ||
| stageDependencyFilesOnly, | ||
| import { jest } from "@jest/globals"; | ||
| import type { | ||
| buildPullRequestBody as buildPullRequestBodyType, | ||
| buildPullRequestTitle as buildPullRequestTitleType, | ||
| collectAdvisoryIdsForPackage as collectAdvisoryIdsForPackageType, | ||
| defaultFixBranchName as defaultFixBranchNameType, | ||
| findingsMeetFailOnThreshold as findingsMeetFailOnThresholdType, | ||
| selectAvailableBranchName as selectAvailableBranchNameType, | ||
| stageDependencyFilesOnly as stageDependencyFilesOnlyType, | ||
| } from "../src/utils/create-pr.js"; | ||
| import type { Finding, OsvVuln } from "../src/types.js"; | ||
| import { validateOptions } from "../src/cli/validate.js"; | ||
| import { parseArgs } from "../src/cli/args.js"; | ||
|
|
||
| const spawnMock = jest.fn(); | ||
| const unstableMockModule = (jest as unknown as { | ||
| unstable_mockModule: (moduleName: string, moduleFactory: () => unknown) => typeof jest; | ||
| }).unstable_mockModule; | ||
|
|
||
| unstableMockModule("node:child_process", () => ({ | ||
| spawn: spawnMock, | ||
| })); | ||
|
|
||
| let buildPullRequestBody: typeof buildPullRequestBodyType; | ||
| let buildPullRequestTitle: typeof buildPullRequestTitleType; | ||
| let collectAdvisoryIdsForPackage: typeof collectAdvisoryIdsForPackageType; | ||
| let defaultFixBranchName: typeof defaultFixBranchNameType; | ||
| let findingsMeetFailOnThreshold: typeof findingsMeetFailOnThresholdType; | ||
| let selectAvailableBranchName: typeof selectAvailableBranchNameType; | ||
| let stageDependencyFilesOnly: typeof stageDependencyFilesOnlyType; | ||
|
|
||
| type MockCommandResult = { | ||
| stdout?: string; | ||
| stderr?: string; | ||
| status?: number | null; | ||
| error?: Error; | ||
| }; | ||
|
|
||
| function queueCommandResults(results: MockCommandResult[]): void { | ||
| const queue = [...results]; | ||
| spawnMock.mockImplementation(() => { | ||
| const result = queue.shift() ?? { status: 0 }; | ||
| const child = new EventEmitter() as EventEmitter & { stdout: EventEmitter; stderr: EventEmitter }; | ||
| child.stdout = new EventEmitter(); | ||
| child.stderr = new EventEmitter(); | ||
|
|
||
| process.nextTick(() => { | ||
| if (result.error) { | ||
| child.emit("error", result.error); | ||
| return; | ||
| } | ||
| if (result.stdout) child.stdout.emit("data", result.stdout); | ||
| if (result.stderr) child.stderr.emit("data", result.stderr); | ||
| child.emit("close", result.status ?? 0); | ||
| }); | ||
|
|
||
| return child; | ||
| }); | ||
| } | ||
|
|
||
| beforeAll(async () => { | ||
| const mod = await import("../src/utils/create-pr.js"); | ||
| buildPullRequestBody = mod.buildPullRequestBody; | ||
| buildPullRequestTitle = mod.buildPullRequestTitle; | ||
| collectAdvisoryIdsForPackage = mod.collectAdvisoryIdsForPackage; | ||
| defaultFixBranchName = mod.defaultFixBranchName; | ||
| findingsMeetFailOnThreshold = mod.findingsMeetFailOnThreshold; | ||
| selectAvailableBranchName = mod.selectAvailableBranchName; | ||
| stageDependencyFilesOnly = mod.stageDependencyFilesOnly; | ||
| }); | ||
|
|
||
| beforeEach(() => { | ||
| spawnMock.mockReset(); | ||
| }); | ||
|
|
||
| function createFinding(overrides?: Partial<Finding>): Finding { | ||
| const vuln: OsvVuln = { | ||
| id: "GHSA-abc", | ||
|
|
@@ -105,28 +167,47 @@ describe("create-pr helpers", () => { | |
| }); | ||
|
|
||
| it("adds numeric suffix when branch already exists", async () => { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This test covers the "branch already exists" case, but there's no test for the happy path where the base branch name is free on the first check - i.e. |
||
| const branch = await selectAvailableBranchName(process.cwd(), "cve-lite/fix-2026-06-02"); | ||
| expect(branch).toMatch(/^cve-lite\/fix-2026-06-02(?:-\d+)?$/); | ||
| queueCommandResults([{ status: 0 }, { status: 1 }]); | ||
|
|
||
| await expect(selectAvailableBranchName("/repo", "cve-lite/fix-2026-06-02")).resolves.toBe( | ||
| "cve-lite/fix-2026-06-02-2", | ||
| ); | ||
| expect(spawnMock).toHaveBeenNthCalledWith( | ||
| 1, | ||
| "git", | ||
| ["rev-parse", "--verify", "cve-lite/fix-2026-06-02"], | ||
| expect.objectContaining({ cwd: "/repo" }), | ||
| ); | ||
| expect(spawnMock).toHaveBeenNthCalledWith( | ||
| 2, | ||
| "git", | ||
| ["rev-parse", "--verify", "cve-lite/fix-2026-06-02-2"], | ||
| expect.objectContaining({ cwd: "/repo" }), | ||
| ); | ||
| }); | ||
|
|
||
| it("stages only existing dependency files without failing on missing lockfiles", async () => { | ||
| it("stages only existing dependency files without requiring a git repository", async () => { | ||
| const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "cve-lite-create-pr-")); | ||
| try { | ||
| execSync("git init", { cwd: tmpDir, stdio: "ignore" }); | ||
| execSync('git config user.email "test@example.com"', { cwd: tmpDir, stdio: "ignore" }); | ||
| execSync('git config user.name "Test User"', { cwd: tmpDir, stdio: "ignore" }); | ||
|
|
||
| fs.writeFileSync(path.join(tmpDir, "package.json"), '{"name":"test"}\n'); | ||
| fs.writeFileSync(path.join(tmpDir, "package-lock.json"), '{"lockfileVersion":3}\n'); | ||
| execSync("git add package.json package-lock.json", { cwd: tmpDir, stdio: "ignore" }); | ||
| execSync('git commit -m "init"', { cwd: tmpDir, stdio: "ignore" }); | ||
|
|
||
| fs.writeFileSync(path.join(tmpDir, "package.json"), '{"name":"test","version":"1.0.1"}\n'); | ||
| queueCommandResults([{ status: 0 }, { status: 0 }]); | ||
|
|
||
| await expect(stageDependencyFilesOnly(tmpDir)).resolves.toBeUndefined(); | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The original test verified something specific: that only the modified file got staged, not the unchanged one. The new test asserts |
||
|
|
||
| const staged = execSync("git diff --cached --name-only", { cwd: tmpDir, encoding: "utf8" }); | ||
| expect(staged.trim().split("\n")).toEqual(["package.json"]); | ||
| expect(spawnMock).toHaveBeenCalledTimes(2); | ||
| expect(spawnMock).toHaveBeenNthCalledWith( | ||
| 1, | ||
| "git", | ||
| ["add", "--", "package.json"], | ||
| expect.objectContaining({ cwd: tmpDir }), | ||
| ); | ||
| expect(spawnMock).toHaveBeenNthCalledWith( | ||
| 2, | ||
| "git", | ||
| ["add", "--", "package-lock.json"], | ||
| expect.objectContaining({ cwd: tmpDir }), | ||
| ); | ||
| } finally { | ||
| fs.rmSync(tmpDir, { recursive: true, force: true }); | ||
| } | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This cast isn't needed -
jest.unstable_mockModuleis typed in@jest/globalssince Jest 29, which this project already has as a dev dependency. Callingjest.unstable_mockModule(...)directly should work and means TypeScript will catch any signature changes.