EngineTests.cs 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624
  1. using System;
  2. using System.Globalization;
  3. using System.IO;
  4. using System.Reflection;
  5. using System.Threading;
  6. using Jint.Native.Number;
  7. using Jint.Parser;
  8. using Jint.Parser.Ast;
  9. using Jint.Runtime;
  10. using Jint.Runtime.Debugger;
  11. using Xunit;
  12. using System.Net;
  13. namespace Jint.Tests.Runtime
  14. {
  15. public class EngineTests : IDisposable
  16. {
  17. private readonly Engine _engine;
  18. private int countBreak = 0;
  19. private StepMode stepMode;
  20. public EngineTests()
  21. {
  22. _engine = new Engine()
  23. .SetValue("log", new Action<object>(Console.WriteLine))
  24. .SetValue("assert", new Action<bool>(Assert.True))
  25. ;
  26. }
  27. void IDisposable.Dispose()
  28. {
  29. }
  30. private void RunTest(string source)
  31. {
  32. _engine.Execute(source);
  33. }
  34. [Theory]
  35. [InlineData("Scratch.js")]
  36. public void ShouldInterpretScriptFile(string file)
  37. {
  38. const string prefix = "Jint.Tests.Runtime.Scripts.";
  39. var assembly = Assembly.GetExecutingAssembly();
  40. var scriptPath = prefix + file;
  41. using (var stream = assembly.GetManifestResourceStream(scriptPath))
  42. if (stream != null)
  43. using (var sr = new StreamReader(stream))
  44. {
  45. var source = sr.ReadToEnd();
  46. RunTest(source);
  47. }
  48. }
  49. [Theory]
  50. [InlineData(42d, "42")]
  51. [InlineData("Hello", "'Hello'")]
  52. public void ShouldInterpretLiterals(object expected, string source)
  53. {
  54. var engine = new Engine();
  55. var result = engine.Execute(source).GetCompletionValue().ToObject();
  56. Assert.Equal(expected, result);
  57. }
  58. [Fact]
  59. public void ShouldInterpretVariableDeclaration()
  60. {
  61. var engine = new Engine();
  62. var result = engine
  63. .Execute("var foo = 'bar'; foo;")
  64. .GetCompletionValue()
  65. .ToObject();
  66. Assert.Equal("bar", result);
  67. }
  68. [Theory]
  69. [InlineData(4d, "1 + 3")]
  70. [InlineData(-2d, "1 - 3")]
  71. [InlineData(3d, "1 * 3")]
  72. [InlineData(2d, "6 / 3")]
  73. [InlineData(9d, "15 & 9")]
  74. [InlineData(15d, "15 | 9")]
  75. [InlineData(6d, "15 ^ 9")]
  76. [InlineData(36d, "9 << 2")]
  77. [InlineData(2d, "9 >> 2")]
  78. [InlineData(4d, "19 >>> 2")]
  79. public void ShouldInterpretBinaryExpression(object expected, string source)
  80. {
  81. var engine = new Engine();
  82. var result = engine.Execute(source).GetCompletionValue().ToObject();
  83. Assert.Equal(expected, result);
  84. }
  85. [Theory]
  86. [InlineData(-59d, "~58")]
  87. [InlineData(58d, "~~58")]
  88. public void ShouldInterpretUnaryExpression(object expected, string source)
  89. {
  90. var engine = new Engine();
  91. var result = engine.Execute(source).GetCompletionValue().ToObject();
  92. Assert.Equal(expected, result);
  93. }
  94. [Fact]
  95. public void ShouldEvaluateHasOwnProperty()
  96. {
  97. RunTest(@"
  98. var x = {};
  99. x.Bar = 42;
  100. assert(x.hasOwnProperty('Bar'));
  101. ");
  102. }
  103. [Fact]
  104. public void FunctionConstructorsShouldCreateNewObjects()
  105. {
  106. RunTest(@"
  107. var Vehicle = function () {};
  108. var vehicle = new Vehicle();
  109. assert(vehicle != undefined);
  110. ");
  111. }
  112. [Fact]
  113. public void NewObjectsInheritFunctionConstructorProperties()
  114. {
  115. RunTest(@"
  116. var Vehicle = function () {};
  117. var vehicle = new Vehicle();
  118. Vehicle.prototype.wheelCount = 4;
  119. assert(vehicle.wheelCount == 4);
  120. assert((new Vehicle()).wheelCount == 4);
  121. ");
  122. }
  123. [Fact]
  124. public void PrototypeFunctionIsInherited()
  125. {
  126. RunTest(@"
  127. function Body(mass){
  128. this.mass = mass;
  129. }
  130. Body.prototype.offsetMass = function(dm) {
  131. this.mass += dm;
  132. return this;
  133. }
  134. var b = new Body(36);
  135. b.offsetMass(6);
  136. assert(b.mass == 42);
  137. ");
  138. }
  139. [Fact]
  140. public void FunctionConstructorCall()
  141. {
  142. RunTest(@"
  143. function Body(mass){
  144. this.mass = mass;
  145. }
  146. var john = new Body(36);
  147. assert(john.mass == 36);
  148. ");
  149. }
  150. [Fact]
  151. public void NewObjectsShouldUsePrivateProperties()
  152. {
  153. RunTest(@"
  154. var Vehicle = function (color) {
  155. this.color = color;
  156. };
  157. var vehicle = new Vehicle('tan');
  158. assert(vehicle.color == 'tan');
  159. ");
  160. }
  161. [Fact]
  162. public void FunctionConstructorsShouldDefinePrototypeChain()
  163. {
  164. RunTest(@"
  165. function Vehicle() {};
  166. var vehicle = new Vehicle();
  167. assert(vehicle.hasOwnProperty('constructor') == false);
  168. ");
  169. }
  170. [Fact]
  171. public void NewObjectsConstructorIsObject()
  172. {
  173. RunTest(@"
  174. var o = new Object();
  175. assert(o.constructor == Object);
  176. ");
  177. }
  178. [Fact]
  179. public void NewObjectsIntanceOfConstructorObject()
  180. {
  181. RunTest(@"
  182. var o = new Object();
  183. assert(o instanceof Object);
  184. ");
  185. }
  186. [Fact]
  187. public void NewObjectsConstructorShouldBeConstructorObject()
  188. {
  189. RunTest(@"
  190. var Vehicle = function () {};
  191. var vehicle = new Vehicle();
  192. assert(vehicle.constructor == Vehicle);
  193. ");
  194. }
  195. [Fact]
  196. public void NewObjectsIntanceOfConstructorFunction()
  197. {
  198. RunTest(@"
  199. var Vehicle = function () {};
  200. var vehicle = new Vehicle();
  201. assert(vehicle instanceof Vehicle);
  202. ");
  203. }
  204. [Fact]
  205. public void ShouldEvaluateForLoops()
  206. {
  207. RunTest(@"
  208. var foo = 0;
  209. for (var i = 0; i < 5; i++) {
  210. foo += i;
  211. }
  212. assert(foo == 10);
  213. ");
  214. }
  215. [Fact]
  216. public void ShouldEvaluateRecursiveFunctions()
  217. {
  218. RunTest(@"
  219. function fib(n) {
  220. if (n < 2) {
  221. return n;
  222. }
  223. return fib(n - 1) + fib(n - 2);
  224. }
  225. var result = fib(6);
  226. assert(result == 8);
  227. ");
  228. }
  229. [Fact]
  230. public void ShouldAccessObjectProperties()
  231. {
  232. RunTest(@"
  233. var o = {};
  234. o.Foo = 'bar';
  235. o.Baz = 42;
  236. o.Blah = o.Foo + o.Baz;
  237. assert(o.Blah == 'bar42');
  238. ");
  239. }
  240. [Fact]
  241. public void ShouldConstructArray()
  242. {
  243. RunTest(@"
  244. var o = [];
  245. assert(o.length == 0);
  246. ");
  247. }
  248. [Fact]
  249. public void ArrayPushShouldIncrementLength()
  250. {
  251. RunTest(@"
  252. var o = [];
  253. o.push(1);
  254. assert(o.length == 1);
  255. ");
  256. }
  257. [Fact]
  258. public void ArrayFunctionInitializesLength()
  259. {
  260. RunTest(@"
  261. assert(Array(3).length == 3);
  262. assert(Array('3').length == 1);
  263. ");
  264. }
  265. [Fact]
  266. public void ArrayIndexerIsAssigned()
  267. {
  268. RunTest(@"
  269. var n = 8;
  270. var o = Array(n);
  271. for (var i = 0; i < n; i++) o[i] = i;
  272. assert(o[0] == 0);
  273. assert(o[7] == 7);
  274. ");
  275. }
  276. [Fact]
  277. public void ArrayPopShouldDecrementLength()
  278. {
  279. RunTest(@"
  280. var o = [42, 'foo'];
  281. var pop = o.pop();
  282. assert(o.length == 1);
  283. assert(pop == 'foo');
  284. ");
  285. }
  286. [Fact]
  287. public void ArrayConstructor()
  288. {
  289. RunTest(@"
  290. var o = [];
  291. assert(o.constructor == Array);
  292. ");
  293. }
  294. [Fact]
  295. public void DateConstructor()
  296. {
  297. RunTest(@"
  298. var o = new Date();
  299. assert(o.constructor == Date);
  300. assert(o.hasOwnProperty('constructor') == false);
  301. ");
  302. }
  303. [Fact]
  304. public void ShouldConvertDateToNumber()
  305. {
  306. RunTest(@"
  307. assert(Number(new Date(0)) === 0);
  308. ");
  309. }
  310. [Fact]
  311. public void DatePrimitiveValueShouldBeNaN()
  312. {
  313. RunTest(@"
  314. assert(isNaN(Date.prototype.valueOf()));
  315. ");
  316. }
  317. [Fact]
  318. public void MathObjectIsDefined()
  319. {
  320. RunTest(@"
  321. var o = Math.abs(-1)
  322. assert(o == 1);
  323. ");
  324. }
  325. [Fact]
  326. public void VoidShouldReturnUndefined()
  327. {
  328. RunTest(@"
  329. assert(void 0 === undefined);
  330. var x = '1';
  331. assert(void x === undefined);
  332. x = 'x';
  333. assert (isNaN(void x) === true);
  334. x = new String('-1');
  335. assert (void x === undefined);
  336. ");
  337. }
  338. [Fact]
  339. public void TypeofObjectShouldReturnString()
  340. {
  341. RunTest(@"
  342. assert(typeof x === 'undefined');
  343. assert(typeof 0 === 'number');
  344. var x = 0;
  345. assert (typeof x === 'number');
  346. var x = new Object();
  347. assert (typeof x === 'object');
  348. ");
  349. }
  350. [Fact]
  351. public void MathAbsReturnsAbsolute()
  352. {
  353. RunTest(@"
  354. assert(1 == Math.abs(-1));
  355. ");
  356. }
  357. [Fact]
  358. public void NaNIsNan()
  359. {
  360. RunTest(@"
  361. var x = NaN;
  362. assert(isNaN(NaN));
  363. assert(isNaN(Math.abs(x)));
  364. ");
  365. }
  366. [Fact]
  367. public void ToNumberHandlesStringObject()
  368. {
  369. RunTest(@"
  370. x = new String('1');
  371. x *= undefined;
  372. assert(isNaN(x));
  373. ");
  374. }
  375. [Fact]
  376. public void FunctionScopesAreChained()
  377. {
  378. RunTest(@"
  379. var x = 0;
  380. function f1(){
  381. function f2(){
  382. return x;
  383. };
  384. return f2();
  385. var x = 1;
  386. }
  387. assert(f1() === undefined);
  388. ");
  389. }
  390. [Fact]
  391. public void EvalFunctionParseAndExecuteCode()
  392. {
  393. RunTest(@"
  394. var x = 0;
  395. eval('assert(x == 0)');
  396. ");
  397. }
  398. [Fact]
  399. public void ForInStatement()
  400. {
  401. RunTest(@"
  402. var x, y, str = '';
  403. for(var z in this) {
  404. str += z;
  405. }
  406. assert(str == 'xystrz');
  407. ");
  408. }
  409. [Fact]
  410. public void WithStatement()
  411. {
  412. RunTest(@"
  413. with (Math) {
  414. assert(cos(0) == 1);
  415. }
  416. ");
  417. }
  418. [Fact]
  419. public void ObjectExpression()
  420. {
  421. RunTest(@"
  422. var o = { x: 1 };
  423. assert(o.x == 1);
  424. ");
  425. }
  426. [Fact]
  427. public void StringFunctionCreatesString()
  428. {
  429. RunTest(@"
  430. assert(String(NaN) === 'NaN');
  431. ");
  432. }
  433. [Fact]
  434. public void ScopeChainInWithStatement()
  435. {
  436. RunTest(@"
  437. var x = 0;
  438. var myObj = {x : 'obj'};
  439. function f1(){
  440. var x = 1;
  441. function f2(){
  442. with(myObj){
  443. return x;
  444. }
  445. };
  446. return f2();
  447. }
  448. assert(f1() === 'obj');
  449. ");
  450. }
  451. [Fact]
  452. public void TryCatchBlockStatement()
  453. {
  454. RunTest(@"
  455. var x, y, z;
  456. try {
  457. x = 1;
  458. throw new TypeError();
  459. x = 2;
  460. }
  461. catch(e) {
  462. assert(x == 1);
  463. assert(e instanceof TypeError);
  464. y = 1;
  465. }
  466. finally {
  467. assert(x == 1);
  468. z = 1;
  469. }
  470. assert(x == 1);
  471. assert(y == 1);
  472. assert(z == 1);
  473. ");
  474. }
  475. [Fact]
  476. public void FunctionsCanBeAssigned()
  477. {
  478. RunTest(@"
  479. var sin = Math.sin;
  480. assert(sin(0) == 0);
  481. ");
  482. }
  483. [Fact]
  484. public void FunctionArgumentsIsDefined()
  485. {
  486. RunTest(@"
  487. function f() {
  488. assert(arguments.length > 0);
  489. }
  490. f(42);
  491. ");
  492. }
  493. [Fact]
  494. public void PrimitiveValueFunctions()
  495. {
  496. RunTest(@"
  497. var s = (1).toString();
  498. assert(s == '1');
  499. ");
  500. }
  501. [Theory]
  502. [InlineData(true, "'ab' == 'a' + 'b'")]
  503. public void OperatorsPrecedence(object expected, string source)
  504. {
  505. var engine = new Engine();
  506. var result = engine.Execute(source).GetCompletionValue().ToObject();
  507. Assert.Equal(expected, result);
  508. }
  509. [Fact]
  510. public void FunctionPrototypeShouldHaveApplyMethod()
  511. {
  512. RunTest(@"
  513. var numbers = [5, 6, 2, 3, 7];
  514. var max = Math.max.apply(null, numbers);
  515. assert(max == 7);
  516. ");
  517. }
  518. [Theory]
  519. [InlineData(double.NaN, "parseInt(NaN)")]
  520. [InlineData(double.NaN, "parseInt(null)")]
  521. [InlineData(double.NaN, "parseInt(undefined)")]
  522. [InlineData(double.NaN, "parseInt(new Boolean(true))")]
  523. [InlineData(double.NaN, "parseInt(Infinity)")]
  524. [InlineData(-1d, "parseInt(-1)")]
  525. [InlineData(-1d, "parseInt('-1')")]
  526. public void ShouldEvaluateParseInt(object expected, string source)
  527. {
  528. var engine = new Engine();
  529. var result = engine.Execute(source).GetCompletionValue().ToObject();
  530. Assert.Equal(expected, result);
  531. }
  532. [Fact]
  533. public void ShouldNotExecuteDebuggerStatement()
  534. {
  535. new Engine().Execute("debugger");
  536. }
  537. [Fact]
  538. public void ShouldThrowStatementCountOverflow()
  539. {
  540. Assert.Throws<StatementsCountOverflowException>(
  541. () => new Engine(cfg => cfg.MaxStatements(100)).Execute("while(true);")
  542. );
  543. }
  544. [Fact]
  545. public void ShouldThrowTimeout()
  546. {
  547. Assert.Throws<TimeoutException>(
  548. () => new Engine(cfg => cfg.TimeoutInterval(new TimeSpan(0, 0, 0, 0, 500))).Execute("while(true);")
  549. );
  550. }
  551. [Fact]
  552. public void CanDiscardRecursion()
  553. {
  554. var script = @"var factorial = function(n) {
  555. if (n>1) {
  556. return n * factorial(n - 1);
  557. }
  558. };
  559. var result = factorial(500);
  560. ";
  561. Assert.Throws<RecursionDepthOverflowException>(
  562. () => new Engine(cfg => cfg.LimitRecursion()).Execute(script)
  563. );
  564. }
  565. [Fact]
  566. public void ShouldDiscardHiddenRecursion()
  567. {
  568. var script = @"var renamedFunc;
  569. var exec = function(callback) {
  570. renamedFunc = callback;
  571. callback();
  572. };
  573. var result = exec(function() {
  574. renamedFunc();
  575. });
  576. ";
  577. Assert.Throws<RecursionDepthOverflowException>(
  578. () => new Engine(cfg => cfg.LimitRecursion()).Execute(script)
  579. );
  580. }
  581. [Fact]
  582. public void ShouldRecognizeAndDiscardChainedRecursion()
  583. {
  584. var script = @" var funcRoot, funcA, funcB, funcC, funcD;
  585. var funcRoot = function() {
  586. funcA();
  587. };
  588. var funcA = function() {
  589. funcB();
  590. };
  591. var funcB = function() {
  592. funcC();
  593. };
  594. var funcC = function() {
  595. funcD();
  596. };
  597. var funcD = function() {
  598. funcRoot();
  599. };
  600. funcRoot();
  601. ";
  602. Assert.Throws<RecursionDepthOverflowException>(
  603. () => new Engine(cfg => cfg.LimitRecursion()).Execute(script)
  604. );
  605. }
  606. [Fact]
  607. public void ShouldProvideCallChainWhenDiscardRecursion()
  608. {
  609. var script = @" var funcRoot, funcA, funcB, funcC, funcD;
  610. var funcRoot = function() {
  611. funcA();
  612. };
  613. var funcA = function() {
  614. funcB();
  615. };
  616. var funcB = function() {
  617. funcC();
  618. };
  619. var funcC = function() {
  620. funcD();
  621. };
  622. var funcD = function() {
  623. funcRoot();
  624. };
  625. funcRoot();
  626. ";
  627. RecursionDepthOverflowException exception = null;
  628. try
  629. {
  630. new Engine(cfg => cfg.LimitRecursion()).Execute(script);
  631. }
  632. catch (RecursionDepthOverflowException ex)
  633. {
  634. exception = ex;
  635. }
  636. Assert.NotNull(exception);
  637. Assert.Equal("funcRoot->funcA->funcB->funcC->funcD", exception.CallChain);
  638. Assert.Equal("funcRoot", exception.CallExpressionReference);
  639. }
  640. [Fact]
  641. public void ShouldAllowShallowRecursion()
  642. {
  643. var script = @"var factorial = function(n) {
  644. if (n>1) {
  645. return n * factorial(n - 1);
  646. }
  647. };
  648. var result = factorial(8);
  649. ";
  650. new Engine(cfg => cfg.LimitRecursion(20)).Execute(script);
  651. }
  652. [Fact]
  653. public void ShouldDiscardDeepRecursion()
  654. {
  655. var script = @"var factorial = function(n) {
  656. if (n>1) {
  657. return n * factorial(n - 1);
  658. }
  659. };
  660. var result = factorial(38);
  661. ";
  662. Assert.Throws<RecursionDepthOverflowException>(
  663. () => new Engine(cfg => cfg.LimitRecursion(20)).Execute(script)
  664. );
  665. }
  666. [Fact]
  667. public void ShouldConvertDoubleToStringWithoutLosingPrecision()
  668. {
  669. RunTest(@"
  670. assert(String(14.915832707045631) === '14.915832707045631');
  671. assert(String(-14.915832707045631) === '-14.915832707045631');
  672. assert(String(0.5) === '0.5');
  673. assert(String(0.00000001) === '1e-8');
  674. assert(String(0.000001) === '0.000001');
  675. assert(String(-1.0) === '-1');
  676. assert(String(30.0) === '30');
  677. assert(String(0.2388906159889881) === '0.2388906159889881');
  678. ");
  679. }
  680. [Fact]
  681. public void ShouldWriteNumbersUsingBases()
  682. {
  683. RunTest(@"
  684. assert(15.0.toString() === '15');
  685. assert(15.0.toString(2) === '1111');
  686. assert(15.0.toString(8) === '17');
  687. assert(15.0.toString(16) === 'f');
  688. assert(15.0.toString(17) === 'f');
  689. assert(15.0.toString(36) === 'f');
  690. assert(15.1.toString(36) === 'f.3llllllllkau6snqkpygsc3di');
  691. ");
  692. }
  693. [Fact]
  694. public void ShouldNotAlterSlashesInRegex()
  695. {
  696. RunTest(@"
  697. assert(new RegExp('/').toString() === '///');
  698. ");
  699. }
  700. [Fact]
  701. public void ShouldHandleEscapedSlashesInRegex()
  702. {
  703. RunTest(@"
  704. var regex = /[a-z]\/[a-z]/;
  705. assert(regex.test('a/b') === true);
  706. assert(regex.test('a\\/b') === false);
  707. ");
  708. }
  709. [Fact]
  710. public void ShouldComputeFractionInBase()
  711. {
  712. Assert.Equal("011", NumberPrototype.ToFractionBase(0.375, 2));
  713. Assert.Equal("14141414141414141414141414141414141414141414141414", NumberPrototype.ToFractionBase(0.375, 5));
  714. }
  715. [Fact]
  716. public void ShouldInvokeAFunctionValue()
  717. {
  718. RunTest(@"
  719. function add(x, y) { return x + y; }
  720. ");
  721. var add = _engine.GetValue("add");
  722. Assert.Equal(3, add.Invoke(1, 2));
  723. }
  724. [Fact]
  725. public void ShouldNotInvokeNonFunctionValue()
  726. {
  727. RunTest(@"
  728. var x= 10;
  729. ");
  730. var x = _engine.GetValue("x");
  731. Assert.Throws<ArgumentException>(() => x.Invoke(1, 2));
  732. }
  733. [Theory]
  734. [InlineData("0", 0, 16)]
  735. [InlineData("1", 1, 16)]
  736. [InlineData("100", 100, 10)]
  737. [InlineData("1100100", 100, 2)]
  738. [InlineData("2s", 100, 36)]
  739. [InlineData("2qgpckvng1s", 10000000000000000L, 36)]
  740. public void ShouldConvertNumbersToDifferentBase(string expected, long number, int radix)
  741. {
  742. var result = NumberPrototype.ToBase(number, radix);
  743. Assert.Equal(expected, result);
  744. }
  745. [Fact]
  746. public void JsonParserShouldParseNegativeNumber()
  747. {
  748. RunTest(@"
  749. var a = JSON.parse('{ ""x"":-1 }');
  750. assert(a.x === -1);
  751. var b = JSON.parse('{ ""x"": -1 }');
  752. assert(b.x === -1);
  753. ");
  754. }
  755. [Fact]
  756. public void JsonParserShouldDetectInvalidNegativeNumberSyntax()
  757. {
  758. RunTest(@"
  759. try {
  760. JSON.parse('{ ""x"": -.1 }'); // Not allowed
  761. assert(false);
  762. }
  763. catch(ex) {
  764. assert(ex instanceof SyntaxError);
  765. }
  766. ");
  767. RunTest(@"
  768. try {
  769. JSON.parse('{ ""x"": - 1 }'); // Not allowed
  770. assert(false);
  771. }
  772. catch(ex) {
  773. assert(ex instanceof SyntaxError);
  774. }
  775. ");
  776. }
  777. [Fact]
  778. public void ShouldBeCultureInvariant()
  779. {
  780. // decimals in french are separated by commas
  781. Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("fr-FR");
  782. var engine = new Engine();
  783. var result = engine.Execute("1.2 + 2.1").GetCompletionValue().AsNumber();
  784. Assert.Equal(3.3d, result);
  785. result = engine.Execute("JSON.parse('{\"x\" : 3.3}').x").GetCompletionValue().AsNumber();
  786. Assert.Equal(3.3d, result);
  787. }
  788. [Fact]
  789. public void ShouldGetTheLastSyntaxNode()
  790. {
  791. var engine = new Engine();
  792. engine.Execute("1.2");
  793. var result = engine.GetLastSyntaxNode();
  794. Assert.Equal(SyntaxNodes.Literal, result.Type);
  795. }
  796. [Fact]
  797. public void ShouldGetParseErrorLocation()
  798. {
  799. var engine = new Engine();
  800. try
  801. {
  802. engine.Execute("1.2+ new", new ParserOptions { Source = "jQuery.js" });
  803. }
  804. catch (ParserException e)
  805. {
  806. Assert.Equal(1, e.LineNumber);
  807. Assert.Equal(9, e.Column);
  808. Assert.Equal("jQuery.js", e.Source);
  809. }
  810. }
  811. [Fact]
  812. public void ParseShouldReturnNumber()
  813. {
  814. var engine = new Engine();
  815. var result = engine.Execute("Date.parse('1970-01-01');").GetCompletionValue().AsNumber();
  816. Assert.Equal(0, result);
  817. }
  818. [Fact]
  819. public void LocalDateTimeShouldNotLoseTimezone()
  820. {
  821. var date = new DateTime(2016, 1, 1, 13, 0, 0, DateTimeKind.Local);
  822. var engine = new Engine().SetValue("localDate", date);
  823. engine.Execute(@"localDate");
  824. var actual = engine.GetCompletionValue().AsDate().ToDateTime();
  825. Assert.Equal(date.ToUniversalTime(), actual.ToUniversalTime());
  826. Assert.Equal(date.ToLocalTime(), actual.ToLocalTime());
  827. }
  828. [Fact]
  829. public void UtcShouldUseUtc()
  830. {
  831. const string customName = "Custom Time";
  832. var customTimeZone = TimeZoneInfo.CreateCustomTimeZone(customName, new TimeSpan(7, 11, 0), customName, customName, customName, null, false);
  833. var engine = new Engine(cfg => cfg.LocalTimeZone(customTimeZone));
  834. var result = engine.Execute("Date.UTC(1970,0,1)").GetCompletionValue().AsNumber();
  835. Assert.Equal(0, result);
  836. }
  837. [Fact]
  838. public void ShouldUseLocalTimeZoneOverride()
  839. {
  840. const string customName = "Custom Time";
  841. var customTimeZone = TimeZoneInfo.CreateCustomTimeZone(customName, new TimeSpan(0, 11, 0), customName, customName, customName, null, false);
  842. var engine = new Engine(cfg => cfg.LocalTimeZone(customTimeZone));
  843. var epochGetLocalMinutes = engine.Execute("var d = new Date(0); d.getMinutes();").GetCompletionValue().AsNumber();
  844. Assert.Equal(11, epochGetLocalMinutes);
  845. var localEpochGetUtcMinutes = engine.Execute("var d = new Date(1970,0,1); d.getUTCMinutes();").GetCompletionValue().AsNumber();
  846. Assert.Equal(-11, localEpochGetUtcMinutes);
  847. var parseLocalEpoch = engine.Execute("Date.parse('January 1, 1970');").GetCompletionValue().AsNumber();
  848. Assert.Equal(-11 * 60 * 1000, parseLocalEpoch);
  849. var epochToLocalString = engine.Execute("var d = new Date(0); d.toString();").GetCompletionValue().AsString();
  850. Assert.Equal("Thu Jan 01 1970 00:11:00 GMT+00:11", epochToLocalString);
  851. var epochToUTCString = engine.Execute("var d = new Date(0); d.toUTCString();").GetCompletionValue().AsString();
  852. Assert.Equal("Thu Jan 01 1970 00:00:00 GMT", epochToUTCString);
  853. }
  854. [Theory]
  855. [InlineData("1970")]
  856. [InlineData("1970-01")]
  857. [InlineData("1970-01-01")]
  858. [InlineData("1970-01-01T00:00")]
  859. [InlineData("1970-01-01T00:00:00")]
  860. [InlineData("1970-01-01T00:00:00.000")]
  861. [InlineData("1970Z")]
  862. [InlineData("1970-1Z")]
  863. [InlineData("1970-1-1Z")]
  864. [InlineData("1970-1-1T0:0Z")]
  865. [InlineData("1970-1-1T0:0:0Z")]
  866. [InlineData("1970-1-1T0:0:0.0Z")]
  867. [InlineData("1970/1Z")]
  868. [InlineData("1970/1/1Z")]
  869. [InlineData("1970/1/1 0:0Z")]
  870. [InlineData("1970/1/1 0:0:0Z")]
  871. [InlineData("1970/1/1 0:0:0.0Z")]
  872. [InlineData("January 1, 1970 GMT")]
  873. [InlineData("1970-01-01T00:00:00.000-00:00")]
  874. public void ShouldParseAsUtc(string date)
  875. {
  876. const string customName = "Custom Time";
  877. var customTimeZone = TimeZoneInfo.CreateCustomTimeZone(customName, new TimeSpan(7, 11, 0), customName, customName, customName, null, false);
  878. var engine = new Engine(cfg => cfg.LocalTimeZone(customTimeZone));
  879. engine.SetValue("d", date);
  880. var result = engine.Execute("Date.parse(d);").GetCompletionValue().AsNumber();
  881. Assert.Equal(0, result);
  882. }
  883. [Theory]
  884. [InlineData("1970/01")]
  885. [InlineData("1970/01/01")]
  886. [InlineData("1970/01/01T00:00")]
  887. [InlineData("1970/01/01 00:00")]
  888. [InlineData("1970-1")]
  889. [InlineData("1970-1-1")]
  890. [InlineData("1970-1-1T0:0")]
  891. [InlineData("1970-1-1 0:0")]
  892. [InlineData("1970/1")]
  893. [InlineData("1970/1/1")]
  894. [InlineData("1970/1/1T0:0")]
  895. [InlineData("1970/1/1 0:0")]
  896. [InlineData("01-1970")]
  897. [InlineData("01-01-1970")]
  898. [InlineData("January 1, 1970")]
  899. [InlineData("1970-01-01T00:00:00.000+00:11")]
  900. public void ShouldParseAsLocalTime(string date)
  901. {
  902. const string customName = "Custom Time";
  903. var customTimeZone = TimeZoneInfo.CreateCustomTimeZone(customName, new TimeSpan(0, 11, 0), customName, customName, customName, null, false);
  904. var engine = new Engine(cfg => cfg.LocalTimeZone(customTimeZone)).SetValue("d", date);
  905. var result = engine.Execute("Date.parse(d);").GetCompletionValue().AsNumber();
  906. Assert.Equal(-11 * 60 * 1000, result);
  907. }
  908. [Fact]
  909. public void EmptyStringShouldMatchRegex()
  910. {
  911. RunTest(@"
  912. var regex = /^(?:$)/g;
  913. assert(''.match(regex) instanceof Array);
  914. ");
  915. }
  916. [Fact]
  917. public void ShouldExecuteHandlebars()
  918. {
  919. var url = "http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js";
  920. var content = new WebClient().DownloadString(url);
  921. RunTest(content);
  922. RunTest(@"
  923. var source = 'Hello {{name}}';
  924. var template = Handlebars.compile(source);
  925. var context = {name: 'Paul'};
  926. var html = template(context);
  927. assert('Hello Paul' == html);
  928. ");
  929. }
  930. [Fact]
  931. public void DateParseReturnsNaN()
  932. {
  933. RunTest(@"
  934. var d = Date.parse('not a date');
  935. assert(isNaN(d));
  936. ");
  937. }
  938. [Fact]
  939. public void ShouldIgnoreHtmlComments()
  940. {
  941. RunTest(@"
  942. var d = Date.parse('not a date'); <!-- a comment -->
  943. assert(isNaN(d));
  944. ");
  945. }
  946. [Fact]
  947. public void DateShouldAllowEntireDotNetDateRange()
  948. {
  949. var engine = new Engine();
  950. var minValue = engine.Execute("new Date('0001-01-01T00:00:00.000')").GetCompletionValue().ToObject();
  951. Assert.Equal(new DateTime(1, 1, 1, 0, 0, 0, DateTimeKind.Utc), minValue);
  952. var maxValue = engine.Execute("new Date('9999-12-31T23:59:59.999')").GetCompletionValue().ToObject();
  953. Assert.Equal(new DateTime(9999, 12, 31, 23, 59, 59, 999, DateTimeKind.Utc), maxValue);
  954. }
  955. [Fact]
  956. public void ShouldConstructNewArrayWithInteger()
  957. {
  958. RunTest(@"
  959. var a = new Array(3);
  960. assert(a.length === 3);
  961. assert(a[0] == undefined);
  962. assert(a[1] == undefined);
  963. assert(a[2] == undefined);
  964. ");
  965. }
  966. [Fact]
  967. public void ShouldConstructNewArrayWithString()
  968. {
  969. RunTest(@"
  970. var a = new Array('foo');
  971. assert(a.length === 1);
  972. assert(a[0] === 'foo');
  973. ");
  974. }
  975. [Fact]
  976. public void ShouldThrowRangeExceptionWhenConstructedWithNonInteger()
  977. {
  978. RunTest(@"
  979. var result = false;
  980. try {
  981. var a = new Array(3.4);
  982. }
  983. catch(e) {
  984. result = e instanceof RangeError;
  985. }
  986. assert(result);
  987. ");
  988. }
  989. [Fact]
  990. public void ShouldInitializeArrayWithSingleIngegerValue()
  991. {
  992. RunTest(@"
  993. var a = [3];
  994. assert(a.length === 1);
  995. assert(a[0] === 3);
  996. ");
  997. }
  998. [Fact]
  999. public void ShouldInitializeJsonObjectArrayWithSingleIntegerValue()
  1000. {
  1001. RunTest(@"
  1002. var x = JSON.parse('{ ""a"": [3] }');
  1003. assert(x.a.length === 1);
  1004. assert(x.a[0] === 3);
  1005. ");
  1006. }
  1007. [Fact]
  1008. public void ShouldInitializeJsonArrayWithSingleIntegerValue()
  1009. {
  1010. RunTest(@"
  1011. var a = JSON.parse('[3]');
  1012. assert(a.length === 1);
  1013. assert(a[0] === 3);
  1014. ");
  1015. }
  1016. [Fact]
  1017. public void ShouldReturnTrueForEmptyIsNaNStatement()
  1018. {
  1019. RunTest(@"
  1020. assert(true === isNaN());
  1021. ");
  1022. }
  1023. [Theory]
  1024. [InlineData(4d, 0, "4")]
  1025. [InlineData(4d, 1, "4.0")]
  1026. [InlineData(4d, 2, "4.00")]
  1027. [InlineData(28.995, 2, "29.00")]
  1028. [InlineData(-28.995, 2, "-29.00")]
  1029. [InlineData(-28.495, 2, "-28.50")]
  1030. [InlineData(-28.445, 2, "-28.45")]
  1031. [InlineData(28.445, 2, "28.45")]
  1032. [InlineData(10.995, 0, "11")]
  1033. public void ShouldRoundToFixedDecimal(double number, int fractionDigits, string result)
  1034. {
  1035. var engine = new Engine();
  1036. var value = engine.Execute(
  1037. String.Format("new Number({0}).toFixed({1})",
  1038. number.ToString(CultureInfo.InvariantCulture),
  1039. fractionDigits.ToString(CultureInfo.InvariantCulture)))
  1040. .GetCompletionValue().ToObject();
  1041. Assert.Equal(value, result);
  1042. }
  1043. [Fact]
  1044. public void ShouldSortArrayWhenCompareFunctionReturnsFloatingPointNumber()
  1045. {
  1046. RunTest(@"
  1047. var nums = [1, 1.1, 1.2, 2, 2, 2.1, 2.2];
  1048. nums.sort(function(a,b){return b-a;});
  1049. assert(nums[0] === 2.2);
  1050. assert(nums[1] === 2.1);
  1051. assert(nums[2] === 2);
  1052. assert(nums[3] === 2);
  1053. assert(nums[4] === 1.2);
  1054. assert(nums[5] === 1.1);
  1055. assert(nums[6] === 1);
  1056. ");
  1057. }
  1058. [Fact]
  1059. public void ShouldBreakWhenBreakpointIsReached()
  1060. {
  1061. countBreak = 0;
  1062. stepMode = StepMode.None;
  1063. var engine = new Engine(options => options.DebugMode());
  1064. engine.Break += EngineStep;
  1065. engine.BreakPoints.Add(new BreakPoint(1, 1));
  1066. engine.Execute(@"var local = true;
  1067. if (local === true)
  1068. {}");
  1069. engine.Break -= EngineStep;
  1070. Assert.Equal(1, countBreak);
  1071. }
  1072. [Fact]
  1073. public void ShouldExecuteStepByStep()
  1074. {
  1075. countBreak = 0;
  1076. stepMode = StepMode.Into;
  1077. var engine = new Engine(options => options.DebugMode());
  1078. engine.Step += EngineStep;
  1079. engine.Execute(@"var local = true;
  1080. var creatingSomeOtherLine = 0;
  1081. var lastOneIPromise = true");
  1082. engine.Step -= EngineStep;
  1083. Assert.Equal(3, countBreak);
  1084. }
  1085. [Fact]
  1086. public void ShouldNotBreakTwiceIfSteppingOverBreakpoint()
  1087. {
  1088. countBreak = 0;
  1089. stepMode = StepMode.Into;
  1090. var engine = new Engine(options => options.DebugMode());
  1091. engine.BreakPoints.Add(new BreakPoint(1, 1));
  1092. engine.Step += EngineStep;
  1093. engine.Break += EngineStep;
  1094. engine.Execute(@"var local = true;");
  1095. engine.Step -= EngineStep;
  1096. engine.Break -= EngineStep;
  1097. Assert.Equal(1, countBreak);
  1098. }
  1099. private StepMode EngineStep(object sender, DebugInformation debugInfo)
  1100. {
  1101. Assert.NotNull(sender);
  1102. Assert.IsType(typeof(Engine), sender);
  1103. Assert.NotNull(debugInfo);
  1104. countBreak++;
  1105. return stepMode;
  1106. }
  1107. [Fact]
  1108. public void ShouldShowProperDebugInformation()
  1109. {
  1110. countBreak = 0;
  1111. stepMode = StepMode.None;
  1112. var engine = new Engine(options => options.DebugMode());
  1113. engine.BreakPoints.Add(new BreakPoint(5, 0));
  1114. engine.Break += EngineStepVerifyDebugInfo;
  1115. engine.Execute(@"var global = true;
  1116. function func1()
  1117. {
  1118. var local = false;
  1119. ;
  1120. }
  1121. func1();");
  1122. engine.Break -= EngineStepVerifyDebugInfo;
  1123. Assert.Equal(1, countBreak);
  1124. }
  1125. private StepMode EngineStepVerifyDebugInfo(object sender, DebugInformation debugInfo)
  1126. {
  1127. Assert.NotNull(sender);
  1128. Assert.IsType(typeof(Engine), sender);
  1129. Assert.NotNull(debugInfo);
  1130. Assert.NotNull(debugInfo.CallStack);
  1131. Assert.NotNull(debugInfo.CurrentStatement);
  1132. Assert.NotNull(debugInfo.Locals);
  1133. Assert.Equal(1, debugInfo.CallStack.Count);
  1134. Assert.Equal("func1()", debugInfo.CallStack.Peek());
  1135. Assert.Contains(debugInfo.Globals, kvp => kvp.Key.Equals("global", StringComparison.Ordinal) && kvp.Value.AsBoolean() == true);
  1136. Assert.Contains(debugInfo.Globals, kvp => kvp.Key.Equals("local", StringComparison.Ordinal) && kvp.Value.AsBoolean() == false);
  1137. Assert.Contains(debugInfo.Locals, kvp => kvp.Key.Equals("local", StringComparison.Ordinal) && kvp.Value.AsBoolean() == false);
  1138. Assert.DoesNotContain(debugInfo.Locals, kvp => kvp.Key.Equals("global", StringComparison.Ordinal));
  1139. countBreak++;
  1140. return stepMode;
  1141. }
  1142. [Fact]
  1143. public void ShouldBreakWhenConditionIsMatched()
  1144. {
  1145. countBreak = 0;
  1146. stepMode = StepMode.None;
  1147. var engine = new Engine(options => options.DebugMode());
  1148. engine.Break += EngineStep;
  1149. engine.BreakPoints.Add(new BreakPoint(5, 16, "condition === true"));
  1150. engine.BreakPoints.Add(new BreakPoint(6, 16, "condition === false"));
  1151. engine.Execute(@"var local = true;
  1152. var condition = true;
  1153. if (local === true)
  1154. {
  1155. ;
  1156. ;
  1157. }");
  1158. engine.Break -= EngineStep;
  1159. Assert.Equal(1, countBreak);
  1160. }
  1161. [Fact]
  1162. public void ShouldNotStepInSameLevelStatementsWhenStepOut()
  1163. {
  1164. countBreak = 0;
  1165. stepMode = StepMode.Out;
  1166. var engine = new Engine(options => options.DebugMode());
  1167. engine.Step += EngineStep;
  1168. engine.Execute(@"function func() // first step - then stepping out
  1169. {
  1170. ; // shall not step
  1171. ; // not even here
  1172. }
  1173. func(); // shall not step
  1174. ; // shall not step ");
  1175. engine.Step -= EngineStep;
  1176. Assert.Equal(1, countBreak);
  1177. }
  1178. [Fact]
  1179. public void ShouldNotStepInIfRequiredToStepOut()
  1180. {
  1181. countBreak = 0;
  1182. var engine = new Engine(options => options.DebugMode());
  1183. engine.Step += EngineStepOutWhenInsideFunction;
  1184. engine.Execute(@"function func() // first step
  1185. {
  1186. ; // third step - now stepping out
  1187. ; // it should not step here
  1188. }
  1189. func(); // second step
  1190. ; // fourth step ");
  1191. engine.Step -= EngineStepOutWhenInsideFunction;
  1192. Assert.Equal(4, countBreak);
  1193. }
  1194. private StepMode EngineStepOutWhenInsideFunction(object sender, DebugInformation debugInfo)
  1195. {
  1196. Assert.NotNull(sender);
  1197. Assert.IsType(typeof(Engine), sender);
  1198. Assert.NotNull(debugInfo);
  1199. countBreak++;
  1200. if (debugInfo.CallStack.Count > 0)
  1201. return StepMode.Out;
  1202. return StepMode.Into;
  1203. }
  1204. [Fact]
  1205. public void ShouldBreakWhenStatementIsMultiLine()
  1206. {
  1207. countBreak = 0;
  1208. stepMode = StepMode.None;
  1209. var engine = new Engine(options => options.DebugMode());
  1210. engine.BreakPoints.Add(new BreakPoint(4, 33));
  1211. engine.Break += EngineStep;
  1212. engine.Execute(@"var global = true;
  1213. function func1()
  1214. {
  1215. var local =
  1216. false;
  1217. }
  1218. func1();");
  1219. engine.Break -= EngineStep;
  1220. Assert.Equal(1, countBreak);
  1221. }
  1222. [Fact]
  1223. public void ShouldNotStepInsideIfRequiredToStepOver()
  1224. {
  1225. countBreak = 0;
  1226. var engine = new Engine(options => options.DebugMode());
  1227. stepMode = StepMode.Over;
  1228. engine.Step += EngineStep;
  1229. engine.Execute(@"function func() // first step
  1230. {
  1231. ; // third step - it shall not step here
  1232. ; // it shall not step here
  1233. }
  1234. func(); // second step
  1235. ; // third step ");
  1236. engine.Step -= EngineStep;
  1237. Assert.Equal(3, countBreak);
  1238. }
  1239. [Fact]
  1240. public void ShouldStepAllStatementsWithoutInvocationsIfStepOver()
  1241. {
  1242. countBreak = 0;
  1243. var engine = new Engine(options => options.DebugMode());
  1244. stepMode = StepMode.Over;
  1245. engine.Step += EngineStep;
  1246. engine.Execute(@"var step1 = 1; // first step
  1247. var step2 = 2; // second step
  1248. if (step1 !== step2) // third step
  1249. { // fourth step
  1250. ; // fifth step
  1251. }");
  1252. engine.Step -= EngineStep;
  1253. Assert.Equal(5, countBreak);
  1254. }
  1255. [Fact]
  1256. public void ShouldEvaluateVariableAssignmentFromLeftToRight()
  1257. {
  1258. RunTest(@"
  1259. var keys = ['a']
  1260. , source = { a: 3}
  1261. , target = {}
  1262. , key
  1263. , i = 0;
  1264. target[key = keys[i++]] = source[key];
  1265. assert(i == 1);
  1266. assert(key == 'a');
  1267. assert(target[key] == 3);
  1268. ");
  1269. }
  1270. [Fact]
  1271. public void ObjectShouldBeExtensible()
  1272. {
  1273. RunTest(@"
  1274. try {
  1275. Object.defineProperty(Object.defineProperty, 'foo', { value: 1 });
  1276. }
  1277. catch(e) {
  1278. assert(false);
  1279. }
  1280. ");
  1281. }
  1282. [Fact]
  1283. public void ArrayIndexShouldBeConvertedToUint32()
  1284. {
  1285. // This is missing from ECMA tests suite
  1286. // http://www.ecma-international.org/ecma-262/5.1/#sec-15.4
  1287. RunTest(@"
  1288. var a = [ 'foo' ];
  1289. assert(a[0] === 'foo');
  1290. assert(a['0'] === 'foo');
  1291. assert(a['00'] === undefined);
  1292. ");
  1293. }
  1294. [Fact]
  1295. public void DatePrototypeFunctionWorkOnDateOnly()
  1296. {
  1297. RunTest(@"
  1298. try {
  1299. var myObj = Object.create(Date.prototype);
  1300. myObj.toDateString();
  1301. } catch (e) {
  1302. assert(e instanceof TypeError);
  1303. }
  1304. ");
  1305. }
  1306. [Fact]
  1307. public void DateToStringMethodsShouldUseCurrentTimeZoneAndCulture()
  1308. {
  1309. // Forcing to PDT and FR for tests
  1310. var PDT = TimeZoneInfo.CreateCustomTimeZone("Pacific Daylight Time", new TimeSpan(-7, 0, 0), "Pacific Daylight Time", "Pacific Daylight Time");
  1311. var FR = CultureInfo.GetCultureInfo("fr-FR");
  1312. var engine = new Engine(options => options.LocalTimeZone(PDT).Culture(FR))
  1313. .SetValue("log", new Action<object>(Console.WriteLine))
  1314. .SetValue("assert", new Action<bool>(Assert.True))
  1315. .SetValue("equal", new Action<object, object>(Assert.Equal))
  1316. ;
  1317. engine.Execute(@"
  1318. var d = new Date(1433160000000);
  1319. equal('Mon Jun 01 2015 05:00:00 GMT-07:00', d.toString());
  1320. equal('Mon Jun 01 2015', d.toDateString());
  1321. equal('05:00:00 GMT-07:00', d.toTimeString());
  1322. equal('lundi 1 juin 2015 05:00:00', d.toLocaleString());
  1323. equal('lundi 1 juin 2015', d.toLocaleDateString());
  1324. equal('05:00:00', d.toLocaleTimeString());
  1325. ");
  1326. }
  1327. [Fact]
  1328. public void DateShouldParseToString()
  1329. {
  1330. // Forcing to PDT and FR for tests
  1331. var PDT = TimeZoneInfo.CreateCustomTimeZone("Pacific Daylight Time", new TimeSpan(-7, 0, 0), "Pacific Daylight Time", "Pacific Daylight Time");
  1332. var FR = CultureInfo.GetCultureInfo("fr-FR");
  1333. new Engine(options => options.LocalTimeZone(PDT).Culture(FR))
  1334. .SetValue("log", new Action<object>(Console.WriteLine))
  1335. .SetValue("assert", new Action<bool>(Assert.True))
  1336. .SetValue("equal", new Action<object, object>(Assert.Equal))
  1337. .Execute(@"
  1338. var d = new Date(1433160000000);
  1339. equal(Date.parse(d.toString()), d.valueOf());
  1340. equal(Date.parse(d.toLocaleString()), d.valueOf());
  1341. ");
  1342. }
  1343. [Fact]
  1344. public void LocaleNumberShouldUseLocalCulture()
  1345. {
  1346. // Forcing to PDT and FR for tests
  1347. var PDT = TimeZoneInfo.CreateCustomTimeZone("Pacific Daylight Time", new TimeSpan(-7, 0, 0), "Pacific Daylight Time", "Pacific Daylight Time");
  1348. var FR = CultureInfo.GetCultureInfo("fr-FR");
  1349. new Engine(options => options.LocalTimeZone(PDT).Culture(FR))
  1350. .SetValue("log", new Action<object>(Console.WriteLine))
  1351. .SetValue("assert", new Action<bool>(Assert.True))
  1352. .SetValue("equal", new Action<object, object>(Assert.Equal))
  1353. .Execute(@"
  1354. var d = new Number(-1.23);
  1355. equal('-1.23', d.toString());
  1356. equal('-1,23', d.toLocaleString());
  1357. ");
  1358. }
  1359. [Fact]
  1360. public void DateCtorShouldAcceptDate()
  1361. {
  1362. RunTest(@"
  1363. var a = new Date();
  1364. var b = new Date(a);
  1365. assert(String(a) === String(b));
  1366. ");
  1367. }
  1368. }
  1369. }