Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-js

Source of release 0.6.0

0.6.0 / src / host / tests.lucb

#==============================================================================================
#
#   tests - Unit tests of the host module
#
#   DESCRIPTION:
#       Checks the pieces a JavaScript test cannot isolate: C formats in std.sprintf, the
#       target layouts of struct stat and struct dirent, file loading, the timer loop, the
#       wait status decoding, os.exec's options, the signal and read handlers, the `os`
#       table and file system calls of each target (Windows included), and the
#       registered native modules.
#       The upstream JavaScript tests (tests/run.py) cover the rest.
#
#==============================================================================================

# mark: Helpers =================================================================================

## A runtime and a standard context with the host state and the system modules.
func test_context() -> Context*:
    let rt = js.js_new_runtime() else trap("no runtime")
    js_std_init_handlers(rt)
    let ctx = js.js_new_context(rt) else trap("no context")
    _ = js_init_module_std(ctx, "std".bytes.data) catch: trap("no std")
    _ = js_init_module_os(ctx, "os".bytes.data) catch: trap("no os")
    return ctx

func free_test_context(ctx: Context*):
    let rt = js.js_get_runtime(ctx)
    js_std_free_handlers(rt)
    js.js_free_context(ctx)
    js.js_free_runtime(rt)

## Evaluate `source` as a module that imports std and os and answers the value of the
## global `result` as text, in `out`.
func eval_to_text(ctx: Context*, source: str, out: u8[]) -> str:
    let func_val = js.js_eval_text(ctx, source, "<test>", js.eval_type_module) catch:
        js_std_dump_error(ctx)
        trap("evaluation failed")
    _ = js_std_await(ctx, func_val) catch: trap("module failed")
    let global_obj = js.js_get_global_object(ctx)
    let result = js.js_get_property_str(ctx, global_obj, "result") catch: trap("no result")
    js.js_free_value(ctx, global_obj)
    let text = js.js_to_c_string(ctx, result) catch: trap("result is not text")
    js.js_free_value(ctx, result)
    let len = cutils.strlen(text)
    assert(len <= out.length)
    _ = cutils.memcpy(out.data, text, len)
    js.js_free_c_string(ctx, text)
    return (str)out[0..<len]

# mark: std =====================================================================================

test "sprintf passes each conversion to C as test_std.js expects":
    let ctx = test_context()
    var buf: u8[256]
    let text = eval_to_text(ctx, """
        import * as std from "std";
        globalThis.result = [
            std.sprintf("a=%d s=%s", 123, "abc"), std.sprintf("%010d", 123),
            std.sprintf("%x", -2), std.sprintf("%lx", -2), std.sprintf("%10.1f", 2.1),
            std.sprintf("%*.*f", 10, 2, -2.13), std.sprintf("%#lx", 0x7fffffffffffffffn),
            std.sprintf("%c%c|%%|%5s", 65, "é", "ab"),
        ].join(";");
        """, buf)
    assert(text == "a=123 s=abc;0000000123;fffffffe;fffffffffffffffe;       2.1;     -2.13;0x7fffffffffffffff;Aé|%|   ab")
    free_test_context(ctx)

test "sprintf reports invalid and missing conversions":
    let ctx = test_context()
    var buf: u8[256]
    let text = eval_to_text(ctx, """
        import * as std from "std";
        let r = [];
        try { std.sprintf("%q", 1) } catch (e) { r.push(e.name) }
        try { std.sprintf("%d") } catch (e) { r.push(e.name) }
        globalThis.result = r.join();
        """, buf)
    assert(text == "TypeError,ReferenceError")
    free_test_context(ctx)

# mark: os ======================================================================================

test "stat and readdir decode this target's layouts":
    let ctx = test_context()
    var buf: u8[256]
    let text = eval_to_text(ctx, """
        import * as os from "os";
        let [st, err] = os.stat(".");
        let [files, err2] = os.readdir(".");
        globalThis.result = [err, (st.mode & os.S_IFMT) == os.S_IFDIR, st.mtime > 1e12,
                             err2, files.indexOf(".") >= 0, files.indexOf("..") >= 0].join();
        """, buf)
    assert(text == "0,true,true,0,true,true")
    free_test_context(ctx)

test "timers run in order from the loop and can be cleared":
    let ctx = test_context()
    var buf: u8[256]
    _ = eval_to_text(ctx, """
        import * as os from "os";
        let r = [];
        os.setTimeout(() => r.push("b"), 300);
        os.setTimeout(() => r.push("a"), 0);
        let t = os.setTimeout(() => r.push("never"), 1);
        os.clearTimeout(t);
        Promise.resolve().then(() => r.push("job"));
        globalThis.log = r;
        globalThis.result = "";
        """, buf)
    js_std_loop(ctx)
    let text = eval_to_text(ctx, "globalThis.result = globalThis.log.join();", buf)
    assert(text == "job,a,b")
    free_test_context(ctx)

test "js_load_file answers the bytes and a NUL, or none":
    var len: usize = 0
    let buf = js_load_file(none, &len, "src/host/ORDER".bytes.data) else trap("cannot load ORDER")
    assert(len > 10 and buf[len] == 0)
    assert(cutils.memcmp(buf, "module.lucb".bytes.data, 11) == 0)
    cutils.c_free(buf)
    assert(js_load_file(none, &len, "no/such/file".bytes.data) == none)
    assert(has_suffix("a/b.json".bytes.data, ".json") and not has_suffix("json".bytes.data, ".json"))

test "wait statuses decode as the POSIX macros do":
    assert(w_if_exited(3 << 8) and w_exit_status(3 << 8) == 3 and not w_if_signaled(3 << 8))
    assert(w_if_signaled(9) and w_term_sig(9) == 9 and not w_if_exited(9))
    # stopped (0x7f in the low bits): neither exited nor signaled
    assert(not w_if_exited(0x137f) and not w_if_signaled(0x137f))

test "exec passes argv, env, cwd, file and stdout, and waitpid reports the status":
    if platform.windows:
        return  # Windows has no os.exec, os.pipe, os.waitpid or os.kill
    let ctx = test_context()
    var buf: u8[256]
    let text = eval_to_text(ctx, """
        import * as std from "std";
        import * as os from "os";
        let r = [os.exec(["sh", "-c", "exit 7"]), os.exec(["no_such_program_xyz"])];
        let fds = os.pipe();
        let pid = os.exec(["x", "-c", "echo $V $(pwd) $0"], { file: "/bin/sh", usePath: false,
                          cwd: "/", env: { V: "v1" }, stdout: fds[1], block: false });
        os.close(fds[1]);
        let f = std.fdopen(fds[0], "r");
        r.push(f.getline());
        f.close();
        let [ret, status] = os.waitpid(pid, 0);
        r.push(ret == pid, status);
        pid = os.exec(["sleep", "10"], { block: false });
        os.kill(pid, os.SIGTERM);
        r.push(os.waitpid(pid, 0)[1] & 0x7f);
        globalThis.result = r.join();
        """, buf)
    assert(text == "7,127,v1 / x,true,0,15")
    free_test_context(ctx)

test "signal and read handlers run from the loop":
    if platform.windows:
        return  # Windows has no os.pipe, os.kill or SIGUSR2
    let ctx = test_context()
    var buf: u8[256]
    _ = eval_to_text(ctx, """
        import * as os from "os";
        let r = [];
        os.signal(os.SIGUSR2, () => { r.push("usr2"); os.signal(os.SIGUSR2, null); });
        os.kill(os.getpid(), os.SIGUSR2);
        let fds = os.pipe();
        os.setReadHandler(fds[0], () => {
            let b = new Uint8Array(4);
            r.push("read " + os.read(fds[0], b.buffer, 0, 4));
            os.setReadHandler(fds[0], null);
            os.close(fds[0]);
        });
        os.setWriteHandler(fds[1], () => {
            os.write(fds[1], new Uint8Array([1, 2]).buffer, 0, 2);
            os.setWriteHandler(fds[1], null);
            os.close(fds[1]);
        });
        globalThis.log = r;
        globalThis.result = "";
        """, buf)
    js_std_loop(ctx)
    let text = eval_to_text(ctx, "globalThis.result = globalThis.log.join();", buf)
    assert(text == "usr2,read 2")
    free_test_context(ctx)

test "the os table has this target's functions and constants":
    let ctx = test_context()
    var buf: u8[256]
    let text = eval_to_text(ctx, """
        import * as os from "os";
        globalThis.result = [os.platform, typeof os.exec, typeof os.lstat, typeof os.SIGUSR1,
                             os.O_BINARY, os.O_CREAT, os.SIGABRT, os.S_IFBLK,
                             "blocks" in os.stat(".")[0]].join();
        """, buf)
    if platform.windows:
        assert(text == "win32,undefined,undefined,undefined,32768,256,22,12288,false")
    elif platform.macos:
        assert(text == "darwin,function,function,number,,512,6,24576,true")
    else:
        assert(text == "linux,function,function,number,,64,6,24576,true")
    free_test_context(ctx)

test "mkdir, open, utimes, stat, realpath, readdir and remove work together":
    let ctx = test_context()
    var buf: u8[256]
    let text = eval_to_text(ctx, """
        import * as os from "os";
        let r = [];
        let dir = "build/host_test_dir";
        os.mkdir("build");
        os.remove(dir + "/f");
        os.remove(dir);
        r.push(os.mkdir(dir));
        let fd = os.open(dir + "/f", os.O_WRONLY | os.O_CREAT | os.O_TRUNC);
        let data = new Uint8Array([1, 10, 13, 10]);
        r.push(os.write(fd, data.buffer, 0, 4), os.seek(fd, 0, 1), os.close(fd));
        r.push(os.utimes(dir + "/f", 86400000, 172800000));
        let [st, err] = os.stat(dir + "/f");
        r.push(err, st.size, st.mtime, (st.mode & os.S_IFMT) == os.S_IFREG);
        let [path, err2] = os.realpath(dir);
        r.push(err2, path.endsWith("host_test_dir"), path.length > dir.length);
        r.push(os.readdir(dir)[0].filter((n) => n[0] != ".").join());
        r.push(os.remove(dir + "/f"), os.remove(dir), os.stat(dir)[1] != 0);
        globalThis.result = r.join();
        """, buf)
    assert(text == "0,4,4,0,0,0,4,172800000,true,0,true,true,f,0,0,true")
    free_test_context(ctx)

# mark: Native modules ==========================================================================

let test_native_funcs: CFunctionListEntry[1] = [
    CFunctionListEntry(name = "answer", def_type = js.def_prop_int32, i32_value = 42),
]

func test_native_init(ctx: Context*, m: ModuleDef*) -> !:
    try js.js_set_module_export_list(ctx, m, test_native_funcs)

func test_native_module(ctx: Context*, module_name: const u8*) -> ModuleDef*!:
    let m = try js.js_new_c_module(ctx, module_name, test_native_init)
    try js.js_add_module_export_list(ctx, m, test_native_funcs)
    return m

func test_native_broken(ctx: Context*, module_name: const u8*) -> ModuleDef*!:
    try js.js_throw_type_error(ctx, "not this one")

test "registered native modules load by their .so file name or their bare name":
    assert(js_register_native_module("answer", test_native_module))
    assert(js_register_native_module("broken", test_native_broken))
    let ctx = test_context()
    js.js_set_module_loader_func2(js.js_get_runtime(ctx), none, js_module_loader, js_module_check_attributes, none)
    var buf: u8[256]
    let text = eval_to_text(ctx, """
        import { answer } from "./some/dir/answer.so";
        import * as bare from "answer";
        let r = [answer, bare.answer];
        for (const name of ["./broken.so", "./missing.so", "broken"]) {
            try { await import(name); r.push("loaded"); } catch (e) { r.push(e.name + ": " + e.message); }
        }
        globalThis.result = r.join("|");
        """, buf)
    let parts = [
        "42", "42",
        "ReferenceError: could not load module filename 'broken.so': initialization error",
        "ReferenceError: could not load module filename 'missing.so' as shared library",
        "ReferenceError: could not load module filename 'broken': initialization error",
    ]
    var pos: usize = 0
    for (i, part) in parts.indexed():
        if i != 0:
            assert(text.bytes[pos] == '|')
            pos += 1
        assert((str)text.bytes[pos..<pos + part.length] == part)
        pos += part.length
    assert(pos == text.length)
    free_test_context(ctx)