blob: c72a410ae49503f09d93d8d2360644291c33b3a7 [file] [log] [blame]
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "gtest/gtest.h"
#include "quickjs-libc.h"
#include "quickjs.h"
// Sanity check test to make sure Hello World works.
TEST(Qjs, Sanity) {
JSRuntime *rt = JS_NewRuntime();
ASSERT_NE(rt, nullptr) << "Cannot allocate JS runtime";
JSContext *ctx = JS_NewContext(rt);
ASSERT_NE(ctx, nullptr) << "Cannot allocate JS context";
/* system modules */
js_init_module_std(ctx, "std");
js_init_module_os(ctx, "os");
const char *str =
"import * as std from 'std';\n"
"import * as os from 'os';\n"
"globalThis.std = std;\n"
"globalThis.os = os;\n";
JSValue init_compile =
JS_Eval(ctx, str, strlen(str), "<input>", JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);
ASSERT_FALSE(JS_IsException(init_compile));
js_module_set_import_meta(ctx, init_compile, 1, 1);
JSValue init_run = JS_EvalFunction(ctx, init_compile);
ASSERT_FALSE(JS_IsException(init_run));
std::string hello_world = "Hello World";
std::string test_val = "globalThis.std.printf('" + hello_world + "');";
JSValue result = JS_Eval(ctx, test_val.c_str(), test_val.length(), "test", 0);
int32_t len;
int to_int_32;
if ((to_int_32 = JS_ToInt32(ctx, &len, result)) != 0) {
js_std_dump_error(ctx);
ASSERT_EQ(0, JS_ToInt32(ctx, &len, result));
}
ASSERT_EQ(hello_world.length(), len);
}