-
Notifications
You must be signed in to change notification settings - Fork 19
/
index.js
336 lines (309 loc) · 13.7 KB
/
index.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
/*
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the W3C Software Notice and
* Document License (2015-05-13) which is available at
* https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document.
*
* SPDX-License-Identifier: EPL-2.0 OR W3C-20150513
*/
const validate = require("./util").validate;
const validateTD = require("./assertionTests-td");
const validateTM = require("./assertionTests-tm");
const checkCoverage = require("./checkCoverage");
const mergeResults = require("./mergeResults");
// JSON to CSV and vice versa libraries
const Json2csvParser = require("json2csv").Parser;
const csvjson = require("csvjson");
const path = require("path");
module.exports.tdAssertions = tdAssertions;
module.exports.tmAssertions = tmAssertions;
module.exports.resultsToCsv = resultsToCsv;
module.exports.validate = validate;
module.exports.tdAssertionTests = validateTD;
module.exports.tmAssertionTests = validateTM;
module.exports.checkCoverage = checkCoverage;
module.exports.mergeResults = mergeResults;
module.exports.manualToJson = manualToJson;
module.exports.collectAssertionSchemas = collectAssertionSchemas;
/**
* Assertion testing function, does assertion testing with one/several TDs and
* returns either a single report or one merged report and all single reports.
* @param {string[]|Buffer[]} tdStrings The Thing Description(s) to check as an array of strings or Buffers.
* @param {Function} fileLoader (string) => string Path to a file as input, should return file content
* @param {Function} logFunc OPT (string) => void; Callback used to log the validation progress.
* @param {object} givenManual OPT JSON object of the manual assertions
* @param {EventEmitter} doneEventEmitter
*/
async function tdAssertions(tdStrings, fileLoader, logFunc, givenManual, doneEventEmitter) {
return new Promise((res, rej) => {
// parameter handling
if (typeof tdStrings !== "object") {
throw new Error("tdStrings has to be an Array of Strings or Buffers");
}
if (typeof fileLoader !== "function") {
throw new Error("jsonLoader has to be a function");
}
if (logFunc === undefined) {
logFunc = console.log;
}
if (givenManual !== undefined && typeof givenManual !== "object") {
throw new Error("givenManual has to be a JSON object if given.");
}
// set directory for node.js and browser environment
let pathOffset;
if (process !== undefined && process.release !== undefined && process.release.name === "node") {
pathOffset = __dirname;
} else {
pathOffset = path.join("./node_modules", "@thing-description-playground", "assertions");
}
// loading files
const loadProm = [];
loadProm.push(
collectAssertionSchemas(
path.join(pathOffset, "./assertions-td"),
path.join(pathOffset, "./assertions-td", "./tdAssertionList.json"),
fileLoader
)
);
loadProm.push(
fileLoader(
path.join(pathOffset, "./node_modules", "@thing-description-playground", "core", "td-schema.json")
)
);
if (givenManual === undefined) {
loadProm.push(fileLoader(path.join(pathOffset, "./assertions-td", "./manual.csv")));
}
Promise.all(loadProm).then(
(promResults) => {
const assertionSchemas = promResults.shift();
const tdSchema = promResults.shift();
const manualAssertionsJSON =
givenManual === undefined ? manualToJson(promResults.shift().toString()) : givenManual;
const jsonResults = {};
tdStrings.forEach(async (tdToValidate) => {
// check if id exists, use it for name if it does, title + some rand number otherwise
let tdName = "";
if ("id" in JSON.parse(tdToValidate)) {
const tdId = JSON.parse(tdToValidate).id;
tdName = tdId.replace(/:/g, "_");
} else {
const tdTitle = JSON.parse(tdToValidate).title;
tdName = tdTitle + Math.floor(Math.random() * 1000);
}
if (doneEventEmitter) doneEventEmitter.emit("start", tdName);
if (typeof tdToValidate === "string") {
tdToValidate = Buffer.from(tdToValidate, "utf8");
}
try {
if (jsonResults[tdName] !== undefined) {
throw new Error("TDs have same Ids or titles: " + tdName);
}
jsonResults[tdName] = validateTD(tdToValidate, assertionSchemas, manualAssertionsJSON, logFunc);
} catch (error) {
console.error(error);
} finally {
if (doneEventEmitter) doneEventEmitter.emit("done", tdName);
}
});
const tdNames = Object.keys(jsonResults);
if (tdNames.length > 1) {
const resultAr = [];
Object.keys(jsonResults).forEach(async (id) => {
resultAr.push(jsonResults[id]);
});
Promise.all(resultAr).then((values) => {
const newArray = values;
mergeResults(newArray).then(
(merged) => {
checkCoverage(merged, logFunc);
res({ jsonResults, merged });
},
(err) => {
rej("merging failed: " + err);
}
);
});
} else {
const merged = jsonResults[tdNames[0]];
checkCoverage(merged, logFunc);
res(merged);
}
},
(err) => {
rej("collectAssertionSchemas function problem: " + err);
}
);
});
}
/**
* Assertion testing function, does assertion testing with one/several TMs and
* returns either a single report or one merged report and all single reports.
* @param {string[]|Buffer[]} tmStrings The Thing Description(s) to check as an array of strings or Buffers.
* @param {Function} fileLoader (string) => string Path to a file as input, should return file content
* @param {Function} logFunc OPT (string) => void; Callback used to log the validation progress.
* @param {object} givenManual OPT JSON object of the manual assertions
*/
function tmAssertions(tmStrings, fileLoader, logFunc, givenManual, doneEventEmitter) {
return new Promise((res, rej) => {
// parameter handling
if (typeof tmStrings !== "object") {
throw new Error("tmStrings has to be an Array of Strings or Buffers");
}
if (typeof fileLoader !== "function") {
throw new Error("jsonLoader has to be a function");
}
if (logFunc === undefined) {
logFunc = console.log;
}
if (givenManual !== undefined && typeof givenManual !== "object") {
throw new Error("givenManual has to be a JSON object if given.");
}
// set directory for node.js and browser environment
let pathOffset;
if (process !== undefined && process.release !== undefined && process.release.name === "node") {
pathOffset = __dirname;
} else {
pathOffset = path.join("./node_modules", "@thing-description-playground", "assertions");
}
// loading files
const loadProm = [];
loadProm.push(
collectAssertionSchemas(
path.join(pathOffset, "./assertions-tm"),
path.join(pathOffset, "./assertions-tm", "./tmAssertionList.json"),
fileLoader
)
);
loadProm.push(
fileLoader(
path.join(pathOffset, "./node_modules", "@thing-description-playground", "core", "tm-schema.json")
)
);
if (givenManual === undefined) {
loadProm.push(fileLoader(path.join(pathOffset, "./assertions-tm", "./manual.csv")));
}
Promise.all(loadProm).then(
(promResults) => {
const assertionSchemas = promResults.shift();
// ! Is needed, do not remove!
const tmSchema = promResults.shift();
const manualAssertionsJSON =
givenManual === undefined ? manualToJson(promResults.shift().toString()) : givenManual;
const jsonResults = {};
tmStrings.forEach((tmToValidate) => {
// check if id exists, use it for name if it does, title + some rand number otherwise
const parsedTm = JSON.parse(tmToValidate);
const generateNumber = () => Math.floor(Math.random() * 1000);
let tmName;
if ("id" in parsedTm) {
const tmId = parsedTm.id;
tmName = tmId.replace(/:/g, "_");
} else if ("title" in parsedTm) {
tmName = parsedTm.title + generateNumber();
} else {
tmName = `Unnamed TM ${generateNumber()}`;
}
if (doneEventEmitter) doneEventEmitter.emit("start", tmName);
if (typeof tmToValidate === "string") {
tmToValidate = Buffer.from(tmToValidate, "utf8");
}
try {
if (jsonResults[tmName] !== undefined) {
throw new Error("TDs have same Ids or titles: " + tmName);
}
jsonResults[tmName] = validateTM(tmToValidate, assertionSchemas, manualAssertionsJSON, logFunc);
} catch (error) {
console.log(error);
} finally {
if (doneEventEmitter) doneEventEmitter.emit("done", tmName);
}
});
const tmNames = Object.keys(jsonResults);
if (tmNames.length > 1) {
const resultAr = [];
Object.keys(jsonResults).forEach((id) => {
resultAr.push(jsonResults[id]);
});
mergeResults(resultAr).then(
(merged) => {
checkCoverage(merged, logFunc);
res({ jsonResults, merged });
},
(err) => {
rej("merging failed: " + err);
}
);
} else {
const merged = jsonResults[tmNames[0]];
checkCoverage(merged, logFunc);
res(merged);
}
},
(err) => {
rej("collectAssertionSchemas function problem: " + err);
}
);
});
}
/**
* Helper: Loads and generates an Array containing all assertion objects
* @param {string} assertionsDirectory path to the directory, which contains the assertions
* @param {string} assertionsList path to the assertion filenames list
* @param {function} loadFunction (string) => string path string as input should return file content as string
* @returns {Array<object>} An array containing all assertion objects (already parsed)
*/
function collectAssertionSchemas(assertionsDirectory, assertionsList, loadFunction) {
return new Promise((res, rej) => {
const assertionSchemas = [];
const assertionProms = [];
loadFunction(assertionsList).then(
(assertionNames) => {
assertionsListLocation = JSON.parse(assertionNames);
assertionsListLocation.forEach((curAssertion) => {
assertionProms.push(
new Promise((resolve, reject) => {
const schemaLocation = path.join(assertionsDirectory, curAssertion);
loadFunction(schemaLocation).then((schemaRaw) => {
const schemaJSON = JSON.parse(schemaRaw);
assertionSchemas.push(schemaJSON);
resolve();
});
})
);
});
Promise.all(assertionProms).then(() => {
res(assertionSchemas);
});
},
(err) => {
rej("Could not load assertion list" + err);
}
);
});
}
/**
* Building the CSV and its corresponding JSON structure
*
* @param {Array<object>} results of one Td as JSON objects array
* @returns {string} csv formatted results
*/
function resultsToCsv(results) {
const fields = ["ID", "Status", "Comment", "Assertion"];
const json2csvParser = new Json2csvParser({
fields,
});
return json2csvParser.parse(results);
}
function manualToJson(csv) {
const options = {
delimiter: ",", // optional
quote: '"', // optional
};
return csvjson.toObject(csv, options);
}