]> git.lizzy.rs Git - rust.git/blob - src/tools/rustdoc-js/tester.js
df3185758bfc087e23bda0b6828dd86fb0665ede
[rust.git] / src / tools / rustdoc-js / tester.js
1 const fs = require('fs');
2 const path = require('path');
3
4 function loadContent(content) {
5     var Module = module.constructor;
6     var m = new Module();
7     m._compile(content, "tmp.js");
8     m.exports.ignore_order = content.indexOf("\n// ignore-order\n") !== -1 ||
9         content.startsWith("// ignore-order\n");
10     m.exports.exact_check = content.indexOf("\n// exact-check\n") !== -1 ||
11         content.startsWith("// exact-check\n");
12     m.exports.should_fail = content.indexOf("\n// should-fail\n") !== -1 ||
13         content.startsWith("// should-fail\n");
14     return m.exports;
15 }
16
17 function readFile(filePath) {
18     return fs.readFileSync(filePath, 'utf8');
19 }
20
21 function contentToDiffLine(key, value) {
22     return `"${key}": "${value}",`;
23 }
24
25 // This function is only called when no matching result was found and therefore will only display
26 // the diff between the two items.
27 function betterLookingDiff(entry, data) {
28     let output = ' {\n';
29     let spaces = '     ';
30     for (let key in entry) {
31         if (!entry.hasOwnProperty(key)) {
32             continue;
33         }
34         if (!data || !data.hasOwnProperty(key)) {
35             output += '-' + spaces + contentToDiffLine(key, entry[key]) + '\n';
36             continue;
37         }
38         let value = data[key];
39         if (value !== entry[key]) {
40             output += '-' + spaces + contentToDiffLine(key, entry[key]) + '\n';
41             output += '+' + spaces + contentToDiffLine(key, value) + '\n';
42         } else {
43             output += spaces + contentToDiffLine(key, value) + '\n';
44         }
45     }
46     return output + ' }';
47 }
48
49 function lookForEntry(entry, data) {
50     for (var i = 0; i < data.length; ++i) {
51         var allGood = true;
52         for (var key in entry) {
53             if (!entry.hasOwnProperty(key)) {
54                 continue;
55             }
56             var value = data[i][key];
57             // To make our life easier, if there is a "parent" type, we add it to the path.
58             if (key === 'path' && data[i]['parent'] !== undefined) {
59                 if (value.length > 0) {
60                     value += '::' + data[i]['parent']['name'];
61                 } else {
62                     value = data[i]['parent']['name'];
63                 }
64             }
65             if (value !== entry[key]) {
66                 allGood = false;
67                 break;
68             }
69         }
70         if (allGood === true) {
71             return i;
72         }
73     }
74     return null;
75 }
76
77 // This function checks if `expected` has all the required fields needed for the checks.
78 function checkNeededFields(fullPath, expected, error_text, queryName, position) {
79     let fieldsToCheck;
80     if (fullPath.length === 0) {
81         fieldsToCheck = [
82             "foundElems",
83             "original",
84             "returned",
85             "typeFilter",
86             "userQuery",
87             "error",
88         ];
89     } else if (fullPath.endsWith("elems") || fullPath.endsWith("generics")) {
90         fieldsToCheck = [
91             "name",
92             "fullPath",
93             "pathWithoutLast",
94             "pathLast",
95             "generics",
96         ];
97     } else {
98         fieldsToCheck = [];
99     }
100     for (var i = 0; i < fieldsToCheck.length; ++i) {
101         const field = fieldsToCheck[i];
102         if (!expected.hasOwnProperty(field)) {
103             let text = `${queryName}==> Mandatory key \`${field}\` is not present`;
104             if (fullPath.length > 0) {
105                 text += ` in field \`${fullPath}\``;
106                 if (position != null) {
107                     text += ` (position ${position})`;
108                 }
109             }
110             error_text.push(text);
111         }
112     }
113 }
114
115 function valueCheck(fullPath, expected, result, error_text, queryName) {
116     if (Array.isArray(expected)) {
117         for (var i = 0; i < expected.length; ++i) {
118             checkNeededFields(fullPath, expected[i], error_text, queryName, i);
119             if (i >= result.length) {
120                 error_text.push(`${queryName}==> EXPECTED has extra value in array from field ` +
121                     `\`${fullPath}\` (position ${i}): \`${JSON.stringify(expected[i])}\``);
122             } else {
123                 valueCheck(fullPath + '[' + i + ']', expected[i], result[i], error_text, queryName);
124             }
125         }
126         for (; i < result.length; ++i) {
127             error_text.push(`${queryName}==> RESULT has extra value in array from field ` +
128                 `\`${fullPath}\` (position ${i}): \`${JSON.stringify(result[i])}\` ` +
129                 'compared to EXPECTED');
130         }
131     } else if (expected !== null && typeof expected !== "undefined" &&
132                expected.constructor == Object) {
133         for (const key in expected) {
134             if (!expected.hasOwnProperty(key)) {
135                 continue;
136             }
137             if (!result.hasOwnProperty(key)) {
138                 error_text.push('==> Unknown key "' + key + '"');
139                 break;
140             }
141             const obj_path = fullPath + (fullPath.length > 0 ? '.' : '') + key;
142             valueCheck(obj_path, expected[key], result[key], error_text, queryName);
143         }
144     } else {
145         expectedValue = JSON.stringify(expected);
146         resultValue = JSON.stringify(result);
147         if (expectedValue != resultValue) {
148             error_text.push(`${queryName}==> Different values for field \`${fullPath}\`:\n` +
149                 `EXPECTED: \`${expectedValue}\`\nRESULT:   \`${resultValue}\``);
150         }
151     }
152 }
153
154 function runParser(query, expected, parseQuery, queryName) {
155     var error_text = [];
156     checkNeededFields("", expected, error_text, queryName, null);
157     if (error_text.length === 0) {
158         valueCheck('', expected, parseQuery(query), error_text, queryName);
159     }
160     return error_text;
161 }
162
163 function runSearch(query, expected, doSearch, loadedFile, queryName) {
164     const ignore_order = loadedFile.ignore_order;
165     const exact_check = loadedFile.exact_check;
166
167     var results = doSearch(query, loadedFile.FILTER_CRATE);
168     var error_text = [];
169
170     for (var key in expected) {
171         if (!expected.hasOwnProperty(key)) {
172             continue;
173         }
174         if (!results.hasOwnProperty(key)) {
175             error_text.push('==> Unknown key "' + key + '"');
176             break;
177         }
178         var entry = expected[key];
179
180         if (exact_check == true && entry.length !== results[key].length) {
181             error_text.push(queryName + "==> Expected exactly " + entry.length +
182                             " results but found " + results[key].length + " in '" + key + "'");
183         }
184
185         var prev_pos = -1;
186         for (var i = 0; i < entry.length; ++i) {
187             var entry_pos = lookForEntry(entry[i], results[key]);
188             if (entry_pos === null) {
189                 error_text.push(queryName + "==> Result not found in '" + key + "': '" +
190                                 JSON.stringify(entry[i]) + "'");
191                 // By default, we just compare the two first items.
192                 let item_to_diff = 0;
193                 if ((ignore_order === false || exact_check === true) && i < results[key].length) {
194                     item_to_diff = i;
195                 }
196                 error_text.push("Diff of first error:\n" +
197                     betterLookingDiff(entry[i], results[key][item_to_diff]));
198             } else if (exact_check === true && prev_pos + 1 !== entry_pos) {
199                 error_text.push(queryName + "==> Exact check failed at position " + (prev_pos + 1) +
200                                 ": expected '" + JSON.stringify(entry[i]) + "' but found '" +
201                                 JSON.stringify(results[key][i]) + "'");
202             } else if (ignore_order === false && entry_pos < prev_pos) {
203                 error_text.push(queryName + "==> '" + JSON.stringify(entry[i]) + "' was supposed " +
204                                 "to be before '" + JSON.stringify(results[key][entry_pos]) + "'");
205             } else {
206                 prev_pos = entry_pos;
207             }
208         }
209     }
210     return error_text;
211 }
212
213 function checkResult(error_text, loadedFile, displaySuccess) {
214     if (error_text.length === 0 && loadedFile.should_fail === true) {
215         console.log("FAILED");
216         console.log("==> Test was supposed to fail but all items were found...");
217     } else if (error_text.length !== 0 && loadedFile.should_fail === false) {
218         console.log("FAILED");
219         console.log(error_text.join("\n"));
220     } else {
221         if (displaySuccess) {
222             console.log("OK");
223         }
224         return 0;
225     }
226     return 1;
227 }
228
229 function runCheck(loadedFile, key, callback) {
230     const expected = loadedFile[key];
231     const query = loadedFile.QUERY;
232
233     if (Array.isArray(query)) {
234         if (!Array.isArray(expected)) {
235             console.log("FAILED");
236             console.log(`==> If QUERY variable is an array, ${key} should be an array too`);
237             return 1;
238         } else if (query.length !== expected.length) {
239             console.log("FAILED");
240             console.log(`==> QUERY variable should have the same length as ${key}`);
241             return 1;
242         }
243         for (var i = 0; i < query.length; ++i) {
244             var error_text = callback(query[i], expected[i], "[ query `" + query[i] + "`]");
245             if (checkResult(error_text, loadedFile, false) !== 0) {
246                 return 1;
247             }
248         }
249         console.log("OK");
250     } else {
251         var error_text = callback(query, expected, "");
252         if (checkResult(error_text, loadedFile, true) !== 0) {
253             return 1;
254         }
255     }
256     return 0;
257 }
258
259 function runChecks(testFile, doSearch, parseQuery) {
260     var checkExpected = false;
261     var checkParsed = false;
262     var testFileContent = readFile(testFile) + 'exports.QUERY = QUERY;';
263
264     if (testFileContent.indexOf("FILTER_CRATE") !== -1) {
265         testFileContent += "exports.FILTER_CRATE = FILTER_CRATE;";
266     } else {
267         testFileContent += "exports.FILTER_CRATE = null;";
268     }
269
270     if (testFileContent.indexOf("\nconst EXPECTED") !== -1) {
271         testFileContent += 'exports.EXPECTED = EXPECTED;';
272         checkExpected = true;
273     }
274     if (testFileContent.indexOf("\nconst PARSED") !== -1) {
275         testFileContent += 'exports.PARSED = PARSED;';
276         checkParsed = true;
277     }
278     if (!checkParsed && !checkExpected) {
279         console.log("FAILED");
280         console.log("==> At least `PARSED` or `EXPECTED` is needed!");
281         return 1;
282     }
283
284     const loadedFile = loadContent(testFileContent);
285     var res = 0;
286
287     if (checkExpected) {
288         res += runCheck(loadedFile, "EXPECTED", (query, expected, text) => {
289             return runSearch(query, expected, doSearch, loadedFile, text);
290         });
291     }
292     if (checkParsed) {
293         res += runCheck(loadedFile, "PARSED", (query, expected, text) => {
294             return runParser(query, expected, parseQuery, text);
295         });
296     }
297     return res;
298 }
299
300 /**
301  * Load searchNNN.js and search-indexNNN.js.
302  *
303  * @param {string} doc_folder      - Path to a folder generated by running rustdoc
304  * @param {string} resource_suffix - Version number between filename and .js, e.g. "1.59.0"
305  * @returns {Object}               - Object containing two keys: `doSearch`, which runs a search
306  *   with the loaded index and returns a table of results; and `parseQuery`, which is the
307  *   `parseQuery` function exported from the search module.
308  */
309 function loadSearchJS(doc_folder, resource_suffix) {
310     const searchJs = path.join(doc_folder, "search" + resource_suffix + ".js");
311     const searchIndexJs = path.join(doc_folder, "search-index" + resource_suffix + ".js");
312     const searchIndex = require(searchIndexJs);
313     const searchModule = require(searchJs);
314     const searchWords = searchModule.initSearch(searchIndex.searchIndex);
315
316     return {
317         doSearch: function (queryStr, filterCrate, currentCrate) {
318             return searchModule.execQuery(searchModule.parseQuery(queryStr), searchWords,
319                 filterCrate, currentCrate);
320         },
321         parseQuery: searchModule.parseQuery,
322     }
323 }
324
325 function showHelp() {
326     console.log("rustdoc-js options:");
327     console.log("  --doc-folder [PATH]        : location of the generated doc folder");
328     console.log("  --help                     : show this message then quit");
329     console.log("  --crate-name [STRING]      : crate name to be used");
330     console.log("  --test-file [PATHs]        : location of the JS test files (can be called " +
331                 "multiple times)");
332     console.log("  --test-folder [PATH]       : location of the JS tests folder");
333     console.log("  --resource-suffix [STRING] : suffix to refer to the correct files");
334 }
335
336 function parseOptions(args) {
337     var opts = {
338         "crate_name": "",
339         "resource_suffix": "",
340         "doc_folder": "",
341         "test_folder": "",
342         "test_file": [],
343     };
344     var correspondences = {
345         "--resource-suffix": "resource_suffix",
346         "--doc-folder": "doc_folder",
347         "--test-folder": "test_folder",
348         "--test-file": "test_file",
349         "--crate-name": "crate_name",
350     };
351
352     for (var i = 0; i < args.length; ++i) {
353         if (correspondences.hasOwnProperty(args[i])) {
354             i += 1;
355             if (i >= args.length) {
356                 console.log("Missing argument after `" + args[i - 1] + "` option.");
357                 return null;
358             }
359             if (args[i - 1] !== "--test-file") {
360                 opts[correspondences[args[i - 1]]] = args[i];
361             } else {
362                 opts[correspondences[args[i - 1]]].push(args[i]);
363             }
364         } else if (args[i] === "--help") {
365             showHelp();
366             process.exit(0);
367         } else {
368             console.log("Unknown option `" + args[i] + "`.");
369             console.log("Use `--help` to see the list of options");
370             return null;
371         }
372     }
373     if (opts["doc_folder"].length < 1) {
374         console.log("Missing `--doc-folder` option.");
375     } else if (opts["crate_name"].length < 1) {
376         console.log("Missing `--crate-name` option.");
377     } else if (opts["test_folder"].length < 1 && opts["test_file"].length < 1) {
378         console.log("At least one of `--test-folder` or `--test-file` option is required.");
379     } else {
380         return opts;
381     }
382     return null;
383 }
384
385 function main(argv) {
386     var opts = parseOptions(argv.slice(2));
387     if (opts === null) {
388         return 1;
389     }
390
391     let parseAndSearch = loadSearchJS(
392         opts["doc_folder"],
393         opts["resource_suffix"]);
394     var errors = 0;
395
396     let doSearch = function (queryStr, filterCrate) {
397         return parseAndSearch.doSearch(queryStr, filterCrate, opts["crate_name"]);
398     };
399
400     if (opts["test_file"].length !== 0) {
401         opts["test_file"].forEach(function (file) {
402             process.stdout.write(`Testing ${file} ... `);
403             errors += runChecks(file, doSearch, parseAndSearch.parseQuery);
404         });
405     } else if (opts["test_folder"].length !== 0) {
406         fs.readdirSync(opts["test_folder"]).forEach(function (file) {
407             if (!file.endsWith(".js")) {
408                 return;
409             }
410             process.stdout.write(`Testing ${file} ... `);
411             errors += runChecks(path.join(opts["test_folder"], file), doSearch,
412                     parseAndSearch.parseQuery);
413         });
414     }
415     return errors > 0 ? 1 : 0;
416 }
417
418 process.exit(main(process.argv));