test(desktop): consolidate archive task and reader coverage (#13419)

This commit is contained in:
morluto authored and GitHub committed 2026-11-22 13:03:54 +00:00
1 parent 58af29e6b0
commit ec56d1b020
4 files changed
+239 -237

No files matched your search

+119 -157
View File
@@ -5,6 +5,7 @@ import { gzipSync } from "node:zlib";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { DesktopApplicationCapture } from "../../domain/desktop/desktopCapture.js";
import { desktopApplicationStateSchema } from "../../domain/desktop/desktopState.js";
import {
@@ -115,17 +116,10 @@ const HOLE = {
tolerance: 0.01,
};
/** The entries of the list document's last version in the capture's state view. */
const endEntries = async (folder: string) => {
const inspectArchives = async (folder: string) => {
const evidence = await inspectDesktopApplicationState(folder, readers);
if (!("normalized_result" in evidence)) throw evidence;
const state = desktopApplicationStateSchema.parse(evidence.normalized_result);
const end = state.paths
.find((entry) => entry.home_path === LIST)
?.versions.at(-1)?.view;
return (
(end as { entries: Record<string, unknown>[] } | undefined)?.entries ?? []
);
if (evidence instanceof Error) throw evidence;
return desktopApplicationStateSchema.parse(evidence.normalized_result);
};
const exportTask = async (folder: string, checks: unknown[]) => {
@@ -161,11 +155,10 @@ it.each([
const seed = gzipSync(archive(seedTitle), { level: 9 });
const end = gzipSync(archive("done"), { level: 0 });
const folder = await archiveCapture([seed, end]);
const state = await inspectDesktopApplicationState(folder, readers);
if (!("normalized_result" in state)) throw state;
const versions = desktopApplicationStateSchema
.parse(state.normalized_result)
.paths.find((entry) => entry.home_path === LIST)?.versions;
const state = await inspectArchives(folder);
const versions = state.paths.find(
(entry) => entry.home_path === LIST,
)?.versions;
expect(versions?.[0]).toMatchObject({
format: null,
compression: "gzip",
@@ -215,122 +208,46 @@ it("retains typed cancellation at the retained ZIP reader boundary", async () =>
expect(failure.cancellation?.reason).toBe(reason);
});
describe("documents saved as zip archives", () => {
it("reads each version into its entries and lists the change by entry and element name", async () => {
const evidence = await inspectDesktopApplicationState(
await archiveCapture(),
readers,
);
if (!("normalized_result" in evidence)) throw evidence;
const state = desktopApplicationStateSchema.parse(
evidence.normalized_result,
);
const path = state.paths.find((entry) => entry.home_path === PLATE);
const HOLE_ADDED =
"/entries/[name=Document.xml]/view/root/children/[name=Objects]/children/[name=Object][@name=Hole]";
expect(path).toMatchObject({
describe("documents saved as zip archives", () => {
it("drafts archive changes by name and exports them with guards that hold at both ends", async () => {
const folder = await archiveCapture();
const state = await inspectArchives(folder);
const plate = state.paths.find((entry) => entry.home_path === PLATE);
expect(plate).toMatchObject({
role: "document",
format: "zip",
versions: [
{ format: "zip", view: { entry_count: 2, truncated: false } },
{ format: "zip", view_error: null },
],
changes: [{ kind: "values", complete: true }],
changes: [
{
kind: "values",
complete: true,
added: expect.arrayContaining([HOLE_ADDED]),
},
],
});
expect(path?.changes[0]?.added).toContain(
"/entries/[name=Document.xml]/view/root/children/[name=Objects]/children/[name=Object][@name=Hole]",
);
});
it("exports a task that checks the hole and the list's namespaced XML by name", async () => {
const folder = await archiveCapture();
const milk = {
kind: "value_equals",
file: LIST,
pointer: `${LIST_TEXT}/[name=text:p]/children/0`,
value: "Buy milk",
const draft = await draftDesktopApplicationTask(folder, readers);
if (draft instanceof Error) throw draft;
const { files, task, guards } = draft.normalized_result as {
files: { file: string }[];
task: { checks: { id: string; file: string; pointer?: string }[] };
guards: { id: string }[];
};
const { result, directory } = await exportTask(folder, [HOLE, milk]);
if (result instanceof Error) throw result;
const verifier = await readFile(
join(directory, "artifacts/cut-hole-check/verify.py"),
"utf8",
);
expect(verifier).toContain(`"tolerance": 0.01`);
expect(verifier).toContain(JSON.stringify(milk.pointer));
});
it("accepts a check on the whole listing, whose value holds namespaced XML", async () => {
const folder = await archiveCapture();
const entries = await endEntries(folder);
expect(entries).toHaveLength(3);
const { result } = await exportTask(folder, [
{ kind: "value_equals", file: LIST, pointer: "/entries", value: entries },
]);
if (result instanceof Error) throw result;
});
it("exports checks of a namespaced entry's metadata, its absence, and the entry compared whole", async () => {
const comments = {
name: "comments.xml",
data: '<office:annotations xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"/>',
};
const folder = await archiveCapture([
odtArchive("Buy bread", [comments]),
odtArchive("Buy milk"),
]);
const content = (await endEntries(folder)).find(
(entry) => entry.name === "content.xml",
);
const { result } = await exportTask(folder, [
{
kind: "value_equals",
file: LIST,
pointer: "/entries/[name=content.xml]/size",
value: content?.size,
},
{
kind: "value_absent",
file: LIST,
pointer: "/entries/[name=comments.xml]",
},
]);
expect(
result instanceof Error
? (result as Error & { userMessage: string }).userMessage
: undefined,
).toBeUndefined();
const whole = await exportTask(folder, [
{
kind: "value_equals",
file: LIST,
pointer: "/entries/[name=content.xml]",
value: content,
},
]);
if (whole.result instanceof Error) throw whole.result;
});
it("drafts name-addressed checks of the archive that the export then accepts", async () => {
const folder = await archiveCapture();
const drafted = await draftDesktopApplicationTask(folder, readers);
if (drafted instanceof Error) throw drafted;
const task = (
drafted.normalized_result as {
task: { checks: { file: string; pointer?: string }[] };
}
).task;
expect(files.find(({ file }) => file === PLATE)).toMatchObject({
values_cut: false,
values: expect.arrayContaining([
expect.objectContaining({ kind: "added", pointer: HOLE_ADDED }),
]),
});
const archived = task.checks.filter(({ file }) => file === PLATE);
expect(archived.length).toBeGreaterThan(0);
expect(
archived.every(({ pointer }) => pointer?.includes("[name=") === true),
).toBe(true);
for (const { pointer } of archived) expect(pointer).toContain("[name=");
expect(task.checks.filter(({ file }) => file === LIST)).toEqual([
expect.objectContaining({
kind: "text_equals",
@@ -338,47 +255,92 @@ describe("documents saved as zip archives", () => {
value: "Buy milk",
}),
]);
const { result } = await exportTask(folder, task.checks);
expect(result).not.toBeInstanceOf(Error);
});
});
describe("task draft values and guards", () => {
/** The draft's files, checks and guards, as describe-desktop-application-task returns them. */
const draftOf = async (folder: string) => {
const drafted = await draftDesktopApplicationTask(folder, readers);
if (drafted instanceof Error) throw drafted;
return drafted.normalized_result as {
files: {
file: string;
values: { pointer: string; kind: string }[];
values_cut: boolean;
}[];
task: { checks: { id: string }[] };
guards: { id: string }[];
};
};
it("lists each archive's values by the pointers checks use, and guards the export accepts beside the checks", async () => {
const folder = await archiveCapture();
const { files, task, guards } = await draftOf(folder);
const plate = files.find(({ file }) => file === PLATE);
expect(plate?.values_cut).toBe(false);
expect(
plate?.values.map(({ kind, pointer }) => [kind, pointer]),
).toContainEqual([
"added",
"/entries/[name=Document.xml]/view/root/children/[name=Objects]/children/[name=Object][@name=Hole]",
]);
expect(guards.map(({ id }) => id)).toEqual(
guards.map((_, index) => `guard-${String(index + 1)}`),
);
expect(guards.length).toBeGreaterThan(0);
// Guards hold at the seed and the end, so the task still fails on the seed only through its checks.
const { result } = await exportTask(folder, [...task.checks, ...guards]);
if (result instanceof Error) throw result;
const report = result.normalized_result as {
tasks: { checks: number; failing_on_seed: string[] }[];
};
expect(report.tasks[0]?.checks).toBe(task.checks.length + guards.length);
const failures = report.tasks[0]?.failing_on_seed;
expect(failures).toContain(archived[0]?.id);
for (const { id } of guards) expect(failures).not.toContain(id);
});
it("exports archive member checks by name, including absence and whole-entry values", async () => {
const folder = await archiveCapture([
odtArchive("Buy bread", [
{
name: "comments.xml",
data: '<office:annotations xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"/>',
},
]),
odtArchive("Buy milk"),
]);
const state = await inspectArchives(folder);
const end = state.paths
.find(({ home_path }) => home_path === LIST)
?.versions.at(-1);
const entries = (
end?.view as { entries: { name: string; size: number }[] } | undefined
)?.entries;
const content = entries?.find(({ name }) => name === "content.xml");
expect(entries).toHaveLength(3);
if (content === undefined) throw new Error("Missing archived content.xml");
const milk = {
kind: "value_equals",
file: LIST,
pointer: `${LIST_TEXT}/[name=text:p]/children/0`,
value: "Buy milk",
};
const { result, directory } = await exportTask(folder, [
{ ...HOLE, value: 5.005 },
milk,
{ kind: "value_equals", file: LIST, pointer: "/entries", value: entries },
{
kind: "value_equals",
file: LIST,
pointer: "/entries/[name=content.xml]/size",
value: content.size,
},
{
kind: "value_absent",
file: LIST,
pointer: "/entries/[name=comments.xml]",
},
{
kind: "value_equals",
file: LIST,
pointer: "/entries/[name=content.xml]",
value: content,
},
]);
expect(
result,
result instanceof AnalysisError ? result.userMessage : undefined,
).toMatchObject({
normalized_result: {
tasks: [
{
failing_on_seed: [
"check-1",
"check-2",
"check-3",
"check-4",
"check-5",
"check-6",
],
},
],
},
});
const verifier = await readFile(
join(directory, "artifacts/cut-hole-check/verify.py"),
"utf8",
);
expect(verifier).toContain(`"tolerance": 0.01`);
expect(verifier).toContain(JSON.stringify(milk.pointer));
});
it("points a refused check at the draft's values", async () => {
@@ -1,4 +1,3 @@
import { randomBytes } from "node:crypto";
import { gzipSync } from "node:zlib";
import { describe, expect, it } from "vitest";
@@ -62,8 +61,7 @@ it("reads and checks BOM-signed UTF-16 project files in either byte order", asyn
bytes: Buffer.from('\ufeff{"zoom":1.5}', "utf16le"),
},
];
await expectSameFileViews(files);
const views = await Promise.all(files.map(typescriptFileView));
const views = await expectSameFileViews(files);
expect(views.map(({ format }) => format)).toEqual([
"xml",
"xml",
@@ -102,11 +100,9 @@ describe("gzip files in the exported module", () => {
it("reads a compressed drawing as the view of the drawing inside, and grades it alike", async () => {
const files = await posters();
const [, plain] = await savedEnds("inkscape", "poster.svg");
const [, after] = files;
if (plain === undefined || after === undefined) throw new Error("fixture");
await expectSameFileViews(files);
expect(await typescriptFileView(after)).toEqual({
if (plain === undefined) throw new Error("fixture");
const [, after] = await expectSameFileViews(files);
expect(after).toEqual({
...(await typescriptFileView(plain)),
compression: "gzip",
});
@@ -149,12 +145,11 @@ describe("gzip files in the exported module", () => {
{ name: "bomb.xml", bytes: bomb },
{
name: "large.txt",
bytes: gzipSync(randomBytes(9 * MIB).toString("hex")),
bytes: gzipSync(Buffer.alloc(16 * MIB + 1), { level: 0 }),
},
];
await expectSameFileViews(files);
const views = await Promise.all(files.map(typescriptFileView));
const views = await expectSameFileViews(files);
expect(views.map(({ format, error }) => [format, error ?? null])).toEqual([
["xml", null],
["xml", null],
@@ -22,6 +22,7 @@ import { zipEntryRefusal } from "../../../src/domain/desktop/zipView.js";
import {
desktopViewPolicy,
pythonDesktopViewPolicy,
type DesktopViewPolicy,
} from "../../../src/domain/desktop/desktopViewPolicy.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
@@ -29,6 +30,7 @@ import {
expectSameFileViews,
exportedPython,
pythonFileViews,
typescriptFileView,
writeFiles,
} from "../../support/desktopExportPython.js";
import {
@@ -44,15 +46,16 @@ const FIXTURES = join(import.meta.dirname, "../../fixtures/freecad");
const saved = (archives: readonly Buffer[]) =>
archives.map((bytes) => ({ name: "plate.FCStd", bytes }));
const expectSameViews = (archives: readonly Buffer[]) =>
expectSameFileViews(saved(archives));
const expectSameViews = (
archives: readonly Buffer[],
policy?: DesktopViewPolicy,
) => expectSameFileViews(saved(archives), policy);
/** REA's view of an archive, once the exported module's is shown to be the same. */
const sameView = async (archive: Buffer) => {
await expectSameViews([archive]);
const read = await readZipView(archive);
if (!read.ok) throw new Error(read.error);
return read.value;
const sameView = async (archive: Buffer, policy?: DesktopViewPolicy) => {
const [file] = await expectSameViews([archive], policy);
if (file?.view == null) throw new Error(file?.error ?? "No ZIP view");
return file.view;
};
/** The exported module's zip view of an archive file, and the most memory reading it traced. */
@@ -61,17 +64,37 @@ const pythonPeak = async (archive: Buffer) =>
exportedPython(
`import tracemalloc
tracemalloc.start()
view = _view(Path(json.load(sys.stdin)[0]))["view"]
file = _view(Path(json.load(sys.stdin)[0]))
peak = tracemalloc.get_traced_memory()[1]
tracemalloc.stop()
print(json.dumps({"view": view, "peak": peak}))`,
print(json.dumps({"file": file, "peak": peak}))`,
await writeFiles(saved([archive])),
),
) as {
view: { entries: Record<string, JsonValue>[]; entry_count: number };
file: {
format: "zip";
truncated: boolean;
view: {
entries: Record<string, JsonValue>[];
entry_count: number;
truncated: boolean;
};
};
peak: number;
};
const expectSameTrackedView = async (archive: Buffer) => {
const {
file: { truncated, ...file },
peak,
} = await pythonPeak(archive);
expect(file).toEqual(
await typescriptFileView({ name: "plate.FCStd", bytes: archive }),
);
expect(truncated).toBe(file.view.truncated);
return { file, peak };
};
const sqliteHeader = Buffer.concat([
Buffer.from("SQLite format 3\0"),
Buffer.alloc(84),
@@ -228,11 +251,13 @@ it("excludes a final Unicode directory without consuming a retained file slot",
]),
},
{ name: "control.json", data: '{"kept":true}' },
{ name: "later.txt", data: "after the selected limit" },
]);
expect(await sameView(archive)).toMatchObject({
const policy = desktopViewPolicy({ zip_entries: 1 });
expect(await sameView(archive, policy)).toMatchObject({
entries: [{ name: "control.json", view: { kept: true } }],
entry_count: 1,
truncated: false,
entry_count: 2,
truncated: true,
});
});
@@ -251,14 +276,9 @@ describe("zip views in the exported module", () => {
{ name: "big.json", data: '{"id": 9007199254740993}' },
];
await expectSameViews([zipArchive(members)]);
const read = await readZipView(zipArchive(members));
expect(read).toMatchObject({
ok: true,
value: { entry_count: 9, truncated: false },
});
if (!read.ok) return;
expect(read.value).toMatchObject({
expect(await sameView(zipArchive(members))).toMatchObject({
entry_count: 9,
truncated: false,
entries: [
{ name: "settings.json", format: "json", view: { zoom: 1.5 } },
{ name: "app.ini", format: "keyfile" },
@@ -311,9 +331,8 @@ describe("zip views in the exported module", () => {
Buffer.alloc(60, 7),
]);
await expectSameViews([archive, damaged]);
const read = await readZipView(archive);
expect(read.ok && read.value).toMatchObject({
const [read, refusal] = await expectSameViews([archive, damaged]);
expect(read?.view).toMatchObject({
entries: [
{ view_error: "encrypted, so it is not read", sha256: null },
{
@@ -331,32 +350,13 @@ describe("zip views in the exported module", () => {
{ format: "text", view_error: null },
],
});
expect(await readZipView(damaged)).toEqual({
ok: false,
expect(refusal).toEqual({
format: "zip",
view: null,
error: "not a readable zip archive",
});
});
it("lists at most 1,000 entries and counts the rest", async () => {
const archive = zipArchive(
Array.from({ length: 1002 }, (_, index) => ({
name: `n/${String(index)}.txt`,
data: String(index),
method: 0,
})),
);
await expectSameViews([archive]);
const read = await readZipView(archive);
expect(read.ok && read.value).toMatchObject({
entry_count: 1002,
truncated: true,
});
expect(
read.ok && (read.value as { entries: unknown[] }).entries,
).toHaveLength(1000);
});
it("stops reading an archive at 64 MiB of entries, as the exported reader does", () => {
const headers = [
[{ size: 10, compressedSize: 10 }, 64 * MIB - 10],
@@ -395,6 +395,36 @@ print(json.dumps([_zip_refusal(SimpleNamespace(flag_bits=0, compress_type=8, fil
});
});
it("charges admitted bytes across the archive and still reads empty entries", async () => {
const archive = zipArchive([
{ name: "over-entry.txt", data: "abc", method: 0 },
{ name: "first.txt", data: "ab", method: 0 },
{ name: "fills-budget.txt", data: "cd", method: 0 },
{ name: "over-budget.txt", data: "e", method: 0 },
{ name: "empty.txt", data: "", method: 0 },
]);
const policy = desktopViewPolicy({ zip_bytes: 4, zip_entry_bytes: 2 });
expect(await sameView(archive, policy)).toMatchObject({
entry_count: 5,
truncated: false,
entries: [
{
name: "over-entry.txt",
sha256: null,
view_error: "larger than the 2 bytes an entry's view reads",
},
{ name: "first.txt", view: { lines: ["ab"] }, view_error: null },
{ name: "fills-budget.txt", view: { lines: ["cd"] }, view_error: null },
{
name: "over-budget.txt",
sha256: null,
view_error: "past the 4 bytes read from one archive",
},
{ name: "empty.txt", size: 0, view_error: null },
],
});
});
describe("zip directories in the exported module", () => {
it("tells directories apart as zip.js does: by a final slash, a Unix mode or the MS-DOS attribute", async () => {
const archive = zipArchive([
@@ -633,13 +663,14 @@ print(json.dumps(None if view is None else {
});
it("lists the first 1,000 of 50,000 entries holding no more of the directory than those", async () => {
const archive = emptyEntriesArchive(50_000);
await expectSameViews([archive]);
const { file, peak } = await expectSameTrackedView(
emptyEntriesArchive(50_000),
);
const { view, peak } = await pythonPeak(archive);
expect(view.entries).toHaveLength(1000);
expect(view.entry_count).toBe(50_000);
expect(file.view).toMatchObject({ entry_count: 50_000, truncated: true });
expect(file.view.entries).toHaveLength(1000);
expect(file.view.entries[0]?.name).toBe("e/0");
expect(file.view.entries.at(-1)?.name).toBe("e/999");
// Parsing every record before the listing limit applied traced about 25 MiB here.
expect(peak).toBeLessThan(4 * MIB);
});
@@ -656,11 +687,11 @@ describe("zip entries the exported module cannot fully read", () => {
crc: 0,
},
]);
await expectSameViews([archive]);
const { file, peak } = await expectSameTrackedView(archive);
const { view, peak } = await pythonPeak(archive);
expect(view.entries[0]?.view_error).toBe("its compressed data is damaged");
expect(file.view.entries[0]?.view_error).toBe(
"its compressed data is damaged",
);
// Reading the stream whole before clipping it traced about 77 MiB here.
expect(peak).toBeLessThan(4 * MIB);
});
+27 -13
View File
@@ -16,6 +16,10 @@ import {
PYTHON_IMPORTS,
} from "../../src/domain/desktop/appExportPython.js";
import { PYTHON_TASK_EVALUATOR } from "../../src/domain/desktop/appTaskPython.js";
import {
pythonDesktopViewPolicy,
type DesktopViewPolicy,
} from "../../src/domain/desktop/desktopViewPolicy.js";
import {
compressionOf,
openStateDocument,
@@ -95,10 +99,14 @@ export const writeFiles = async (files: readonly SavedFile[]) => {
};
/** The exported module's data/get entry for each file: its format and view, or its error. */
export const pythonFileViews = async (files: readonly SavedFile[]) =>
export const pythonFileViews = async (
files: readonly SavedFile[],
policy?: DesktopViewPolicy,
) =>
printed<Record<string, JsonValue>>(
exportedPython(
`for path in json.load(sys.stdin):
`${policy === undefined ? "" : pythonDesktopViewPolicy(policy)}
for path in json.load(sys.stdin):
print(json.dumps(_view(Path(path))))`,
await writeFiles(files),
),
@@ -130,11 +138,11 @@ export const pythonXmlViews = (texts: readonly string[]) =>
);
/** REA's state view of a zip, text, JSON, key file, XML or binary file, plain or gzip-compressed, in the shape data/get serves it. */
export const typescriptFileView = async ({
name,
bytes,
}: SavedFile): Promise<TaskFileView> => {
const document = openStateDocument(name, bytes);
export const typescriptFileView = async (
{ name, bytes }: SavedFile,
policy?: DesktopViewPolicy,
): Promise<TaskFileView> => {
const document = openStateDocument(name, bytes, policy);
const file = { format: document.format, ...compressionOf(document) };
if ("error" in document)
return { ...file, view: null, error: document.error };
@@ -144,24 +152,30 @@ export const typescriptFileView = async ({
if (format === "binary") return { ...file, view: null };
const read =
format === "zip"
? await readZipView(document.bytes)
: textualView(format, document.bytes);
? await readZipView(document.bytes, undefined, policy)
: textualView(format, document.bytes, policy);
return read.ok
? { ...file, view: read.value }
: { ...file, view: null, error: read.error };
};
/** Both readers give each file the same format and view, or the same error. */
export const expectSameFileViews = async (files: readonly SavedFile[]) => {
const fromPython = await pythonFileViews(files);
/** Check format, view and error parity. Return the host views for assertions. */
export const expectSameFileViews = async (
files: readonly SavedFile[],
policy?: DesktopViewPolicy,
) => {
const fromPython = await pythonFileViews(files, policy);
const views: TaskFileView[] = [];
for (const [index, file] of files.entries()) {
const ours = await typescriptFileView(file);
const ours = await typescriptFileView(file, policy);
const theirs = fromPython[index] ?? {};
expect(theirs.format).toBe(ours.format);
expect(theirs.compression).toBe(ours.compression);
expect(theirs.view).toEqual(ours.view);
expect(theirs.error).toBe(ours.error);
views.push(ours);
}
return views;
};
/** Both evaluators give the same results and descriptions on each file read as the home path `home`; REA's. */