1
// @vitest-environment node
3
import path from "path";
4
import { loadPyodide, PyodideInterface } from "pyodide";
5
import { describe, it, expect, beforeEach, beforeAll } from "vitest";
6
import { writeFileWithParents, renameWithParents } from "./file";
8
describe("writeFileWithParents()", () => {
9
let pyodide: PyodideInterface;
11
beforeAll(async () => {
12
pyodide = await loadPyodide({
13
indexURL: path.resolve(__dirname, "../../node_modules/pyodide")
17
const testCases: { paths: string[] }[] = [
18
{ paths: ["foo.py"] },
19
{ paths: ["foo/bar.py"] },
20
{ paths: ["foo/bar/baz.py", "foo/hoge.py"] },
21
{ paths: ["foo/bar/baz/pii.py"] },
22
{ paths: ["foo/bar/baz/boo.py", "foo/bar/hoge.py"] },
23
{ paths: ["/boo/foo.py"] }
25
testCases.forEach(({ paths }) => {
26
it(`writes files (${paths})`, () => {
27
for (const path of paths) {
28
expect(pyodide.FS.analyzePath(path).exists).toBe(false);
30
writeFileWithParents(pyodide, path, "# Test");
32
expect(pyodide.FS.analyzePath(path).exists).toBe(true);
33
expect(pyodide.FS.readFile(path, { encoding: "utf8" })).toEqual(
40
it("can write binary files", () => {
41
const path = "foo/bar.dat";
42
const uint8View = new Uint8Array([0, 1, 2, 3]); // Random data
43
writeFileWithParents(pyodide, path, uint8View);
44
expect(pyodide.FS.readFile(path)).toEqual(uint8View);
48
describe("renameWithParents", () => {
49
let pyodide: PyodideInterface;
51
beforeAll(async () => {
52
pyodide = await loadPyodide({
53
indexURL: path.resolve(__dirname, "../../node_modules/pyodide")
57
const testCases: { oldPath: string; newPath: string }[] = [
58
{ oldPath: "foo.py", newPath: "bar.py" }, // Same dir, without a parent path
59
{ oldPath: "foo.py", newPath: "bar/baz.py" }, // To a nested dir
60
{ oldPath: "baz/foo.py", newPath: "bar.py" }, // From a nested dir
61
{ oldPath: "foo/bar.py", newPath: "foo/baz.py" }, // Same dir with a parent path
62
{ oldPath: "foo/bar.py", newPath: "baz/qux.py" } // With parent paths, different dirs
64
testCases.forEach(({ oldPath, newPath }) => {
65
it(`renames "${oldPath}" to "${newPath}"`, () => {
66
writeFileWithParents(pyodide, oldPath, "# Test");
67
expect(pyodide.FS.analyzePath(oldPath).exists).toBe(true);
69
renameWithParents(pyodide, oldPath, newPath);
71
expect(pyodide.FS.analyzePath(oldPath).exists).toBe(false);
72
expect(pyodide.FS.analyzePath(newPath).exists).toBe(true);
73
expect(pyodide.FS.readFile(newPath, { encoding: "utf8" })).toEqual(
79
["foo.py", "foo/bar.py"].forEach((path) => {
80
it(`does nothing when the source and the destination are the same`, () => {
81
writeFileWithParents(pyodide, path, "# Test");
82
expect(pyodide.FS.analyzePath(path).exists).toBe(true);
84
renameWithParents(pyodide, path, path);
86
expect(pyodide.FS.analyzePath(path).exists).toBe(true);
87
expect(pyodide.FS.readFile(path, { encoding: "utf8" })).toEqual("# Test");