EngineTests.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539
  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 UtcShouldUseUtc()
  820. {
  821. const string customName = "Custom Time";
  822. var customTimeZone = TimeZoneInfo.CreateCustomTimeZone(customName, new TimeSpan(7, 11, 0), customName, customName, customName, null, false);
  823. var engine = new Engine(cfg => cfg.LocalTimeZone(customTimeZone));
  824. var result = engine.Execute("Date.UTC(1970,0,1)").GetCompletionValue().AsNumber();
  825. Assert.Equal(0, result);
  826. }
  827. [Fact]
  828. public void ShouldUseLocalTimeZoneOverride()
  829. {
  830. const string customName = "Custom Time";
  831. var customTimeZone = TimeZoneInfo.CreateCustomTimeZone(customName, new TimeSpan(0, 11, 0), customName, customName, customName, null, false);
  832. var engine = new Engine(cfg => cfg.LocalTimeZone(customTimeZone));
  833. var epochGetLocalMinutes = engine.Execute("var d = new Date(0); d.getMinutes();").GetCompletionValue().AsNumber();
  834. Assert.Equal(11, epochGetLocalMinutes);
  835. var localEpochGetUtcMinutes = engine.Execute("var d = new Date(1970,0,1); d.getUTCMinutes();").GetCompletionValue().AsNumber();
  836. Assert.Equal(-11, localEpochGetUtcMinutes);
  837. var parseLocalEpoch = engine.Execute("Date.parse('January 1, 1970');").GetCompletionValue().AsNumber();
  838. Assert.Equal(-11 * 60 * 1000, parseLocalEpoch);
  839. var epochToLocalString = engine.Execute("var d = new Date(0); d.toString();").GetCompletionValue().AsString();
  840. Assert.Equal("Thu Jan 01 1970 00:11:00 GMT", epochToLocalString);
  841. }
  842. [Theory]
  843. [InlineData("1970")]
  844. [InlineData("1970-01")]
  845. [InlineData("1970-01-01")]
  846. [InlineData("1970-01-01T00:00")]
  847. [InlineData("1970-01-01T00:00:00")]
  848. [InlineData("1970-01-01T00:00:00.000")]
  849. [InlineData("1970Z")]
  850. [InlineData("1970-1Z")]
  851. [InlineData("1970-1-1Z")]
  852. [InlineData("1970-1-1T0:0Z")]
  853. [InlineData("1970-1-1T0:0:0Z")]
  854. [InlineData("1970-1-1T0:0:0.0Z")]
  855. [InlineData("1970/1Z")]
  856. [InlineData("1970/1/1Z")]
  857. [InlineData("1970/1/1 0:0Z")]
  858. [InlineData("1970/1/1 0:0:0Z")]
  859. [InlineData("1970/1/1 0:0:0.0Z")]
  860. [InlineData("January 1, 1970 GMT")]
  861. [InlineData("1970-01-01T00:00:00.000-00:00")]
  862. public void ShouldParseAsUtc(string date)
  863. {
  864. const string customName = "Custom Time";
  865. var customTimeZone = TimeZoneInfo.CreateCustomTimeZone(customName, new TimeSpan(7, 11, 0), customName, customName, customName, null, false);
  866. var engine = new Engine(cfg => cfg.LocalTimeZone(customTimeZone));
  867. engine.SetValue("d", date);
  868. var result = engine.Execute("Date.parse(d);").GetCompletionValue().AsNumber();
  869. Assert.Equal(0, result);
  870. }
  871. [Theory]
  872. [InlineData("1970/01")]
  873. [InlineData("1970/01/01")]
  874. [InlineData("1970/01/01T00:00")]
  875. [InlineData("1970/01/01 00:00")]
  876. [InlineData("1970-1")]
  877. [InlineData("1970-1-1")]
  878. [InlineData("1970-1-1T0:0")]
  879. [InlineData("1970-1-1 0:0")]
  880. [InlineData("1970/1")]
  881. [InlineData("1970/1/1")]
  882. [InlineData("1970/1/1T0:0")]
  883. [InlineData("1970/1/1 0:0")]
  884. [InlineData("01-1970")]
  885. [InlineData("01-01-1970")]
  886. [InlineData("January 1, 1970")]
  887. [InlineData("1970-01-01T00:00:00.000+00:11")]
  888. public void ShouldParseAsLocalTime(string date)
  889. {
  890. const string customName = "Custom Time";
  891. var customTimeZone = TimeZoneInfo.CreateCustomTimeZone(customName, new TimeSpan(0, 11, 0), customName, customName, customName, null, false);
  892. var engine = new Engine(cfg => cfg.LocalTimeZone(customTimeZone)).SetValue("d", date);
  893. var result = engine.Execute("Date.parse(d);").GetCompletionValue().AsNumber();
  894. Assert.Equal(-11 * 60 * 1000, result);
  895. }
  896. [Fact]
  897. public void EmptyStringShouldMatchRegex()
  898. {
  899. RunTest(@"
  900. var regex = /^(?:$)/g;
  901. assert(''.match(regex) instanceof Array);
  902. ");
  903. }
  904. [Fact]
  905. public void ShouldExecuteHandlebars()
  906. {
  907. var url = "http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js";
  908. var content = new WebClient().DownloadString(url);
  909. RunTest(content);
  910. RunTest(@"
  911. var source = 'Hello {{name}}';
  912. var template = Handlebars.compile(source);
  913. var context = {name: 'Paul'};
  914. var html = template(context);
  915. assert('Hello Paul' == html);
  916. ");
  917. }
  918. [Fact]
  919. public void DateParseReturnsNaN()
  920. {
  921. RunTest(@"
  922. var d = Date.parse('not a date');
  923. assert(isNaN(d));
  924. ");
  925. }
  926. [Fact]
  927. public void ShouldIgnoreHtmlComments()
  928. {
  929. RunTest(@"
  930. var d = Date.parse('not a date'); <!-- a comment -->
  931. assert(isNaN(d));
  932. ");
  933. }
  934. [Fact]
  935. public void DateShouldAllowEntireDotNetDateRange()
  936. {
  937. var engine = new Engine();
  938. var minValue = engine.Execute("new Date('0001-01-01T00:00:00.000')").GetCompletionValue().ToObject();
  939. Assert.Equal(new DateTime(1, 1, 1, 0, 0, 0, DateTimeKind.Utc), minValue);
  940. var maxValue = engine.Execute("new Date('9999-12-31T23:59:59.999')").GetCompletionValue().ToObject();
  941. Assert.Equal(new DateTime(9999, 12, 31, 23, 59, 59, 999, DateTimeKind.Utc), maxValue);
  942. }
  943. [Fact]
  944. public void ShouldConstructNewArrayWithInteger()
  945. {
  946. RunTest(@"
  947. var a = new Array(3);
  948. assert(a.length === 3);
  949. assert(a[0] == undefined);
  950. assert(a[1] == undefined);
  951. assert(a[2] == undefined);
  952. ");
  953. }
  954. [Fact]
  955. public void ShouldConstructNewArrayWithString()
  956. {
  957. RunTest(@"
  958. var a = new Array('foo');
  959. assert(a.length === 1);
  960. assert(a[0] === 'foo');
  961. ");
  962. }
  963. [Fact]
  964. public void ShouldThrowRangeExceptionWhenConstructedWithNonInteger()
  965. {
  966. RunTest(@"
  967. var result = false;
  968. try {
  969. var a = new Array(3.4);
  970. }
  971. catch(e) {
  972. result = e instanceof RangeError;
  973. }
  974. assert(result);
  975. ");
  976. }
  977. [Fact]
  978. public void ShouldInitializeArrayWithSingleIngegerValue()
  979. {
  980. RunTest(@"
  981. var a = [3];
  982. assert(a.length === 1);
  983. assert(a[0] === 3);
  984. ");
  985. }
  986. [Fact]
  987. public void ShouldInitializeJsonObjectArrayWithSingleIntegerValue()
  988. {
  989. RunTest(@"
  990. var x = JSON.parse('{ ""a"": [3] }');
  991. assert(x.a.length === 1);
  992. assert(x.a[0] === 3);
  993. ");
  994. }
  995. [Fact]
  996. public void ShouldInitializeJsonArrayWithSingleIntegerValue()
  997. {
  998. RunTest(@"
  999. var a = JSON.parse('[3]');
  1000. assert(a.length === 1);
  1001. assert(a[0] === 3);
  1002. ");
  1003. }
  1004. [Fact]
  1005. public void ShouldReturnTrueForEmptyIsNaNStatement()
  1006. {
  1007. RunTest(@"
  1008. assert(true === isNaN());
  1009. ");
  1010. }
  1011. [Theory]
  1012. [InlineData(4d, 0, "4")]
  1013. [InlineData(4d, 1, "4.0")]
  1014. [InlineData(4d, 2, "4.00")]
  1015. [InlineData(28.995, 2, "29.00")]
  1016. [InlineData(-28.995, 2, "-29.00")]
  1017. [InlineData(-28.495, 2, "-28.50")]
  1018. [InlineData(-28.445, 2, "-28.45")]
  1019. [InlineData(28.445, 2, "28.45")]
  1020. [InlineData(10.995, 0, "11")]
  1021. public void ShouldRoundToFixedDecimal(double number, int fractionDigits, string result)
  1022. {
  1023. var engine = new Engine();
  1024. var value = engine.Execute(
  1025. String.Format("new Number({0}).toFixed({1})",
  1026. number.ToString(CultureInfo.InvariantCulture),
  1027. fractionDigits.ToString(CultureInfo.InvariantCulture)))
  1028. .GetCompletionValue().ToObject();
  1029. Assert.Equal(value, result);
  1030. }
  1031. [Fact]
  1032. public void ShouldSortArrayWhenCompareFunctionReturnsFloatingPointNumber()
  1033. {
  1034. RunTest(@"
  1035. var nums = [1, 1.1, 1.2, 2, 2, 2.1, 2.2];
  1036. nums.sort(function(a,b){return b-a;});
  1037. assert(nums[0] === 2.2);
  1038. assert(nums[1] === 2.1);
  1039. assert(nums[2] === 2);
  1040. assert(nums[3] === 2);
  1041. assert(nums[4] === 1.2);
  1042. assert(nums[5] === 1.1);
  1043. assert(nums[6] === 1);
  1044. ");
  1045. }
  1046. [Fact]
  1047. public void ShouldBreakWhenBreakpointIsReached()
  1048. {
  1049. countBreak = 0;
  1050. stepMode = StepMode.None;
  1051. var engine = new Engine(options => options.DebugMode());
  1052. engine.Break += EngineStep;
  1053. engine.BreakPoints.Add(new BreakPoint(1, 1));
  1054. engine.Execute(@"var local = true;
  1055. if (local === true)
  1056. {}");
  1057. engine.Break -= EngineStep;
  1058. Assert.Equal(1, countBreak);
  1059. }
  1060. [Fact]
  1061. public void ShouldExecuteStepByStep()
  1062. {
  1063. countBreak = 0;
  1064. stepMode = StepMode.Into;
  1065. var engine = new Engine(options => options.DebugMode());
  1066. engine.Step += EngineStep;
  1067. engine.Execute(@"var local = true;
  1068. var creatingSomeOtherLine = 0;
  1069. var lastOneIPromise = true");
  1070. engine.Step -= EngineStep;
  1071. Assert.Equal(3, countBreak);
  1072. }
  1073. [Fact]
  1074. public void ShouldNotBreakTwiceIfSteppingOverBreakpoint()
  1075. {
  1076. countBreak = 0;
  1077. stepMode = StepMode.Into;
  1078. var engine = new Engine(options => options.DebugMode());
  1079. engine.BreakPoints.Add(new BreakPoint(1, 1));
  1080. engine.Step += EngineStep;
  1081. engine.Break += EngineStep;
  1082. engine.Execute(@"var local = true;");
  1083. engine.Step -= EngineStep;
  1084. engine.Break -= EngineStep;
  1085. Assert.Equal(1, countBreak);
  1086. }
  1087. private StepMode EngineStep(object sender, DebugInformation debugInfo)
  1088. {
  1089. Assert.NotNull(sender);
  1090. Assert.IsType(typeof(Engine), sender);
  1091. Assert.NotNull(debugInfo);
  1092. countBreak++;
  1093. return stepMode;
  1094. }
  1095. [Fact]
  1096. public void ShouldShowProperDebugInformation()
  1097. {
  1098. countBreak = 0;
  1099. stepMode = StepMode.None;
  1100. var engine = new Engine(options => options.DebugMode());
  1101. engine.BreakPoints.Add(new BreakPoint(5, 0));
  1102. engine.Break += EngineStepVerifyDebugInfo;
  1103. engine.Execute(@"var global = true;
  1104. function func1()
  1105. {
  1106. var local = false;
  1107. ;
  1108. }
  1109. func1();");
  1110. engine.Break -= EngineStepVerifyDebugInfo;
  1111. Assert.Equal(1, countBreak);
  1112. }
  1113. private StepMode EngineStepVerifyDebugInfo(object sender, DebugInformation debugInfo)
  1114. {
  1115. Assert.NotNull(sender);
  1116. Assert.IsType(typeof(Engine), sender);
  1117. Assert.NotNull(debugInfo);
  1118. Assert.NotNull(debugInfo.CallStack);
  1119. Assert.NotNull(debugInfo.CurrentStatement);
  1120. Assert.NotNull(debugInfo.Locals);
  1121. Assert.Equal(1, debugInfo.CallStack.Count);
  1122. Assert.Equal("func1()", debugInfo.CallStack.Peek());
  1123. Assert.Contains(debugInfo.Globals, kvp => kvp.Key.Equals("global", StringComparison.Ordinal) && kvp.Value.AsBoolean() == true);
  1124. Assert.Contains(debugInfo.Globals, kvp => kvp.Key.Equals("local", StringComparison.Ordinal) && kvp.Value.AsBoolean() == false);
  1125. Assert.Contains(debugInfo.Locals, kvp => kvp.Key.Equals("local", StringComparison.Ordinal) && kvp.Value.AsBoolean() == false);
  1126. Assert.DoesNotContain(debugInfo.Locals, kvp => kvp.Key.Equals("global", StringComparison.Ordinal));
  1127. countBreak++;
  1128. return stepMode;
  1129. }
  1130. [Fact]
  1131. public void ShouldBreakWhenConditionIsMatched()
  1132. {
  1133. countBreak = 0;
  1134. stepMode = StepMode.None;
  1135. var engine = new Engine(options => options.DebugMode());
  1136. engine.Break += EngineStep;
  1137. engine.BreakPoints.Add(new BreakPoint(5, 16, "condition === true"));
  1138. engine.BreakPoints.Add(new BreakPoint(6, 16, "condition === false"));
  1139. engine.Execute(@"var local = true;
  1140. var condition = true;
  1141. if (local === true)
  1142. {
  1143. ;
  1144. ;
  1145. }");
  1146. engine.Break -= EngineStep;
  1147. Assert.Equal(1, countBreak);
  1148. }
  1149. [Fact]
  1150. public void ShouldNotStepInSameLevelStatementsWhenStepOut()
  1151. {
  1152. countBreak = 0;
  1153. stepMode = StepMode.Out;
  1154. var engine = new Engine(options => options.DebugMode());
  1155. engine.Step += EngineStep;
  1156. engine.Execute(@"function func() // first step - then stepping out
  1157. {
  1158. ; // shall not step
  1159. ; // not even here
  1160. }
  1161. func(); // shall not step
  1162. ; // shall not step ");
  1163. engine.Step -= EngineStep;
  1164. Assert.Equal(1, countBreak);
  1165. }
  1166. [Fact]
  1167. public void ShouldNotStepInIfRequiredToStepOut()
  1168. {
  1169. countBreak = 0;
  1170. var engine = new Engine(options => options.DebugMode());
  1171. engine.Step += EngineStepOutWhenInsideFunction;
  1172. engine.Execute(@"function func() // first step
  1173. {
  1174. ; // third step - now stepping out
  1175. ; // it should not step here
  1176. }
  1177. func(); // second step
  1178. ; // fourth step ");
  1179. engine.Step -= EngineStepOutWhenInsideFunction;
  1180. Assert.Equal(4, countBreak);
  1181. }
  1182. private StepMode EngineStepOutWhenInsideFunction(object sender, DebugInformation debugInfo)
  1183. {
  1184. Assert.NotNull(sender);
  1185. Assert.IsType(typeof(Engine), sender);
  1186. Assert.NotNull(debugInfo);
  1187. countBreak++;
  1188. if (debugInfo.CallStack.Count > 0)
  1189. return StepMode.Out;
  1190. return StepMode.Into;
  1191. }
  1192. [Fact]
  1193. public void ShouldBreakWhenStatementIsMultiLine()
  1194. {
  1195. countBreak = 0;
  1196. stepMode = StepMode.None;
  1197. var engine = new Engine(options => options.DebugMode());
  1198. engine.BreakPoints.Add(new BreakPoint(4, 33));
  1199. engine.Break += EngineStep;
  1200. engine.Execute(@"var global = true;
  1201. function func1()
  1202. {
  1203. var local =
  1204. false;
  1205. }
  1206. func1();");
  1207. engine.Break -= EngineStep;
  1208. Assert.Equal(1, countBreak);
  1209. }
  1210. [Fact]
  1211. public void ShouldNotStepInsideIfRequiredToStepOver()
  1212. {
  1213. countBreak = 0;
  1214. var engine = new Engine(options => options.DebugMode());
  1215. stepMode = StepMode.Over;
  1216. engine.Step += EngineStep;
  1217. engine.Execute(@"function func() // first step
  1218. {
  1219. ; // third step - it shall not step here
  1220. ; // it shall not step here
  1221. }
  1222. func(); // second step
  1223. ; // third step ");
  1224. engine.Step -= EngineStep;
  1225. Assert.Equal(3, countBreak);
  1226. }
  1227. [Fact]
  1228. public void ShouldStepAllStatementsWithoutInvocationsIfStepOver()
  1229. {
  1230. countBreak = 0;
  1231. var engine = new Engine(options => options.DebugMode());
  1232. stepMode = StepMode.Over;
  1233. engine.Step += EngineStep;
  1234. engine.Execute(@"var step1 = 1; // first step
  1235. var step2 = 2; // second step
  1236. if (step1 !== step2) // third step
  1237. { // fourth step
  1238. ; // fifth step
  1239. }");
  1240. engine.Step -= EngineStep;
  1241. Assert.Equal(5, countBreak);
  1242. }
  1243. [Fact]
  1244. public void ShouldEvaluateVariableAssignmentFromLeftToRight()
  1245. {
  1246. RunTest(@"
  1247. var keys = ['a']
  1248. , source = { a: 3}
  1249. , target = {}
  1250. , key
  1251. , i = 0;
  1252. target[key = keys[i++]] = source[key];
  1253. assert(i == 1);
  1254. assert(key == 'a');
  1255. assert(target[key] == 3);
  1256. ");
  1257. }
  1258. [Fact]
  1259. public void ObjectShouldBeExtensible()
  1260. {
  1261. RunTest(@"
  1262. try {
  1263. Object.defineProperty(Object.defineProperty, 'foo', { value: 1 });
  1264. }
  1265. catch(e) {
  1266. assert(false);
  1267. }
  1268. ");
  1269. }
  1270. [Fact]
  1271. public void ArrayIndexShouldBeConvertedToUint32()
  1272. {
  1273. // This is missing from ECMA tests suite
  1274. // http://www.ecma-international.org/ecma-262/5.1/#sec-15.4
  1275. RunTest(@"
  1276. var a = [ 'foo' ];
  1277. assert(a[0] === 'foo');
  1278. assert(a['0'] === 'foo');
  1279. assert(a['00'] === undefined);
  1280. ");
  1281. }
  1282. [Fact]
  1283. public void DatePrototypeFunctionWorkOnDateOnly()
  1284. {
  1285. RunTest(@"
  1286. try {
  1287. var myObj = Object.create(Date.prototype);
  1288. myObj.toDateString();
  1289. } catch (e) {
  1290. assert(e instanceof TypeError);
  1291. }
  1292. ");
  1293. }
  1294. }
  1295. }