-
Notifications
You must be signed in to change notification settings - Fork 101
Expand file tree
/
Copy pathfunction_call.cpp
More file actions
116 lines (99 loc) · 2.93 KB
/
Copy pathfunction_call.cpp
File metadata and controls
116 lines (99 loc) · 2.93 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include "quickjs/quickjs.h"
#include "quickjspp.hpp"
#include <iostream>
#include <string_view>
int test_not_enough_arguments(qjs::Context & ctx) {
std::string msg;
ctx.global()["test_fcn"] = [](int a, int b, int c) {
return a + b + c;
};
try
{
ctx.eval(R"xxx(
function assert(b, str = "FAIL") {
if (b) {
return;
} else {
throw Error("assertion failed: " + str);
}
}
function assert_eq(a, b, str = "") {
assert(a === b, `${JSON.stringify(a)} should be equal to ${JSON.stringify(b)}. ${str}`);
}
try {
test_fcn(1);
assert(false);
} catch (err) {
assert(err instanceof TypeError);
assert_eq(err.message, 'Expected at least 3 arguments but received 1');
}
)xxx");
}
catch(qjs::exception)
{
auto exc = ctx.getException();
std::cerr << (std::string) exc << std::endl;
if((bool) exc["stack"])
std::cerr << (std::string) exc["stack"] << std::endl;
return 1;
}
return 0;
}
int test_call_with_rest_parameters(qjs::Context & ctx) {
ctx.global()["test_fcn_rest"] = [](int a, qjs::rest<int> args) {
for (auto arg : args) {
a += arg;
}
return a;
};
ctx.global()["test_fcn_vec"] = [](int a, std::vector<int> args) {
for (auto arg : args) {
a += arg;
}
return a;
};
try
{
ctx.eval(R"xxx(
function assert(b, str = "FAIL") {
if (b) {
return;
} else {
throw Error("assertion failed: " + str);
}
}
function assert_eq(a, b, str = "") {
assert(a === b, `${JSON.stringify(a)} should be equal to ${JSON.stringify(b)}. ${str}`);
}
function assert_throw(g, str = "") {
try {
f();
assert(false, `Expression should have thrown`)
} catch (e) {
}
}
assert_eq(test_fcn_rest(1, 2, 3, 4), 10);
assert_eq(test_fcn_vec(1, [2, 3, 4]), 10);
assert_throw(() => test_fcn_rest(1, [2, 3, 4]));
assert_throw(() => test_fcn_vec(1, 2, 3, 4));
)xxx");
}
catch(qjs::exception)
{
auto exc = ctx.getException();
std::cerr << (std::string) exc << std::endl;
if((bool) exc["stack"])
std::cerr << (std::string) exc["stack"] << std::endl;
return 1;
}
return 0;
}
int main()
{
qjs::Runtime runtime;
qjs::Context context(runtime);
int ret = 0;
ret |= test_not_enough_arguments(context);
ret |= test_call_with_rest_parameters(context);
return ret;
}