forked from actility/device-catalog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdriver-examples.spec.js
413 lines (363 loc) · 13 KB
/
driver-examples.spec.js
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
const path = require("path");
const fs = require("fs-extra");
const yaml = require("js-yaml");
const ivm = require("isolated-vm");
/**
* Read predefined Isolated Buffer that acts exactly as the NodeJs Buffer library to prevent access to external from the isolated sandbox
*/
const isoBuffer = fs.readFileSync(path.join(__dirname, "../../../..", "iso-libraries", "iso-buffer.js"), "utf8");
/**
* Read the driver's signature from `driver.yaml`
*/
const driverYaml = yaml.load(fs.readFileSync(path.join(__dirname, "driver.yaml"), "utf8"));
const signature = driverYaml.signature;
/**
* Validate if decodeDownlink function is defined in the driver
* as some drivers may have encodeDownlink but no decodeDownlink
* and there exist examples with legacy type "downlink" that should be wrapped only to "downlink-encode"
*/
const isDownlinkDecodeDefined = (() =>{
const packageJson = fs.readJsonSync(path.join(__dirname, "package.json"));
const driverFns = require("./" + packageJson.main);
switch (signature){
case "ttn":
case "chirpstack":
return false;
case "lora-alliance":
case "actility":
default:
let fn;
if(typeof driverFns.driver === 'undefined' || typeof driverFns.driver.decodeUplink !== 'function') {
fn = driverFns;
} else {
fn = driverFns.driver;
}
return typeof fn.decodeDownlink === 'function';
}
})();
/**
* Read the examples according to the signature of driver, wrap them if needed
*/
const examples = (() =>{
// for default (lora-alliance) signature,
// all examples are stored in one file on the root `examples.json`
if(fs.pathExistsSync(path.join(__dirname, "examples.json"))){
return fs.readJsonSync(path.join(__dirname, "examples.json"));
}
// for the rest of signature,
// examples are stored in a separate folder, in one or several json files that ends with `.examples.json`
// Get the list of files in the directory `examples`
// The examples are stored in a legacy format
// They should be wrapped
if(!fs.pathExistsSync(path.join(__dirname, "examples"))){
return [];
}
let examplesFiles = fs.readdirSync("examples");
// Wrap and store all the examples in an array
let examples = [];
for (const exampleFile of examplesFiles) {
if (exampleFile.endsWith(".examples.json")) {
let neWExamples = fs.readJsonSync(path.join(__dirname, "examples", exampleFile));
for(const example of neWExamples){
if(example.type === "uplink"){
let wrappedExample = {
type: example.type,
description: example.description,
input: {
bytes: example.bytes,
fPort: example.fPort,
time: example.time,
thing: example.thing
},
output: example.data
}
examples.push(wrappedExample);
} else if(example.type === "downlink"){
// map to downlink-decode examples only on drivers which have this function
if(isDownlinkDecodeDefined){
let wrappedDecodeDownlink = {
type: "downlink-decode",
description: example.description,
input: {
bytes: example.bytes,
fPort: example.fPort,
time: example.time,
thing: example.thing
},
output: example.data
}
examples.push(wrappedDecodeDownlink);
}
let wrappedEncodeDownlink = {
type: "downlink-encode",
description: example.description,
input: {
data: example.data,
fPort: example.fPort
},
output: {
bytes: example.bytes,
fPort: example.fPort,
}
}
examples.push(wrappedEncodeDownlink);
}
}
}
}
return examples;
})();
/**
* Read the legacy error examples if there is any
*/
const errors = (() =>{
// error examples are stored in a separate folder, in one or several json files
// Get the list of files in the directory `examples`
if(!fs.pathExistsSync(path.join(__dirname, "errors"))){
return [];
}
let errorFiles = fs.readdirSync("errors");
// Storing all the error files in an array
let errors = [];
for (const errorFile of errorFiles) {
if (errorFile.endsWith(".errors.json")) {
errors = examples.concat(fs.readJsonSync(path.join(__dirname, "errors", errorFile)));
}
}
return errors;
})();
/**
* Read the functions call script according to the signature of driver
*/
const fnCall = (() => {
let fnCallRef;
switch (signature){
case "actility":
fnCallRef = "tpxFnCall.js";
break;
case "ttn":
fnCallRef = "ttnFnCall.js";
break;
case "chirpstack":
fnCallRef = "chirpstackFnCall.js";
break;
case "lora-alliance":
default:
fnCallRef = "loraAllianceFnCall.js";
break;
}
return fs.readFileSync(path.join(__dirname, "../../../..", "iso-libraries", fnCallRef), "utf8");
})();
/**
* Read the driver code according to the main file specified in the npm package
*/
const code = (() => {
const packageJson = fs.readJsonSync(path.join(__dirname, "package.json"));
return fs.readFileSync(path.join(__dirname, packageJson.main), "utf8");
})();
/**
* Checking whether the driver is trusted or not
*/
function isTrusted() {
const packageJson = fs.readJsonSync(path.join(__dirname, "package.json"));
return packageJson.trusted ?? false;
}
const trusted = isTrusted();
/**
* Create an isolated-vm sandbox to run the code inside
*/
let isolate;
let script;
if(!trusted) {
isolate = new ivm.Isolate();
script = isolate.compileScriptSync(isoBuffer.concat("\n" + code).concat("\n" + fnCall));
}
/**
* @param input : input from example to run the driver with
* @param operation : operation to be operated on the input
* @return result: output of the driver with the given input and operation
*/
async function run(input, operation){
if(trusted) {
let result;
eval(
code
+ ";\n"
+ `result = decodeUplink(input)`
);
return result;
}
const context = await isolate.createContext();
await context.global.set("operation", operation);
await context.global.set("input", new ivm.ExternalCopy(input).copyInto());
await context.global.set("exports", new ivm.ExternalCopy({}).copyInto());
await script.run(context, { timeout: 1000 });
const getDriverEngineResult = await context.global.get("getDriverEngineResult");
const result = getDriverEngineResult();
await context.release();
return result;
}
/**
Test suites compatible with all driver types
*/
describe("Decode uplink", () => {
examples.forEach((example) => {
if (example.type === "uplink") {
it(example.description, async () => {
// Given
const input = example.input;
// Adaptation
input.bytes = adaptBytesArray(input.bytes);
// When
const result = await run(input, "decodeUplink");
// Then
const expected = example.output;
// Adaptations
adaptDates(result, expected);
expect(result).toStrictEqual(expected);
});
}
});
});
describe("Decode downlink", () => {
examples.forEach((example) => {
if (example.type === "downlink-decode") {
it(example.description, async () => {
// Given
const input = example.input;
// Adaptation
input.bytes = adaptBytesArray(input.bytes);
// When
const result = await run(input, "decodeDownlink");
// Then
const expected = example.output;
// Then
expect(result).toStrictEqual(expected);
});
}
});
});
describe("Encode downlink", () => {
examples.forEach((example) => {
if (example.type === "downlink-encode") {
it(example.description, async () => {
// Given
const input = example.input;
// When
const result = await run(input, "encodeDownlink");
// Then
const expected = example.output;
// Adaptation
if(result.bytes){
result.bytes = adaptBytesArray(result.bytes);
}
if(expected.bytes){
expected.bytes = adaptBytesArray(expected.bytes);
}
expect(result).toStrictEqual(expected);
});
}
});
});
describe("Legacy Decode uplink errors", () => {
errors.forEach((error) => {
if (error.type === "uplink" && !error.data) {
it(error.description, () => {
// Given
const input = {
bytes: adaptBytesArray(error.bytes),
fPort: error.fPort,
time: error.time
};
// When / Then
const expected = error.error;
expect(async () => await run(input, "decodeUplink").toThrow(expected));
});
}
});
});
describe("Legacy Decode downlink errors", () => {
errors.forEach((error) => {
if (error.type === "uplink" && !error.data) {
it(error.description, () => {
// Given
const input = {
bytes: adaptBytesArray(error.bytes),
fPort: error.fPort,
time: error.time
};
// When / Then
const expected = error.error;
expect(async () => await run(input, "decodeDownlink").toThrow(expected));
});
}
});
});
describe("Legacy Encode downlink errors", () => {
errors.forEach((error) => {
if (error.type === "uplink" && error.data) {
it(error.description, () => {
// Given
const input = error.data;
// When / Then
const expected = error.error;
expect(async () => await run(input, "encodeDownlink").toThrow(expected));
});
}
});
});
/**
Utils used for unusual inputs
*/
function adaptBytesArray(bytes){
// if the bytes in example are in hexadecimal format instead of array of integers
if(typeof bytes === "string"){
return Array.from(Buffer.from(bytes, "hex"));
}
return bytes;
}
// UTIL
function adaptDates(result, expected) {
for(let property of listProperties(result)) {
let keys = property.split('.');
let value = result;
let expectedValue = expected;
let skipProperty = false;
for(let key of keys) {
value = value[key];
expectedValue = expectedValue[key];
if(expectedValue == null) {
skipProperty = true;
break;
}
}
if(skipProperty) continue;
let isDate = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/.test(value);
isDate |= value instanceof Date;
if(isDate) {
let displayedResult = value;
if(displayedResult instanceof Date) displayedResult = displayedResult.toISOString();
if(expectedValue === "XXXX-XX-XXTXX:XX:XX.XXXZ") displayedResult = "XXXX-XX-XXTXX:XX:XX.XXXZ";
value = result;
for (let i = 0; i < keys.length - 1; i++) {
if (!value[keys[i]] || typeof value[keys[i]] !== 'object') {
value[keys[i]] = {};
}
value = value[keys[i]];
}
value[keys[keys.length - 1]] = displayedResult;
}
}
}
function listProperties(obj, parent = '', result = []) {
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
if (typeof obj[key] === 'object' && !(obj[key] instanceof Date) && obj[key] !== null) {
listProperties(obj[key], parent + key + '.', result);
} else {
result.push(parent + key);
}
}
}
return result;
}