test_quickjs.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. import concurrent.futures
  2. import gc
  3. import json
  4. import unittest
  5. import quickjs
  6. class LoadModule(unittest.TestCase):
  7. def test_42(self):
  8. self.assertEqual(quickjs.test(), 42)
  9. class Context(unittest.TestCase):
  10. def setUp(self):
  11. self.context = quickjs.Context()
  12. def test_eval_int(self):
  13. self.assertEqual(self.context.eval("40 + 2"), 42)
  14. def test_eval_float(self):
  15. self.assertEqual(self.context.eval("40.0 + 2.0"), 42.0)
  16. def test_eval_str(self):
  17. self.assertEqual(self.context.eval("'4' + '2'"), "42")
  18. def test_eval_bool(self):
  19. self.assertEqual(self.context.eval("true || false"), True)
  20. self.assertEqual(self.context.eval("true && false"), False)
  21. def test_eval_null(self):
  22. self.assertIsNone(self.context.eval("null"))
  23. def test_eval_undefined(self):
  24. self.assertIsNone(self.context.eval("undefined"))
  25. def test_wrong_type(self):
  26. with self.assertRaises(TypeError):
  27. self.assertEqual(self.context.eval(1), 42)
  28. def test_context_between_calls(self):
  29. self.context.eval("x = 40; y = 2;")
  30. self.assertEqual(self.context.eval("x + y"), 42)
  31. def test_function(self):
  32. self.context.eval("""
  33. function special(x) {
  34. return 40 + x;
  35. }
  36. """)
  37. self.assertEqual(self.context.eval("special(2)"), 42)
  38. def test_get(self):
  39. self.context.eval("x = 42; y = 'foo';")
  40. self.assertEqual(self.context.get("x"), 42)
  41. self.assertEqual(self.context.get("y"), "foo")
  42. self.assertEqual(self.context.get("z"), None)
  43. def test_set(self):
  44. self.context.eval("x = 'overriden'")
  45. self.context.set("x", 42)
  46. self.context.set("y", "foo")
  47. self.assertTrue(self.context.eval("x == 42"))
  48. self.assertTrue(self.context.eval("y == 'foo'"))
  49. def test_module(self):
  50. self.context.module("""
  51. export function test() {
  52. return 42;
  53. }
  54. """)
  55. def test_error(self):
  56. with self.assertRaisesRegex(quickjs.JSException, "ReferenceError: 'missing' is not defined"):
  57. self.context.eval("missing + missing")
  58. def test_lifetime(self):
  59. def get_f():
  60. context = quickjs.Context()
  61. f = context.eval("""
  62. a = function(x) {
  63. return 40 + x;
  64. }
  65. """)
  66. return f
  67. f = get_f()
  68. self.assertTrue(f)
  69. # The context has left the scope after f. f needs to keep the context alive for the
  70. # its lifetime. Otherwise, we will get problems.
  71. def test_backtrace(self):
  72. try:
  73. self.context.eval("""
  74. function funcA(x) {
  75. x.a.b = 1;
  76. }
  77. function funcB(x) {
  78. funcA(x);
  79. }
  80. funcB({});
  81. """)
  82. except Exception as e:
  83. msg = str(e)
  84. else:
  85. self.fail("Expected exception.")
  86. self.assertIn("at funcA (<input>:3)\n", msg)
  87. self.assertIn("at funcB (<input>:6)\n", msg)
  88. def test_memory_limit(self):
  89. code = """
  90. (function() {
  91. let arr = [];
  92. for (let i = 0; i < 1000; ++i) {
  93. arr.push(i);
  94. }
  95. })();
  96. """
  97. self.context.eval(code)
  98. self.context.set_memory_limit(1000)
  99. with self.assertRaisesRegex(quickjs.JSException, "null"):
  100. self.context.eval(code)
  101. self.context.set_memory_limit(1000000)
  102. self.context.eval(code)
  103. def test_time_limit(self):
  104. code = """
  105. (function() {
  106. let arr = [];
  107. for (let i = 0; i < 100000; ++i) {
  108. arr.push(i);
  109. }
  110. return arr;
  111. })();
  112. """
  113. self.context.eval(code)
  114. self.context.set_time_limit(0)
  115. with self.assertRaisesRegex(quickjs.JSException, "InternalError: interrupted"):
  116. self.context.eval(code)
  117. self.context.set_time_limit(-1)
  118. self.context.eval(code)
  119. def test_memory_usage(self):
  120. self.assertIn("memory_used_size", self.context.memory().keys())
  121. def test_json_simple(self):
  122. self.assertEqual(self.context.parse_json("42"), 42)
  123. def test_json_error(self):
  124. with self.assertRaisesRegex(quickjs.JSException, "unexpected token"):
  125. self.context.parse_json("a b c")
  126. def test_execute_pending_job(self):
  127. self.context.eval("obj = {}")
  128. self.assertEqual(self.context.execute_pending_job(), False)
  129. self.context.eval("Promise.resolve().then(() => {obj.x = 1;})")
  130. self.assertEqual(self.context.execute_pending_job(), True)
  131. self.assertEqual(self.context.eval("obj.x"), 1)
  132. self.assertEqual(self.context.execute_pending_job(), False)
  133. def test_global(self):
  134. self.context.set("f", self.context.globalThis)
  135. self.assertTrue(isinstance(self.context.globalThis, quickjs.Object))
  136. self.assertTrue(self.context.eval("f === globalThis"))
  137. with self.assertRaises(AttributeError):
  138. self.context.globalThis = 1
  139. class CallIntoPython(unittest.TestCase):
  140. def setUp(self):
  141. self.context = quickjs.Context()
  142. def test_make_function(self):
  143. self.context.add_callable("f", lambda x: x + 2)
  144. self.assertEqual(self.context.eval("f(40)"), 42)
  145. self.assertEqual(self.context.eval("f.name"), "f")
  146. def test_make_two_functions(self):
  147. for i in range(10):
  148. self.context.add_callable("f", lambda x: i + x + 2)
  149. self.context.add_callable("g", lambda x: i + x + 40)
  150. f = self.context.get("f")
  151. g = self.context.get("g")
  152. self.assertEqual(f(40) - i, 42)
  153. self.assertEqual(g(2) - i, 42)
  154. self.assertEqual(self.context.eval("((f, a) => f(a))")(f, 40) - i, 42)
  155. def test_make_function_call_from_js(self):
  156. self.context.add_callable("f", lambda x: x + 2)
  157. g = self.context.eval("""(
  158. function() {
  159. return f(20) + 20;
  160. }
  161. )""")
  162. self.assertEqual(g(), 42)
  163. def test_python_function_raises(self):
  164. def error(a):
  165. raise ValueError("A")
  166. self.context.add_callable("error", error)
  167. with self.assertRaisesRegex(quickjs.JSException, "Python call failed"):
  168. self.context.eval("error(0)")
  169. def test_python_function_not_callable(self):
  170. with self.assertRaisesRegex(TypeError, "Argument must be callable."):
  171. self.context.add_callable("not_callable", 1)
  172. def test_python_function_no_slots(self):
  173. for i in range(2**16):
  174. self.context.add_callable(f"a{i}", lambda i=i: i + 1)
  175. self.assertEqual(self.context.eval("a0()"), 1)
  176. self.assertEqual(self.context.eval(f"a{2**16 - 1}()"), 2**16)
  177. def test_function_after_context_del(self):
  178. def make():
  179. ctx = quickjs.Context()
  180. ctx.add_callable("f", lambda: 1)
  181. f = ctx.get("f")
  182. del ctx
  183. return f
  184. gc.collect()
  185. f = make()
  186. self.assertEqual(f(), 1)
  187. def test_python_function_unwritable(self):
  188. self.context.eval("""
  189. Object.defineProperty(globalThis, "obj", {
  190. value: "test",
  191. writable: false,
  192. });
  193. """)
  194. with self.assertRaisesRegex(TypeError, "Failed adding the callable."):
  195. self.context.add_callable("obj", lambda: None)
  196. def test_python_function_is_function(self):
  197. self.context.add_callable("f", lambda: None)
  198. self.assertTrue(self.context.eval("f instanceof Function"))
  199. self.assertTrue(self.context.eval("typeof f === 'function'"))
  200. def test_make_function_two_args(self):
  201. def concat(a, b):
  202. return a + b
  203. self.context.add_callable("concat", concat)
  204. result = self.context.eval("concat(40, 2)")
  205. self.assertEqual(result, 42)
  206. concat = self.context.get("concat")
  207. result = self.context.eval("((f, a, b) => 22 + f(a, b))")(concat, 10, 10)
  208. self.assertEqual(result, 42)
  209. def test_make_function_two_string_args(self):
  210. """Without the JS_DupValue in js_c_function, this test crashes."""
  211. def concat(a, b):
  212. return a + "-" + b
  213. self.context.add_callable("concat", concat)
  214. concat = self.context.get("concat")
  215. result = concat("aaa", "bbb")
  216. self.assertEqual(result, "aaa-bbb")
  217. def test_can_eval_in_same_context(self):
  218. self.context.add_callable("f", lambda: 40 + self.context.eval("1 + 1"))
  219. self.assertEqual(self.context.eval("f()"), 42)
  220. def test_can_call_in_same_context(self):
  221. inner = self.context.eval("(function() { return 42; })")
  222. self.context.add_callable("f", lambda: inner())
  223. self.assertEqual(self.context.eval("f()"), 42)
  224. def test_delete_function_from_inside_js(self):
  225. self.context.add_callable("f", lambda: None)
  226. # Segfaults if js_python_function_finalizer does not handle threading
  227. # states carefully.
  228. self.context.eval("delete f")
  229. self.assertIsNone(self.context.get("f"))
  230. def test_invalid_argument(self):
  231. self.context.add_callable("p", lambda: 42)
  232. self.assertEqual(self.context.eval("p()"), 42)
  233. with self.assertRaisesRegex(quickjs.JSException, "Python call failed"):
  234. self.context.eval("p(1)")
  235. with self.assertRaisesRegex(quickjs.JSException, "Python call failed"):
  236. self.context.eval("p({})")
  237. def test_time_limit_disallowed(self):
  238. self.context.add_callable("f", lambda x: x + 2)
  239. self.context.set_time_limit(1000)
  240. with self.assertRaises(quickjs.JSException):
  241. self.context.eval("f(40)")
  242. def test_conversion_failure_does_not_raise_system_error(self):
  243. # https://github.com/PetterS/quickjs/issues/38
  244. def test_list():
  245. return [1, 2, 3]
  246. self.context.add_callable("test_list", test_list)
  247. with self.assertRaises(quickjs.JSException):
  248. # With incorrect error handling, this (safely) made Python raise a SystemError
  249. # instead of a JS exception.
  250. self.context.eval("test_list()")
  251. class Object(unittest.TestCase):
  252. def setUp(self):
  253. self.context = quickjs.Context()
  254. def test_function_is_object(self):
  255. f = self.context.eval("""
  256. a = function(x) {
  257. return 40 + x;
  258. }
  259. """)
  260. self.assertIsInstance(f, quickjs.Object)
  261. def test_function_call_int(self):
  262. f = self.context.eval("""
  263. f = function(x) {
  264. return 40 + x;
  265. }
  266. """)
  267. self.assertEqual(f(2), 42)
  268. def test_function_call_int_two_args(self):
  269. f = self.context.eval("""
  270. f = function(x, y) {
  271. return 40 + x + y;
  272. }
  273. """)
  274. self.assertEqual(f(3, -1), 42)
  275. def test_function_call_many_times(self):
  276. n = 1000
  277. f = self.context.eval("""
  278. f = function(x, y) {
  279. return x + y;
  280. }
  281. """)
  282. s = 0
  283. for i in range(n):
  284. s += f(1, 1)
  285. self.assertEqual(s, 2 * n)
  286. def test_function_call_str(self):
  287. f = self.context.eval("""
  288. f = function(a) {
  289. return a + " hej";
  290. }
  291. """)
  292. self.assertEqual(f("1"), "1 hej")
  293. def test_function_call_str_three_args(self):
  294. f = self.context.eval("""
  295. f = function(a, b, c) {
  296. return a + " hej " + b + " ho " + c;
  297. }
  298. """)
  299. self.assertEqual(f("1", "2", "3"), "1 hej 2 ho 3")
  300. def test_function_call_object(self):
  301. d = self.context.eval("d = {data: 42};")
  302. f = self.context.eval("""
  303. f = function(d) {
  304. return d.data;
  305. }
  306. """)
  307. self.assertEqual(f(d), 42)
  308. # Try again to make sure refcounting works.
  309. self.assertEqual(f(d), 42)
  310. self.assertEqual(f(d), 42)
  311. def test_function_call_unsupported_arg(self):
  312. f = self.context.eval("""
  313. f = function(x) {
  314. return 40 + x;
  315. }
  316. """)
  317. with self.assertRaisesRegex(TypeError, "Unsupported type"):
  318. self.assertEqual(f({}), 42)
  319. def test_json(self):
  320. d = self.context.eval("d = {data: 42};")
  321. self.assertEqual(json.loads(d.json()), {"data": 42})
  322. def test_call_nonfunction(self):
  323. d = self.context.eval("({data: 42})")
  324. with self.assertRaisesRegex(quickjs.JSException, "TypeError: not a function"):
  325. d(1)
  326. def test_wrong_context(self):
  327. context1 = quickjs.Context()
  328. context2 = quickjs.Context()
  329. f = context1.eval("(function(x) { return x.a; })")
  330. d = context2.eval("({a: 1})")
  331. with self.assertRaisesRegex(ValueError, "Can not mix JS objects from different contexts."):
  332. f(d)
  333. class FunctionTest(unittest.TestCase):
  334. def test_adder(self):
  335. f = quickjs.Function(
  336. "adder", """
  337. function adder(x, y) {
  338. return x + y;
  339. }
  340. """)
  341. self.assertEqual(f(1, 1), 2)
  342. self.assertEqual(f(100, 200), 300)
  343. self.assertEqual(f("a", "b"), "ab")
  344. def test_identity(self):
  345. identity = quickjs.Function(
  346. "identity", """
  347. function identity(x) {
  348. return x;
  349. }
  350. """)
  351. for x in [True, [1], {"a": 2}, 1, 1.5, "hej", None]:
  352. self.assertEqual(identity(x), x)
  353. def test_bool(self):
  354. f = quickjs.Function(
  355. "f", """
  356. function f(x) {
  357. return [typeof x ,!x];
  358. }
  359. """)
  360. self.assertEqual(f(False), ["boolean", True])
  361. self.assertEqual(f(True), ["boolean", False])
  362. def test_empty(self):
  363. f = quickjs.Function("f", "function f() { }")
  364. self.assertEqual(f(), None)
  365. def test_lists(self):
  366. f = quickjs.Function(
  367. "f", """
  368. function f(arr) {
  369. const result = [];
  370. arr.forEach(function(elem) {
  371. result.push(elem + 42);
  372. });
  373. return result;
  374. }""")
  375. self.assertEqual(f([0, 1, 2]), [42, 43, 44])
  376. def test_dict(self):
  377. f = quickjs.Function(
  378. "f", """
  379. function f(obj) {
  380. return obj.data;
  381. }""")
  382. self.assertEqual(f({"data": {"value": 42}}), {"value": 42})
  383. def test_time_limit(self):
  384. f = quickjs.Function(
  385. "f", """
  386. function f() {
  387. let arr = [];
  388. for (let i = 0; i < 100000; ++i) {
  389. arr.push(i);
  390. }
  391. return arr;
  392. }
  393. """)
  394. f()
  395. f.set_time_limit(0)
  396. with self.assertRaisesRegex(quickjs.JSException, "InternalError: interrupted"):
  397. f()
  398. f.set_time_limit(-1)
  399. f()
  400. def test_garbage_collection(self):
  401. f = quickjs.Function(
  402. "f", """
  403. function f() {
  404. let a = {};
  405. let b = {};
  406. a.b = b;
  407. b.a = a;
  408. a.i = 42;
  409. return a.i;
  410. }
  411. """)
  412. initial_count = f.memory()["obj_count"]
  413. for i in range(10):
  414. prev_count = f.memory()["obj_count"]
  415. self.assertEqual(f(run_gc=False), 42)
  416. current_count = f.memory()["obj_count"]
  417. self.assertGreater(current_count, prev_count)
  418. f.gc()
  419. self.assertLessEqual(f.memory()["obj_count"], initial_count)
  420. def test_deep_recursion(self):
  421. f = quickjs.Function(
  422. "f", """
  423. function f(v) {
  424. if (v <= 0) {
  425. return 0;
  426. } else {
  427. return 1 + f(v - 1);
  428. }
  429. }
  430. """)
  431. self.assertEqual(f(100), 100)
  432. limit = 500
  433. with self.assertRaises(quickjs.StackOverflow):
  434. f(limit)
  435. f.set_max_stack_size(2000 * limit)
  436. self.assertEqual(f(limit), limit)
  437. def test_add_callable(self):
  438. f = quickjs.Function(
  439. "f", """
  440. function f() {
  441. return pfunc();
  442. }
  443. """)
  444. f.add_callable("pfunc", lambda: 42)
  445. self.assertEqual(f(), 42)
  446. def test_execute_pending_job(self):
  447. f = quickjs.Function(
  448. "f", """
  449. obj = {x: 0, y: 0};
  450. async function a() {
  451. obj.x = await 1;
  452. }
  453. a();
  454. Promise.resolve().then(() => {obj.y = 1});
  455. function f() {
  456. return obj.x + obj.y;
  457. }
  458. """)
  459. self.assertEqual(f(), 0)
  460. self.assertEqual(f.execute_pending_job(), True)
  461. self.assertEqual(f(), 1)
  462. self.assertEqual(f.execute_pending_job(), True)
  463. self.assertEqual(f(), 2)
  464. self.assertEqual(f.execute_pending_job(), False)
  465. def test_global(self):
  466. f = quickjs.Function(
  467. "f", """
  468. function f() {
  469. }
  470. """)
  471. self.assertTrue(isinstance(f.globalThis, quickjs.Object))
  472. with self.assertRaises(AttributeError):
  473. f.globalThis = 1
  474. class JavascriptFeatures(unittest.TestCase):
  475. def test_unicode_strings(self):
  476. identity = quickjs.Function(
  477. "identity", """
  478. function identity(x) {
  479. return x;
  480. }
  481. """)
  482. context = quickjs.Context()
  483. for x in ["äpple", "≤≥", "☺"]:
  484. self.assertEqual(identity(x), x)
  485. self.assertEqual(context.eval('(function(){ return "' + x + '";})()'), x)
  486. def test_es2020_optional_chaining(self):
  487. f = quickjs.Function(
  488. "f", """
  489. function f(x) {
  490. return x?.one?.two;
  491. }
  492. """)
  493. self.assertIsNone(f({}))
  494. self.assertIsNone(f({"one": 12}))
  495. self.assertEqual(f({"one": {"two": 42}}), 42)
  496. def test_es2020_null_coalescing(self):
  497. f = quickjs.Function(
  498. "f", """
  499. function f(x) {
  500. return x ?? 42;
  501. }
  502. """)
  503. self.assertEqual(f(""), "")
  504. self.assertEqual(f(0), 0)
  505. self.assertEqual(f(11), 11)
  506. self.assertEqual(f(None), 42)
  507. def test_symbol_conversion(self):
  508. context = quickjs.Context()
  509. context.eval("a = Symbol();")
  510. context.set("b", context.eval("a"))
  511. self.assertTrue(context.eval("a === b"))
  512. def test_large_python_integers_to_quickjs(self):
  513. context = quickjs.Context()
  514. # Without a careful implementation, this made Python raise a SystemError/OverflowError.
  515. context.set("v", 10**25)
  516. # There is precision loss occurring in JS due to
  517. # the floating point implementation of numbers.
  518. self.assertTrue(context.eval("v == 1e25"))
  519. def test_bigint(self):
  520. context = quickjs.Context()
  521. self.assertEqual(context.eval(f"BigInt('{10**100}')"), 10**100)
  522. self.assertEqual(context.eval(f"BigInt('{-10**100}')"), -10**100)
  523. class Threads(unittest.TestCase):
  524. def setUp(self):
  525. self.context = quickjs.Context()
  526. self.executor = concurrent.futures.ThreadPoolExecutor()
  527. def tearDown(self):
  528. self.executor.shutdown()
  529. def test_concurrent(self):
  530. """Demonstrates that the execution will crash unless the function executes on the same
  531. thread every time.
  532. If the executor in Function is not present, this test will fail.
  533. """
  534. data = list(range(1000))
  535. jssum = quickjs.Function(
  536. "sum", """
  537. function sum(data) {
  538. return data.reduce((a, b) => a + b, 0)
  539. }
  540. """)
  541. futures = [self.executor.submit(jssum, data) for _ in range(10)]
  542. expected = sum(data)
  543. for future in concurrent.futures.as_completed(futures):
  544. self.assertEqual(future.result(), expected)
  545. def test_concurrent_own_executor(self):
  546. data = list(range(1000))
  547. jssum1 = quickjs.Function("sum",
  548. """
  549. function sum(data) {
  550. return data.reduce((a, b) => a + b, 0)
  551. }
  552. """,
  553. own_executor=True)
  554. jssum2 = quickjs.Function("sum",
  555. """
  556. function sum(data) {
  557. return data.reduce((a, b) => a + b, 0)
  558. }
  559. """,
  560. own_executor=True)
  561. futures = [self.executor.submit(f, data) for _ in range(10) for f in (jssum1, jssum2)]
  562. expected = sum(data)
  563. for future in concurrent.futures.as_completed(futures):
  564. self.assertEqual(future.result(), expected)
  565. class QJS(object):
  566. def __init__(self):
  567. self.interp = quickjs.Context()
  568. self.interp.eval('var foo = "bar";')
  569. class QuickJSContextInClass(unittest.TestCase):
  570. def test_github_issue_7(self):
  571. # This used to give stack overflow internal error, due to how QuickJS calculates stack
  572. # frames. Passes with the 2021-03-27 release.
  573. qjs = QJS()
  574. self.assertEqual(qjs.interp.eval('2+2'), 4)