PageRenderTime 48ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/src/static/vendor/lodash/vendor/underscore/test/utility.js

https://gitlab.com/pidlisnyi/lisbon
JavaScript | 420 lines | 389 code | 27 blank | 4 comment | 21 complexity | 7a7841928225b97bd542465aa36c7917 MD5 | raw file
  1. (function() {
  2. var _ = typeof require == 'function' ? require('..') : window._;
  3. var templateSettings;
  4. QUnit.module('Utility', {
  5. beforeEach: function() {
  6. templateSettings = _.clone(_.templateSettings);
  7. },
  8. afterEach: function() {
  9. _.templateSettings = templateSettings;
  10. }
  11. });
  12. if (typeof this == 'object') {
  13. QUnit.test('noConflict', function(assert) {
  14. var underscore = _.noConflict();
  15. assert.equal(underscore.identity(1), 1);
  16. if (typeof require != 'function') {
  17. assert.equal(this._, void 0, 'global underscore is removed');
  18. this._ = underscore;
  19. } else if (typeof global !== 'undefined') {
  20. delete global._;
  21. }
  22. });
  23. }
  24. if (typeof require == 'function') {
  25. QUnit.test('noConflict (node vm)', function(assert) {
  26. assert.expect(2);
  27. var done = assert.async();
  28. var fs = require('fs');
  29. var vm = require('vm');
  30. var filename = __dirname + '/../underscore.js';
  31. fs.readFile(filename, function(err, content){
  32. var sandbox = vm.createScript(
  33. content + 'this.underscore = this._.noConflict();',
  34. filename
  35. );
  36. var context = {_: 'oldvalue'};
  37. sandbox.runInNewContext(context);
  38. assert.equal(context._, 'oldvalue');
  39. assert.equal(context.underscore.VERSION, _.VERSION);
  40. done();
  41. });
  42. });
  43. }
  44. QUnit.test('#750 - Return _ instance.', function(assert) {
  45. assert.expect(2);
  46. var instance = _([]);
  47. assert.ok(_(instance) === instance);
  48. assert.ok(new _(instance) === instance);
  49. });
  50. QUnit.test('identity', function(assert) {
  51. var stooge = {name: 'moe'};
  52. assert.equal(_.identity(stooge), stooge, 'stooge is the same as his identity');
  53. });
  54. QUnit.test('constant', function(assert) {
  55. var stooge = {name: 'moe'};
  56. assert.equal(_.constant(stooge)(), stooge, 'should create a function that returns stooge');
  57. });
  58. QUnit.test('noop', function(assert) {
  59. assert.strictEqual(_.noop('curly', 'larry', 'moe'), void 0, 'should always return undefined');
  60. });
  61. QUnit.test('property', function(assert) {
  62. var stooge = {name: 'moe'};
  63. assert.equal(_.property('name')(stooge), 'moe', 'should return the property with the given name');
  64. assert.equal(_.property('name')(null), void 0, 'should return undefined for null values');
  65. assert.equal(_.property('name')(void 0), void 0, 'should return undefined for undefined values');
  66. });
  67. QUnit.test('propertyOf', function(assert) {
  68. var stoogeRanks = _.propertyOf({curly: 2, moe: 1, larry: 3});
  69. assert.equal(stoogeRanks('curly'), 2, 'should return the property with the given name');
  70. assert.equal(stoogeRanks(null), void 0, 'should return undefined for null values');
  71. assert.equal(stoogeRanks(void 0), void 0, 'should return undefined for undefined values');
  72. function MoreStooges() { this.shemp = 87; }
  73. MoreStooges.prototype = {curly: 2, moe: 1, larry: 3};
  74. var moreStoogeRanks = _.propertyOf(new MoreStooges());
  75. assert.equal(moreStoogeRanks('curly'), 2, 'should return properties from further up the prototype chain');
  76. var nullPropertyOf = _.propertyOf(null);
  77. assert.equal(nullPropertyOf('curly'), void 0, 'should return undefined when obj is null');
  78. var undefPropertyOf = _.propertyOf(void 0);
  79. assert.equal(undefPropertyOf('curly'), void 0, 'should return undefined when obj is undefined');
  80. });
  81. QUnit.test('random', function(assert) {
  82. var array = _.range(1000);
  83. var min = Math.pow(2, 31);
  84. var max = Math.pow(2, 62);
  85. assert.ok(_.every(array, function() {
  86. return _.random(min, max) >= min;
  87. }), 'should produce a random number greater than or equal to the minimum number');
  88. assert.ok(_.some(array, function() {
  89. return _.random(Number.MAX_VALUE) > 0;
  90. }), 'should produce a random number when passed `Number.MAX_VALUE`');
  91. });
  92. QUnit.test('now', function(assert) {
  93. var diff = _.now() - new Date().getTime();
  94. assert.ok(diff <= 0 && diff > -5, 'Produces the correct time in milliseconds');//within 5ms
  95. });
  96. QUnit.test('uniqueId', function(assert) {
  97. var ids = [], i = 0;
  98. while (i++ < 100) ids.push(_.uniqueId());
  99. assert.equal(_.uniq(ids).length, ids.length, 'can generate a globally-unique stream of ids');
  100. });
  101. QUnit.test('times', function(assert) {
  102. var vals = [];
  103. _.times(3, function(i) { vals.push(i); });
  104. assert.deepEqual(vals, [0, 1, 2], 'is 0 indexed');
  105. //
  106. vals = [];
  107. _(3).times(function(i) { vals.push(i); });
  108. assert.deepEqual(vals, [0, 1, 2], 'works as a wrapper');
  109. // collects return values
  110. assert.deepEqual([0, 1, 2], _.times(3, function(i) { return i; }), 'collects return values');
  111. assert.deepEqual(_.times(0, _.identity), []);
  112. assert.deepEqual(_.times(-1, _.identity), []);
  113. assert.deepEqual(_.times(parseFloat('-Infinity'), _.identity), []);
  114. });
  115. QUnit.test('mixin', function(assert) {
  116. _.mixin({
  117. myReverse: function(string) {
  118. return string.split('').reverse().join('');
  119. }
  120. });
  121. assert.equal(_.myReverse('panacea'), 'aecanap', 'mixed in a function to _');
  122. assert.equal(_('champ').myReverse(), 'pmahc', 'mixed in a function to the OOP wrapper');
  123. });
  124. QUnit.test('_.escape', function(assert) {
  125. assert.equal(_.escape(null), '');
  126. });
  127. QUnit.test('_.unescape', function(assert) {
  128. var string = 'Curly & Moe';
  129. assert.equal(_.unescape(null), '');
  130. assert.equal(_.unescape(_.escape(string)), string);
  131. assert.equal(_.unescape(string), string, 'don\'t unescape unnecessarily');
  132. });
  133. // Don't care what they escape them to just that they're escaped and can be unescaped
  134. QUnit.test('_.escape & unescape', function(assert) {
  135. // test & (&amp;) seperately obviously
  136. var escapeCharacters = ['<', '>', '"', '\'', '`'];
  137. _.each(escapeCharacters, function(escapeChar) {
  138. var s = 'a ' + escapeChar + ' string escaped';
  139. var e = _.escape(s);
  140. assert.notEqual(s, e, escapeChar + ' is escaped');
  141. assert.equal(s, _.unescape(e), escapeChar + ' can be unescaped');
  142. s = 'a ' + escapeChar + escapeChar + escapeChar + 'some more string' + escapeChar;
  143. e = _.escape(s);
  144. assert.equal(e.indexOf(escapeChar), -1, 'can escape multiple occurances of ' + escapeChar);
  145. assert.equal(_.unescape(e), s, 'multiple occurrences of ' + escapeChar + ' can be unescaped');
  146. });
  147. // handles multiple escape characters at once
  148. var joiner = ' other stuff ';
  149. var allEscaped = escapeCharacters.join(joiner);
  150. allEscaped += allEscaped;
  151. assert.ok(_.every(escapeCharacters, function(escapeChar) {
  152. return allEscaped.indexOf(escapeChar) !== -1;
  153. }), 'handles multiple characters');
  154. assert.ok(allEscaped.indexOf(joiner) >= 0, 'can escape multiple escape characters at the same time');
  155. // test & -> &amp;
  156. var str = 'some string & another string & yet another';
  157. var escaped = _.escape(str);
  158. assert.ok(escaped.indexOf('&') !== -1, 'handles & aka &amp;');
  159. assert.equal(_.unescape(str), str, 'can unescape &amp;');
  160. });
  161. QUnit.test('template', function(assert) {
  162. var basicTemplate = _.template("<%= thing %> is gettin' on my noives!");
  163. var result = basicTemplate({thing: 'This'});
  164. assert.equal(result, "This is gettin' on my noives!", 'can do basic attribute interpolation');
  165. var sansSemicolonTemplate = _.template('A <% this %> B');
  166. assert.equal(sansSemicolonTemplate(), 'A B');
  167. var backslashTemplate = _.template('<%= thing %> is \\ridanculous');
  168. assert.equal(backslashTemplate({thing: 'This'}), 'This is \\ridanculous');
  169. var escapeTemplate = _.template('<%= a ? "checked=\\"checked\\"" : "" %>');
  170. assert.equal(escapeTemplate({a: true}), 'checked="checked"', 'can handle slash escapes in interpolations.');
  171. var fancyTemplate = _.template('<ul><% ' +
  172. ' for (var key in people) { ' +
  173. '%><li><%= people[key] %></li><% } %></ul>');
  174. result = fancyTemplate({people: {moe: 'Moe', larry: 'Larry', curly: 'Curly'}});
  175. assert.equal(result, '<ul><li>Moe</li><li>Larry</li><li>Curly</li></ul>', 'can run arbitrary javascript in templates');
  176. var escapedCharsInJavascriptTemplate = _.template('<ul><% _.each(numbers.split("\\n"), function(item) { %><li><%= item %></li><% }) %></ul>');
  177. result = escapedCharsInJavascriptTemplate({numbers: 'one\ntwo\nthree\nfour'});
  178. assert.equal(result, '<ul><li>one</li><li>two</li><li>three</li><li>four</li></ul>', 'Can use escaped characters (e.g. \\n) in JavaScript');
  179. var namespaceCollisionTemplate = _.template('<%= pageCount %> <%= thumbnails[pageCount] %> <% _.each(thumbnails, function(p) { %><div class="thumbnail" rel="<%= p %>"></div><% }); %>');
  180. result = namespaceCollisionTemplate({
  181. pageCount: 3,
  182. thumbnails: {
  183. 1: 'p1-thumbnail.gif',
  184. 2: 'p2-thumbnail.gif',
  185. 3: 'p3-thumbnail.gif'
  186. }
  187. });
  188. assert.equal(result, '3 p3-thumbnail.gif <div class="thumbnail" rel="p1-thumbnail.gif"></div><div class="thumbnail" rel="p2-thumbnail.gif"></div><div class="thumbnail" rel="p3-thumbnail.gif"></div>');
  189. var noInterpolateTemplate = _.template('<div><p>Just some text. Hey, I know this is silly but it aids consistency.</p></div>');
  190. result = noInterpolateTemplate();
  191. assert.equal(result, '<div><p>Just some text. Hey, I know this is silly but it aids consistency.</p></div>');
  192. var quoteTemplate = _.template("It's its, not it's");
  193. assert.equal(quoteTemplate({}), "It's its, not it's");
  194. var quoteInStatementAndBody = _.template('<% ' +
  195. " if(foo == 'bar'){ " +
  196. "%>Statement quotes and 'quotes'.<% } %>");
  197. assert.equal(quoteInStatementAndBody({foo: 'bar'}), "Statement quotes and 'quotes'.");
  198. var withNewlinesAndTabs = _.template('This\n\t\tis: <%= x %>.\n\tok.\nend.');
  199. assert.equal(withNewlinesAndTabs({x: 'that'}), 'This\n\t\tis: that.\n\tok.\nend.');
  200. var template = _.template('<i><%- value %></i>');
  201. result = template({value: '<script>'});
  202. assert.equal(result, '<i>&lt;script&gt;</i>');
  203. var stooge = {
  204. name: 'Moe',
  205. template: _.template("I'm <%= this.name %>")
  206. };
  207. assert.equal(stooge.template(), "I'm Moe");
  208. template = _.template('\n ' +
  209. ' <%\n ' +
  210. ' // a comment\n ' +
  211. ' if (data) { data += 12345; }; %>\n ' +
  212. ' <li><%= data %></li>\n '
  213. );
  214. assert.equal(template({data: 12345}).replace(/\s/g, ''), '<li>24690</li>');
  215. _.templateSettings = {
  216. evaluate: /\{\{([\s\S]+?)\}\}/g,
  217. interpolate: /\{\{=([\s\S]+?)\}\}/g
  218. };
  219. var custom = _.template('<ul>{{ for (var key in people) { }}<li>{{= people[key] }}</li>{{ } }}</ul>');
  220. result = custom({people: {moe: 'Moe', larry: 'Larry', curly: 'Curly'}});
  221. assert.equal(result, '<ul><li>Moe</li><li>Larry</li><li>Curly</li></ul>', 'can run arbitrary javascript in templates');
  222. var customQuote = _.template("It's its, not it's");
  223. assert.equal(customQuote({}), "It's its, not it's");
  224. quoteInStatementAndBody = _.template("{{ if(foo == 'bar'){ }}Statement quotes and 'quotes'.{{ } }}");
  225. assert.equal(quoteInStatementAndBody({foo: 'bar'}), "Statement quotes and 'quotes'.");
  226. _.templateSettings = {
  227. evaluate: /<\?([\s\S]+?)\?>/g,
  228. interpolate: /<\?=([\s\S]+?)\?>/g
  229. };
  230. var customWithSpecialChars = _.template('<ul><? for (var key in people) { ?><li><?= people[key] ?></li><? } ?></ul>');
  231. result = customWithSpecialChars({people: {moe: 'Moe', larry: 'Larry', curly: 'Curly'}});
  232. assert.equal(result, '<ul><li>Moe</li><li>Larry</li><li>Curly</li></ul>', 'can run arbitrary javascript in templates');
  233. var customWithSpecialCharsQuote = _.template("It's its, not it's");
  234. assert.equal(customWithSpecialCharsQuote({}), "It's its, not it's");
  235. quoteInStatementAndBody = _.template("<? if(foo == 'bar'){ ?>Statement quotes and 'quotes'.<? } ?>");
  236. assert.equal(quoteInStatementAndBody({foo: 'bar'}), "Statement quotes and 'quotes'.");
  237. _.templateSettings = {
  238. interpolate: /\{\{(.+?)\}\}/g
  239. };
  240. var mustache = _.template('Hello {{planet}}!');
  241. assert.equal(mustache({planet: 'World'}), 'Hello World!', 'can mimic mustache.js');
  242. var templateWithNull = _.template('a null undefined {{planet}}');
  243. assert.equal(templateWithNull({planet: 'world'}), 'a null undefined world', 'can handle missing escape and evaluate settings');
  244. });
  245. QUnit.test('_.template provides the generated function source, when a SyntaxError occurs', function(assert) {
  246. var source;
  247. try {
  248. _.template('<b><%= if x %></b>');
  249. } catch (ex) {
  250. source = ex.source;
  251. }
  252. assert.ok(/__p/.test(source));
  253. });
  254. QUnit.test('_.template handles \\u2028 & \\u2029', function(assert) {
  255. var tmpl = _.template('<p>\u2028<%= "\\u2028\\u2029" %>\u2029</p>');
  256. assert.strictEqual(tmpl(), '<p>\u2028\u2028\u2029\u2029</p>');
  257. });
  258. QUnit.test('result calls functions and returns primitives', function(assert) {
  259. var obj = {w: '', x: 'x', y: function(){ return this.x; }};
  260. assert.strictEqual(_.result(obj, 'w'), '');
  261. assert.strictEqual(_.result(obj, 'x'), 'x');
  262. assert.strictEqual(_.result(obj, 'y'), 'x');
  263. assert.strictEqual(_.result(obj, 'z'), void 0);
  264. assert.strictEqual(_.result(null, 'x'), void 0);
  265. });
  266. QUnit.test('result returns a default value if object is null or undefined', function(assert) {
  267. assert.strictEqual(_.result(null, 'b', 'default'), 'default');
  268. assert.strictEqual(_.result(void 0, 'c', 'default'), 'default');
  269. assert.strictEqual(_.result(''.match('missing'), 1, 'default'), 'default');
  270. });
  271. QUnit.test('result returns a default value if property of object is missing', function(assert) {
  272. assert.strictEqual(_.result({d: null}, 'd', 'default'), null);
  273. assert.strictEqual(_.result({e: false}, 'e', 'default'), false);
  274. });
  275. QUnit.test('result only returns the default value if the object does not have the property or is undefined', function(assert) {
  276. assert.strictEqual(_.result({}, 'b', 'default'), 'default');
  277. assert.strictEqual(_.result({d: void 0}, 'd', 'default'), 'default');
  278. });
  279. QUnit.test('result does not return the default if the property of an object is found in the prototype', function(assert) {
  280. var Foo = function(){};
  281. Foo.prototype.bar = 1;
  282. assert.strictEqual(_.result(new Foo, 'bar', 2), 1);
  283. });
  284. QUnit.test('result does use the fallback when the result of invoking the property is undefined', function(assert) {
  285. var obj = {a: function() {}};
  286. assert.strictEqual(_.result(obj, 'a', 'failed'), void 0);
  287. });
  288. QUnit.test('result fallback can use a function', function(assert) {
  289. var obj = {a: [1, 2, 3]};
  290. assert.strictEqual(_.result(obj, 'b', _.constant(5)), 5);
  291. assert.strictEqual(_.result(obj, 'b', function() {
  292. return this.a;
  293. }), obj.a, 'called with context');
  294. });
  295. QUnit.test('_.templateSettings.variable', function(assert) {
  296. var s = '<%=data.x%>';
  297. var data = {x: 'x'};
  298. var tmp = _.template(s, {variable: 'data'});
  299. assert.strictEqual(tmp(data), 'x');
  300. _.templateSettings.variable = 'data';
  301. assert.strictEqual(_.template(s)(data), 'x');
  302. });
  303. QUnit.test('#547 - _.templateSettings is unchanged by custom settings.', function(assert) {
  304. assert.ok(!_.templateSettings.variable);
  305. _.template('', {}, {variable: 'x'});
  306. assert.ok(!_.templateSettings.variable);
  307. });
  308. QUnit.test('#556 - undefined template variables.', function(assert) {
  309. var template = _.template('<%=x%>');
  310. assert.strictEqual(template({x: null}), '');
  311. assert.strictEqual(template({x: void 0}), '');
  312. var templateEscaped = _.template('<%-x%>');
  313. assert.strictEqual(templateEscaped({x: null}), '');
  314. assert.strictEqual(templateEscaped({x: void 0}), '');
  315. var templateWithProperty = _.template('<%=x.foo%>');
  316. assert.strictEqual(templateWithProperty({x: {}}), '');
  317. assert.strictEqual(templateWithProperty({x: {}}), '');
  318. var templateWithPropertyEscaped = _.template('<%-x.foo%>');
  319. assert.strictEqual(templateWithPropertyEscaped({x: {}}), '');
  320. assert.strictEqual(templateWithPropertyEscaped({x: {}}), '');
  321. });
  322. QUnit.test('interpolate evaluates code only once.', function(assert) {
  323. assert.expect(2);
  324. var count = 0;
  325. var template = _.template('<%= f() %>');
  326. template({f: function(){ assert.ok(!count++); }});
  327. var countEscaped = 0;
  328. var templateEscaped = _.template('<%- f() %>');
  329. templateEscaped({f: function(){ assert.ok(!countEscaped++); }});
  330. });
  331. QUnit.test('#746 - _.template settings are not modified.', function(assert) {
  332. assert.expect(1);
  333. var settings = {};
  334. _.template('', null, settings);
  335. assert.deepEqual(settings, {});
  336. });
  337. QUnit.test('#779 - delimeters are applied to unescaped text.', function(assert) {
  338. assert.expect(1);
  339. var template = _.template('<<\nx\n>>', null, {evaluate: /<<(.*?)>>/g});
  340. assert.strictEqual(template(), '<<\nx\n>>');
  341. });
  342. }());