-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathsimulateScript.test.ts
331 lines (261 loc) · 9.99 KB
/
simulateScript.test.ts
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import http from 'http'
import { simulateScript } from '../../src'
import type { AddressInfo } from 'net'
describe('simulateScript', () => {
describe('successful simulation', () => {
it('simulates script', async () => {
const result = await simulateScript({
source:
"console.log('start'); return Functions.encodeString(args[0] + bytesArgs[0] + secrets.key);",
args: ['MockArg'],
bytesArgs: ['0x1234'],
secrets: {
key: 'MockSecret',
},
})
const expected = {
capturedTerminalOutput: 'start\n',
responseBytesHexstring: '0x4d6f636b4172673078313233344d6f636b536563726574',
}
expect(result).toEqual(expected)
})
it('simulates script with HTTP request', async () => {
const server = createTestServer()
const port = (server.address() as AddressInfo).port
const result = await simulateScript({
source: `const response = await fetch('http://localhost:${port}'); const jsonResponse = await response.json(); console.log(jsonResponse); return Functions.encodeString(jsonResponse.message);`,
})
const expected = {
capturedTerminalOutput: '{ message: "Hello, world!" }\n',
responseBytesHexstring: '0x48656c6c6f2c20776f726c6421',
}
expect(result).toEqual(expected)
server.close()
})
it('should handle multiple simultaneous HTTP requests', async () => {
const server = createTestServer()
const port = (server.address() as AddressInfo).port
const url = `http://localhost:${port}`
const result = await simulateScript({
source: `const req1 = fetch('${url}'); const req2 = fetch('${url}'); const req3 = fetch('${url}');\
const [ res1, res2, res3 ] = await Promise.all([req1, req2, req3]);\
const [ json1, json2, json3 ] = await Promise.all([res1.json(), res2.json(), res3.json()]);\
console.log(json1); console.log(json2); console.log(json3);\
return Functions.encodeString(json1.message + json2.message + json3.message);`,
})
const expected = {
capturedTerminalOutput:
'{ message: "Hello, world!" }\n{ message: "Hello, world!" }\n{ message: "Hello, world!" }\n',
responseBytesHexstring:
'0x48656c6c6f2c20776f726c642148656c6c6f2c20776f726c642148656c6c6f2c20776f726c6421',
}
expect(result).toEqual(expected)
server.close()
})
it('should handle script with type error', async () => {
const result = await simulateScript({
source: 'const myString: string = 123; return Functions.encodeUint256(myString);',
})
const expected = {
capturedTerminalOutput: '',
responseBytesHexstring:
'0x000000000000000000000000000000000000000000000000000000000000007b',
}
expect(result).toEqual(expected)
})
})
describe('handle errors during simulation', () => {
it('should handle when HTTP request takes longer than max time', async () => {
const server = createTestServerWithResponseDelay()
const port = (server.address() as AddressInfo).port
const result = await simulateScript({
source: `const response = await fetch('http://localhost:${port}'); const jsonResponse = await response.json(); console.log(jsonResponse); return Functions.encodeUint256(1);`,
maxQueryDurationMs: 50,
})
const expected = {
capturedTerminalOutput: '{ error: "HTTP query exceeded time limit of 50ms" }\n',
responseBytesHexstring:
'0x0000000000000000000000000000000000000000000000000000000000000001',
}
expect(result).toEqual(expected)
server.close()
})
it('should handle when response size is exceeded', async () => {
const result = await simulateScript({
source: "console.log('start'); return Functions.encodeString('0123456789012');",
maxOnChainResponseBytes: 10,
})
const expected = {
capturedTerminalOutput: 'start\n',
errorString: 'response >10 bytes',
}
expect(result).toEqual(expected)
})
it('should handle when script throws error', async () => {
const result = await simulateScript({
source: "throw new Error('test');",
})
const expected = {
capturedTerminalOutput: '',
errorString: 'test',
}
expect(result).toEqual(expected)
})
it('should handle when script throws string', async () => {
const result = await simulateScript({
source: "throw 'test';",
})
const expected = {
capturedTerminalOutput: '',
errorString: 'test',
}
expect(result).toEqual(expected)
})
it('should handle when script throws unsupported value', async () => {
const result = await simulateScript({
source: 'throw 123;',
})
const expected = {
capturedTerminalOutput: '',
errorString: 'invalid value thrown of type number',
}
expect(result).toEqual(expected)
})
it('should capture syntax error', async () => {
const result = await simulateScript({
source: "console.log('start'); return Functions.encodeString(",
})
expect(result.capturedTerminalOutput).toContain(
"The module's source code could not be parsed",
)
expect(result.errorString).toBe('syntax error, RAM exceeded, or other error')
})
it('should capture incorrect return value', async () => {
const result = await simulateScript({
source: "return 'invalid'",
})
const expected = {
capturedTerminalOutput: '',
errorString: 'returned value not an ArrayBuffer or Uint8Array',
}
expect(result).toEqual(expected)
})
it('should handle when no value is returned', async () => {
const result = await simulateScript({
source: 'return',
})
const expected = {
capturedTerminalOutput: '',
errorString: 'returned value not an ArrayBuffer or Uint8Array',
}
expect(result).toEqual(expected)
})
it('should capture timeout error', async () => {
const result = await simulateScript({
source: 'while (true) {}',
maxExecutionTimeMs: 100,
})
const expected = {
capturedTerminalOutput: '',
errorString: 'script runtime exceeded',
}
expect(result).toEqual(expected)
})
it('should capture permissions error', async () => {
const result = await simulateScript({
source: "Deno.openSync('test.txt')",
maxExecutionTimeMs: 100,
})
const expected = {
capturedTerminalOutput: '',
errorString: 'attempted access to blocked resource detected',
}
expect(result).toEqual(expected)
})
})
describe('validation errors', () => {
it('should throw error for invalid source', async () => {
const result = simulateScript({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
source: 123 as any,
})
await expect(result).rejects.toThrow('source param is missing or invalid')
})
it('should throw error for invalid secrets', async () => {
const result = simulateScript({
source: 'return',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
secrets: { bad: 1 } as any,
})
await expect(result).rejects.toThrow('secrets param not a string map')
})
it('should throw error for invalid args', async () => {
const result = simulateScript({
source: 'return',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
args: 123 as any,
})
await expect(result).rejects.toThrow('args param not an array')
})
it('should throw error when an element of args is not a string', async () => {
const result = simulateScript({
source: 'return',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
args: [123] as any,
})
await expect(result).rejects.toThrow('args param not a string array')
})
it('should throw error for invalid bytesArgs', async () => {
const result = simulateScript({
source: 'return',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
bytesArgs: 123 as any,
})
await expect(result).rejects.toThrow('bytesArgs param not an array')
})
it('should throw error when an element of bytesArgs is not a hex string', async () => {
const result = simulateScript({
source: 'return',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
bytesArgs: ['invalid'] as any,
})
await expect(result).rejects.toThrow('bytesArgs param contains invalid hex string')
})
it('should allow 3rd party imports', async () => {
const result = await simulateScript({
source:
'const { escape } = await import("https://deno.land/std/regexp/mod.ts"); return Functions.encodeString(escape("$hello*world?"));',
})
expect(result.responseBytesHexstring).toEqual(
`0x${Buffer.from('\\$hello\\*world\\?').toString('hex')}`,
)
})
it('should allow NPM imports', async () => {
const result = await simulateScript({
source:
'const { format } = await import("npm:date-fns"); return Functions.encodeString(format(new Date(), "yyyy-MM-dd"));',
})
expect(Buffer.from(result.responseBytesHexstring?.slice(2) as string, 'hex').length).toEqual(
10,
)
})
})
})
const createTestServer = (): http.Server => {
const server = http.createServer((_, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ message: 'Hello, world!' }))
})
server.listen()
return server
}
const createTestServerWithResponseDelay = (): http.Server => {
const server = http.createServer((_, res) => {
setTimeout(() => {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ message: 'Hello, world!' }))
}, 100)
})
server.listen()
return server
}