less-test.js 20 KB

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