-
Notifications
You must be signed in to change notification settings - Fork 58
/
NodejsEmbeddingTests.cs
419 lines (363 loc) · 13.9 KB
/
NodejsEmbeddingTests.cs
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma warning disable CA1822 // Mark members as static
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.JavaScript.NodeApi.DotNetHost;
using Microsoft.JavaScript.NodeApi.Interop;
using Microsoft.JavaScript.NodeApi.Runtime;
using Xunit;
using static Microsoft.JavaScript.NodeApi.Test.TestUtils;
namespace Microsoft.JavaScript.NodeApi.Test;
public class NodejsEmbeddingTests
{
private static string LibnodePath { get; } = GetLibnodePath();
// The Node.js platform may only be initialized once per process.
internal static NodejsPlatform? NodejsPlatform { get; } =
File.Exists(LibnodePath) ? new(LibnodePath, args: new[] { "node", "--expose-gc" }) : null;
internal static NodejsEnvironment CreateNodejsEnvironment()
{
Skip.If(NodejsPlatform == null, "Node shared library not found at " + LibnodePath);
return NodejsPlatform.CreateEnvironment(Path.Combine(GetRepoRootDirectory(), "test"));
}
internal static void RunInNodejsEnvironment(Action action)
{
using NodejsEnvironment nodejs = CreateNodejsEnvironment();
nodejs.SynchronizationContext.Run(action);
}
[SkippableFact]
public void StartEnvironment()
{
using NodejsEnvironment nodejs = CreateNodejsEnvironment();
nodejs.Run(() =>
{
JSValue result = JSValue.RunScript("require('node:path').join('a', 'b')");
Assert.Equal(Path.Combine("a", "b"), (string)result);
});
nodejs.Dispose();
Assert.Equal(0, nodejs.ExitCode);
}
[SkippableFact]
public void RestartEnvironment()
{
// Create and destory a Node.js environment twice, using the same platform instance.
StartEnvironment();
StartEnvironment();
}
public interface IConsole { void Log(string message); }
[SkippableFact]
public void CallFunction()
{
using NodejsEnvironment nodejs = CreateNodejsEnvironment();
nodejs.SynchronizationContext.Run(() =>
{
JSFunction func = (JSFunction)JSValue.RunScript("function jsFunction() { }; jsFunction");
func.CallAsStatic();
});
nodejs.Dispose();
Assert.Equal(0, nodejs.ExitCode);
}
[SkippableFact]
public void ImportBuiltinModule()
{
using NodejsEnvironment nodejs = CreateNodejsEnvironment();
nodejs.Run(() =>
{
JSValue fsModule = nodejs.Import("fs");
Assert.Equal(JSValueType.Object, fsModule.TypeOf());
Assert.Equal(JSValueType.Function, fsModule["stat"].TypeOf());
JSValue nodeFsModule = nodejs.Import("node:fs");
Assert.Equal(JSValueType.Object, nodeFsModule.TypeOf());
Assert.Equal(JSValueType.Function, nodeFsModule["stat"].TypeOf());
});
nodejs.Dispose();
Assert.Equal(0, nodejs.ExitCode);
}
[SkippableFact]
public void ImportCommonJSModule()
{
using NodejsEnvironment nodejs = CreateNodejsEnvironment();
nodejs.Run(() =>
{
JSValue testModule = nodejs.Import("./test-module.cjs");
Assert.Equal(JSValueType.Object, testModule.TypeOf());
Assert.Equal(JSValueType.Function, testModule["test"].TypeOf());
Assert.Equal("test", testModule.CallMethod("test"));
});
nodejs.Dispose();
Assert.Equal(0, nodejs.ExitCode);
}
[SkippableFact]
public void ImportCommonJSPackage()
{
using NodejsEnvironment nodejs = CreateNodejsEnvironment();
nodejs.Run(() =>
{
JSValue testModule = nodejs.Import("./test-cjs-package");
Assert.Equal(JSValueType.Object, testModule.TypeOf());
Assert.Equal(JSValueType.Function, testModule["test"].TypeOf());
Assert.Equal("test", testModule.CallMethod("test"));
});
nodejs.Dispose();
Assert.Equal(0, nodejs.ExitCode);
}
[SkippableFact]
public async Task ImportESModule()
{
using NodejsEnvironment nodejs = CreateNodejsEnvironment();
await nodejs.RunAsync(async () =>
{
JSValue testModule = await nodejs.ImportAsync(
"./test-module.mjs", null, esModule: true);
Assert.Equal(JSValueType.Object, testModule.TypeOf());
Assert.Equal(JSValueType.Function, testModule["test"].TypeOf());
Assert.Equal("test", testModule.CallMethod("test"));
});
nodejs.Dispose();
Assert.Equal(0, nodejs.ExitCode);
}
[SkippableFact]
public async Task ImportESPackage()
{
using NodejsEnvironment nodejs = CreateNodejsEnvironment();
await nodejs.RunAsync(async () =>
{
JSValue testModule = await nodejs.ImportAsync(
"./test-esm-package", esModule: true);
Assert.Equal(JSValueType.Object, testModule.TypeOf());
Assert.Equal(JSValueType.Function, testModule["test"].TypeOf());
Assert.Equal("test", testModule.CallMethod("test"));
// Check that module resolution handles sub-paths from conditional exports.
// https://nodejs.org/api/packages.html#conditional-exports
JSValue testModuleFeature = await nodejs.ImportAsync(
"./test-esm-package/feature", esModule: true);
Assert.Equal(JSValueType.Object, testModuleFeature.TypeOf());
Assert.Equal(JSValueType.Function, testModuleFeature["test2"].TypeOf());
Assert.Equal("test2", testModuleFeature.CallMethod("test2"));
// Directly import a property from the module
JSValue testModuleProperty = await nodejs.ImportAsync(
"./test-esm-package", "test", esModule: true);
Assert.Equal(JSValueType.Function, testModuleProperty.TypeOf());
Assert.Equal("test", testModuleProperty.Call());
});
nodejs.Dispose();
Assert.Equal(0, nodejs.ExitCode);
}
[SkippableFact]
public void UnhandledRejection()
{
using NodejsEnvironment nodejs = CreateNodejsEnvironment();
string? errorMessage = null;
nodejs.UnhandledPromiseRejection += (_, e) =>
{
errorMessage = (string)e.Error.GetProperty("message");
};
nodejs.Run(() =>
{
JSValue.RunScript("new Promise((resolve, reject) => reject(new Error('test')))");
});
// The unhandled rejection event is not synchronous. Wait for it.
for (int wait = 10; wait < 1000 && errorMessage == null; wait += 10) Thread.Sleep(10);
Assert.Equal("test", errorMessage);
}
[SkippableFact]
public void ErrorPropagation()
{
using NodejsEnvironment nodejs = CreateNodejsEnvironment();
JSException exception = Assert.Throws<JSException>(() =>
{
nodejs.Run(() =>
{
JSValue.RunScript(
"function throwError() { throw new Error('test'); }\n" +
"throwError();");
});
});
Assert.Equal("Exception thrown from JS thread: test", exception.Message);
Assert.IsType<JSException>(exception.InnerException);
exception = (JSException)exception.InnerException;
Assert.Equal("test", exception.Message);
Assert.NotNull(exception.StackTrace);
string[] stackLines = exception.StackTrace
.Split('\n')
.Select((line) => line.Trim())
.ToArray();
// The first line of the stack trace should refer to the JS function that threw.
Assert.StartsWith("at throwError ", stackLines[0]);
// The stack trace should include lines that refer to the .NET method that called JS.
Assert.Contains(
stackLines,
(line) => line.StartsWith($"at {typeof(NodejsEmbeddingTests).FullName}."));
}
[SkippableFact]
public async Task WorkerIsMainThread()
{
await TestWorker(
mainPrepare: () =>
{
Assert.True(NodeWorker.IsMainThread);
return new NodeWorker.Options { Eval = true };
},
workerScript: @"
const assert = require('node:assert');
const { isMainThread } = require('node:worker_threads');
assert(!isMainThread);
",
mainRun: (worker) => Task.CompletedTask);
}
[SkippableFact]
public async Task WorkerArgs()
{
await TestWorker(
mainPrepare: () =>
{
return new NodeWorker.Options
{
Eval = true,
#pragma warning disable CA1861 // Prefer 'static readonly' fields over constant array arguments
Argv = new[] { "test1", "test2" },
#pragma warning restore CA1861
WorkerData = true,
};
},
workerScript: @"
const assert = require('node:assert');
const process = require('node:process');
const { workerData } = require('node:worker_threads');
assert.deepStrictEqual(process.argv.slice(2), ['test1', 'test2']);
assert.strictEqual(typeof workerData, 'boolean');
assert(workerData);
",
mainRun: (worker) => Task.CompletedTask);
}
[SkippableFact]
public async Task WorkerEnv()
{
await TestWorker(
mainPrepare: () =>
{
NodeWorker.SetEnvironmentData("test", JSValue.True);
return new NodeWorker.Options
{
Eval = true,
};
},
workerScript: @"
const assert = require('node:assert');
const { getEnvironmentData } = require('node:worker_threads');
assert.strictEqual(getEnvironmentData('test'), true);
",
mainRun: (worker) => Task.CompletedTask);
}
[SkippableFact]
public async Task WorkerMessages()
{
await TestWorker(
mainPrepare: () =>
{
return new NodeWorker.Options { Eval = true };
},
workerScript: @"
const { parentPort } = require('node:worker_threads');
parentPort.on('message', (msg) => parentPort.postMessage(msg)); // echo
",
mainRun: async (worker) =>
{
TaskCompletionSource<string> echoCompletion = new();
worker.Message += (_, e) => echoCompletion.TrySetResult((string)e.Value);
worker.Error += (_, e) => echoCompletion.TrySetException(
new JSException(e.Error));
worker.Exit += (_, e) => echoCompletion.TrySetException(
new InvalidOperationException("Worker exited without echoing!"));
worker.PostMessage("test");
string echo = await echoCompletion.Task;
Assert.Equal("test", echo);
});
}
[SkippableFact]
public async Task WorkerStdinStdout()
{
await TestWorker(
mainPrepare: () =>
{
return new NodeWorker.Options
{
Eval = true,
Stdin = true,
Stdout = true,
};
},
workerScript: @"process.stdin.pipe(process.stdout)",
mainRun: async (worker) =>
{
TaskCompletionSource<string> echoCompletion = new();
worker.Error += (_, e) => echoCompletion.TrySetException(
new JSException(e.Error));
worker.Exit += (_, e) => echoCompletion.TrySetException(
new InvalidOperationException("Worker exited without echoing!"));
Assert.NotNull(worker.Stdin);
await worker.Stdin.WriteAsync(Encoding.ASCII.GetBytes("test\n"), 0, 5);
byte[] buffer = new byte[25];
int count = await worker.Stdout.ReadAsync(buffer, 0, buffer.Length);
Assert.Equal("test\n", Encoding.ASCII.GetString(buffer, 0, count));
});
}
private static async Task TestWorker(
Func<NodeWorker.Options> mainPrepare,
string workerScript,
Func<NodeWorker, Task> mainRun)
{
using NodejsEnvironment nodejs = CreateNodejsEnvironment();
await nodejs.RunAsync(async () =>
{
NodeWorker.Options workerOptions = mainPrepare.Invoke();
NodeWorker worker = new(workerScript, workerOptions);
TaskCompletionSource<bool> onlineCompletion = new();
worker.Online += (sender, e) => onlineCompletion.SetResult(true);
TaskCompletionSource<int> exitCompletion = new();
worker.Error += (sender, e) => exitCompletion.SetException(new JSException(e.Error));
worker.Exit += (sender, e) => exitCompletion.TrySetResult(e.ExitCode);
await onlineCompletion.Task;
try
{
await mainRun.Invoke(worker);
}
finally
{
await worker.Terminate();
}
await exitCompletion.Task;
});
}
/// <summary>
/// Tests the functionality of dynamically exporting and marshalling a class type from .NET
/// to JS (as opposed to relying on [JSExport] (compile-time code-generation) for marshalling.
/// </summary>
[SkippableFact]
public void MarshalClass()
{
using NodejsEnvironment nodejs = CreateNodejsEnvironment();
nodejs.Run(() =>
{
JSMarshaller marshaller = new();
TypeExporter exporter = new(marshaller);
exporter.ExportType(typeof(TestClass));
TestClass obj = new()
{
Value = "test"
};
JSValue objJs = marshaller.ToJS(obj);
Assert.Equal(JSValueType.Object, objJs.TypeOf());
Assert.Equal("test", (string)objJs["Value"]);
});
}
// Used for marshalling tests.
public class TestClass
{
public string? Value { get; set; }
}
}