less-test.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  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 testImports(name, err, compiledLess, doReplacements, sourcemap, baseFolder, imports) {
  153. if (err) {
  154. fail('ERROR: ' + (err && err.message));
  155. return;
  156. }
  157. function stringify(str) {
  158. return JSON.stringify(imports, null, ' ')
  159. }
  160. /** Imports are not sorted */
  161. const importsString = stringify(imports.sort())
  162. fs.readFile(path.join(lessFolder, name) + '.json', 'utf8', function (e, expectedImports) {
  163. if (e) {
  164. fail('ERROR: ' + (e && e.message));
  165. return;
  166. }
  167. process.stdout.write('- ' + path.join(baseFolder, name) + ': ');
  168. expectedImports = stringify(JSON.parse(expectedImports).sort());
  169. expectedImports = globalReplacements(expectedImports, baseFolder);
  170. if (expectedImports === importsString) {
  171. ok('OK');
  172. } else if (err) {
  173. fail('ERROR: ' + (err && err.message));
  174. if (isVerbose) {
  175. process.stdout.write('\n');
  176. process.stdout.write(err.stack + '\n');
  177. }
  178. } else {
  179. difference('FAIL', expectedImports, importsString);
  180. }
  181. });
  182. }
  183. function testErrors(name, err, compiledLess, doReplacements, sourcemap, baseFolder) {
  184. fs.readFile(path.join(baseFolder, name) + '.txt', 'utf8', function (e, expectedErr) {
  185. process.stdout.write('- ' + path.join(baseFolder, name) + ': ');
  186. expectedErr = doReplacements(expectedErr, baseFolder, err && err.filename);
  187. if (!err) {
  188. if (compiledLess) {
  189. fail('No Error', 'red');
  190. } else {
  191. fail('No Error, No Output');
  192. }
  193. } else {
  194. var errMessage = err.toString();
  195. if (errMessage === expectedErr) {
  196. ok('OK');
  197. } else {
  198. difference('FAIL', expectedErr, errMessage);
  199. }
  200. }
  201. });
  202. }
  203. // To fix ci fail about error format change in upstream v8 project
  204. // https://github.com/v8/v8/commit/c0fd89c3c089e888c4f4e8582e56db7066fa779b
  205. // Node 16.9.0+ include this change via https://github.com/nodejs/node/pull/39947
  206. function testTypeErrors(name, err, compiledLess, doReplacements, sourcemap, baseFolder) {
  207. const fileSuffix = semver.gte(process.version, 'v16.9.0') ? '-2.txt' : '.txt';
  208. fs.readFile(path.join(baseFolder, name) + fileSuffix, 'utf8', function (e, expectedErr) {
  209. process.stdout.write('- ' + path.join(baseFolder, name) + ': ');
  210. expectedErr = doReplacements(expectedErr, baseFolder, err && err.filename);
  211. if (!err) {
  212. if (compiledLess) {
  213. fail('No Error', 'red');
  214. } else {
  215. fail('No Error, No Output');
  216. }
  217. } else {
  218. var errMessage = err.toString();
  219. if (errMessage === expectedErr) {
  220. ok('OK');
  221. } else {
  222. difference('FAIL', expectedErr, errMessage);
  223. }
  224. }
  225. });
  226. }
  227. // https://github.com/less/less.js/issues/3112
  228. function testJSImport() {
  229. process.stdout.write('- Testing root function registry');
  230. less.functions.functionRegistry.add('ext', function() {
  231. return new less.tree.Anonymous('file');
  232. });
  233. var expected = '@charset "utf-8";\n';
  234. toCSS({}, path.join(lessFolder, 'root-registry', 'root.less'), function(error, output) {
  235. if (error) {
  236. return fail('ERROR: ' + error);
  237. }
  238. if (output.css === expected) {
  239. return ok('OK');
  240. }
  241. difference('FAIL', expected, output.css);
  242. });
  243. }
  244. function globalReplacements(input, directory, filename) {
  245. var path = require('path');
  246. var p = filename ? path.join(path.dirname(filename), '/') : directory,
  247. pathimport = path.join(directory + 'import/'),
  248. pathesc = p.replace(/[.:/\\]/g, function(a) { return '\\' + (a == '\\' ? '\/' : a); }),
  249. pathimportesc = pathimport.replace(/[.:/\\]/g, function(a) { return '\\' + (a == '\\' ? '\/' : a); });
  250. return input.replace(/\{path\}/g, p)
  251. .replace(/\{node\}/g, '')
  252. .replace(/\{\/node\}/g, '')
  253. .replace(/\{pathhref\}/g, '')
  254. .replace(/\{404status\}/g, '')
  255. .replace(/\{nodepath\}/g, path.join(process.cwd(), 'node_modules', '/'))
  256. .replace(/\{pathrel\}/g, path.join(path.relative(lessFolder, p), '/'))
  257. .replace(/\{pathesc\}/g, pathesc)
  258. .replace(/\{pathimport\}/g, pathimport)
  259. .replace(/\{pathimportesc\}/g, pathimportesc)
  260. .replace(/\r\n/g, '\n');
  261. }
  262. function checkGlobalLeaks() {
  263. return Object.keys(global).filter(function(v) {
  264. return globals.indexOf(v) < 0;
  265. });
  266. }
  267. function testSyncronous(options, filenameNoExtension) {
  268. if (oneTestOnly && ('Test Sync ' + filenameNoExtension) !== oneTestOnly) {
  269. return;
  270. }
  271. totalTests++;
  272. queue(function() {
  273. var isSync = true;
  274. toCSS(options, path.join(lessFolder, filenameNoExtension + '.less'), function (err, result) {
  275. process.stdout.write('- Test Sync ' + filenameNoExtension + ': ');
  276. if (isSync) {
  277. ok('OK');
  278. } else {
  279. fail('Not Sync');
  280. }
  281. release();
  282. });
  283. isSync = false;
  284. });
  285. }
  286. function runTestSet(options, foldername, verifyFunction, nameModifier, doReplacements, getFilename) {
  287. options = options ? clone(options) : {};
  288. runTestSetInternal(lessFolder, options, foldername, verifyFunction, nameModifier, doReplacements, getFilename);
  289. }
  290. function runTestSetNormalOnly(options, foldername, verifyFunction, nameModifier, doReplacements, getFilename) {
  291. runTestSetInternal(lessFolder, options, foldername, verifyFunction, nameModifier, doReplacements, getFilename);
  292. }
  293. function runTestSetInternal(baseFolder, opts, foldername, verifyFunction, nameModifier, doReplacements, getFilename) {
  294. foldername = foldername || '';
  295. var originalOptions = opts || {};
  296. if (!doReplacements) {
  297. doReplacements = globalReplacements;
  298. }
  299. function getBasename(file) {
  300. return foldername + path.basename(file, '.less');
  301. }
  302. fs.readdirSync(path.join(baseFolder, foldername)).forEach(function (file) {
  303. if (!/\.less$/.test(file)) { return; }
  304. var options = clone(originalOptions);
  305. var name = getBasename(file);
  306. if (oneTestOnly && name !== oneTestOnly) {
  307. return;
  308. }
  309. totalTests++;
  310. if (options.sourceMap && !options.sourceMap.sourceMapFileInline) {
  311. options.sourceMap = {
  312. sourceMapOutputFilename: name + '.css',
  313. sourceMapBasepath: baseFolder,
  314. sourceMapRootpath: 'testweb/',
  315. disableSourcemapAnnotation: options.sourceMap.disableSourcemapAnnotation
  316. };
  317. // This options is normally set by the bin/lessc script. Setting it causes the sourceMappingURL comment to be appended to the CSS
  318. // output. The value is designed to allow the sourceMapBasepath option to be tested, as it should be removed by less before
  319. // setting the sourceMappingURL value, leaving just the sourceMapOutputFilename and .map extension.
  320. options.sourceMap.sourceMapFilename = options.sourceMap.sourceMapBasepath + '/' + options.sourceMap.sourceMapOutputFilename + '.map';
  321. }
  322. options.getVars = function(file) {
  323. try {
  324. return JSON.parse(fs.readFileSync(getFilename(getBasename(file), 'vars', baseFolder), 'utf8'));
  325. }
  326. catch (e) {
  327. return {};
  328. }
  329. };
  330. var doubleCallCheck = false;
  331. queue(function() {
  332. toCSS(options, path.join(baseFolder, foldername + file), function (err, result) {
  333. if (doubleCallCheck) {
  334. totalTests++;
  335. fail('less is calling back twice');
  336. process.stdout.write(doubleCallCheck + '\n');
  337. process.stdout.write((new Error()).stack + '\n');
  338. return;
  339. }
  340. doubleCallCheck = (new Error()).stack;
  341. /**
  342. * @todo - refactor so the result object is sent to the verify function
  343. */
  344. if (verifyFunction) {
  345. var verificationResult = verifyFunction(
  346. name, err, result && result.css, doReplacements, result && result.map, baseFolder, result && result.imports
  347. );
  348. release();
  349. return verificationResult;
  350. }
  351. if (err) {
  352. fail('ERROR: ' + (err && err.message));
  353. if (isVerbose) {
  354. process.stdout.write('\n');
  355. if (err.stack) {
  356. process.stdout.write(err.stack + '\n');
  357. } else {
  358. // this sometimes happen - show the whole error object
  359. console.log(err);
  360. }
  361. }
  362. release();
  363. return;
  364. }
  365. var css_name = name;
  366. if (nameModifier) { css_name = nameModifier(name); }
  367. fs.readFile(path.join(testFolder, 'css', css_name) + '.css', 'utf8', function (e, css) {
  368. process.stdout.write('- ' + path.join(baseFolder, css_name) + ': ');
  369. css = css && doReplacements(css, path.join(baseFolder, foldername));
  370. if (result.css === css) { ok('OK'); }
  371. else {
  372. difference('FAIL', css, result.css);
  373. }
  374. release();
  375. });
  376. });
  377. });
  378. });
  379. }
  380. function diff(left, right) {
  381. require('diff').diffLines(left, right).forEach(function(item) {
  382. if (item.added || item.removed) {
  383. var text = item.value && item.value.replace('\n', String.fromCharCode(182) + '\n').replace('\ufeff', '[[BOM]]');
  384. process.stdout.write(stylize(text, item.added ? 'green' : 'red'));
  385. } else {
  386. process.stdout.write(item.value && item.value.replace('\ufeff', '[[BOM]]'));
  387. }
  388. });
  389. process.stdout.write('\n');
  390. }
  391. function fail(msg) {
  392. process.stdout.write(stylize(msg, 'red') + '\n');
  393. failedTests++;
  394. endTest();
  395. }
  396. function difference(msg, left, right) {
  397. process.stdout.write(stylize(msg, 'yellow') + '\n');
  398. failedTests++;
  399. diff(left || '', right || '');
  400. endTest();
  401. }
  402. function ok(msg) {
  403. process.stdout.write(stylize(msg, 'green') + '\n');
  404. passedTests++;
  405. endTest();
  406. }
  407. function finished() {
  408. isFinished = true;
  409. endTest();
  410. }
  411. function endTest() {
  412. if (isFinished && ((failedTests + passedTests) >= totalTests)) {
  413. clearInterval(finishTimer);
  414. var leaked = checkGlobalLeaks();
  415. process.stdout.write('\n');
  416. if (failedTests > 0) {
  417. process.stdout.write(failedTests + stylize(' Failed', 'red') + ', ' + passedTests + ' passed\n');
  418. } else {
  419. process.stdout.write(stylize('All Passed ', 'green') + passedTests + ' run\n');
  420. }
  421. if (leaked.length > 0) {
  422. process.stdout.write('\n');
  423. process.stdout.write(stylize('Global leak detected: ', 'red') + leaked.join(', ') + '\n');
  424. }
  425. if (leaked.length || failedTests) {
  426. process.on('exit', function() { process.reallyExit(1); });
  427. }
  428. }
  429. }
  430. function contains(fullArray, obj) {
  431. for (var i = 0; i < fullArray.length; i++) {
  432. if (fullArray[i] === obj) {
  433. return true;
  434. }
  435. }
  436. return false;
  437. }
  438. /**
  439. *
  440. * @param {Object} options
  441. * @param {string} filePath
  442. * @param {Function} callback
  443. */
  444. function toCSS(options, filePath, callback) {
  445. options = options || {};
  446. var str = fs.readFileSync(filePath, 'utf8'), addPath = path.dirname(filePath);
  447. if (typeof options.paths !== 'string') {
  448. options.paths = options.paths || [];
  449. if (!contains(options.paths, addPath)) {
  450. options.paths.push(addPath);
  451. }
  452. } else {
  453. options.paths = [options.paths]
  454. }
  455. options.paths = options.paths.map(searchPath => {
  456. return path.resolve(lessFolder, searchPath)
  457. })
  458. options.filename = path.resolve(process.cwd(), filePath);
  459. options.optimization = options.optimization || 0;
  460. if (options.globalVars) {
  461. options.globalVars = options.getVars(filePath);
  462. } else if (options.modifyVars) {
  463. options.modifyVars = options.getVars(filePath);
  464. }
  465. if (options.plugin) {
  466. var Plugin = require(path.resolve(process.cwd(), options.plugin));
  467. options.plugins = [Plugin];
  468. }
  469. less.render(str, options, callback);
  470. }
  471. function testNoOptions() {
  472. if (oneTestOnly && 'Integration' !== oneTestOnly) {
  473. return;
  474. }
  475. totalTests++;
  476. try {
  477. process.stdout.write('- Integration - creating parser without options: ');
  478. less.render('');
  479. } catch (e) {
  480. fail(stylize('FAIL\n', 'red'));
  481. return;
  482. }
  483. ok(stylize('OK\n', 'green'));
  484. }
  485. function testImportRedirect(nockScope) {
  486. return (name, err, css, doReplacements, sourcemap, baseFolder) => {
  487. process.stdout.write('- ' + path.join(baseFolder, name) + ': ');
  488. if (err) {
  489. fail('FAIL: ' + (err && err.message));
  490. return;
  491. }
  492. const expected = 'h1 {\n color: red;\n}\n';
  493. if (css !== expected) {
  494. difference('FAIL', expected, css);
  495. return;
  496. }
  497. nockScope.done();
  498. ok('OK');
  499. };
  500. }
  501. function testDisablePluginRule() {
  502. less.render(
  503. '@plugin "../../plugin/some_plugin";',
  504. {disablePluginRule: true},
  505. function(err) {
  506. // TODO: Need a better way of identifing exactly which error is thrown. Checking
  507. // text like this tends to be rather brittle.
  508. const EXPECTED = '@plugin statements are not allowed when disablePluginRule is set to true';
  509. if (!err || String(err).indexOf(EXPECTED) < 0) {
  510. fail('ERROR: Expected "' + EXPECTED + '" error');
  511. return;
  512. }
  513. ok(stylize('OK\n', 'green'));
  514. }
  515. );
  516. }
  517. return {
  518. runTestSet: runTestSet,
  519. runTestSetNormalOnly: runTestSetNormalOnly,
  520. testSyncronous: testSyncronous,
  521. testErrors: testErrors,
  522. testTypeErrors: testTypeErrors,
  523. testSourcemap: testSourcemap,
  524. testSourcemapWithoutUrlAnnotation: testSourcemapWithoutUrlAnnotation,
  525. testImports: testImports,
  526. testImportRedirect: testImportRedirect,
  527. testEmptySourcemap: testEmptySourcemap,
  528. testNoOptions: testNoOptions,
  529. testDisablePluginRule: testDisablePluginRule,
  530. testJSImport: testJSImport,
  531. finished: finished
  532. };
  533. };