forked from lihaoyi/macropy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
js_snippets.py
67 lines (54 loc) · 2.13 KB
/
js_snippets.py
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import unittest
from macropy.experimental.js_snippets import macros, pyjs, js, std_lib_script
from macropy.tracing import macros, require
from selenium import webdriver
class Tests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.driver = webdriver.Chrome()
@classmethod
def tearDownClass(cls):
cls.driver.close()
def exec_js(self, script):
return Tests.driver.execute_script(
std_lib_script + "return " + script
)
def exec_js_func(self, script, *args):
arg_list = ", ".join("arguments[%s]" % i for i in range(len(args)))
return Tests.driver.execute_script(
std_lib_script + "return (" + script + ")(%s)" % arg_list,
*args
)
def test_literals(self):
# these work
with require:
self.exec_js(js[10]) == 10
self.exec_js(js["i am a cow"]) == "i am a cow"
# these literals are buggy, and it seems to be PJs' fault
# ??? all the results seem to turn into strings ???
with require:
self.exec_js(js[3.14]) == str(3.14)
self.exec_js(js[[1, 2, 'lol']]) == str([1, 2, 'lol'])
self.exec_js(js[{"moo": 2, "cow": 1}]) == str({"moo": 2, "cow": 1})
# set literals don't work so this throws an exception at macro-expansion time
#self.exec_js(js%{1, 2, 'lol'})
def test_executions(self):
with require:
self.exec_js(js[(lambda x: x * 2)(10)]) == 20
self.exec_js(js[sum([x for x in range(10) if x > 5])]) == 30
def test_pyjs(self):
# cross-compiling a trivial predicate
code, javascript = pyjs[lambda x: x > 5 and x % 2 == 0]
for i in range(10):
with require:
code(i) == self.exec_js_func(javascript, i)
code, javascript = pyjs[lambda n: [
x for x in range(n)
if 0 == len([
y for y in range(2, x-2)
if x % y == 0
])
]]
# this is also wrongly stringifying the result =(
with require:
str(code(20)) == str(self.exec_js_func(javascript, 20))