less-test.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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. erro(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. var name = getBasename(file);
  327. if (oneTestOnly && name !== oneTestOnly) {
  328. return;
  329. }
  330. totalTests++;
  331. if (options.sourceMap && !options.sourceMap.sourceMapFileInline) {
  332. options.sourceMap = {
  333. sourceMapOutputFilename: name + '.css',
  334. sourceMapBasepath: baseFolder,
  335. sourceMapRootpath: 'testweb/',
  336. disableSourcemapAnnotation: options.sourceMap.disableSourcemapAnnotation
  337. };
  338. // This options is normally set by the bin/lessc script. Setting it causes the sourceMappingURL comment to be appended to the CSS
  339. // output. The value is designed to allow the sourceMapBasepath option to be tested, as it should be removed by less before
  340. // setting the sourceMappingURL value, leaving just the sourceMapOutputFilename and .map extension.
  341. options.sourceMap.sourceMapFilename = options.sourceMap.sourceMapBasepath + '/' + options.sourceMap.sourceMapOutputFilename + '.map';
  342. }
  343. options.getVars = function(file) {
  344. try {
  345. return JSON.parse(fs.readFileSync(getFilename(getBasename(file), 'vars', baseFolder), 'utf8'));
  346. }
  347. catch (e) {
  348. return {};
  349. }
  350. };
  351. var doubleCallCheck = false;
  352. queue(function() {
  353. toCSS(options, path.join(baseFolder, foldername + file), function (err, result) {
  354. if (doubleCallCheck) {
  355. totalTests++;
  356. fail('less is calling back twice');
  357. process.stdout.write(doubleCallCheck + '\n');
  358. process.stdout.write((new Error()).stack + '\n');
  359. return;
  360. }
  361. doubleCallCheck = (new Error()).stack;
  362. /**
  363. * @todo - refactor so the result object is sent to the verify function
  364. */
  365. if (verifyFunction) {
  366. var verificationResult = verifyFunction(
  367. name, err, result && result.css, doReplacements, result && result.map, baseFolder, result && result.imports
  368. );
  369. release();
  370. return verificationResult;
  371. }
  372. if (err) {
  373. fail('ERROR: ' + (err && err.message));
  374. if (isVerbose) {
  375. process.stdout.write('\n');
  376. if (err.stack) {
  377. process.stdout.write(err.stack + '\n');
  378. } else {
  379. // this sometimes happen - show the whole error object
  380. console.log(err);
  381. }
  382. }
  383. release();
  384. return;
  385. }
  386. var css_name = name;
  387. if (nameModifier) { css_name = nameModifier(name); }
  388. fs.readFile(path.join(testFolder, 'css', css_name) + '.css', 'utf8', function (e, css) {
  389. process.stdout.write('- ' + path.join(baseFolder, css_name) + ': ');
  390. css = css && doReplacements(css, path.join(baseFolder, foldername));
  391. if (result.css === css) { ok('OK'); }
  392. else {
  393. difference('FAIL', css, result.css);
  394. }
  395. release();
  396. });
  397. });
  398. });
  399. });
  400. }
  401. function diff(left, right) {
  402. require('diff').diffLines(left, right).forEach(function(item) {
  403. if (item.added || item.removed) {
  404. var text = item.value && item.value.replace('\n', String.fromCharCode(182) + '\n').replace('\ufeff', '[[BOM]]');
  405. process.stdout.write(stylize(text, item.added ? 'green' : 'red'));
  406. } else {
  407. process.stdout.write(item.value && item.value.replace('\ufeff', '[[BOM]]'));
  408. }
  409. });
  410. process.stdout.write('\n');
  411. }
  412. function fail(msg) {
  413. process.stdout.write(stylize(msg, 'red') + '\n');
  414. failedTests++;
  415. endTest();
  416. }
  417. function difference(msg, left, right) {
  418. process.stdout.write(stylize(msg, 'yellow') + '\n');
  419. failedTests++;
  420. diff(left || '', right || '');
  421. endTest();
  422. }
  423. function ok(msg) {
  424. process.stdout.write(stylize(msg, 'green') + '\n');
  425. passedTests++;
  426. endTest();
  427. }
  428. function finished() {
  429. isFinished = true;
  430. endTest();
  431. }
  432. function endTest() {
  433. if (isFinished && ((failedTests + passedTests) >= totalTests)) {
  434. clearInterval(finishTimer);
  435. var leaked = checkGlobalLeaks();
  436. process.stdout.write('\n');
  437. if (failedTests > 0) {
  438. process.stdout.write(failedTests + stylize(' Failed', 'red') + ', ' + passedTests + ' passed\n');
  439. } else {
  440. process.stdout.write(stylize('All Passed ', 'green') + passedTests + ' run\n');
  441. }
  442. if (leaked.length > 0) {
  443. process.stdout.write('\n');
  444. process.stdout.write(stylize('Global leak detected: ', 'red') + leaked.join(', ') + '\n');
  445. }
  446. if (leaked.length || failedTests) {
  447. process.on('exit', function() { process.reallyExit(1); });
  448. }
  449. }
  450. }
  451. function contains(fullArray, obj) {
  452. for (var i = 0; i < fullArray.length; i++) {
  453. if (fullArray[i] === obj) {
  454. return true;
  455. }
  456. }
  457. return false;
  458. }
  459. /**
  460. *
  461. * @param {Object} options
  462. * @param {string} filePath
  463. * @param {Function} callback
  464. */
  465. function toCSS(options, filePath, callback) {
  466. options = options || {};
  467. var str = fs.readFileSync(filePath, 'utf8'), addPath = path.dirname(filePath);
  468. if (typeof options.paths !== 'string') {
  469. options.paths = options.paths || [];
  470. if (!contains(options.paths, addPath)) {
  471. options.paths.push(addPath);
  472. }
  473. } else {
  474. options.paths = [options.paths]
  475. }
  476. options.paths = options.paths.map(searchPath => {
  477. return path.resolve(lessFolder, searchPath)
  478. })
  479. options.filename = path.resolve(process.cwd(), filePath);
  480. options.optimization = options.optimization || 0;
  481. if (options.globalVars) {
  482. options.globalVars = options.getVars(filePath);
  483. } else if (options.modifyVars) {
  484. options.modifyVars = options.getVars(filePath);
  485. }
  486. if (options.plugin) {
  487. var Plugin = require(path.resolve(process.cwd(), options.plugin));
  488. options.plugins = [Plugin];
  489. }
  490. less.render(str, options, callback);
  491. }
  492. function testNoOptions() {
  493. if (oneTestOnly && 'Integration' !== oneTestOnly) {
  494. return;
  495. }
  496. totalTests++;
  497. try {
  498. process.stdout.write('- Integration - creating parser without options: ');
  499. less.render('');
  500. } catch (e) {
  501. fail(stylize('FAIL\n', 'red'));
  502. return;
  503. }
  504. ok(stylize('OK\n', 'green'));
  505. }
  506. function testImportRedirect(nockScope) {
  507. return (name, err, css, doReplacements, sourcemap, baseFolder) => {
  508. process.stdout.write('- ' + path.join(baseFolder, name) + ': ');
  509. if (err) {
  510. fail('FAIL: ' + (err && err.message));
  511. return;
  512. }
  513. const expected = 'h1 {\n color: red;\n}\n';
  514. if (css !== expected) {
  515. difference('FAIL', expected, css);
  516. return;
  517. }
  518. nockScope.done();
  519. ok('OK');
  520. };
  521. }
  522. function testDisablePluginRule() {
  523. less.render(
  524. '@plugin "../../plugin/some_plugin";',
  525. {disablePluginRule: true},
  526. function(err) {
  527. // TODO: Need a better way of identifing exactly which error is thrown. Checking
  528. // text like this tends to be rather brittle.
  529. const EXPECTED = '@plugin statements are not allowed when disablePluginRule is set to true';
  530. if (!err || String(err).indexOf(EXPECTED) < 0) {
  531. fail('ERROR: Expected "' + EXPECTED + '" error');
  532. return;
  533. }
  534. ok(stylize('OK\n', 'green'));
  535. }
  536. );
  537. }
  538. return {
  539. runTestSet: runTestSet,
  540. runTestSetNormalOnly: runTestSetNormalOnly,
  541. testSyncronous: testSyncronous,
  542. testErrors: testErrors,
  543. testTypeErrors: testTypeErrors,
  544. testSourcemap: testSourcemap,
  545. testSourcemapWithoutUrlAnnotation: testSourcemapWithoutUrlAnnotation,
  546. testSourcemapWithVariableInSelector: testSourcemapWithVariableInSelector,
  547. testImports: testImports,
  548. testImportRedirect: testImportRedirect,
  549. testEmptySourcemap: testEmptySourcemap,
  550. testNoOptions: testNoOptions,
  551. testDisablePluginRule: testDisablePluginRule,
  552. testJSImport: testJSImport,
  553. finished: finished
  554. };
  555. };