mirror of
https://github.com/awalsh128/cache-apt-pkgs-action.git
synced 2026-11-13 21:36:56 +00:00
test: cover cache restore and save failure paths
Codecov flagged lines in #246 as uncovered patch lines; they were untested before the reformat touched them. Add behavior tests for: - Cache: cache miss, missing or empty manifests, unreadable cache dir, metapackage-only restore, install scripts running after their archive with dpkg actions, existing archives, unavailable cache service, and save failures. - ManifestEntry.fromJSON round trip. - buildFileList dropping missing files, updateAptLists skipping update for populated lists and searching only to max depth, and fromInput ignoring a version without a package name. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
64a160d1cc
commit
eec6442bbe
|
|
@ -13,7 +13,7 @@ import {
|
|||
MANIFEST_MAIN_FILENAME,
|
||||
} from "../src/cache.js";
|
||||
import { Manifest, ManifestEntry } from "../src/manifest.js";
|
||||
import { ActionPackageNames } from "../src/packages.js";
|
||||
import { ActionPackageNames, findInstallScript } from "../src/packages.js";
|
||||
|
||||
// Cache resolves its directory from os.homedir(), so point it at a temp dir.
|
||||
const { HOME_DIR } = await vi.hoisted(async () => {
|
||||
|
|
@ -29,6 +29,11 @@ vi.mock("node:os", async (importOriginal) => {
|
|||
const actual = await importOriginal<typeof import("node:os")>();
|
||||
return { ...actual, homedir: () => HOME_DIR };
|
||||
});
|
||||
// Restore looks for install scripts under the real "/", so stub the lookup.
|
||||
vi.mock("../src/packages.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../src/packages.js")>();
|
||||
return { ...actual, findInstallScript: vi.fn() };
|
||||
});
|
||||
vi.mock("@actions/cache", () => ({
|
||||
restoreCache: vi.fn(),
|
||||
saveCache: vi.fn(),
|
||||
|
|
@ -66,18 +71,20 @@ async function writeCache(archivedPackages = INSTALL_ORDER): Promise<void> {
|
|||
archivedPackages.forEach((pkg) => fs.writeFileSync(archivePath(pkg), ""));
|
||||
}
|
||||
|
||||
/** Archive operations observed through the command runner. */
|
||||
/** Archive and install script operations observed through the command runner. */
|
||||
interface TarCalls {
|
||||
created: [archive: string, files: string[]][];
|
||||
extracted: string[];
|
||||
/** Number of commands run that extracted archives. */
|
||||
extractCommands?: number;
|
||||
/** Extractions and script runs, in the order they ran. */
|
||||
events?: string[];
|
||||
}
|
||||
|
||||
const argValue = (args: string[], flag: string) =>
|
||||
args.find((arg) => arg.startsWith(`${flag}=`))?.slice(flag.length + 1);
|
||||
|
||||
/** Records sudo tar calls, including the file list piped to tar create. */
|
||||
/** Records sudo tar and script calls, including the file list piped to tar create. */
|
||||
function recordTar(calls: TarCalls) {
|
||||
return vi.fn(async (_command: string, args: string[] = [], options: CommandOptions = {}) => {
|
||||
const archive = argValue(args, "--file") ?? "";
|
||||
|
|
@ -88,6 +95,11 @@ function recordTar(calls: TarCalls) {
|
|||
if (args[0] === "sh" && args[1] === "-c") {
|
||||
calls.extracted.push(...args.slice(4));
|
||||
calls.extractCommands = (calls.extractCommands ?? 0) + 1;
|
||||
calls.events?.push(...args.slice(4).map((archive) => `extract ${path.basename(archive)}`));
|
||||
}
|
||||
// Install scripts run as `sh -x <script> <action>`.
|
||||
if (args[0] === "sh" && args[1] === "-x") {
|
||||
calls.events?.push(`script ${path.basename(args[2] ?? "")} ${args[3]}`);
|
||||
}
|
||||
return { cmdLine: "", stdout: "", stderr: "", exitCode: 0 };
|
||||
});
|
||||
|
|
@ -103,6 +115,7 @@ describe("Cache", () => {
|
|||
vi.mocked(ghcache.restoreCache).mockResolvedValue(KEY.hash);
|
||||
vi.mocked(ghcache.saveCache).mockResolvedValue(CACHE_ID);
|
||||
vi.mocked(ghcache.isFeatureAvailable).mockReturnValue(true);
|
||||
vi.mocked(findInstallScript).mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
|
|
@ -196,4 +209,103 @@ describe("Cache", () => {
|
|||
[REQUESTED_PACKAGE.serialize(), filesOf(REQUESTED_PACKAGE)],
|
||||
]);
|
||||
});
|
||||
it("loadAndRestore cache miss returns undefined without extracting", async () => {
|
||||
vi.mocked(ghcache.restoreCache).mockResolvedValue(undefined);
|
||||
const calls: TarCalls = { created: [], extracted: [] };
|
||||
|
||||
const manifest = await createCache(calls).loadAndRestore(KEY, false);
|
||||
|
||||
expect(manifest).toBeUndefined();
|
||||
expect(calls.extracted).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["main manifest missing", MANIFEST_MAIN_FILENAME, undefined],
|
||||
["all manifest missing", MANIFEST_ALL_FILENAME, undefined],
|
||||
["all manifest empty", MANIFEST_ALL_FILENAME, new Manifest(MANIFEST.created, [], KEY)],
|
||||
])("loadAndRestore %s returns undefined without extracting", async (_case, filename, replacement) => {
|
||||
await writeCache();
|
||||
const filePath = path.join(CACHE_DIR, filename);
|
||||
fs.rmSync(filePath);
|
||||
await replacement?.writeToFile(filePath);
|
||||
const calls: TarCalls = { created: [], extracted: [] };
|
||||
|
||||
const manifest = await createCache(calls).loadAndRestore(KEY, false);
|
||||
|
||||
expect(manifest).toBeUndefined();
|
||||
expect(calls.extracted).toEqual([]);
|
||||
});
|
||||
|
||||
it("loadAndRestore cache hit without cache directory logs it as unreadable and returns undefined", async () => {
|
||||
const logger = winston.createLogger({ silent: true });
|
||||
const errorSpy = vi.spyOn(logger, "error");
|
||||
const cache = new Cache({ run: vi.fn() } as never, logger);
|
||||
|
||||
const manifest = await cache.loadAndRestore(KEY, false);
|
||||
|
||||
expect(manifest).toBeUndefined();
|
||||
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("Unable to read cache directory contents"));
|
||||
});
|
||||
|
||||
it("loadAndRestore only packages without files runs no extract command", async () => {
|
||||
fs.mkdirSync(CACHE_DIR, { recursive: true });
|
||||
const metaOnly = new Manifest(MANIFEST.created, [new ManifestEntry(METAPACKAGE)], KEY);
|
||||
await metaOnly.writeToFile(path.join(CACHE_DIR, MANIFEST_MAIN_FILENAME));
|
||||
await metaOnly.writeToFile(path.join(CACHE_DIR, MANIFEST_ALL_FILENAME));
|
||||
const calls: TarCalls = { created: [], extracted: [] };
|
||||
|
||||
const manifest = await createCache(calls).loadAndRestore(KEY, false);
|
||||
|
||||
expect(manifest?.entries).toHaveLength(1);
|
||||
expect(calls.extractCommands).toBeUndefined();
|
||||
});
|
||||
|
||||
it("loadAndRestore with install scripts runs each found script after its archive with the dpkg action", async () => {
|
||||
await writeCache();
|
||||
const [first, second] = INSTALL_ORDER;
|
||||
vi.mocked(findInstallScript).mockImplementation(async (packageName, scriptType) =>
|
||||
packageName.name === first!.name ? `/var/lib/dpkg/info/${packageName.name}.${scriptType}` : undefined,
|
||||
);
|
||||
const calls: TarCalls = { created: [], extracted: [], events: [] };
|
||||
|
||||
await createCache(calls).loadAndRestore(KEY, true);
|
||||
|
||||
expect(calls.events?.slice(0, 4)).toEqual([
|
||||
`extract ${path.basename(archivePath(first!))}`,
|
||||
`script ${first!.name}.preinst install`,
|
||||
`script ${first!.name}.postinst configure`,
|
||||
`extract ${path.basename(archivePath(second!))}`,
|
||||
]);
|
||||
});
|
||||
|
||||
it("archiveAndSave cache service unavailable throws without archiving", async () => {
|
||||
vi.mocked(ghcache.isFeatureAvailable).mockReturnValue(false);
|
||||
const calls: TarCalls = { created: [], extracted: [] };
|
||||
|
||||
await expect(createCache(calls).archiveAndSave(MANIFEST)).rejects.toThrow("not available");
|
||||
expect(calls.created).toEqual([]);
|
||||
});
|
||||
|
||||
it("archiveAndSave archive already exists skips recreating it", async () => {
|
||||
const [existing, ...rest] = INSTALL_ORDER;
|
||||
fs.mkdirSync(CACHE_DIR, { recursive: true });
|
||||
fs.writeFileSync(archivePath(existing!), "");
|
||||
const calls: TarCalls = { created: [], extracted: [] };
|
||||
|
||||
await createCache(calls).archiveAndSave(MANIFEST);
|
||||
|
||||
expect(calls.created.map(([archive]) => archive)).toEqual(rest.map(archivePath));
|
||||
});
|
||||
|
||||
it.each([
|
||||
["no cache ID", () => Promise.resolve(undefined), "no cache action ID returned"],
|
||||
["an Error", () => Promise.reject(new Error("upload failed")), "upload failed"],
|
||||
["a non-Error", () => Promise.reject("upload failed"), "upload failed"],
|
||||
])("archiveAndSave save returns %s throws a save error", async (_case, saveResult, message) => {
|
||||
vi.mocked(ghcache.saveCache).mockImplementation(saveResult as never);
|
||||
|
||||
await expect(createCache().archiveAndSave(MANIFEST)).rejects.toThrow(
|
||||
new RegExp(`^Failed to save cache: .*${message}`),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -37,4 +37,15 @@ describe("manifest", () => {
|
|||
expect(parsed.entries).toHaveLength(1);
|
||||
expect(parsed.entries[0]?.packageName.serialize()).toBe("curl:amd64=8.1.0");
|
||||
});
|
||||
|
||||
it("ManifestEntry fromJSON parsed entry returns package and sorted files", () => {
|
||||
const entry = new ManifestEntry(createPackageName("curl", "8.1.0", "amd64"), [
|
||||
"usr/bin/curl",
|
||||
"etc/curlrc",
|
||||
]);
|
||||
|
||||
const parsed = ManifestEntry.fromJSON(JSON.parse(JSON.stringify(entry)));
|
||||
|
||||
expect(parsed).toEqual(entry);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -101,6 +101,42 @@ describe("packages", () => {
|
|||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("buildFileList installed paths missing on disk excludes them", async () => {
|
||||
const root = makeTempRoot("pkg-missing-file-");
|
||||
const presentFile = path.join(root, "present");
|
||||
fs.writeFileSync(presentFile, "", "utf8");
|
||||
const manager = {
|
||||
listInstalledFiles: vi.fn().mockResolvedValue([presentFile, path.join(root, "absent")]),
|
||||
};
|
||||
|
||||
const result = await buildFileList(PACKAGE_NAME, manager as any, root);
|
||||
|
||||
expect(result).toEqual([presentFile.slice(1)]);
|
||||
});
|
||||
|
||||
it("updateAptLists lists directory with files skips update", async () => {
|
||||
const aptListsPath = makeTempRoot("apt-lists-populated-");
|
||||
fs.mkdirSync(path.join(aptListsPath, "partial"));
|
||||
fs.writeFileSync(path.join(aptListsPath, "partial", "archive_Packages"), "", "utf8");
|
||||
const packageManager = { update: vi.fn() };
|
||||
|
||||
await updateAptLists(packageManager as any, { info: vi.fn() } as any, aptListsPath);
|
||||
|
||||
expect(packageManager.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("updateAptLists files only below max search depth runs update", async () => {
|
||||
const aptListsPath = makeTempRoot("apt-lists-deep-");
|
||||
const deepDir = path.join(aptListsPath, "a", "b", "c", "d", "e");
|
||||
fs.mkdirSync(deepDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(deepDir, "archive_Packages"), "", "utf8");
|
||||
const packageManager = { update: vi.fn().mockResolvedValue(undefined) };
|
||||
|
||||
await updateAptLists(packageManager as any, { info: vi.fn() } as any, aptListsPath);
|
||||
|
||||
expect(packageManager.update).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("updateAptLists calls the package manager's update method", async () => {
|
||||
const aptListsPath = makeTempRoot("apt-lists-");
|
||||
|
||||
|
|
@ -128,6 +164,12 @@ describe("packages", () => {
|
|||
]);
|
||||
});
|
||||
|
||||
it("fromInput version without package name ignores the token", () => {
|
||||
const result = ActionPackageNames.fromInput("=1.0.0 curl");
|
||||
|
||||
expect(result.toArray()).toEqual([createPackageName("curl")]);
|
||||
});
|
||||
|
||||
it("fromInput returns an empty list when input is empty", () => {
|
||||
const result = ActionPackageNames.fromInput("");
|
||||
expect(result.toArray()).toEqual([]);
|
||||
|
|
|
|||
Loading…
Reference in a new issue