Path: blob/main/python/python-wasm/src/test/python.test.ts
1067 views
import { syncPython } from "../node";12test("add 2+3", async () => {3const { exec, repr } = await syncPython();4exec("a = 2+3");5expect(repr("a")).toBe("5");6});789test("Exec involving multiline statement", async () => {10const { exec, repr } = await syncPython();11exec(`12def double(n : int) -> int:13return 2*n1415def f(n : int) -> int:16s = 017for i in range(1,n+1):18s += i19return double(s);20`);21expect(repr("f(100)")).toBe(`${5050 * 2}`);22});2324test("sys.platform is wasi", async () => {25const { exec, repr } = await syncPython();26exec("import sys");27expect(repr("sys.platform")).toBe("'wasi'");28});2930test("sleeping for a quarter of a second", async () => {31const { exec } = await syncPython();32const t0 = new Date().valueOf();33exec("import time; time.sleep(0.25)");34const t = new Date().valueOf() - t0;35expect(t >= 240 && t <= 500).toBe(true);36});3738test("that sys.executable is set to something", async () => {39const { exec, repr } = await syncPython();40exec("import sys");41const executable = eval(repr("sys.executable"));42expect(existsSync(executable)).toBe(true);43expect(executable.length).toBeGreaterThan(0);44});4546import { execFileSync } from "child_process";47import { existsSync } from "fs";48test("that sys.executable is set and exists -- when running python-wasm via command line", () => {49const stdout = execFileSync("./bin/python-wasm", [50"-c",51"import sys; print(sys.executable)",52])53.toString()54.trim();55expect(existsSync(stdout)).toBe(true);56});5758test("test that getcwd works", async () => {59const { exec, repr, kernel } = await syncPython();60await exec("import os; os.chdir('/tmp')");61const cwd = eval(repr('os.path.abspath(".")'));62expect(cwd).toBe("/tmp");63// this is the interesting call:64expect(kernel.getcwd()).toBe("/tmp");65});6667test("test that getcwd is fast", async () => {68const { exec, repr, kernel } = await syncPython();69await exec("import os; os.chdir('/tmp')");70const t0 = new Date().valueOf();71for (let i = 0; i < 10 ** 5; i++) {72kernel.getcwd();73}74// Doing 10**6 of them takes about a second on my laptop,75// so 2s should be safe for a test.76expect(new Date().valueOf() - t0).toBeLessThan(2000);77const cwd = eval(repr('os.path.abspath(".")'));78expect(cwd).toBe("/tmp");79});8081test("an annoying-to-real-mathematicians new 'feature' of Python can be disabled", async () => {82// See https://discuss.python.org/t/int-str-conversions-broken-in-latest-python-bugfix-releases/18889/18483const { exec, repr } = await syncPython();84exec("import sys; sys.set_int_max_str_digits(0)");85expect(repr("len(str(10**5000))")).toEqual("5001");86});878889