less-test.js 20 KB

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