Best JavaScript code snippet using chai
string_test.js
Source:string_test.js
...14 },15 testGsubWithReplacementFunction: function() {16 var source = 'foo boo boz';17 18 this.assertEqual('Foo Boo BoZ',19 source.gsub(/[^o]+/, function(match) {20 return match[0].toUpperCase()21 }));22 this.assertEqual('f2 b2 b1z',23 source.gsub(/o+/, function(match) {24 return match[0].length;25 }));26 this.assertEqual('f0 b0 b1z',27 source.gsub(/o+/, function(match) {28 return match[0].length % 2;29 }));30 },31 32 testGsubWithReplacementString: function() {33 var source = 'foo boo boz';34 35 this.assertEqual('foobooboz',36 source.gsub(/\s+/, ''));37 this.assertEqual(' z', 38 source.gsub(/(.)(o+)/, ''));39 40 this.assertEqual('ã¦ã£ã¡ã³ãº2007<br/>ã¯ã«ã¼ãºã³ã¬ã¯ã·ã§ã³', 41 'ã¦ã£ã¡ã³ãº2007\nã¯ã«ã¼ãºã³ã¬ã¯ã·ã§ã³'.gsub(/\n/,'<br/>'));42 this.assertEqual('ã¦ã£ã¡ã³ãº2007<br/>ã¯ã«ã¼ãºã³ã¬ã¯ã·ã§ã³', 43 'ã¦ã£ã¡ã³ãº2007\nã¯ã«ã¼ãºã³ã¬ã¯ã·ã§ã³'.gsub('\n','<br/>'));44 },45 46 testGsubWithReplacementTemplateString: function() {47 var source = 'foo boo boz';48 49 this.assertEqual('-oo-#{1}- -oo-#{1}- -o-#{1}-z',50 source.gsub(/(.)(o+)/, '-#{2}-\\#{1}-'));51 this.assertEqual('-foo-f- -boo-b- -bo-b-z',52 source.gsub(/(.)(o+)/, '-#{0}-#{1}-'));53 this.assertEqual('-oo-f- -oo-b- -o-b-z',54 source.gsub(/(.)(o+)/, '-#{2}-#{1}-'));55 this.assertEqual(' z',56 source.gsub(/(.)(o+)/, '#{3}')); 57 },58 59 testSubWithReplacementFunction: function() {60 var source = 'foo boo boz';61 this.assertEqual('Foo boo boz',62 source.sub(/[^o]+/, function(match) {63 return match[0].toUpperCase()64 }), 1);65 this.assertEqual('Foo Boo boz',66 source.sub(/[^o]+/, function(match) {67 return match[0].toUpperCase()68 }, 2), 2);69 this.assertEqual(source,70 source.sub(/[^o]+/, function(match) {71 return match[0].toUpperCase()72 }, 0), 0);73 this.assertEqual(source,74 source.sub(/[^o]+/, function(match) {75 return match[0].toUpperCase()76 }, -1), -1);77 },78 79 testSubWithReplacementString: function() {80 var source = 'foo boo boz';81 82 this.assertEqual('oo boo boz',83 source.sub(/[^o]+/, ''));84 this.assertEqual('oooo boz',85 source.sub(/[^o]+/, '', 2));86 this.assertEqual('-f-oo boo boz',87 source.sub(/[^o]+/, '-#{0}-'));88 this.assertEqual('-f-oo- b-oo boz',89 source.sub(/[^o]+/, '-#{0}-', 2));90 },91 92 testScan: function() {93 var source = 'foo boo boz', results = [];94 var str = source.scan(/[o]+/, function(match) {95 results.push(match[0].length);96 });97 this.assertEnumEqual([2, 2, 1], results);98 this.assertEqual(source, source.scan(/x/, this.fail));99 this.assert(typeof str == 'string');100 },101 102 testToArray: function() {103 this.assertEnumEqual([],''.toArray());104 this.assertEnumEqual(['a'],'a'.toArray());105 this.assertEnumEqual(['a','b'],'ab'.toArray());106 this.assertEnumEqual(['f','o','o'],'foo'.toArray());107 },108 /* 109 Note that camelize() differs from its Rails counterpart,110 as it is optimized for dealing with JavaScript object111 properties in conjunction with CSS property names:112 - Looks for dashes, not underscores113 - CamelCases first word if there is a front dash114 */115 testCamelize: function() {116 this.assertEqual('', ''.camelize());117 this.assertEqual('', '-'.camelize());118 this.assertEqual('foo', 'foo'.camelize());119 this.assertEqual('foo_bar', 'foo_bar'.camelize());120 this.assertEqual('FooBar', '-foo-bar'.camelize());121 this.assertEqual('FooBar', 'FooBar'.camelize());122 123 this.assertEqual('fooBar', 'foo-bar'.camelize());124 this.assertEqual('borderBottomWidth', 'border-bottom-width'.camelize());125 126 this.assertEqual('classNameTest','class-name-test'.camelize());127 this.assertEqual('classNameTest','className-test'.camelize());128 this.assertEqual('classNameTest','class-nameTest'.camelize());129 130 /* this.benchmark(function(){131 'class-name-test'.camelize();132 },10000); */133 },134 testCapitalize: function() {135 this.assertEqual('',''.capitalize());136 this.assertEqual('Ã','ä'.capitalize());137 this.assertEqual('A','A'.capitalize());138 this.assertEqual('Hello','hello'.capitalize());139 this.assertEqual('Hello','HELLO'.capitalize());140 this.assertEqual('Hello','Hello'.capitalize());141 this.assertEqual('Hello world','hello WORLD'.capitalize());142 }, 143 144 testUnderscore: function() {145 this.assertEqual('', ''.underscore());146 this.assertEqual('_', '-'.underscore());147 this.assertEqual('foo', 'foo'.underscore());148 this.assertEqual('foo', 'Foo'.underscore());149 this.assertEqual('foo_bar', 'foo_bar'.underscore());150 this.assertEqual('border_bottom', 'borderBottom'.underscore());151 this.assertEqual('border_bottom_width', 'borderBottomWidth'.underscore());152 this.assertEqual('border_bottom_width', 'border-Bottom-Width'.underscore()); 153 },154 155 testDasherize: function() {156 this.assertEqual('', ''.dasherize());157 this.assertEqual('foo', 'foo'.dasherize());158 this.assertEqual('Foo', 'Foo'.dasherize());159 this.assertEqual('foo-bar', 'foo-bar'.dasherize());160 this.assertEqual('border-bottom-width', 'border_bottom_width'.dasherize());161 },162 163 testTruncate: function() {164 var source = 'foo boo boz foo boo boz foo boo boz foo boo boz';165 this.assertEqual(source, source.truncate(source.length));166 this.assertEqual('foo boo boz foo boo boz foo...', source.truncate(0));167 this.assertEqual('fo...', source.truncate(5));168 this.assertEqual('foo b', source.truncate(5, ''));169 170 this.assert(typeof 'foo'.truncate(5) == 'string');171 this.assert(typeof 'foo bar baz'.truncate(5) == 'string');172 },173 174 testStrip: function() {175 this.assertEqual('hello world', ' hello world '.strip());176 this.assertEqual('hello world', 'hello world'.strip());177 this.assertEqual('hello \n world', ' hello \n world '.strip());178 this.assertEqual('', ' '.strip());179 },180 181 testStripTags: function() {182 this.assertEqual('hello world', 'hello world'.stripTags());183 this.assertEqual('hello world', 'hello <span>world</span>'.stripTags());184 this.assertEqual('hello world', '<a href="#" onclick="moo!">hello</a> world'.stripTags());185 this.assertEqual('hello world', 'h<b><em>e</em></b>l<i>l</i>o w<span class="moo" id="x"><b>o</b></span>rld'.stripTags());186 this.assertEqual('1\n2', '1\n2'.stripTags());187 },188 189 testStripScripts: function() {190 this.assertEqual('foo bar', 'foo bar'.stripScripts());191 this.assertEqual('foo bar', ('foo <script>boo();<'+'/script>bar').stripScripts());192 this.assertEqual('foo bar', ('foo <script type="text/javascript">boo();\nmoo();<'+'/script>bar').stripScripts());193 },194 195 testExtractScripts: function() {196 this.assertEnumEqual([], 'foo bar'.extractScripts());197 this.assertEnumEqual(['boo();'], ('foo <script>boo();<'+'/script>bar').extractScripts());198 this.assertEnumEqual(['boo();','boo();\nmoo();'], 199 ('foo <script>boo();<'+'/script><script type="text/javascript">boo();\nmoo();<'+'/script>bar').extractScripts());200 this.assertEnumEqual(['boo();','boo();\nmoo();'], 201 ('foo <script>boo();<'+'/script>blub\nblub<script type="text/javascript">boo();\nmoo();<'+'/script>bar').extractScripts());202 },203 204 testEvalScripts: function() {205 this.assertEqual(0, evalScriptsCounter);206 207 ('foo <script>evalScriptsCounter++<'+'/script>bar').evalScripts();208 this.assertEqual(1, evalScriptsCounter);209 210 var stringWithScripts = '';211 (3).times(function(){ stringWithScripts += 'foo <script>evalScriptsCounter++<'+'/script>bar' });212 stringWithScripts.evalScripts();213 this.assertEqual(4, evalScriptsCounter);214 },215 216 testEscapeHTML: function() {217 this.assertEqual('foo bar', 'foo bar'.escapeHTML());218 this.assertEqual('foo <span>bar</span>', 'foo <span>bar</span>'.escapeHTML());219 this.assertEqual('foo à bar', 'foo à bar'.escapeHTML());220 221 this.assertEqual('ã¦ã£ã¡ã³ãº2007\nã¯ã«ã¼ãºã³ã¬ã¯ã·ã§ã³', 222 'ã¦ã£ã¡ã³ãº2007\nã¯ã«ã¼ãºã³ã¬ã¯ã·ã§ã³'.escapeHTML());223 224 this.assertEqual('a<a href="blah">blub</a>b<span><div></div></span>cdef<strong>!!!!</strong>g',225 'a<a href="blah">blub</a>b<span><div></div></span>cdef<strong>!!!!</strong>g'.escapeHTML());226 227 this.assertEqual(largeTextEscaped, largeTextUnescaped.escapeHTML());228 229 this.assertEqual('1\n2', '1\n2'.escapeHTML());230 231 this.benchmark(function() { largeTextUnescaped.escapeHTML() }, 1000);232 },233 234 testUnescapeHTML: function() {235 this.assertEqual('foo bar', 'foo bar'.unescapeHTML());236 this.assertEqual('foo <span>bar</span>', 'foo <span>bar</span>'.unescapeHTML());237 this.assertEqual('foo à bar', 'foo à bar'.unescapeHTML());238 239 this.assertEqual('a<a href="blah">blub</a>b<span><div></div></span>cdef<strong>!!!!</strong>g',240 'a<a href="blah">blub</a>b<span><div></div></span>cdef<strong>!!!!</strong>g'.unescapeHTML());241 242 this.assertEqual(largeTextUnescaped, largeTextEscaped.unescapeHTML());243 244 this.assertEqual('1\n2', '1\n2'.unescapeHTML());245 this.assertEqual('Pride & Prejudice', '<h1>Pride & Prejudice</h1>'.unescapeHTML());246 247 this.benchmark(function() { largeTextEscaped.unescapeHTML() }, 1000);248 249 },250 251 testTemplateEvaluation: function() {252 var source = '<tr><td>#{name}</td><td>#{age}</td></tr>';253 var person = {name: 'Sam', age: 21};254 var template = new Template(source);255 256 this.assertEqual('<tr><td>Sam</td><td>21</td></tr>',257 template.evaluate(person));258 this.assertEqual('<tr><td></td><td></td></tr>',259 template.evaluate({}));260 },261 testTemplateEvaluationWithEmptyReplacement: function() {262 var template = new Template('##{}');263 this.assertEqual('#', template.evaluate({}));264 this.assertEqual('#', template.evaluate({foo: 'bar'}));265 template = new Template('#{}');266 this.assertEqual('', template.evaluate({}));267 },268 testTemplateEvaluationWithFalses: function() {269 var source = '<tr><td>#{zero}</td><td>#{_false}</td><td>#{undef}</td><td>#{_null}</td><td>#{empty}</td></tr>';270 var falses = {zero:0, _false:false, undef:undefined, _null:null, empty:""};271 var template = new Template(source);272 273 this.assertEqual('<tr><td>0</td><td>false</td><td></td><td></td><td></td></tr>',274 template.evaluate(falses));275 },276 testTemplateEvaluationWithNested: function() {277 var source = '#{name} #{manager.name} #{manager.age} #{manager.undef} #{manager.age.undef} #{colleagues.first.name}';278 var subject = { manager: { name: 'John', age: 29 }, name: 'Stephan', age: 22, colleagues: { first: { name: 'Mark' }} };279 this.assertEqual('Stephan', new Template('#{name}').evaluate(subject));280 this.assertEqual('John', new Template('#{manager.name}').evaluate(subject));281 this.assertEqual('29', new Template('#{manager.age}').evaluate(subject));282 this.assertEqual('', new Template('#{manager.undef}').evaluate(subject));283 this.assertEqual('', new Template('#{manager.age.undef}').evaluate(subject));284 this.assertEqual('Mark', new Template('#{colleagues.first.name}').evaluate(subject));285 this.assertEqual('Stephan John 29 Mark', new Template(source).evaluate(subject));286 },287 testTemplateEvaluationWithIndexing: function() {288 var source = '#{0} = #{[0]} - #{1} = #{[1]} - #{[2][0]} - #{[2].name} - #{first[0]} - #{[first][0]} - #{[\\]]} - #{first[\\]]}';289 var subject = [ 'zero', 'one', [ 'two-zero' ] ];290 subject[2].name = 'two-zero-name';291 subject.first = subject[2];292 subject[']'] = '\\';293 subject.first[']'] = 'first\\';294 this.assertEqual('zero', new Template('#{[0]}').evaluate(subject));295 this.assertEqual('one', new Template('#{[1]}').evaluate(subject));296 this.assertEqual('two-zero', new Template('#{[2][0]}').evaluate(subject));297 this.assertEqual('two-zero-name', new Template('#{[2].name}').evaluate(subject));298 this.assertEqual('two-zero', new Template('#{first[0]}').evaluate(subject));299 this.assertEqual('\\', new Template('#{[\\]]}').evaluate(subject));300 this.assertEqual('first\\', new Template('#{first[\\]]}').evaluate(subject));301 this.assertEqual('empty - empty2', new Template('#{[]} - #{m[]}').evaluate({ '': 'empty', m: {'': 'empty2'}}));302 this.assertEqual('zero = zero - one = one - two-zero - two-zero-name - two-zero - two-zero - \\ - first\\', new Template(source).evaluate(subject));303 },304 testTemplateToTemplateReplacements: function() {305 var source = 'My name is #{name}, my job is #{job}';306 var subject = {307 name: 'Stephan',308 getJob: function() { return 'Web developer'; },309 toTemplateReplacements: function() { return { name: this.name, job: this.getJob() } }310 };311 this.assertEqual('My name is Stephan, my job is Web developer', new Template(source).evaluate(subject));312 },313 testTemplateEvaluationCombined: function() {314 var source = '#{name} is #{age} years old, managed by #{manager.name}, #{manager.age}.\n' +315 'Colleagues include #{colleagues[0].name} and #{colleagues[1].name}.';316 var subject = {317 name: 'Stephan', age: 22,318 manager: { name: 'John', age: 29 },319 colleagues: [ { name: 'Mark' }, { name: 'Indy' } ]320 };321 this.assertEqual('Stephan is 22 years old, managed by John, 29.\n' +322 'Colleagues include Mark and Indy.',323 new Template(source).evaluate(subject));324 },325 testInterpolate: function() {326 var subject = { name: 'Stephan' };327 var pattern = /(^|.|\r|\n)(#\((.*?)\))/;328 this.assertEqual('#{name}: Stephan', '\\#{name}: #{name}'.interpolate(subject));329 this.assertEqual('#(name): Stephan', '\\#(name): #(name)'.interpolate(subject, pattern));330 },331 testToQueryParams: function() {332 // only the query part333 var result = {a:undefined, b:'c'};334 this.assertHashEqual({}, ''.toQueryParams(), 'empty query');335 this.assertHashEqual({}, 'foo?'.toQueryParams(), 'empty query with URL');336 this.assertHashEqual(result, 'foo?a&b=c'.toQueryParams(), 'query with URL');337 this.assertHashEqual(result, 'foo?a&b=c#fragment'.toQueryParams(), 'query with URL and fragment');338 this.assertHashEqual(result, 'a;b=c'.toQueryParams(';'), 'custom delimiter');339 340 this.assertHashEqual({a:undefined}, 'a'.toQueryParams(), 'key without value');341 this.assertHashEqual({a:'b'}, 'a=b&=c'.toQueryParams(), 'empty key');342 this.assertHashEqual({a:'b', c:''}, 'a=b&c='.toQueryParams(), 'empty value');343 344 this.assertHashEqual({'a b':'c', d:'e f', g:'h'},345 'a%20b=c&d=e%20f&g=h'.toQueryParams(), 'proper decoding');346 this.assertHashEqual({a:'b=c=d'}, 'a=b=c=d'.toQueryParams(), 'multiple equal signs');347 this.assertHashEqual({a:'b', c:'d'}, '&a=b&&&c=d'.toQueryParams(), 'proper splitting');348 349 this.assertEnumEqual($w('r g b'), 'col=r&col=g&col=b'.toQueryParams()['col'],350 'collection without square brackets');351 var msg = 'empty values inside collection';352 this.assertEnumEqual(['r', '', 'b'], 'c=r&c=&c=b'.toQueryParams()['c'], msg);353 this.assertEnumEqual(['', 'blue'], 'c=&c=blue'.toQueryParams()['c'], msg);354 this.assertEnumEqual(['blue', ''], 'c=blue&c='.toQueryParams()['c'], msg);355 },356 357 testInspect: function() {358 this.assertEqual('\'\'', ''.inspect());359 this.assertEqual('\'test\'', 'test'.inspect());360 this.assertEqual('\'test \\\'test\\\' "test"\'', 'test \'test\' "test"'.inspect());361 this.assertEqual('\"test \'test\' \\"test\\"\"', 'test \'test\' "test"'.inspect(true));362 this.assertEqual('\'\\b\\t\\n\\f\\r"\\\\\'', '\b\t\n\f\r"\\'.inspect());363 this.assertEqual('\"\\b\\t\\n\\f\\r\\"\\\\\"', '\b\t\n\f\r"\\'.inspect(true));364 this.assertEqual('\'\\b\\t\\n\\f\\r\'', '\x08\x09\x0a\x0c\x0d'.inspect());365 this.assertEqual('\'\\u001a\'', '\x1a'.inspect());366 },367 368 testInclude: function() {369 this.assert('hello world'.include('h'));370 this.assert('hello world'.include('hello'));371 this.assert('hello world'.include('llo w'));372 this.assert('hello world'.include('world')); 373 this.assert(!'hello world'.include('bye'));374 this.assert(!''.include('bye'));375 },376 377 testStartsWith: function() {378 this.assert('hello world'.startsWith('h'));379 this.assert('hello world'.startsWith('hello'));380 this.assert(!'hello world'.startsWith('bye'));381 this.assert(!''.startsWith('bye'));382 this.assert(!'hell'.startsWith('hello'));383 },384 385 testEndsWith: function() {386 this.assert('hello world'.endsWith('d'));387 this.assert('hello world'.endsWith(' world'));388 this.assert(!'hello world'.endsWith('planet'));389 this.assert(!''.endsWith('planet'));390 this.assert('hello world world'.endsWith(' world'));391 this.assert(!'z'.endsWith('az'));392 },393 394 testBlank: function() {395 this.assert(''.blank());396 this.assert(' '.blank());397 this.assert('\t\r\n '.blank());398 this.assert(!'a'.blank());399 this.assert(!'\t y \n'.blank());400 },401 402 testEmpty: function() {403 this.assert(''.empty());404 this.assert(!' '.empty());405 this.assert(!'\t\r\n '.empty());406 this.assert(!'a'.empty());407 this.assert(!'\t y \n'.empty());408 },409 410 testSucc: function() {411 this.assertEqual('b', 'a'.succ());412 this.assertEqual('B', 'A'.succ());413 this.assertEqual('1', '0'.succ());414 this.assertEqual('abce', 'abcd'.succ());415 this.assertEqual('{', 'z'.succ());416 this.assertEqual(':', '9'.succ());417 },418 testTimes: function() {419 this.assertEqual('', ''.times(0));420 this.assertEqual('', ''.times(5));421 this.assertEqual('', 'a'.times(-1));422 this.assertEqual('', 'a'.times(0));423 this.assertEqual('a', 'a'.times(1));424 this.assertEqual('aa', 'a'.times(2));425 this.assertEqual('aaaaa', 'a'.times(5));426 this.assertEqual('foofoofoofoofoo', 'foo'.times(5));427 this.assertEqual('', 'foo'.times(-5));428 429 /*window.String.prototype.oldTimes = function(count) {430 var result = '';431 for (var i = 0; i < count; i++) result += this;432 return result;433 };434 435 this.benchmark(function() {436 'foo'.times(15);437 }, 1000, 'new: ');438 439 this.benchmark(function() {440 'foo'.oldTimes(15);441 }, 1000, 'previous: ');*/442 },443 444 testToJSON: function() {445 this.assertEqual('\"\"', ''.toJSON());446 this.assertEqual('\"test\"', 'test'.toJSON());447 },448 449 testIsJSON: function() {450 this.assert(!''.isJSON());451 this.assert(!' '.isJSON());452 this.assert('""'.isJSON());453 this.assert('"foo"'.isJSON());454 this.assert('{}'.isJSON());455 this.assert('[]'.isJSON());456 this.assert('null'.isJSON());457 this.assert('123'.isJSON());458 this.assert('true'.isJSON());459 this.assert('false'.isJSON());460 this.assert('"\\""'.isJSON());461 this.assert(!'\\"'.isJSON());462 this.assert(!'new'.isJSON());463 this.assert(!'\u0028\u0029'.isJSON());464 // we use '@' as a placeholder for characters authorized only inside brackets,465 // so this tests make sure it is not considered authorized elsewhere.466 this.assert(!'@'.isJSON());467 },468 testEvalJSON: function() {469 var valid = '{"test": \n\r"hello world!"}';470 var invalid = '{"test": "hello world!"';471 var dangerous = '{});attackTarget = "attack succeeded!";({}';472 // use smaller huge string size for KHTML473 var size = navigator.userAgent.include('KHTML') ? 20 : 100;474 var longString = '"' + '123456789\\"'.times(size * 10) + '"';475 var object = '{' + longString + ': ' + longString + '},';476 var huge = '[' + object.times(size) + '{"test": 123}]';477 478 this.assertEqual('hello world!', valid.evalJSON().test);479 this.assertEqual('hello world!', valid.evalJSON(true).test);480 this.assertRaise('SyntaxError', function() { invalid.evalJSON() });481 this.assertRaise('SyntaxError', function() { invalid.evalJSON(true) });482 attackTarget = "scared";483 dangerous.evalJSON();484 this.assertEqual("attack succeeded!", attackTarget);485 486 attackTarget = "Not scared!";487 this.assertRaise('SyntaxError', function(){dangerous.evalJSON(true)});488 this.assertEqual("Not scared!", attackTarget);489 this.assertEqual('hello world!', ('/*-secure- \r \n ' + valid + ' \n */').evalJSON().test);490 var temp = Prototype.JSONFilter;491 Prototype.JSONFilter = /^\/\*([\s\S]*)\*\/$/; // test custom delimiters.492 this.assertEqual('hello world!', ('/*' + valid + '*/').evalJSON().test);493 Prototype.JSONFilter = temp;494 495 this.assertMatch(123, huge.evalJSON(true).last().test);496 497 this.assertEqual('', '""'.evalJSON());498 this.assertEqual('foo', '"foo"'.evalJSON());499 this.assert('object', typeof '{}'.evalJSON());500 this.assert(Object.isArray('[]'.evalJSON()));501 this.assertNull('null'.evalJSON());502 this.assert(123, '123'.evalJSON());503 this.assertIdentical(true, 'true'.evalJSON());504 this.assertIdentical(false, 'false'.evalJSON());505 this.assertEqual('"', '"\\""'.evalJSON());506 }...
test_int.py
Source:test_int.py
...42 (unichr(0x200), ValueError),43]44class IntTestCases(unittest.TestCase):45 def test_basic(self):46 self.assertEqual(int(314), 314)47 self.assertEqual(int(3.14), 3)48 self.assertEqual(int(314L), 314)49 # Check that conversion from float truncates towards zero50 self.assertEqual(int(-3.14), -3)51 self.assertEqual(int(3.9), 3)52 self.assertEqual(int(-3.9), -3)53 self.assertEqual(int(3.5), 3)54 self.assertEqual(int(-3.5), -3)55 # Different base:56 self.assertEqual(int("10",16), 16L)57 if have_unicode:58 self.assertEqual(int(unicode("10"),16), 16L)59 # Test conversion from strings and various anomalies60 for s, v in L:61 for sign in "", "+", "-":62 for prefix in "", " ", "\t", " \t\t ":63 ss = prefix + sign + s64 vv = v65 if sign == "-" and v is not ValueError:66 vv = -v67 try:68 self.assertEqual(int(ss), vv)69 except v:70 pass71 s = repr(-1-sys.maxint)72 x = int(s)73 self.assertEqual(x+1, -sys.maxint)74 self.assertIsInstance(x, int)75 # should return long76 self.assertEqual(int(s[1:]), sys.maxint+1)77 # should return long78 x = int(1e100)79 self.assertIsInstance(x, long)80 x = int(-1e100)81 self.assertIsInstance(x, long)82 # SF bug 434186: 0x80000000/2 != 0x80000000>>1.83 # Worked by accident in Windows release build, but failed in debug build.84 # Failed in all Linux builds.85 x = -1-sys.maxint86 self.assertEqual(x >> 1, x//2)87 self.assertRaises(ValueError, int, '123\0')88 self.assertRaises(ValueError, int, '53', 40)89 # SF bug 1545497: embedded NULs were not detected with90 # explicit base91 self.assertRaises(ValueError, int, '123\0', 10)92 self.assertRaises(ValueError, int, '123\x00 245', 20)93 x = int('1' * 600)94 self.assertIsInstance(x, long)95 if have_unicode:96 x = int(unichr(0x661) * 600)97 self.assertIsInstance(x, long)98 self.assertRaises(TypeError, int, 1, 12)99 self.assertEqual(int('0123', 0), 83)100 self.assertEqual(int('0x123', 16), 291)101 # Bug 1679: "0x" is not a valid hex literal102 self.assertRaises(ValueError, int, "0x", 16)103 self.assertRaises(ValueError, int, "0x", 0)104 self.assertRaises(ValueError, int, "0o", 8)105 self.assertRaises(ValueError, int, "0o", 0)106 self.assertRaises(ValueError, int, "0b", 2)107 self.assertRaises(ValueError, int, "0b", 0)108 # SF bug 1334662: int(string, base) wrong answers109 # Various representations of 2**32 evaluated to 0110 # rather than 2**32 in previous versions111 self.assertEqual(int('100000000000000000000000000000000', 2), 4294967296L)112 self.assertEqual(int('102002022201221111211', 3), 4294967296L)113 self.assertEqual(int('10000000000000000', 4), 4294967296L)114 self.assertEqual(int('32244002423141', 5), 4294967296L)115 self.assertEqual(int('1550104015504', 6), 4294967296L)116 self.assertEqual(int('211301422354', 7), 4294967296L)117 self.assertEqual(int('40000000000', 8), 4294967296L)118 self.assertEqual(int('12068657454', 9), 4294967296L)119 self.assertEqual(int('4294967296', 10), 4294967296L)120 self.assertEqual(int('1904440554', 11), 4294967296L)121 self.assertEqual(int('9ba461594', 12), 4294967296L)122 self.assertEqual(int('535a79889', 13), 4294967296L)123 self.assertEqual(int('2ca5b7464', 14), 4294967296L)124 self.assertEqual(int('1a20dcd81', 15), 4294967296L)125 self.assertEqual(int('100000000', 16), 4294967296L)126 self.assertEqual(int('a7ffda91', 17), 4294967296L)127 self.assertEqual(int('704he7g4', 18), 4294967296L)128 self.assertEqual(int('4f5aff66', 19), 4294967296L)129 self.assertEqual(int('3723ai4g', 20), 4294967296L)130 self.assertEqual(int('281d55i4', 21), 4294967296L)131 self.assertEqual(int('1fj8b184', 22), 4294967296L)132 self.assertEqual(int('1606k7ic', 23), 4294967296L)133 self.assertEqual(int('mb994ag', 24), 4294967296L)134 self.assertEqual(int('hek2mgl', 25), 4294967296L)135 self.assertEqual(int('dnchbnm', 26), 4294967296L)136 self.assertEqual(int('b28jpdm', 27), 4294967296L)137 self.assertEqual(int('8pfgih4', 28), 4294967296L)138 self.assertEqual(int('76beigg', 29), 4294967296L)139 self.assertEqual(int('5qmcpqg', 30), 4294967296L)140 self.assertEqual(int('4q0jto4', 31), 4294967296L)141 self.assertEqual(int('4000000', 32), 4294967296L)142 self.assertEqual(int('3aokq94', 33), 4294967296L)143 self.assertEqual(int('2qhxjli', 34), 4294967296L)144 self.assertEqual(int('2br45qb', 35), 4294967296L)145 self.assertEqual(int('1z141z4', 36), 4294967296L)146 # tests with base 0147 # this fails on 3.0, but in 2.x the old octal syntax is allowed148 self.assertEqual(int(' 0123 ', 0), 83)149 self.assertEqual(int(' 0123 ', 0), 83)150 self.assertEqual(int('000', 0), 0)151 self.assertEqual(int('0o123', 0), 83)152 self.assertEqual(int('0x123', 0), 291)153 self.assertEqual(int('0b100', 0), 4)154 self.assertEqual(int(' 0O123 ', 0), 83)155 self.assertEqual(int(' 0X123 ', 0), 291)156 self.assertEqual(int(' 0B100 ', 0), 4)157 self.assertEqual(int('0', 0), 0)158 self.assertEqual(int('+0', 0), 0)159 self.assertEqual(int('-0', 0), 0)160 self.assertEqual(int('00', 0), 0)161 self.assertRaises(ValueError, int, '08', 0)162 self.assertRaises(ValueError, int, '-012395', 0)163 # without base still base 10164 self.assertEqual(int('0123'), 123)165 self.assertEqual(int('0123', 10), 123)166 # tests with prefix and base != 0167 self.assertEqual(int('0x123', 16), 291)168 self.assertEqual(int('0o123', 8), 83)169 self.assertEqual(int('0b100', 2), 4)170 self.assertEqual(int('0X123', 16), 291)171 self.assertEqual(int('0O123', 8), 83)172 self.assertEqual(int('0B100', 2), 4)173 # the code has special checks for the first character after the174 # type prefix175 self.assertRaises(ValueError, int, '0b2', 2)176 self.assertRaises(ValueError, int, '0b02', 2)177 self.assertRaises(ValueError, int, '0B2', 2)178 self.assertRaises(ValueError, int, '0B02', 2)179 self.assertRaises(ValueError, int, '0o8', 8)180 self.assertRaises(ValueError, int, '0o08', 8)181 self.assertRaises(ValueError, int, '0O8', 8)182 self.assertRaises(ValueError, int, '0O08', 8)183 self.assertRaises(ValueError, int, '0xg', 16)184 self.assertRaises(ValueError, int, '0x0g', 16)185 self.assertRaises(ValueError, int, '0Xg', 16)186 self.assertRaises(ValueError, int, '0X0g', 16)187 # SF bug 1334662: int(string, base) wrong answers188 # Checks for proper evaluation of 2**32 + 1189 self.assertEqual(int('100000000000000000000000000000001', 2), 4294967297L)190 self.assertEqual(int('102002022201221111212', 3), 4294967297L)191 self.assertEqual(int('10000000000000001', 4), 4294967297L)192 self.assertEqual(int('32244002423142', 5), 4294967297L)193 self.assertEqual(int('1550104015505', 6), 4294967297L)194 self.assertEqual(int('211301422355', 7), 4294967297L)195 self.assertEqual(int('40000000001', 8), 4294967297L)196 self.assertEqual(int('12068657455', 9), 4294967297L)197 self.assertEqual(int('4294967297', 10), 4294967297L)198 self.assertEqual(int('1904440555', 11), 4294967297L)199 self.assertEqual(int('9ba461595', 12), 4294967297L)200 self.assertEqual(int('535a7988a', 13), 4294967297L)201 self.assertEqual(int('2ca5b7465', 14), 4294967297L)202 self.assertEqual(int('1a20dcd82', 15), 4294967297L)203 self.assertEqual(int('100000001', 16), 4294967297L)204 self.assertEqual(int('a7ffda92', 17), 4294967297L)205 self.assertEqual(int('704he7g5', 18), 4294967297L)206 self.assertEqual(int('4f5aff67', 19), 4294967297L)207 self.assertEqual(int('3723ai4h', 20), 4294967297L)208 self.assertEqual(int('281d55i5', 21), 4294967297L)209 self.assertEqual(int('1fj8b185', 22), 4294967297L)210 self.assertEqual(int('1606k7id', 23), 4294967297L)211 self.assertEqual(int('mb994ah', 24), 4294967297L)212 self.assertEqual(int('hek2mgm', 25), 4294967297L)213 self.assertEqual(int('dnchbnn', 26), 4294967297L)214 self.assertEqual(int('b28jpdn', 27), 4294967297L)215 self.assertEqual(int('8pfgih5', 28), 4294967297L)216 self.assertEqual(int('76beigh', 29), 4294967297L)217 self.assertEqual(int('5qmcpqh', 30), 4294967297L)218 self.assertEqual(int('4q0jto5', 31), 4294967297L)219 self.assertEqual(int('4000001', 32), 4294967297L)220 self.assertEqual(int('3aokq95', 33), 4294967297L)221 self.assertEqual(int('2qhxjlj', 34), 4294967297L)222 self.assertEqual(int('2br45qc', 35), 4294967297L)223 self.assertEqual(int('1z141z5', 36), 4294967297L)224 def test_bit_length(self):225 tiny = 1e-10226 for x in xrange(-65000, 65000):227 k = x.bit_length()228 # Check equivalence with Python version229 self.assertEqual(k, len(bin(x).lstrip('-0b')))230 # Behaviour as specified in the docs231 if x != 0:232 self.assertTrue(2**(k-1) <= abs(x) < 2**k)233 else:234 self.assertEqual(k, 0)235 # Alternative definition: x.bit_length() == 1 + floor(log_2(x))236 if x != 0:237 # When x is an exact power of 2, numeric errors can238 # cause floor(log(x)/log(2)) to be one too small; for239 # small x this can be fixed by adding a small quantity240 # to the quotient before taking the floor.241 self.assertEqual(k, 1 + math.floor(242 math.log(abs(x))/math.log(2) + tiny))243 self.assertEqual((0).bit_length(), 0)244 self.assertEqual((1).bit_length(), 1)245 self.assertEqual((-1).bit_length(), 1)246 self.assertEqual((2).bit_length(), 2)247 self.assertEqual((-2).bit_length(), 2)248 for i in [2, 3, 15, 16, 17, 31, 32, 33, 63, 64]:249 a = 2**i250 self.assertEqual((a-1).bit_length(), i)251 self.assertEqual((1-a).bit_length(), i)252 self.assertEqual((a).bit_length(), i+1)253 self.assertEqual((-a).bit_length(), i+1)254 self.assertEqual((a+1).bit_length(), i+1)255 self.assertEqual((-a-1).bit_length(), i+1)256 @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),257 "test requires IEEE 754 doubles")258 def test_float_conversion(self):259 # values exactly representable as floats260 exact_values = [-2, -1, 0, 1, 2, 2**52, 2**53-1, 2**53, 2**53+2,261 2**53+4, 2**54-4, 2**54-2, 2**63, -2**63, 2**64,262 -2**64, 10**20, 10**21, 10**22]263 for value in exact_values:264 self.assertEqual(int(float(int(value))), value)265 # test round-half-to-even266 self.assertEqual(int(float(2**53+1)), 2**53)267 self.assertEqual(int(float(2**53+2)), 2**53+2)268 self.assertEqual(int(float(2**53+3)), 2**53+4)269 self.assertEqual(int(float(2**53+5)), 2**53+4)270 self.assertEqual(int(float(2**53+6)), 2**53+6)271 self.assertEqual(int(float(2**53+7)), 2**53+8)272 self.assertEqual(int(float(-2**53-1)), -2**53)273 self.assertEqual(int(float(-2**53-2)), -2**53-2)274 self.assertEqual(int(float(-2**53-3)), -2**53-4)275 self.assertEqual(int(float(-2**53-5)), -2**53-4)276 self.assertEqual(int(float(-2**53-6)), -2**53-6)277 self.assertEqual(int(float(-2**53-7)), -2**53-8)278 self.assertEqual(int(float(2**54-2)), 2**54-2)279 self.assertEqual(int(float(2**54-1)), 2**54)280 self.assertEqual(int(float(2**54+2)), 2**54)281 self.assertEqual(int(float(2**54+3)), 2**54+4)282 self.assertEqual(int(float(2**54+5)), 2**54+4)283 self.assertEqual(int(float(2**54+6)), 2**54+8)284 self.assertEqual(int(float(2**54+10)), 2**54+8)285 self.assertEqual(int(float(2**54+11)), 2**54+12)286 def test_intconversion(self):287 # Test __int__()288 class ClassicMissingMethods:289 pass290 self.assertRaises(AttributeError, int, ClassicMissingMethods())291 class MissingMethods(object):292 pass293 self.assertRaises(TypeError, int, MissingMethods())294 class Foo0:295 def __int__(self):296 return 42297 class Foo1(object):298 def __int__(self):299 return 42300 class Foo2(int):301 def __int__(self):302 return 42303 class Foo3(int):304 def __int__(self):305 return self306 class Foo4(int):307 def __int__(self):308 return 42L309 class Foo5(int):310 def __int__(self):311 return 42.312 self.assertEqual(int(Foo0()), 42)313 self.assertEqual(int(Foo1()), 42)314 self.assertEqual(int(Foo2()), 42)315 self.assertEqual(int(Foo3()), 0)316 self.assertEqual(int(Foo4()), 42L)317 self.assertRaises(TypeError, int, Foo5())318 class Classic:319 pass320 for base in (object, Classic):321 class IntOverridesTrunc(base):322 def __int__(self):323 return 42324 def __trunc__(self):325 return -12326 self.assertEqual(int(IntOverridesTrunc()), 42)327 class JustTrunc(base):328 def __trunc__(self):329 return 42330 self.assertEqual(int(JustTrunc()), 42)331 for trunc_result_base in (object, Classic):332 class Integral(trunc_result_base):333 def __int__(self):334 return 42335 class TruncReturnsNonInt(base):336 def __trunc__(self):337 return Integral()338 self.assertEqual(int(TruncReturnsNonInt()), 42)339 class NonIntegral(trunc_result_base):340 def __trunc__(self):341 # Check that we avoid infinite recursion.342 return NonIntegral()343 class TruncReturnsNonIntegral(base):344 def __trunc__(self):345 return NonIntegral()346 try:347 int(TruncReturnsNonIntegral())348 except TypeError as e:349 self.assertEqual(str(e),350 "__trunc__ returned non-Integral"351 " (type NonIntegral)")352 else:353 self.fail("Failed to raise TypeError with %s" %354 ((base, trunc_result_base),))355def test_main():356 run_unittest(IntTestCases)357if __name__ == "__main__":...
test_int_literal.py
Source:test_int_literal.py
...5from test import test_support6class TestHexOctBin(unittest.TestCase):7 def test_hex_baseline(self):8 # A few upper/lowercase tests9 self.assertEqual(0x0, 0X0)10 self.assertEqual(0x1, 0X1)11 self.assertEqual(0x123456789abcdef, 0X123456789abcdef)12 # Baseline tests13 self.assertEqual(0x0, 0)14 self.assertEqual(0x10, 16)15 self.assertEqual(0x7fffffff, 2147483647)16 self.assertEqual(0x7fffffffffffffff, 9223372036854775807)17 # Ditto with a minus sign and parentheses18 self.assertEqual(-(0x0), 0)19 self.assertEqual(-(0x10), -16)20 self.assertEqual(-(0x7fffffff), -2147483647)21 self.assertEqual(-(0x7fffffffffffffff), -9223372036854775807)22 # Ditto with a minus sign and NO parentheses23 self.assertEqual(-0x0, 0)24 self.assertEqual(-0x10, -16)25 self.assertEqual(-0x7fffffff, -2147483647)26 self.assertEqual(-0x7fffffffffffffff, -9223372036854775807)27 def test_hex_unsigned(self):28 # Positive constants29 self.assertEqual(0x80000000, 2147483648L)30 self.assertEqual(0xffffffff, 4294967295L)31 # Ditto with a minus sign and parentheses32 self.assertEqual(-(0x80000000), -2147483648L)33 self.assertEqual(-(0xffffffff), -4294967295L)34 # Ditto with a minus sign and NO parentheses35 # This failed in Python 2.2 through 2.2.2 and in 2.3a136 self.assertEqual(-0x80000000, -2147483648L)37 self.assertEqual(-0xffffffff, -4294967295L)38 # Positive constants39 self.assertEqual(0x8000000000000000, 9223372036854775808L)40 self.assertEqual(0xffffffffffffffff, 18446744073709551615L)41 # Ditto with a minus sign and parentheses42 self.assertEqual(-(0x8000000000000000), -9223372036854775808L)43 self.assertEqual(-(0xffffffffffffffff), -18446744073709551615L)44 # Ditto with a minus sign and NO parentheses45 # This failed in Python 2.2 through 2.2.2 and in 2.3a146 self.assertEqual(-0x8000000000000000, -9223372036854775808L)47 self.assertEqual(-0xffffffffffffffff, -18446744073709551615L)48 def test_oct_baseline(self):49 # Baseline tests50 self.assertEqual(00, 0)51 self.assertEqual(020, 16)52 self.assertEqual(017777777777, 2147483647)53 self.assertEqual(0777777777777777777777, 9223372036854775807)54 # Ditto with a minus sign and parentheses55 self.assertEqual(-(00), 0)56 self.assertEqual(-(020), -16)57 self.assertEqual(-(017777777777), -2147483647)58 self.assertEqual(-(0777777777777777777777), -9223372036854775807)59 # Ditto with a minus sign and NO parentheses60 self.assertEqual(-00, 0)61 self.assertEqual(-020, -16)62 self.assertEqual(-017777777777, -2147483647)63 self.assertEqual(-0777777777777777777777, -9223372036854775807)64 def test_oct_baseline_new(self):65 # A few upper/lowercase tests66 self.assertEqual(0o0, 0O0)67 self.assertEqual(0o1, 0O1)68 self.assertEqual(0o1234567, 0O1234567)69 # Baseline tests70 self.assertEqual(0o0, 0)71 self.assertEqual(0o20, 16)72 self.assertEqual(0o17777777777, 2147483647)73 self.assertEqual(0o777777777777777777777, 9223372036854775807)74 # Ditto with a minus sign and parentheses75 self.assertEqual(-(0o0), 0)76 self.assertEqual(-(0o20), -16)77 self.assertEqual(-(0o17777777777), -2147483647)78 self.assertEqual(-(0o777777777777777777777), -9223372036854775807)79 # Ditto with a minus sign and NO parentheses80 self.assertEqual(-0o0, 0)81 self.assertEqual(-0o20, -16)82 self.assertEqual(-0o17777777777, -2147483647)83 self.assertEqual(-0o777777777777777777777, -9223372036854775807)84 def test_oct_unsigned(self):85 # Positive constants86 self.assertEqual(020000000000, 2147483648L)87 self.assertEqual(037777777777, 4294967295L)88 # Ditto with a minus sign and parentheses89 self.assertEqual(-(020000000000), -2147483648L)90 self.assertEqual(-(037777777777), -4294967295L)91 # Ditto with a minus sign and NO parentheses92 # This failed in Python 2.2 through 2.2.2 and in 2.3a193 self.assertEqual(-020000000000, -2147483648L)94 self.assertEqual(-037777777777, -4294967295L)95 # Positive constants96 self.assertEqual(01000000000000000000000, 9223372036854775808L)97 self.assertEqual(01777777777777777777777, 18446744073709551615L)98 # Ditto with a minus sign and parentheses99 self.assertEqual(-(01000000000000000000000), -9223372036854775808L)100 self.assertEqual(-(01777777777777777777777), -18446744073709551615L)101 # Ditto with a minus sign and NO parentheses102 # This failed in Python 2.2 through 2.2.2 and in 2.3a1103 self.assertEqual(-01000000000000000000000, -9223372036854775808L)104 self.assertEqual(-01777777777777777777777, -18446744073709551615L)105 def test_oct_unsigned_new(self):106 # Positive constants107 self.assertEqual(0o20000000000, 2147483648L)108 self.assertEqual(0o37777777777, 4294967295L)109 # Ditto with a minus sign and parentheses110 self.assertEqual(-(0o20000000000), -2147483648L)111 self.assertEqual(-(0o37777777777), -4294967295L)112 # Ditto with a minus sign and NO parentheses113 # This failed in Python 2.2 through 2.2.2 and in 2.3a1114 self.assertEqual(-0o20000000000, -2147483648L)115 self.assertEqual(-0o37777777777, -4294967295L)116 # Positive constants117 self.assertEqual(0o1000000000000000000000, 9223372036854775808L)118 self.assertEqual(0o1777777777777777777777, 18446744073709551615L)119 # Ditto with a minus sign and parentheses120 self.assertEqual(-(0o1000000000000000000000), -9223372036854775808L)121 self.assertEqual(-(0o1777777777777777777777), -18446744073709551615L)122 # Ditto with a minus sign and NO parentheses123 # This failed in Python 2.2 through 2.2.2 and in 2.3a1124 self.assertEqual(-0o1000000000000000000000, -9223372036854775808L)125 self.assertEqual(-0o1777777777777777777777, -18446744073709551615L)126 def test_bin_baseline(self):127 # A few upper/lowercase tests128 self.assertEqual(0b0, 0B0)129 self.assertEqual(0b1, 0B1)130 self.assertEqual(0b10101010101, 0B10101010101)131 # Baseline tests132 self.assertEqual(0b0, 0)133 self.assertEqual(0b10000, 16)134 self.assertEqual(0b1111111111111111111111111111111, 2147483647)135 self.assertEqual(0b111111111111111111111111111111111111111111111111111111111111111, 9223372036854775807)136 # Ditto with a minus sign and parentheses137 self.assertEqual(-(0b0), 0)138 self.assertEqual(-(0b10000), -16)139 self.assertEqual(-(0b1111111111111111111111111111111), -2147483647)140 self.assertEqual(-(0b111111111111111111111111111111111111111111111111111111111111111), -9223372036854775807)141 # Ditto with a minus sign and NO parentheses142 self.assertEqual(-0b0, 0)143 self.assertEqual(-0b10000, -16)144 self.assertEqual(-0b1111111111111111111111111111111, -2147483647)145 self.assertEqual(-0b111111111111111111111111111111111111111111111111111111111111111, -9223372036854775807)146 def test_bin_unsigned(self):147 # Positive constants148 self.assertEqual(0b10000000000000000000000000000000, 2147483648L)149 self.assertEqual(0b11111111111111111111111111111111, 4294967295L)150 # Ditto with a minus sign and parentheses151 self.assertEqual(-(0b10000000000000000000000000000000), -2147483648L)152 self.assertEqual(-(0b11111111111111111111111111111111), -4294967295L)153 # Ditto with a minus sign and NO parentheses154 # This failed in Python 2.2 through 2.2.2 and in 2.3a1155 self.assertEqual(-0b10000000000000000000000000000000, -2147483648L)156 self.assertEqual(-0b11111111111111111111111111111111, -4294967295L)157 # Positive constants158 self.assertEqual(0b1000000000000000000000000000000000000000000000000000000000000000, 9223372036854775808L)159 self.assertEqual(0b1111111111111111111111111111111111111111111111111111111111111111, 18446744073709551615L)160 # Ditto with a minus sign and parentheses161 self.assertEqual(-(0b1000000000000000000000000000000000000000000000000000000000000000), -9223372036854775808L)162 self.assertEqual(-(0b1111111111111111111111111111111111111111111111111111111111111111), -18446744073709551615L)163 # Ditto with a minus sign and NO parentheses164 # This failed in Python 2.2 through 2.2.2 and in 2.3a1165 self.assertEqual(-0b1000000000000000000000000000000000000000000000000000000000000000, -9223372036854775808L)166 self.assertEqual(-0b1111111111111111111111111111111111111111111111111111111111111111, -18446744073709551615L)167def test_main():168 test_support.run_unittest(TestHexOctBin)169if __name__ == "__main__":...
array_test.js
Source:array_test.js
...17 },18 19 testToArrayOnNodeList: function(){20 // direct HTML21 this.assertEqual(3, $A($('test_node').childNodes).length);22 23 // DOM24 var element = document.createElement('div');25 element.appendChild(document.createTextNode('22'));26 (2).times(function(){ element.appendChild(document.createElement('span')) });27 this.assertEqual(3, $A(element.childNodes).length);28 29 // HTML String30 element = document.createElement('div');31 $(element).update('22<span></span><span></span');32 this.assertEqual(3, $A(element.childNodes).length);33 },34 35 testClear: function(){36 this.assertEnumEqual([], [].clear());37 this.assertEnumEqual([], [1].clear());38 this.assertEnumEqual([], [1,2].clear());39 },40 41 testClone: function(){42 this.assertEnumEqual([], [].clone());43 this.assertEnumEqual([1], [1].clone());44 this.assertEnumEqual([1,2], [1,2].clone());45 this.assertEnumEqual([0,1,2], [0,1,2].clone());46 var a = [0,1,2];47 var b = a;48 this.assertIdentical(a, b);49 b = a.clone();50 this.assertNotIdentical(a, b);51 },52 53 testFirst: function(){54 this.assertUndefined([].first());55 this.assertEqual(1, [1].first());56 this.assertEqual(1, [1,2].first());57 },58 59 testLast: function(){60 this.assertUndefined([].last());61 this.assertEqual(1, [1].last());62 this.assertEqual(2, [1,2].last());63 },64 65 testCompact: function(){66 this.assertEnumEqual([], [].compact());67 this.assertEnumEqual([1,2,3], [1,2,3].compact());68 this.assertEnumEqual([0,1,2,3], [0,null,1,2,undefined,3].compact());69 this.assertEnumEqual([1,2,3], [null,1,2,3,null].compact());70 },71 72 testFlatten: function(){73 this.assertEnumEqual([], [].flatten());74 this.assertEnumEqual([1,2,3], [1,2,3].flatten());75 this.assertEnumEqual([1,2,3], [1,[[[2,3]]]].flatten());76 this.assertEnumEqual([1,2,3], [[1],[2],[3]].flatten());77 this.assertEnumEqual([1,2,3], [[[[[[[1]]]]]],2,3].flatten());78 },79 80 testIndexOf: function(){81 this.assertEqual(-1, [].indexOf(1));82 this.assertEqual(-1, [0].indexOf(1));83 this.assertEqual(0, [1].indexOf(1));84 this.assertEqual(1, [0,1,2].indexOf(1));85 this.assertEqual(0, [1,2,1].indexOf(1));86 this.assertEqual(2, [1,2,1].indexOf(1, -1));87 this.assertEqual(1, [undefined,null].indexOf(null));88 },89 testLastIndexOf: function(){90 this.assertEqual(-1,[].lastIndexOf(1));91 this.assertEqual(-1, [0].lastIndexOf(1));92 this.assertEqual(0, [1].lastIndexOf(1));93 this.assertEqual(2, [0,2,4,6].lastIndexOf(4));94 this.assertEqual(3, [4,4,2,4,6].lastIndexOf(4));95 this.assertEqual(3, [0,2,4,6].lastIndexOf(6,3));96 this.assertEqual(-1, [0,2,4,6].lastIndexOf(6,2));97 this.assertEqual(0, [6,2,4,6].lastIndexOf(6,2));98 99 var fixture = [1,2,3,4,3];100 this.assertEqual(4, fixture.lastIndexOf(3));101 this.assertEnumEqual([1,2,3,4,3],fixture);102 103 //tests from http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:lastIndexOf104 var array = [2, 5, 9, 2];105 this.assertEqual(3,array.lastIndexOf(2));106 this.assertEqual(-1,array.lastIndexOf(7));107 this.assertEqual(3,array.lastIndexOf(2,3));108 this.assertEqual(0,array.lastIndexOf(2,2));109 this.assertEqual(0,array.lastIndexOf(2,-2));110 this.assertEqual(3,array.lastIndexOf(2,-1));111 },112 113 testInspect: function(){114 this.assertEqual('[]',[].inspect());115 this.assertEqual('[1]',[1].inspect());116 this.assertEqual('[\'a\']',['a'].inspect());117 this.assertEqual('[\'a\', 1]',['a',1].inspect());118 },119 120 testIntersect: function(){121 this.assertEnumEqual([1,3], [1,1,3,5].intersect([1,2,3]));122 this.assertEnumEqual([1], [1,1].intersect([1,1]));123 this.assertEnumEqual([], [1,1,3,5].intersect([4]));124 this.assertEnumEqual([], [1].intersect(['1']));125 126 this.assertEnumEqual(127 ['B','C','D'], 128 $R('A','Z').toArray().intersect($R('B','D').toArray())129 );130 },131 132 testToJSON: function(){133 this.assertEqual('[]', [].toJSON());134 this.assertEqual('[\"a\"]', ['a'].toJSON());135 this.assertEqual('[\"a\", 1]', ['a', 1].toJSON());136 this.assertEqual('[\"a\", {\"b\": null}]', ['a', {'b': null}].toJSON());137 },138 139 testReduce: function(){140 this.assertUndefined([].reduce());141 this.assertNull([null].reduce());142 this.assertEqual(1, [1].reduce());143 this.assertEnumEqual([1,2,3], [1,2,3].reduce());144 this.assertEnumEqual([1,null,3], [1,null,3].reduce());145 },146 147 testReverse: function(){148 this.assertEnumEqual([], [].reverse());149 this.assertEnumEqual([1], [1].reverse());150 this.assertEnumEqual([2,1], [1,2].reverse());151 this.assertEnumEqual([3,2,1], [1,2,3].reverse());152 },153 154 testSize: function(){155 this.assertEqual(4, [0, 1, 2, 3].size());156 this.assertEqual(0, [].size());157 },158 testUniq: function(){159 this.assertEnumEqual([1], [1, 1, 1].uniq());160 this.assertEnumEqual([1], [1].uniq());161 this.assertEnumEqual([], [].uniq());162 this.assertEnumEqual([0, 1, 2, 3], [0, 1, 2, 2, 3, 0, 2].uniq());163 this.assertEnumEqual([0, 1, 2, 3], [0, 0, 1, 1, 2, 3, 3, 3].uniq(true));164 },165 166 testWithout: function(){167 this.assertEnumEqual([], [].without(0));168 this.assertEnumEqual([], [0].without(0));169 this.assertEnumEqual([1], [0,1].without(0));170 this.assertEnumEqual([1,2], [0,1,2].without(0));...
Using AI Code Generation
1const assert = require('chai').assert;2const head = require('../head');3describe("#head", () => {4 it("returns 1 for [1, 2, 3]", () => {5 assert.strictEqual(head([1, 2, 3]), 1);6 });7});8const head = function(array) {9 return array[0];10};11module.exports = head;12const assert = require('chai').assert;13const head = require('../head');14describe("#head", () => {15 it("returns '5' for ['5']", () => {16 assert.strictEqual(head(['5']), '5'); 17 });18});19const head = function(array) {20 return array[0];21};22module.exports = head;23const assert = require('chai').assert;24const head = require('../head');25describe("#head", () => {26 it("returns 'Hello' for ['Hello', 'Lighthouse', 'Labs']", () => {27 assert.strictEqual(head(["Hello", "Lighthouse", "Labs"]), "Hello"); 28 });29});30const head = function(array) {31 return array[0];32};33module.exports = head;34const assert = require('chai').assert;35const head = require('../head');36describe("#head", () => {37 it("returns '5' for ['5']", () => {38 assert.strictEqual(head(['5']), '5'); 39 });40});41const head = function(array) {42 return array[0];43};44module.exports = head;45const assert = require('chai').assert;46const head = require('../head');47describe("#head", () => {48 it("returns '5' for ['5']", () => {49 assert.strictEqual(head(['5']), '5'); 50 });51});52const head = function(array) {53 return array[0];54};55module.exports = head;56const assert = require('chai').assert;
Using AI Code Generation
1const assert = require('chai').assert;2const head = require('../head');3describe("#head", () => {4 it("returns 1 for [1, 2, 3]", () => {5 assert.strictEqual(head([1, 2, 3]), 1);6 });7 it("returns '5' for ['5']", () => {8 assert.strictEqual(head(['5']), '5'); 9 });10});11const head = function(array) {12 return array[0];13};14module.exports = head;15const assert = require('chai').assert;16const head = require('../head');17describe("#head", () => {18 it("returns 1 for [1, 2, 3]", () => {19 assert.strictEqual(head([1, 2, 3]), 1);20 });21 it("returns '5' for ['5']", () => {22 assert.strictEqual(head(['5']), '5'); 23 });24});25const tail = function(array) {26 let newArray = [];27 for (let i = 1; i < array.length; i++) {28 newArray.push(array[i]);29 }30 return newArray;31};32module.exports = tail;33const assert = require('chai').assert;34const tail = require('../tail');35describe("#tail", () => {36 it("returns [2, 3] for [1, 2, 3]", () => {37 assert.deepEqual(tail([1, 2, 3]), [2, 3]);38 });39 it("returns ['Lighthouse', 'Labs'] for ['Yo Yo', 'Lighthouse', 'Labs']", () => {40 assert.deepEqual(tail(['Yo Yo', 'Lighthouse', 'Labs']), ['Lighthouse', 'Labs']); 41 });42});43const middle = function(array) {44 let middle = [];45 if (array.length <= 2) {46 return middle;47 } else if (array.length % 2 === 0) {48 middle.push(array[(array.length / 2) - 1]);49 middle.push(array[array.length / 2]);50 } else {51 middle.push(array[Math.floor(array.length / 2)]);52 }53 return middle;54};55module.exports = middle;
Using AI Code Generation
1const assert = require('chai').assert;2const head = require('../head');3describe("#head", () => {4 it("returns 1 for [1, 2, 3]", () => {5 assert.strictEqual(head([1, 2, 3]), 1);6 });7 it("returns '5' for ['5']", () => {8 assert.strictEqual(head(['5']), '5'); 9 });10 it("returns 5 for [5,6,7]", () => {11 assert.strictEqual(head([5,6,7]), 5); 12 });13 it("returns 'Hello' for ['Hello', 'Lighthouse', 'Labs']", () => {14 assert.strictEqual(head(["Hello", "Lighthouse", "Labs"]), "Hello"); 15 });16 it("returns undefined for []", () => {17 assert.strictEqual(head([]), undefined); 18 });19});20const head = function(array) {21 if (array.length === 0) {22 return undefined;23 }24 return array[0];25};26module.exports = head;27{28 "dependencies": {},29 "devDependencies": {30 },31 "scripts": {32 },33 "repository": {
Using AI Code Generation
1const assert = require('chai').assert;2const app = require('../app');3let sayHelloResult = app.sayHello();4let addNumbersResult = app.addNumbers(5,5);5describe('App', function(){6 describe('sayHello()', function(){7 it('sayHello should return hello', function(){8 assert.equal(sayHelloResult, 'hello');9 });10 it('sayHello should return type string', function(){11 assert.typeOf(sayHelloResult, 'string');12 });13 });14 describe('addNumbers()', function(){15 it('addNumbers should be above 5', function(){16 assert.isAbove(addNumbersResult, 5);17 });18 it('addNumbers should return type number', function(){19 assert.typeOf(addNumbersResult, 'number');20 });21 });22});23module.exports = {24 sayHello: function(){25 return 'hello';26 },27 addNumbers: function(value1, value2){28 return value1 + value2;29 }30};31{32 "scripts": {33 },34 "dependencies": {35 }36}
Using AI Code Generation
1const assert = require('chai').assert;2const { sum, isOddOrEven } = require('./mathEnforcer');3describe('mathEnforcer', () => {4 describe('sum', () => {5 it('should return undefined if the first param is not a number', () => {6 assert.isUndefined(sum('1', 1));7 });8 it('should return undefined if the second param is not a number', () => {9 assert.isUndefined(sum(1, '1'));10 });11 it('should return undefined if the both params are not a number', () => {12 assert.isUndefined(sum('1', '1'));13 });14 it('should return correct result if the params are numbers', () => {15 assert.equal(sum(1, 1), 2);16 });17 it('should return correct result if the params are negative numbers', () => {18 assert.equal(sum(-1, -1), -2);19 });20 it('should return correct result if the params are floating point numbers', () => {21 assert.equal(sum(1.1, 1.1), 2.2);22 });23 });24 describe('subtract', () => {25 it('should return undefined if the first param is not a number', () => {26 assert.isUndefined(subtract('1', 1));27 });28 it('should return undefined if the second param is not a number', () => {29 assert.isUndefined(subtract(1, '1'));30 });31 it('should return undefined if the both params are not a number', () => {32 assert.isUndefined(subtract('1', '1'));33 });34 it('should return correct result if the params are numbers', () => {35 assert.equal(subtract(1, 1), 0);36 });37 it('should return correct result if the params are negative numbers', () => {38 assert.equal(subtract(-1, -1), 0);39 });40 it('should return correct result if the params are floating point numbers', () => {41 assert.equal(subtract(1.1, 1.1), 0);42 });43 });44 describe('sum', () => {45 it('should return undefined if the first param is not a number', () => {46 assert.isUndefined(sum('1', 1));47 });48 it('should return undefined if the second param is
Using AI Code Generation
1var assert = require('chai').assert;2var myApp = require('../app/library.js');3describe("Compute the sum of all the numbers in an array", function() {4 it("should return 10 for [1,2,3,4]", function() {5 assert.equal(myApp.sum([1,2,3,4]), 10);6 });7 it("should return 15 for [5,6,4]", function() {8 assert.equal(myApp.sum([5,6,4]), 15);9 });10 it("should return 0 for []", function() {11 assert.equal(myApp.sum([]), 0);12 });13 it("should return 1 for [1]", function() {14 assert.equal(myApp.sum([1]), 1);15 });16 it("should return 0 for ['a','b','c']", function() {17 assert.equal(myApp.sum(['a','b','c']), 0);18 });19 it("should return 0 for ['1','2','3']", function() {20 assert.equal(myApp.sum(['1','2','3']), 0);21 });22 it("should return 0 for [1,2,'3']", function() {23 assert.equal(myApp.sum([1,2,'3']), 0);24 });25 it("should return 0 for ['1',2,3]", function() {26 assert.equal(myApp.sum(['1',2,3]), 0);27 });28});29module.exports = {30 sum: function(numbers) {31 var sum = 0;32 for (var i = 0; i < numbers.length; i++) {33 if (typeof numbers[i] != 'number') {34 return 0;35 }36 sum += numbers[i];37 }38 return sum;39 }40};
Using AI Code Generation
1const assert = require("chai").assert;2const myFunc = require("../index");3describe("myFunc", function() {4 it("should return the sum of the two numbers", function() {5 let result = myFunc(1, 2);6 assert.equal(result, 3);7 });8});9function myFunc(num1, num2) {10 return num1 + num2;11}12module.exports = myFunc;13{14 "scripts": {15 },16 "dependencies": {17 }18}19const expect = require("chai").expect;20const myFunc = require("../index");21describe("myFunc", function() {22 it("should return the sum of the two numbers", function() {23 let result = myFunc(1, 2);24 expect(result).to.equal(3);25 });26});27function myFunc(num1, num2) {28 return num1 + num2;29}30module.exports = myFunc;31{32 "scripts": {33 },
Using AI Code Generation
1var assert = require('chai').assert;2var myApp = require('../app/library.js');3describe("Days of the week", function() {4 it("should return the day of the week for the date 1/1/2017", function() {5 assert.equal(myApp.dayOfTheWeek(new Date('1/1/2017')), 'Saturday');6 });7 it("should return the day of the week for the date 1/2/2017", function() {8 assert.equal(myApp.dayOfTheWeek(new Date('1/2/2017')), 'Sunday');9 });10 it("should return the day of the week for the date 1/3/2017", function() {11 assert.equal(myApp.dayOfTheWeek(new Date('1/3/2017')), 'Monday');12 });13 it("should return the day of the week for the date 1/4/2017", function() {14 assert.equal(myApp.dayOfTheWeek(new Date('1/4/2017')), 'Tuesday');15 });16 it("should return the day of the week for the date 1/5/2017", function() {17 assert.equal(myApp.dayOfTheWeek(new Date('1/5/2017')), 'Wednesday');18 });19 it("should return the day of the week for the date 1/6/2017", function() {20 assert.equal(myApp.dayOfTheWeek(new Date('1/6/2017')), 'Thursday');21 });22 it("should return the day of the week for the date 1/7/2017", function() {23 assert.equal(myApp.dayOfTheWeek(new Date('1/7/2017')), 'Friday');24 });25});26module.exports = {27 dayOfTheWeek: function(date) {28 var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];29 return days[date.getDay()];30 }31}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!