test.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. /* jshint esversion: 6 */
  2. /* eslint "indent": [ "error", 4, { "SwitchCase": 1 } ] */
  3. /* eslint "no-console": off */
  4. const fs = require('fs');
  5. const path = require('path');
  6. const process = require('process');
  7. const child_process = require('child_process');
  8. const http = require('http');
  9. const https = require('https');
  10. const url = require('url');
  11. const protobuf = require('protobufjs');
  12. const sidebar = require('../src/view-sidebar.js');
  13. const view = require('../src/view.js');
  14. const zip = require('../src/zip');
  15. const gzip = require('../src/gzip');
  16. const tar = require('../src/tar');
  17. const xmldom = require('xmldom');
  18. global.protobuf = protobuf;
  19. global.DOMParser = xmldom.DOMParser;
  20. global.TextDecoder = class {
  21. constructor(encoding) {
  22. global.TextDecoder._TextDecoder = global.TextDecoder._TextDecoder || require('util').TextDecoder;
  23. if (encoding !== 'ascii') {
  24. this._textDecoder = new global.TextDecoder._TextDecoder(encoding);
  25. }
  26. }
  27. decode(data) {
  28. if (this._textDecoder) {
  29. return this._textDecoder.decode(data);
  30. }
  31. if (data.length < 32) {
  32. return String.fromCharCode.apply(null, data);
  33. }
  34. var buffer = [];
  35. var start = 0;
  36. do {
  37. var end = start + 32;
  38. if (end > data.length) {
  39. end = data.length;
  40. }
  41. buffer.push(String.fromCharCode.apply(null, data.subarray(start, end)));
  42. start = end;
  43. }
  44. while (start < data.length);
  45. return buffer.join('');
  46. }
  47. };
  48. var type = process.argv.length > 2 ? process.argv[2] : null;
  49. var items = JSON.parse(fs.readFileSync(__dirname + '/models.json', 'utf-8'));
  50. var dataFolder = __dirname + '/data';
  51. class TestHost {
  52. constructor() {
  53. this._document = new HTMLDocument();
  54. }
  55. get document() {
  56. return this._document;
  57. }
  58. initialize(/* view */) {
  59. }
  60. environment(name) {
  61. if (name == 'zoom') {
  62. return 'none';
  63. }
  64. return null;
  65. }
  66. screen(/* name */) {
  67. }
  68. require(id) {
  69. try {
  70. var file = path.join(path.join(__dirname, '../src'), id + '.js');
  71. return Promise.resolve(require(file));
  72. }
  73. catch (error) {
  74. return Promise.reject(error);
  75. }
  76. }
  77. request(base, file, encoding) {
  78. var pathname = path.join(base || path.join(__dirname, '../src'), file);
  79. if (!fs.existsSync(pathname)) {
  80. return Promise.reject(new Error('File not found.'));
  81. }
  82. return Promise.resolve(fs.readFileSync(pathname, encoding));
  83. }
  84. event(/* category, action, label, value */) {
  85. }
  86. exception(err /*, fatal */) {
  87. this._raise('exception', { exception: err });
  88. }
  89. on(event, callback) {
  90. this._events = this._events || {};
  91. this._events[event] = this._events[event] || [];
  92. this._events[event].push(callback);
  93. }
  94. _raise(event, data) {
  95. if (this._events && this._events[event]) {
  96. for (var callback of this._events[event]) {
  97. callback(this, data);
  98. }
  99. }
  100. }
  101. }
  102. class TestContext {
  103. constructor(host, folder, identifier, buffer) {
  104. this._host = host;
  105. this._folder = folder;
  106. this._identifier = identifier;
  107. this._buffer = buffer;
  108. }
  109. request(file, encoding) {
  110. return this._host.request(this._folder, file, encoding);
  111. }
  112. get identifier() {
  113. return this._identifier;
  114. }
  115. get buffer() {
  116. return this._buffer;
  117. }
  118. }
  119. class HTMLDocument {
  120. constructor() {
  121. this._elements = {};
  122. this.documentElement = new HTMLHtmlElement();
  123. this.body = new HTMLBodyElement();
  124. }
  125. createElementNS(/* namespace, name */) {
  126. return new HTMLHtmlElement();
  127. }
  128. createTextNode(/* text */) {
  129. return new HTMLHtmlElement();
  130. }
  131. getElementById(id) {
  132. var element = this._elements[id];
  133. if (!element) {
  134. element = new HTMLHtmlElement();
  135. this._elements[id] = element;
  136. }
  137. return element;
  138. }
  139. addEventListener(/* event, callback */) {
  140. }
  141. removeEventListener(/* event, callback */) {
  142. }
  143. }
  144. class HTMLHtmlElement {
  145. constructor() {
  146. this._attributes = {};
  147. this.style = new CSSStyleDeclaration();
  148. }
  149. appendChild(/* node */) {
  150. }
  151. setAttribute(name, value) {
  152. this._attributes[name] = value;
  153. }
  154. getBBox() {
  155. return { x: 0, y: 0, width: 10, height: 10 };
  156. }
  157. getElementsByClassName(/* name */) {
  158. return null;
  159. }
  160. addEventListener(/* event, callback */) {
  161. }
  162. removeEventListener(/* event, callback */) {
  163. }
  164. }
  165. class HTMLBodyElement {
  166. constructor() {
  167. this.style = new CSSStyleDeclaration();
  168. }
  169. addEventListener(/* event, callback */) {
  170. }
  171. }
  172. class CSSStyleDeclaration {
  173. constructor() {
  174. this._properties = {};
  175. }
  176. setProperty(name, value) {
  177. this._properties[name] = value;
  178. }
  179. }
  180. function makeDir(dir) {
  181. if (!fs.existsSync(dir)){
  182. makeDir(path.dirname(dir));
  183. fs.mkdirSync(dir);
  184. }
  185. }
  186. function decompress(buffer, identifier) {
  187. var archive = null;
  188. var extension = identifier.split('.').pop().toLowerCase();
  189. if (extension == 'gz' || extension == 'tgz') {
  190. archive = new gzip.Archive(buffer);
  191. if (archive.entries.length == 1) {
  192. var entry = archive.entries[0];
  193. if (entry.name) {
  194. identifier = entry.name;
  195. }
  196. else {
  197. identifier = identifier.substring(0, identifier.lastIndexOf('.'));
  198. if (extension == 'tgz') {
  199. identifier += '.tar';
  200. }
  201. }
  202. buffer = entry.data;
  203. archive = null;
  204. }
  205. }
  206. switch (identifier.split('.').pop().toLowerCase()) {
  207. case 'tar':
  208. archive = new tar.Archive(buffer);
  209. break;
  210. case 'zip':
  211. archive = new zip.Archive(buffer);
  212. break;
  213. }
  214. return archive;
  215. }
  216. function request(location, cookie) {
  217. var options = { rejectUnauthorized: false };
  218. var httpRequest = null;
  219. switch (url.parse(location).protocol) {
  220. case 'http:':
  221. httpRequest = http.request(location, options);
  222. break;
  223. case 'https:':
  224. httpRequest = https.request(location, options);
  225. break;
  226. }
  227. if (cookie && cookie.length > 0) {
  228. httpRequest.setHeader('Cookie', cookie);
  229. }
  230. return new Promise((resolve, reject) => {
  231. httpRequest.on('response', (response) => {
  232. resolve(response);
  233. });
  234. httpRequest.on('error', (error) => {
  235. reject(error);
  236. });
  237. httpRequest.end();
  238. });
  239. }
  240. function downloadFile(location, cookie) {
  241. var data = [];
  242. var position = 0;
  243. return request(location, cookie).then((response) => {
  244. if (response.statusCode == 200 &&
  245. url.parse(location).hostname == 'drive.google.com' &&
  246. response.headers['set-cookie'].some((cookie) => cookie.startsWith('download_warning_'))) {
  247. cookie = response.headers['set-cookie'];
  248. var download = cookie.filter((cookie) => cookie.startsWith('download_warning_')).shift();
  249. var confirm = download.split(';').shift().split('=').pop();
  250. location = location + '&confirm=' + confirm;
  251. return downloadFile(location, cookie);
  252. }
  253. if (response.statusCode == 301 || response.statusCode == 302) {
  254. location = url.parse(response.headers.location).hostname ?
  255. response.headers.location :
  256. url.parse(location).protocol + '//' + url.parse(location).hostname + response.headers.location;
  257. return downloadFile(location, cookie);
  258. }
  259. if (response.statusCode != 200) {
  260. throw new Error(response.statusCode.toString() + ' ' + location);
  261. }
  262. return new Promise((resolve, reject) => {
  263. var length = response.headers['content-length'] ? Number(response.headers['content-length']) : -1;
  264. response.on('data', (chunk) => {
  265. position += chunk.length;
  266. if (length >= 0) {
  267. var label = location.length > 70 ? location.substring(0, 66) + '...' : location;
  268. process.stdout.write(' (' + (' ' + Math.floor(100 * (position / length))).slice(-3) + '%) ' + label + '\r');
  269. }
  270. else {
  271. process.stdout.write(' ' + position + ' bytes\r');
  272. }
  273. data.push(chunk);
  274. });
  275. response.on('end', () => {
  276. resolve(Buffer.concat(data));
  277. });
  278. response.on('error', (error) => {
  279. reject(error);
  280. });
  281. });
  282. });
  283. }
  284. function download(folder, targets, sources) {
  285. if (targets.every((file) => fs.existsSync(folder + '/' + file))) {
  286. return Promise.resolve();
  287. }
  288. if (!sources) {
  289. return Promise.reject(new Error('Download source not specified.'));
  290. }
  291. var source = '';
  292. var sourceFiles = [];
  293. var startIndex = sources.indexOf('[');
  294. var endIndex = sources.indexOf(']');
  295. if (startIndex != -1 && endIndex != -1 && endIndex > startIndex) {
  296. sourceFiles = sources.substring(startIndex + 1, endIndex).split(',').map((sourceFile) => sourceFile.trim());
  297. source = sources.substring(0, startIndex);
  298. sources = sources.substring(endIndex + 1);
  299. if (sources.startsWith(',')) {
  300. sources = sources.substring(1);
  301. }
  302. }
  303. else {
  304. var commaIndex = sources.indexOf(',');
  305. if (commaIndex != -1) {
  306. source = sources.substring(0, commaIndex);
  307. sources = sources.substring(commaIndex + 1);
  308. }
  309. else {
  310. source = sources;
  311. sources = '';
  312. }
  313. }
  314. var target;
  315. for (target of targets) {
  316. makeDir(path.dirname(folder + '/' + target));
  317. }
  318. return downloadFile(source).then((data) => {
  319. if (sourceFiles.length > 0) {
  320. if (process.stdout.clearLine) {
  321. process.stdout.clearLine();
  322. }
  323. process.stdout.write(' decompress...\r');
  324. var archive = decompress(data, source.split('/').pop());
  325. for (var file of sourceFiles) {
  326. if (process.stdout.clearLine) {
  327. process.stdout.clearLine();
  328. }
  329. process.stdout.write(' write ' + file + '\n');
  330. var entry = archive.entries.filter((entry) => entry.name == file)[0];
  331. if (!entry) {
  332. throw new Error("Entry not found '" + file + '. Archive contains entries: ' + JSON.stringify(archive.entries.map((entry) => entry.name)) + " .");
  333. }
  334. var target = targets.shift();
  335. fs.writeFileSync(folder + '/' + target, entry.data, null);
  336. }
  337. }
  338. else {
  339. target = targets.shift();
  340. if (process.stdout.clearLine) {
  341. process.stdout.clearLine();
  342. }
  343. process.stdout.write(' write ' + target + '\r');
  344. fs.writeFileSync(folder + '/' + target, data, null);
  345. }
  346. if (process.stdout.clearLine) {
  347. process.stdout.clearLine();
  348. }
  349. if (sources.length > 0) {
  350. return download(folder, targets, sources);
  351. }
  352. return;
  353. });
  354. }
  355. function script(folder, targets, command, args) {
  356. if (targets.every((file) => fs.existsSync(folder + '/' + file))) {
  357. return Promise.resolve();
  358. }
  359. return new Promise((resolve, reject) => {
  360. try {
  361. console.log(' ' + command + ' ' + args);
  362. child_process.execSync(command + ' ' + args, { stdio: [ 0, 1 , 2] });
  363. resolve();
  364. }
  365. catch (error) {
  366. reject(error);
  367. }
  368. });
  369. }
  370. function loadModel(target, item) {
  371. var host = new TestHost();
  372. var exceptions = [];
  373. host.on('exception', (_, data) => {
  374. exceptions.push(data.exception);
  375. });
  376. var folder = path.dirname(target);
  377. var identifier = path.basename(target);
  378. var size = fs.statSync(target).size;
  379. var buffer = new Uint8Array(size);
  380. var fd = fs.openSync(target, 'r');
  381. fs.readSync(fd, buffer, 0, size, 0);
  382. fs.closeSync(fd);
  383. var context = new TestContext(host, folder, identifier, buffer);
  384. var modelFactoryService = new view.ModelFactoryService(host);
  385. var opened = false;
  386. return modelFactoryService.open(context).then((model) => {
  387. if (opened) {
  388. throw new Error("Model opened more than once '" + target + "'.");
  389. }
  390. opened = true;
  391. if (!model.format || (item.format && model.format != item.format)) {
  392. throw new Error("Invalid model format '" + model.format + "'.");
  393. }
  394. if (item.producer && model.producer != item.producer) {
  395. throw new Error("Invalid producer '" + model.producer + "'.");
  396. }
  397. if (item.runtime && model.runtime != item.runtime) {
  398. throw new Error("Invalid runtime '" + model.runtime + "'.");
  399. }
  400. model.version;
  401. model.description;
  402. model.author;
  403. model.license;
  404. for (var graph of model.graphs) {
  405. var input;
  406. var argument;
  407. for (input of graph.inputs) {
  408. input.name.toString();
  409. input.name.length;
  410. for (argument of input.arguments) {
  411. argument.id.toString();
  412. argument.id.length;
  413. if (argument.type) {
  414. argument.type.toString();
  415. }
  416. }
  417. }
  418. var output;
  419. for (output of graph.outputs) {
  420. output.name.toString();
  421. output.name.length;
  422. for (argument of output.arguments) {
  423. argument.id.toString();
  424. if (argument.type) {
  425. argument.type.toString();
  426. }
  427. }
  428. }
  429. for (var node of graph.nodes) {
  430. node.name.toString();
  431. node.name.length;
  432. node.description;
  433. node.documentation.toString();
  434. node.category.toString();
  435. for (var attribute of node.attributes) {
  436. attribute.name.toString();
  437. attribute.name.length;
  438. var value = sidebar.NodeSidebar.formatAttributeValue(attribute.value, attribute.type)
  439. if (value && value.length > 1000) {
  440. value = value.substring(0, 1000) + '...';
  441. }
  442. value = value.split('<');
  443. }
  444. for (input of node.inputs) {
  445. input.name.toString();
  446. input.name.length;
  447. for (argument of input.arguments) {
  448. argument.id.toString();
  449. argument.id.length;
  450. argument.description;
  451. if (argument.type) {
  452. argument.type.toString();
  453. }
  454. if (argument.initializer) {
  455. argument.initializer.toString();
  456. argument.initializer.type.toString();
  457. }
  458. }
  459. }
  460. for (output of node.outputs) {
  461. output.name.toString();
  462. output.name.length;
  463. for (argument of output.arguments) {
  464. argument.id.toString();
  465. argument.id.length;
  466. if (argument.type) {
  467. argument.type.toString();
  468. }
  469. }
  470. }
  471. if (node.chain) {
  472. for (var chain of node.chain) {
  473. chain.name.toString();
  474. chain.name.length;
  475. }
  476. }
  477. }
  478. }
  479. if (exceptions.length > 0) {
  480. throw exceptions[0];
  481. }
  482. return model;
  483. });
  484. }
  485. function render(model) {
  486. try {
  487. var host = new TestHost();
  488. var currentView = new view.View(host);
  489. if (!currentView.showAttributes) {
  490. currentView.toggleAttributes();
  491. }
  492. if (!currentView.showInitializers) {
  493. currentView.toggleInitializers();
  494. }
  495. return currentView.renderGraph(model.graphs[0]);
  496. }
  497. catch (error) {
  498. return Promise.reject(error);
  499. }
  500. }
  501. function next() {
  502. if (items.length == 0) {
  503. return;
  504. }
  505. var item = items.shift();
  506. if (!item.type) {
  507. console.error("Property 'type' is required for item '" + JSON.stringify(item) + "'.");
  508. return;
  509. }
  510. if (type && item.type != type) {
  511. next();
  512. return;
  513. }
  514. if (process.stdout.clearLine) {
  515. process.stdout.clearLine();
  516. }
  517. var targets = item.target.split(',');
  518. var target = targets[0];
  519. var folder = dataFolder + '/' + item.type;
  520. process.stdout.write(item.type + '/' + target + '\n');
  521. var promise = null;
  522. if (item.script) {
  523. var root = path.dirname(__dirname);
  524. var command = item.script[0].replace('${root}', root);
  525. var args = item.script[1].replace('${root}', root);
  526. promise = script(folder, targets, command, args);
  527. }
  528. else {
  529. var sources = item.source;
  530. promise = download(folder, targets, sources);
  531. }
  532. return promise.then(() => {
  533. return loadModel(folder + '/' + target, item).then((model) => {
  534. var promise = null;
  535. if (item.render == 'skip') {
  536. promise = Promise.resolve();
  537. }
  538. else {
  539. promise = render(model);
  540. }
  541. return promise.then(() => {
  542. if (item.error) {
  543. console.error('Expected error.');
  544. }
  545. else {
  546. return next();
  547. }
  548. });
  549. });
  550. }).catch((error) => {
  551. if (!item.error || item.error != error.message) {
  552. console.error(error);
  553. }
  554. else {
  555. return next();
  556. }
  557. });
  558. }
  559. next();