test.js 19 KB

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