File: test_JSContext.R

package info (click to toggle)
r-cran-quickjsr 1.9.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 3,040 kB
  • sloc: ansic: 64,073; cpp: 3,953; sh: 13; makefile: 2
file content (44 lines) | stat: -rw-r--r-- 1,550 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

jsc <- JSContext$new()
jsc$source(code = "function add_test(x, y) { return x + y; }")
expect_true(jsc$validate("add_test"))

expect_equal(jsc$call("add_test", 1, 2), 3)
expect_equal(jsc$call("add_test", 1, "a"), "1a")

js_file <- tempfile(fileext = ".js")
writeLines("function mult_test(x, y) { return x * y; }", con = js_file)
jsc$source(file = js_file)

expect_true(jsc$validate("mult_test"))
expect_equal(jsc$call("mult_test", 1, 2), 2)
expect_equal(jsc$call("mult_test", 10, 15), 150)

# Test that R functions can be passed and evaluated in JS
jsc$source(code = "function fun_test(f, x, y) { return f(x, y); }")
expect_equal(jsc$call("fun_test", function(x, y){ x + y }, 1, 2), 3)

# Test that closures/captures work
a <- 3
expect_equal(jsc$call("fun_test", function(x, y){ (x + y) * a }, 1, 2), 9)
expect_equal(jsc$call("fun_test", function(x, y){ paste(x, y) }, "a", "b"), "a b")

# Test that R environments can be passed to JS and values accessed
jsc$source(code = "function env_test(env) { return env.a + env.b; }")
env <- new.env()
env$a <- 1
env$b <- 2
expect_equal(jsc$call("env_test", env), 3)

# Test JS functions can update values in R environments
jsc$source(code = "function env_update(env) { env.a = 10; env.b = 20; }")
jsc$call("env_update", env)
expect_equal(env$a, 10)
expect_equal(env$b, 20)


# Fails on 3.6 CI, but can't be replicated locally
exit_if_not(R.version$major  > "3")

jsc$source(code = 'function r_fun_test1() { return R.package("base")["Sys.Date"]() }')
expect_equal(as.Date(jsc$call("r_fun_test1")), Sys.Date())