test.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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 (let 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. createElementNS(/* namespace, name */) {
  127. return new HTMLHtmlElement();
  128. }
  129. createTextNode(/* text */) {
  130. return new HTMLHtmlElement();
  131. }
  132. getElementById(id) {
  133. let element = this._elements[id];
  134. if (!element) {
  135. element = new HTMLHtmlElement();
  136. this._elements[id] = element;
  137. }
  138. return element;
  139. }
  140. addEventListener(/* event, callback */) {
  141. }
  142. removeEventListener(/* event, callback */) {
  143. }
  144. }
  145. class HTMLHtmlElement {
  146. constructor() {
  147. this._attributes = {};
  148. this.style = new CSSStyleDeclaration();
  149. }
  150. appendChild(/* node */) {
  151. }
  152. setAttribute(name, value) {
  153. this._attributes[name] = value;
  154. }
  155. getBBox() {
  156. return { x: 0, y: 0, width: 10, height: 10 };
  157. }
  158. getElementsByClassName(/* name */) {
  159. return null;
  160. }
  161. addEventListener(/* event, callback */) {
  162. }
  163. removeEventListener(/* event, callback */) {
  164. }
  165. }
  166. class HTMLBodyElement {
  167. constructor() {
  168. this.style = new CSSStyleDeclaration();
  169. }
  170. addEventListener(/* event, callback */) {
  171. }
  172. }
  173. class CSSStyleDeclaration {
  174. constructor() {
  175. this._properties = {};
  176. }
  177. setProperty(name, value) {
  178. this._properties[name] = value;
  179. }
  180. }
  181. function makeDir(dir) {
  182. if (!fs.existsSync(dir)){
  183. makeDir(path.dirname(dir));
  184. fs.mkdirSync(dir);
  185. }
  186. }
  187. function decompress(buffer, identifier) {
  188. let archive = null;
  189. const extension = identifier.split('.').pop().toLowerCase();
  190. if (extension == 'gz' || extension == 'tgz') {
  191. archive = new gzip.Archive(buffer);
  192. if (archive.entries.length == 1) {
  193. const entry = archive.entries[0];
  194. if (entry.name) {
  195. identifier = entry.name;
  196. }
  197. else {
  198. identifier = identifier.substring(0, identifier.lastIndexOf('.'));
  199. if (extension == 'tgz') {
  200. identifier += '.tar';
  201. }
  202. }
  203. buffer = entry.data;
  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. const options = { rejectUnauthorized: false };
  218. let 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. let data = [];
  242. let 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. const download = cookie.filter((cookie) => cookie.startsWith('download_warning_')).shift();
  249. const 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. const 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. const 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. let source = '';
  292. let sourceFiles = [];
  293. const startIndex = sources.indexOf('[');
  294. const 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. const 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. for (let target of targets) {
  315. makeDir(path.dirname(folder + '/' + target));
  316. }
  317. return downloadFile(source).then((data) => {
  318. if (sourceFiles.length > 0) {
  319. if (process.stdout.clearLine) {
  320. process.stdout.clearLine();
  321. }
  322. process.stdout.write(' decompress...\r');
  323. const archive = decompress(data, source.split('?').shift().split('/').pop());
  324. for (let file of sourceFiles) {
  325. if (process.stdout.clearLine) {
  326. process.stdout.clearLine();
  327. }
  328. process.stdout.write(' write ' + file + '\n');
  329. const entry = archive.entries.filter((entry) => entry.name == file)[0];
  330. if (!entry) {
  331. throw new Error("Entry not found '" + file + '. Archive contains entries: ' + JSON.stringify(archive.entries.map((entry) => entry.name)) + " .");
  332. }
  333. const target = targets.shift();
  334. fs.writeFileSync(folder + '/' + target, entry.data, null);
  335. }
  336. }
  337. else {
  338. const target = targets.shift();
  339. if (process.stdout.clearLine) {
  340. process.stdout.clearLine();
  341. }
  342. process.stdout.write(' write ' + target + '\r');
  343. fs.writeFileSync(folder + '/' + target, data, null);
  344. }
  345. if (process.stdout.clearLine) {
  346. process.stdout.clearLine();
  347. }
  348. if (sources.length > 0) {
  349. return download(folder, targets, sources);
  350. }
  351. return;
  352. });
  353. }
  354. function script(folder, targets, command, args) {
  355. if (targets.every((file) => fs.existsSync(folder + '/' + file))) {
  356. return Promise.resolve();
  357. }
  358. return new Promise((resolve, reject) => {
  359. try {
  360. console.log(' ' + command + ' ' + args);
  361. if (process.platform === 'win32' && process.env.SHELL) {
  362. process.env.COMSPEC = process.env.SHELL;
  363. }
  364. child_process.execSync(command + ' ' + args, { stdio: [ 0, 1 , 2] });
  365. resolve();
  366. }
  367. catch (error) {
  368. reject(error);
  369. }
  370. });
  371. }
  372. function loadModel(target, item) {
  373. const host = new TestHost();
  374. let exceptions = [];
  375. host.on('exception', (_, data) => {
  376. exceptions.push(data.exception);
  377. });
  378. const folder = path.dirname(target);
  379. const identifier = path.basename(target);
  380. const size = fs.statSync(target).size;
  381. const buffer = new Uint8Array(size);
  382. const fd = fs.openSync(target, 'r');
  383. fs.readSync(fd, buffer, 0, size, 0);
  384. fs.closeSync(fd);
  385. const context = new TestContext(host, folder, identifier, buffer);
  386. const modelFactoryService = new view.ModelFactoryService(host);
  387. let opened = false;
  388. return modelFactoryService.open(context).then((model) => {
  389. if (opened) {
  390. throw new Error("Model opened more than once '" + target + "'.");
  391. }
  392. opened = true;
  393. if (!model.format || (item.format && model.format != item.format)) {
  394. throw new Error("Invalid model format '" + model.format + "'.");
  395. }
  396. if (item.producer && model.producer != item.producer) {
  397. throw new Error("Invalid producer '" + model.producer + "'.");
  398. }
  399. if (item.runtime && model.runtime != item.runtime) {
  400. throw new Error("Invalid runtime '" + model.runtime + "'.");
  401. }
  402. model.version;
  403. model.description;
  404. model.author;
  405. model.license;
  406. for (let graph of model.graphs) {
  407. for (let input of graph.inputs) {
  408. input.name.toString();
  409. input.name.length;
  410. for (let argument of input.arguments) {
  411. argument.id.toString();
  412. argument.id.length;
  413. if (argument.type) {
  414. argument.type.toString();
  415. }
  416. }
  417. }
  418. for (let output of graph.outputs) {
  419. output.name.toString();
  420. output.name.length;
  421. for (let argument of output.arguments) {
  422. argument.id.toString();
  423. argument.id.length;
  424. if (argument.type) {
  425. argument.type.toString();
  426. }
  427. }
  428. }
  429. for (let 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 (let attribute of node.attributes) {
  436. attribute.name.toString();
  437. attribute.name.length;
  438. let 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 (let input of node.inputs) {
  445. input.name.toString();
  446. input.name.length;
  447. for (let 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 (let output of node.outputs) {
  461. output.name.toString();
  462. output.name.length;
  463. for (let 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 (let 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. const host = new TestHost();
  488. const 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. const 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. const targets = item.target.split(',');
  515. const target = targets[0];
  516. const folder = dataFolder + '/' + item.type;
  517. const name = item.type + '/' + target;
  518. if (filter && !name.startsWith(filter)) {
  519. next();
  520. return;
  521. }
  522. if (process.stdout.clearLine) {
  523. process.stdout.clearLine();
  524. }
  525. process.stdout.write(item.type + '/' + target + '\n');
  526. let promise = null;
  527. if (item.script) {
  528. const root = path.dirname(__dirname);
  529. const command = path.resolve(root, item.script[0]);
  530. const args = item.script[1];
  531. promise = script(folder, targets, command, args);
  532. }
  533. else {
  534. const sources = item.source;
  535. promise = download(folder, targets, sources);
  536. }
  537. return promise.then(() => {
  538. return loadModel(folder + '/' + target, item).then((model) => {
  539. let promise = null;
  540. if (item.render == 'skip') {
  541. promise = Promise.resolve();
  542. }
  543. else {
  544. promise = render(model);
  545. }
  546. return promise.then(() => {
  547. if (item.error) {
  548. console.error('Expected error.');
  549. }
  550. else {
  551. return next();
  552. }
  553. });
  554. });
  555. }).catch((error) => {
  556. if (!item.error || item.error != error.message) {
  557. console.error(error);
  558. }
  559. else {
  560. return next();
  561. }
  562. });
  563. }
  564. next();