EngineTests.cs 58 KB

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