less-test.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. /* jshint latedef: nofunc */
  2. var semver = require('semver');
  3. var logger = require('../lib/less/logger').default;
  4. var isVerbose = process.env.npm_config_loglevel !== 'concise';
  5. logger.addListener({
  6. info(msg) {
  7. if (isVerbose) {
  8. process.stdout.write(msg + '\n');
  9. }
  10. },
  11. warn(msg) {
  12. process.stdout.write(msg + '\n');
  13. },
  14. error(msg) {
  15. process.stdout.write(msg + '\n');
  16. }
  17. });
  18. module.exports = function() {
  19. var path = require('path'),
  20. fs = require('fs'),
  21. clone = require('copy-anything').copy;
  22. var less = require('../');
  23. var stylize = require('../lib/less-node/lessc-helper').stylize;
  24. var globals = Object.keys(global);
  25. var oneTestOnly = process.argv[2],
  26. isFinished = false;
  27. var testFolder = path.dirname(require.resolve('@less/test-data'));
  28. var lessFolder = path.join(testFolder, 'less');
  29. // Define String.prototype.endsWith if it doesn't exist (in older versions of node)
  30. // This is required by the testSourceMap function below
  31. if (typeof String.prototype.endsWith !== 'function') {
  32. String.prototype.endsWith = function (str) {
  33. return this.slice(-str.length) === str;
  34. }
  35. }
  36. var queueList = [],
  37. queueRunning = false;
  38. function queue(func) {
  39. if (queueRunning) {
  40. // console.log("adding to queue");
  41. queueList.push(func);
  42. } else {
  43. // console.log("first in queue - starting");
  44. queueRunning = true;
  45. func();
  46. }
  47. }
  48. function release() {
  49. if (queueList.length) {
  50. // console.log("running next in queue");
  51. var func = queueList.shift();
  52. setTimeout(func, 0);
  53. } else {
  54. // console.log("stopping queue");
  55. queueRunning = false;
  56. }
  57. }
  58. var totalTests = 0,
  59. failedTests = 0,
  60. passedTests = 0,
  61. finishTimer = setInterval(endTest, 500);
  62. less.functions.functionRegistry.addMultiple({
  63. add: function (a, b) {
  64. return new(less.tree.Dimension)(a.value + b.value);
  65. },
  66. increment: function (a) {
  67. return new(less.tree.Dimension)(a.value + 1);
  68. },
  69. _color: function (str) {
  70. if (str.value === 'evil red') { return new(less.tree.Color)('600'); }
  71. }
  72. });
  73. function testSourcemap(name, err, compiledLess, doReplacements, sourcemap, baseFolder) {
  74. if (err) {
  75. fail('ERROR: ' + (err && err.message));
  76. return;
  77. }
  78. // Check the sourceMappingURL at the bottom of the file
  79. var expectedSourceMapURL = name + '.css.map',
  80. sourceMappingPrefix = '/*# sourceMappingURL=',
  81. sourceMappingSuffix = ' */',
  82. expectedCSSAppendage = sourceMappingPrefix + expectedSourceMapURL + sourceMappingSuffix;
  83. if (!compiledLess.endsWith(expectedCSSAppendage)) {
  84. // To display a better error message, we need to figure out what the actual sourceMappingURL value was, if it was even present
  85. var indexOfSourceMappingPrefix = compiledLess.indexOf(sourceMappingPrefix);
  86. if (indexOfSourceMappingPrefix === -1) {
  87. fail('ERROR: sourceMappingURL was not found in ' + baseFolder + '/' + name + '.css.');
  88. return;
  89. }
  90. var startOfSourceMappingValue = indexOfSourceMappingPrefix + sourceMappingPrefix.length,
  91. indexOfNextSpace = compiledLess.indexOf(' ', startOfSourceMappingValue),
  92. actualSourceMapURL = compiledLess.substring(startOfSourceMappingValue, indexOfNextSpace === -1 ? compiledLess.length : indexOfNextSpace);
  93. fail('ERROR: sourceMappingURL should be "' + expectedSourceMapURL + '" but is "' + actualSourceMapURL + '".');
  94. }
  95. fs.readFile(path.join('test/', name) + '.json', 'utf8', function (e, expectedSourcemap) {
  96. process.stdout.write('- ' + path.join(baseFolder, name) + ': ');
  97. if (sourcemap === expectedSourcemap) {
  98. ok('OK');
  99. } else if (err) {
  100. fail('ERROR: ' + (err && err.message));
  101. if (isVerbose) {
  102. process.stdout.write('\n');
  103. process.stdout.write(err.stack + '\n');
  104. }
  105. } else {
  106. difference('FAIL', expectedSourcemap, sourcemap);
  107. }
  108. });
  109. }
  110. function testSourcemapWithoutUrlAnnotation(name, err, compiledLess, doReplacements, sourcemap, baseFolder) {
  111. if (err) {
  112. fail('ERROR: ' + (err && err.message));
  113. return;
  114. }
  115. // This matches with strings that end($) with source mapping url annotation.
  116. var sourceMapRegExp = /\/\*# sourceMappingURL=.+\.css\.map \*\/$/;
  117. if (sourceMapRegExp.test(compiledLess)) {
  118. fail('ERROR: sourceMappingURL found in ' + baseFolder + '/' + name + '.css.');
  119. return;
  120. }
  121. // Even if annotation is not necessary, the map file should be there.
  122. fs.readFile(path.join('test/', name) + '.json', 'utf8', function (e, expectedSourcemap) {
  123. process.stdout.write('- ' + path.join(baseFolder, name) + ': ');
  124. if (sourcemap === expectedSourcemap) {
  125. ok('OK');
  126. } else if (err) {
  127. fail('ERROR: ' + (err && err.message));
  128. if (isVerbose) {
  129. process.stdout.write('\n');
  130. process.stdout.write(err.stack + '\n');
  131. }
  132. } else {
  133. difference('FAIL', expectedSourcemap, sourcemap);
  134. }
  135. });
  136. }
  137. function testEmptySourcemap(name, err, compiledLess, doReplacements, sourcemap, baseFolder) {
  138. process.stdout.write('- ' + path.join(baseFolder, name) + ': ');
  139. if (err) {
  140. fail('ERROR: ' + (err && err.message));
  141. } else {
  142. var expectedSourcemap = undefined;
  143. if ( compiledLess !== '' ) {
  144. difference('\nCompiledLess must be empty', '', compiledLess);
  145. } else if (sourcemap !== expectedSourcemap) {
  146. fail('Sourcemap must be undefined');
  147. } else {
  148. ok('OK');
  149. }
  150. }
  151. }
  152. function testSourcemapWithVariableInSelector(name, err, compiledLess, doReplacements, sourcemap, baseFolder) {
  153. if (err) {
  154. fail('ERROR: ' + (err && err.message));
  155. return;
  156. }
  157. // Even if annotation is not necessary, the map file should be there.
  158. fs.readFile(path.join('test/', name) + '.json', 'utf8', function (e, expectedSourcemap) {
  159. process.stdout.write('- ' + path.join(baseFolder, name) + ': ');
  160. if (sourcemap === expectedSourcemap) {
  161. ok('OK');
  162. } else if (err) {
  163. fail('ERROR: ' + (err && err.message));
  164. if (isVerbose) {
  165. process.stdout.write('\n');
  166. process.stdout.write(err.stack + '\n');
  167. }
  168. } else {
  169. difference('FAIL', expectedSourcemap, sourcemap);
  170. }
  171. });
  172. }
  173. function testImports(name, err, compiledLess, doReplacements, sourcemap, baseFolder, imports) {
  174. if (err) {
  175. fail('ERROR: ' + (err && err.message));
  176. return;
  177. }
  178. function stringify(str) {
  179. return JSON.stringify(imports, null, ' ')
  180. }
  181. /** Imports are not sorted */
  182. const importsString = stringify(imports.sort())
  183. fs.readFile(path.join(lessFolder, name) + '.json', 'utf8', function (e, expectedImports) {
  184. if (e) {
  185. fail('ERROR: ' + (e && e.message));
  186. return;
  187. }
  188. process.stdout.write('- ' + path.join(baseFolder, name) + ': ');
  189. expectedImports = stringify(JSON.parse(expectedImports).sort());
  190. expectedImports = globalReplacements(expectedImports, baseFolder);
  191. if (expectedImports === importsString) {
  192. ok('OK');
  193. } else if (err) {
  194. fail('ERROR: ' + (err && err.message));
  195. if (isVerbose) {
  196. process.stdout.write('\n');
  197. process.stdout.write(err.stack + '\n');
  198. }
  199. } else {
  200. difference('FAIL', expectedImports, importsString);
  201. }
  202. });
  203. }
  204. function testErrors(name, err, compiledLess, doReplacements, sourcemap, baseFolder) {
  205. fs.readFile(path.join(baseFolder, name) + '.txt', 'utf8', function (e, expectedErr) {
  206. process.stdout.write('- ' + path.join(baseFolder, name) + ': ');
  207. expectedErr = doReplacements(expectedErr, baseFolder, err && err.filename);
  208. if (!err) {
  209. if (compiledLess) {
  210. fail('No Error', 'red');
  211. } else {
  212. fail('No Error, No Output');
  213. }
  214. } else {
  215. var errMessage = err.toString();
  216. if (errMessage === expectedErr) {
  217. ok('OK');
  218. } else {
  219. difference('FAIL', expectedErr, errMessage);
  220. }
  221. }
  222. });
  223. }
  224. // To fix ci fail about error format change in upstream v8 project
  225. // https://github.com/v8/v8/commit/c0fd89c3c089e888c4f4e8582e56db7066fa779b
  226. // Node 16.9.0+ include this change via https://github.com/nodejs/node/pull/39947
  227. function testTypeErrors(name, err, compiledLess, doReplacements, sourcemap, baseFolder) {
  228. const fileSuffix = semver.gte(process.version, 'v16.9.0') ? '-2.txt' : '.txt';
  229. fs.readFile(path.join(baseFolder, name) + fileSuffix, 'utf8', function (e, expectedErr) {
  230. process.stdout.write('- ' + path.join(baseFolder, name) + ': ');
  231. expectedErr = doReplacements(expectedErr, baseFolder, err && err.filename);
  232. if (!err) {
  233. if (compiledLess) {
  234. fail('No Error', 'red');
  235. } else {
  236. fail('No Error, No Output');
  237. }
  238. } else {
  239. var errMessage = err.toString();
  240. if (errMessage === expectedErr) {
  241. ok('OK');
  242. } else {
  243. difference('FAIL', expectedErr, errMessage);
  244. }
  245. }
  246. });
  247. }
  248. // https://github.com/less/less.js/issues/3112
  249. function testJSImport() {
  250. process.stdout.write('- Testing root function registry');
  251. less.functions.functionRegistry.add('ext', function() {
  252. return new less.tree.Anonymous('file');
  253. });
  254. var expected = '@charset "utf-8";\n';
  255. toCSS({}, path.join(lessFolder, 'root-registry', 'root.less'), function(error, output) {
  256. if (error) {
  257. return fail('ERROR: ' + error);
  258. }
  259. if (output.css === expected) {
  260. return ok('OK');
  261. }
  262. difference('FAIL', expected, output.css);
  263. });
  264. }
  265. function globalReplacements(input, directory, filename) {
  266. var path = require('path');
  267. var p = filename ? path.join(path.dirname(filename), '/') : directory,
  268. pathimport = path.join(directory + 'import/'),
  269. pathesc = p.replace(/[.:/\\]/g, function(a) { return '\\' + (a == '\\' ? '\/' : a); }),
  270. pathimportesc = pathimport.replace(/[.:/\\]/g, function(a) { return '\\' + (a == '\\' ? '\/' : a); });
  271. return input.replace(/\{path\}/g, p)
  272. .replace(/\{node\}/g, '')
  273. .replace(/\{\/node\}/g, '')
  274. .replace(/\{pathhref\}/g, '')
  275. .replace(/\{404status\}/g, '')
  276. .replace(/\{nodepath\}/g, path.join(process.cwd(), 'node_modules', '/'))
  277. .replace(/\{pathrel\}/g, path.join(path.relative(lessFolder, p), '/'))
  278. .replace(/\{pathesc\}/g, pathesc)
  279. .replace(/\{pathimport\}/g, pathimport)
  280. .replace(/\{pathimportesc\}/g, pathimportesc)
  281. .replace(/\r\n/g, '\n');
  282. }
  283. function checkGlobalLeaks() {
  284. return Object.keys(global).filter(function(v) {
  285. return globals.indexOf(v) < 0;
  286. });
  287. }
  288. function testSyncronous(options, filenameNoExtension) {
  289. if (oneTestOnly && ('Test Sync ' + filenameNoExtension) !== oneTestOnly) {
  290. return;
  291. }
  292. totalTests++;
  293. queue(function() {
  294. var isSync = true;
  295. toCSS(options, path.join(lessFolder, filenameNoExtension + '.less'), function (err, result) {
  296. process.stdout.write('- Test Sync ' + filenameNoExtension + ': ');
  297. if (isSync) {
  298. ok('OK');
  299. } else {
  300. fail('Not Sync');
  301. }
  302. release();
  303. });
  304. isSync = false;
  305. });
  306. }
  307. function runTestSet(options, foldername, verifyFunction, nameModifier, doReplacements, getFilename) {
  308. options = options ? clone(options) : {};
  309. runTestSetInternal(lessFolder, options, foldername, verifyFunction, nameModifier, doReplacements, getFilename);
  310. }
  311. function runTestSetNormalOnly(options, foldername, verifyFunction, nameModifier, doReplacements, getFilename) {
  312. runTestSetInternal(lessFolder, options, foldername, verifyFunction, nameModifier, doReplacements, getFilename);
  313. }
  314. function runTestSetInternal(baseFolder, opts, foldername, verifyFunction, nameModifier, doReplacements, getFilename) {
  315. foldername = foldername || '';
  316. var originalOptions = opts || {};
  317. if (!doReplacements) {
  318. doReplacements = globalReplacements;
  319. }
  320. function getBasename(file) {
  321. return foldername + path.basename(file, '.less');
  322. }
  323. fs.readdirSync(path.join(baseFolder, foldername)).forEach(function (file) {
  324. if (!/\.less$/.test(file)) { return; }
  325. var options = clone(originalOptions);
  326. options.stylize = stylize;
  327. var name = getBasename(file);
  328. if (oneTestOnly && name !== oneTestOnly) {
  329. return;
  330. }
  331. totalTests++;
  332. if (options.sourceMap && !options.sourceMap.sourceMapFileInline) {
  333. options.sourceMap = {
  334. sourceMapOutputFilename: name + '.css',
  335. sourceMapBasepath: baseFolder,
  336. sourceMapRootpath: 'testweb/',
  337. disableSourcemapAnnotation: options.sourceMap.disableSourcemapAnnotation
  338. };
  339. // This options is normally set by the bin/lessc script. Setting it causes the sourceMappingURL comment to be appended to the CSS
  340. // output. The value is designed to allow the sourceMapBasepath option to be tested, as it should be removed by less before
  341. // setting the sourceMappingURL value, leaving just the sourceMapOutputFilename and .map extension.
  342. options.sourceMap.sourceMapFilename = options.sourceMap.sourceMapBasepath + '/' + options.sourceMap.sourceMapOutputFilename + '.map';
  343. }
  344. options.getVars = function(file) {
  345. try {
  346. return JSON.parse(fs.readFileSync(getFilename(getBasename(file), 'vars', baseFolder), 'utf8'));
  347. }
  348. catch (e) {
  349. return {};
  350. }
  351. };
  352. var doubleCallCheck = false;
  353. queue(function() {
  354. toCSS(options, path.join(baseFolder, foldername + file), function (err, result) {
  355. if (doubleCallCheck) {
  356. totalTests++;
  357. fail('less is calling back twice');
  358. process.stdout.write(doubleCallCheck + '\n');
  359. process.stdout.write((new Error()).stack + '\n');
  360. return;
  361. }
  362. doubleCallCheck = (new Error()).stack;
  363. /**
  364. * @todo - refactor so the result object is sent to the verify function
  365. */
  366. if (verifyFunction) {
  367. var verificationResult = verifyFunction(
  368. name, err, result && result.css, doReplacements, result && result.map, baseFolder, result && result.imports
  369. );
  370. release();
  371. return verificationResult;
  372. }
  373. if (err) {
  374. fail('ERROR: ' + (err && err.message));
  375. if (isVerbose) {
  376. process.stdout.write('\n');
  377. if (err.stack) {
  378. process.stdout.write(err.stack + '\n');
  379. } else {
  380. // this sometimes happen - show the whole error object
  381. console.log(err);
  382. }
  383. }
  384. release();
  385. return;
  386. }
  387. var css_name = name;
  388. if (nameModifier) { css_name = nameModifier(name); }
  389. fs.readFile(path.join(testFolder, 'css', css_name) + '.css', 'utf8', function (e, css) {
  390. process.stdout.write('- ' + path.join(baseFolder, css_name) + ': ');
  391. css = css && doReplacements(css, path.join(baseFolder, foldername));
  392. if (result.css === css) { ok('OK'); }
  393. else {
  394. difference('FAIL', css, result.css);
  395. }
  396. release();
  397. });
  398. });
  399. });
  400. });
  401. }
  402. function diff(left, right) {
  403. require('diff').diffLines(left, right).forEach(function(item) {
  404. if (item.added || item.removed) {
  405. var text = item.value && item.value.replace('\n', String.fromCharCode(182) + '\n').replace('\ufeff', '[[BOM]]');
  406. process.stdout.write(stylize(text, item.added ? 'green' : 'red'));
  407. } else {
  408. process.stdout.write(item.value && item.value.replace('\ufeff', '[[BOM]]'));
  409. }
  410. });
  411. process.stdout.write('\n');
  412. }
  413. function fail(msg) {
  414. process.stdout.write(stylize(msg, 'red') + '\n');
  415. failedTests++;
  416. endTest();
  417. }
  418. function difference(msg, left, right) {
  419. process.stdout.write(stylize(msg, 'yellow') + '\n');
  420. failedTests++;
  421. diff(left || '', right || '');
  422. endTest();
  423. }
  424. function ok(msg) {
  425. process.stdout.write(stylize(msg, 'green') + '\n');
  426. passedTests++;
  427. endTest();
  428. }
  429. function finished() {
  430. isFinished = true;
  431. endTest();
  432. }
  433. function endTest() {
  434. if (isFinished && ((failedTests + passedTests) >= totalTests)) {
  435. clearInterval(finishTimer);
  436. var leaked = checkGlobalLeaks();
  437. process.stdout.write('\n');
  438. if (failedTests > 0) {
  439. process.stdout.write(failedTests + stylize(' Failed', 'red') + ', ' + passedTests + ' passed\n');
  440. } else {
  441. process.stdout.write(stylize('All Passed ', 'green') + passedTests + ' run\n');
  442. }
  443. if (leaked.length > 0) {
  444. process.stdout.write('\n');
  445. process.stdout.write(stylize('Global leak detected: ', 'red') + leaked.join(', ') + '\n');
  446. }
  447. if (leaked.length || failedTests) {
  448. process.on('exit', function() { process.reallyExit(1); });
  449. }
  450. }
  451. }
  452. function contains(fullArray, obj) {
  453. for (var i = 0; i < fullArray.length; i++) {
  454. if (fullArray[i] === obj) {
  455. return true;
  456. }
  457. }
  458. return false;
  459. }
  460. /**
  461. *
  462. * @param {Object} options
  463. * @param {string} filePath
  464. * @param {Function} callback
  465. */
  466. function toCSS(options, filePath, callback) {
  467. options = options || {};
  468. var str = fs.readFileSync(filePath, 'utf8'), addPath = path.dirname(filePath);
  469. if (typeof options.paths !== 'string') {
  470. options.paths = options.paths || [];
  471. if (!contains(options.paths, addPath)) {
  472. options.paths.push(addPath);
  473. }
  474. } else {
  475. options.paths = [options.paths]
  476. }
  477. options.paths = options.paths.map(searchPath => {
  478. return path.resolve(lessFolder, searchPath)
  479. })
  480. options.filename = path.resolve(process.cwd(), filePath);
  481. options.optimization = options.optimization || 0;
  482. if (options.globalVars) {
  483. options.globalVars = options.getVars(filePath);
  484. } else if (options.modifyVars) {
  485. options.modifyVars = options.getVars(filePath);
  486. }
  487. if (options.plugin) {
  488. var Plugin = require(path.resolve(process.cwd(), options.plugin));
  489. options.plugins = [Plugin];
  490. }
  491. less.render(str, options, callback);
  492. }
  493. function testNoOptions() {
  494. if (oneTestOnly && 'Integration' !== oneTestOnly) {
  495. return;
  496. }
  497. totalTests++;
  498. try {
  499. process.stdout.write('- Integration - creating parser without options: ');
  500. less.render('');
  501. } catch (e) {
  502. fail(stylize('FAIL\n', 'red'));
  503. return;
  504. }
  505. ok(stylize('OK\n', 'green'));
  506. }
  507. function testImportRedirect(nockScope) {
  508. return (name, err, css, doReplacements, sourcemap, baseFolder) => {
  509. process.stdout.write('- ' + path.join(baseFolder, name) + ': ');
  510. if (err) {
  511. fail('FAIL: ' + (err && err.message));
  512. return;
  513. }
  514. const expected = 'h1 {\n color: red;\n}\n';
  515. if (css !== expected) {
  516. difference('FAIL', expected, css);
  517. return;
  518. }
  519. nockScope.done();
  520. ok('OK');
  521. };
  522. }
  523. function testDisablePluginRule() {
  524. less.render(
  525. '@plugin "../../plugin/some_plugin";',
  526. {disablePluginRule: true},
  527. function(err) {
  528. // TODO: Need a better way of identifing exactly which error is thrown. Checking
  529. // text like this tends to be rather brittle.
  530. const EXPECTED = '@plugin statements are not allowed when disablePluginRule is set to true';
  531. if (!err || String(err).indexOf(EXPECTED) < 0) {
  532. fail('ERROR: Expected "' + EXPECTED + '" error');
  533. return;
  534. }
  535. ok(stylize('OK\n', 'green'));
  536. }
  537. );
  538. }
  539. return {
  540. runTestSet: runTestSet,
  541. runTestSetNormalOnly: runTestSetNormalOnly,
  542. testSyncronous: testSyncronous,
  543. testErrors: testErrors,
  544. testTypeErrors: testTypeErrors,
  545. testSourcemap: testSourcemap,
  546. testSourcemapWithoutUrlAnnotation: testSourcemapWithoutUrlAnnotation,
  547. testSourcemapWithVariableInSelector: testSourcemapWithVariableInSelector,
  548. testImports: testImports,
  549. testImportRedirect: testImportRedirect,
  550. testEmptySourcemap: testEmptySourcemap,
  551. testNoOptions: testNoOptions,
  552. testDisablePluginRule: testDisablePluginRule,
  553. testJSImport: testJSImport,
  554. finished: finished
  555. };
  556. };