mujs_test.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /* Host smoke test for the vendored MuJS engine. */
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include "mujs.h"
  5. static int reports;
  6. static void report(js_State *J, const char *message)
  7. {
  8. (void)J;
  9. printf("mujs report: %s\n", message);
  10. reports++;
  11. }
  12. int main(void)
  13. {
  14. js_State *J = js_newstate(0, 0, JS_STRICT);
  15. int failures = 0;
  16. if (!J) {
  17. printf("mujs test: cannot create a state\n");
  18. return 1;
  19. }
  20. js_setreport(J, report);
  21. if (js_dostring(J, "if (1 + 2 !== 3) throw 'arithmetic';")) {
  22. printf("mujs test: arithmetic failed\n");
  23. failures++;
  24. }
  25. if (js_dostring(J,
  26. "var s = 'x'; s += 42;"
  27. "if (s !== 'x42') throw 'string ' + s;")) {
  28. printf("mujs test: string failed\n");
  29. failures++;
  30. }
  31. if (js_dostring(J,
  32. "if (Math.sqrt(9) !== 3) throw 'sqrt';"
  33. "if (Math.pow(2, 10) !== 1024) throw 'pow';"
  34. "if (Math.abs(-4) !== 4) throw 'abs';")) {
  35. printf("mujs test: math failed\n");
  36. failures++;
  37. }
  38. if (js_dostring(J,
  39. "var d = new Date(0);"
  40. "if (d.getUTCFullYear() !== 1970 || d.getUTCMonth() !== 0 ||"
  41. " d.getUTCDate() !== 1) throw 'date';"
  42. "if (Date.UTC(2020, 0, 1) !== 1577836800000) throw 'utc';")) {
  43. printf("mujs test: date failed\n");
  44. failures++;
  45. }
  46. if (js_dostring(J,
  47. "var o = JSON.parse('{\"a\":[1,2,3]}');"
  48. "if (o.a.length !== 3 || o.a[2] !== 3) throw 'json parse';"
  49. "if (JSON.stringify({x: 1}) !== '{\"x\":1}') throw 'json print';")) {
  50. printf("mujs test: json failed\n");
  51. failures++;
  52. }
  53. /* A thrown error must be reported and must not take the process down. */
  54. reports = 0;
  55. if (!js_dostring(J, "throw new Error('expected');")) {
  56. printf("mujs test: exception not caught\n");
  57. failures++;
  58. }
  59. if (reports != 1) {
  60. printf("mujs test: expected one report, got %d\n", reports);
  61. failures++;
  62. }
  63. /* The run limit turns an endless loop into a catchable exception. */
  64. reports = 0;
  65. js_setlimit(J, 2000, 0);
  66. if (!js_dostring(J, "while (1) {}")) {
  67. printf("mujs test: run limit did not fire\n");
  68. failures++;
  69. }
  70. if (reports != 1) {
  71. printf("mujs test: run limit report count %d\n", reports);
  72. failures++;
  73. }
  74. js_freestate(J);
  75. if (failures)
  76. printf("mujs test: %d failure(s)\n", failures);
  77. else
  78. printf("mujs test: OK\n");
  79. return failures != 0;
  80. }