EngineTests.cs 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851
  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 WithStatement()
  410. {
  411. RunTest(@"
  412. with (Math) {
  413. assert(cos(0) == 1);
  414. }
  415. ");
  416. }
  417. [Fact]
  418. public void ObjectExpression()
  419. {
  420. RunTest(@"
  421. var o = { x: 1 };
  422. assert(o.x == 1);
  423. ");
  424. }
  425. [Fact]
  426. public void StringFunctionCreatesString()
  427. {
  428. RunTest(@"
  429. assert(String(NaN) === 'NaN');
  430. ");
  431. }
  432. [Fact]
  433. public void ScopeChainInWithStatement()
  434. {
  435. RunTest(@"
  436. var x = 0;
  437. var myObj = {x : 'obj'};
  438. function f1(){
  439. var x = 1;
  440. function f2(){
  441. with(myObj){
  442. return x;
  443. }
  444. };
  445. return f2();
  446. }
  447. assert(f1() === 'obj');
  448. ");
  449. }
  450. [Fact]
  451. public void TryCatchBlockStatement()
  452. {
  453. RunTest(@"
  454. var x, y, z;
  455. try {
  456. x = 1;
  457. throw new TypeError();
  458. x = 2;
  459. }
  460. catch(e) {
  461. assert(x == 1);
  462. assert(e instanceof TypeError);
  463. y = 1;
  464. }
  465. finally {
  466. assert(x == 1);
  467. z = 1;
  468. }
  469. assert(x == 1);
  470. assert(y == 1);
  471. assert(z == 1);
  472. ");
  473. }
  474. [Fact]
  475. public void FunctionsCanBeAssigned()
  476. {
  477. RunTest(@"
  478. var sin = Math.sin;
  479. assert(sin(0) == 0);
  480. ");
  481. }
  482. [Fact]
  483. public void FunctionArgumentsIsDefined()
  484. {
  485. RunTest(@"
  486. function f() {
  487. assert(arguments.length > 0);
  488. }
  489. f(42);
  490. ");
  491. }
  492. [Fact]
  493. public void PrimitiveValueFunctions()
  494. {
  495. RunTest(@"
  496. var s = (1).toString();
  497. assert(s == '1');
  498. ");
  499. }
  500. [Theory]
  501. [InlineData(true, "'ab' == 'a' + 'b'")]
  502. public void OperatorsPrecedence(object expected, string source)
  503. {
  504. var engine = new Engine();
  505. var result = engine.Execute(source).GetCompletionValue().ToObject();
  506. Assert.Equal(expected, result);
  507. }
  508. [Fact]
  509. public void FunctionPrototypeShouldHaveApplyMethod()
  510. {
  511. RunTest(@"
  512. var numbers = [5, 6, 2, 3, 7];
  513. var max = Math.max.apply(null, numbers);
  514. assert(max == 7);
  515. ");
  516. }
  517. [Theory]
  518. [InlineData(double.NaN, "parseInt(NaN)")]
  519. [InlineData(double.NaN, "parseInt(null)")]
  520. [InlineData(double.NaN, "parseInt(undefined)")]
  521. [InlineData(double.NaN, "parseInt(new Boolean(true))")]
  522. [InlineData(double.NaN, "parseInt(Infinity)")]
  523. [InlineData(-1d, "parseInt(-1)")]
  524. [InlineData(-1d, "parseInt('-1')")]
  525. public void ShouldEvaluateParseInt(object expected, string source)
  526. {
  527. var engine = new Engine();
  528. var result = engine.Execute(source).GetCompletionValue().ToObject();
  529. Assert.Equal(expected, result);
  530. }
  531. [Fact]
  532. public void ShouldNotExecuteDebuggerStatement()
  533. {
  534. new Engine().Execute("debugger");
  535. }
  536. [Fact]
  537. public void ShouldThrowStatementCountOverflow()
  538. {
  539. Assert.Throws<StatementsCountOverflowException>(
  540. () => new Engine(cfg => cfg.MaxStatements(100)).Execute("while(true);")
  541. );
  542. }
  543. [Fact]
  544. public void ShouldThrowTimeout()
  545. {
  546. Assert.Throws<TimeoutException>(
  547. () => new Engine(cfg => cfg.TimeoutInterval(new TimeSpan(0, 0, 0, 0, 500))).Execute("while(true);")
  548. );
  549. }
  550. [Fact]
  551. public void CanDiscardRecursion()
  552. {
  553. var script = @"var factorial = function(n) {
  554. if (n>1) {
  555. return n * factorial(n - 1);
  556. }
  557. };
  558. var result = factorial(500);
  559. ";
  560. Assert.Throws<RecursionDepthOverflowException>(
  561. () => new Engine(cfg => cfg.LimitRecursion()).Execute(script)
  562. );
  563. }
  564. [Fact]
  565. public void ShouldDiscardHiddenRecursion()
  566. {
  567. var script = @"var renamedFunc;
  568. var exec = function(callback) {
  569. renamedFunc = callback;
  570. callback();
  571. };
  572. var result = exec(function() {
  573. renamedFunc();
  574. });
  575. ";
  576. Assert.Throws<RecursionDepthOverflowException>(
  577. () => new Engine(cfg => cfg.LimitRecursion()).Execute(script)
  578. );
  579. }
  580. [Fact]
  581. public void ShouldRecognizeAndDiscardChainedRecursion()
  582. {
  583. var script = @" var funcRoot, funcA, funcB, funcC, funcD;
  584. var funcRoot = function() {
  585. funcA();
  586. };
  587. var funcA = function() {
  588. funcB();
  589. };
  590. var funcB = function() {
  591. funcC();
  592. };
  593. var funcC = function() {
  594. funcD();
  595. };
  596. var funcD = function() {
  597. funcRoot();
  598. };
  599. funcRoot();
  600. ";
  601. Assert.Throws<RecursionDepthOverflowException>(
  602. () => new Engine(cfg => cfg.LimitRecursion()).Execute(script)
  603. );
  604. }
  605. [Fact]
  606. public void ShouldProvideCallChainWhenDiscardRecursion()
  607. {
  608. var script = @" var funcRoot, funcA, funcB, funcC, funcD;
  609. var funcRoot = function() {
  610. funcA();
  611. };
  612. var funcA = function() {
  613. funcB();
  614. };
  615. var funcB = function() {
  616. funcC();
  617. };
  618. var funcC = function() {
  619. funcD();
  620. };
  621. var funcD = function() {
  622. funcRoot();
  623. };
  624. funcRoot();
  625. ";
  626. RecursionDepthOverflowException exception = null;
  627. try
  628. {
  629. new Engine(cfg => cfg.LimitRecursion()).Execute(script);
  630. }
  631. catch (RecursionDepthOverflowException ex)
  632. {
  633. exception = ex;
  634. }
  635. Assert.NotNull(exception);
  636. Assert.Equal("funcRoot->funcA->funcB->funcC->funcD", exception.CallChain);
  637. Assert.Equal("funcRoot", exception.CallExpressionReference);
  638. }
  639. [Fact]
  640. public void ShouldAllowShallowRecursion()
  641. {
  642. var script = @"var factorial = function(n) {
  643. if (n>1) {
  644. return n * factorial(n - 1);
  645. }
  646. };
  647. var result = factorial(8);
  648. ";
  649. new Engine(cfg => cfg.LimitRecursion(20)).Execute(script);
  650. }
  651. [Fact]
  652. public void ShouldDiscardDeepRecursion()
  653. {
  654. var script = @"var factorial = function(n) {
  655. if (n>1) {
  656. return n * factorial(n - 1);
  657. }
  658. };
  659. var result = factorial(38);
  660. ";
  661. Assert.Throws<RecursionDepthOverflowException>(
  662. () => new Engine(cfg => cfg.LimitRecursion(20)).Execute(script)
  663. );
  664. }
  665. [Fact]
  666. public void ShouldConvertDoubleToStringWithoutLosingPrecision()
  667. {
  668. RunTest(@"
  669. assert(String(14.915832707045631) === '14.915832707045631');
  670. assert(String(-14.915832707045631) === '-14.915832707045631');
  671. assert(String(0.5) === '0.5');
  672. assert(String(0.00000001) === '1e-8');
  673. assert(String(0.000001) === '0.000001');
  674. assert(String(-1.0) === '-1');
  675. assert(String(30.0) === '30');
  676. assert(String(0.2388906159889881) === '0.2388906159889881');
  677. ");
  678. }
  679. [Fact]
  680. public void ShouldWriteNumbersUsingBases()
  681. {
  682. RunTest(@"
  683. assert(15.0.toString() === '15');
  684. assert(15.0.toString(2) === '1111');
  685. assert(15.0.toString(8) === '17');
  686. assert(15.0.toString(16) === 'f');
  687. assert(15.0.toString(17) === 'f');
  688. assert(15.0.toString(36) === 'f');
  689. assert(15.1.toString(36) === 'f.3llllllllkau6snqkpygsc3di');
  690. ");
  691. }
  692. [Fact]
  693. public void ShouldNotAlterSlashesInRegex()
  694. {
  695. RunTest(@"
  696. assert(new RegExp('/').toString() === '///');
  697. ");
  698. }
  699. [Fact]
  700. public void ShouldHandleEscapedSlashesInRegex()
  701. {
  702. RunTest(@"
  703. var regex = /[a-z]\/[a-z]/;
  704. assert(regex.test('a/b') === true);
  705. assert(regex.test('a\\/b') === false);
  706. ");
  707. }
  708. [Fact]
  709. public void ShouldComputeFractionInBase()
  710. {
  711. Assert.Equal("011", NumberPrototype.ToFractionBase(0.375, 2));
  712. Assert.Equal("14141414141414141414141414141414141414141414141414", NumberPrototype.ToFractionBase(0.375, 5));
  713. }
  714. [Fact]
  715. public void ShouldInvokeAFunctionValue()
  716. {
  717. RunTest(@"
  718. function add(x, y) { return x + y; }
  719. ");
  720. var add = _engine.GetValue("add");
  721. Assert.Equal(3, add.Invoke(1, 2));
  722. }
  723. [Fact]
  724. public void ShouldNotInvokeNonFunctionValue()
  725. {
  726. RunTest(@"
  727. var x= 10;
  728. ");
  729. var x = _engine.GetValue("x");
  730. Assert.Throws<ArgumentException>(() => x.Invoke(1, 2));
  731. }
  732. [Fact]
  733. public void ShouldInvokeAFunctionValueThatBelongsToAnObject()
  734. {
  735. RunTest(@"
  736. var obj = { foo: 5, getFoo: function (bar) { return 'foo is ' + this.foo + ', bar is ' + bar; } };
  737. ");
  738. var obj = _engine.GetValue("obj").AsObject();
  739. var getFoo = obj.Get("getFoo");
  740. Assert.Equal("foo is 5, bar is 7", _engine.Invoke(getFoo, obj, new object[] { 7 }).AsString());
  741. }
  742. [Fact]
  743. public void ShouldNotInvokeNonFunctionValueThatBelongsToAnObject()
  744. {
  745. RunTest(@"
  746. var obj = { foo: 2 };
  747. ");
  748. var obj = _engine.GetValue("obj").AsObject();
  749. var foo = obj.Get("foo");
  750. Assert.Throws<ArgumentException>(() => _engine.Invoke(foo, obj, new object[] { }));
  751. }
  752. [Theory]
  753. [InlineData("0", 0, 16)]
  754. [InlineData("1", 1, 16)]
  755. [InlineData("100", 100, 10)]
  756. [InlineData("1100100", 100, 2)]
  757. [InlineData("2s", 100, 36)]
  758. [InlineData("2qgpckvng1s", 10000000000000000L, 36)]
  759. public void ShouldConvertNumbersToDifferentBase(string expected, long number, int radix)
  760. {
  761. var result = NumberPrototype.ToBase(number, radix);
  762. Assert.Equal(expected, result);
  763. }
  764. [Fact]
  765. public void JsonParserShouldParseNegativeNumber()
  766. {
  767. RunTest(@"
  768. var a = JSON.parse('{ ""x"":-1 }');
  769. assert(a.x === -1);
  770. var b = JSON.parse('{ ""x"": -1 }');
  771. assert(b.x === -1);
  772. ");
  773. }
  774. [Fact]
  775. public void JsonParserShouldUseToString()
  776. {
  777. RunTest(@"
  778. var a = JSON.parse(null); // Equivalent to JSON.parse('null')
  779. assert(a === null);
  780. ");
  781. RunTest(@"
  782. var a = JSON.parse(true); // Equivalent to JSON.parse('true')
  783. assert(a === true);
  784. ");
  785. RunTest(@"
  786. var a = JSON.parse(false); // Equivalent to JSON.parse('false')
  787. assert(a === false);
  788. ");
  789. RunTest(@"
  790. try {
  791. JSON.parse(undefined); // Equivalent to JSON.parse('undefined')
  792. assert(false);
  793. }
  794. catch(ex) {
  795. assert(ex instanceof SyntaxError);
  796. }
  797. ");
  798. RunTest(@"
  799. try {
  800. JSON.parse({}); // Equivalent to JSON.parse('[object Object]')
  801. assert(false);
  802. }
  803. catch(ex) {
  804. assert(ex instanceof SyntaxError);
  805. }
  806. ");
  807. RunTest(@"
  808. try {
  809. JSON.parse(function() { }); // Equivalent to JSON.parse('function () {}')
  810. assert(false);
  811. }
  812. catch(ex) {
  813. assert(ex instanceof SyntaxError);
  814. }
  815. ");
  816. }
  817. [Fact]
  818. public void JsonParserShouldDetectInvalidNegativeNumberSyntax()
  819. {
  820. RunTest(@"
  821. try {
  822. JSON.parse('{ ""x"": -.1 }'); // Not allowed
  823. assert(false);
  824. }
  825. catch(ex) {
  826. assert(ex instanceof SyntaxError);
  827. }
  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. }
  839. [Fact]
  840. [ReplaceCulture("fr-FR")]
  841. public void ShouldBeCultureInvariant()
  842. {
  843. // decimals in french are separated by commas
  844. var engine = new Engine();
  845. var result = engine.Execute("1.2 + 2.1").GetCompletionValue().AsNumber();
  846. Assert.Equal(3.3d, result);
  847. result = engine.Execute("JSON.parse('{\"x\" : 3.3}').x").GetCompletionValue().AsNumber();
  848. Assert.Equal(3.3d, result);
  849. }
  850. [Fact]
  851. public void ShouldGetTheLastSyntaxNode()
  852. {
  853. var engine = new Engine();
  854. engine.Execute("1.2");
  855. var result = engine.GetLastSyntaxNode();
  856. Assert.Equal(SyntaxNodes.Literal, result.Type);
  857. }
  858. [Fact]
  859. public void ShouldGetParseErrorLocation()
  860. {
  861. var engine = new Engine();
  862. try
  863. {
  864. engine.Execute("1.2+ new", new ParserOptions { Source = "jQuery.js" });
  865. }
  866. catch (ParserException e)
  867. {
  868. Assert.Equal(1, e.LineNumber);
  869. Assert.Equal(9, e.Column);
  870. Assert.Equal("jQuery.js", e.Source);
  871. }
  872. }
  873. #region DateParsingAndStrings
  874. [Fact]
  875. public void ParseShouldReturnNumber()
  876. {
  877. var engine = new Engine();
  878. var result = engine.Execute("Date.parse('1970-01-01');").GetCompletionValue().AsNumber();
  879. Assert.Equal(0, result);
  880. }
  881. [Fact]
  882. public void LocalDateTimeShouldNotLoseTimezone()
  883. {
  884. var date = new DateTime(2016, 1, 1, 13, 0, 0, DateTimeKind.Local);
  885. var engine = new Engine().SetValue("localDate", date);
  886. engine.Execute(@"localDate");
  887. var actual = engine.GetCompletionValue().AsDate().ToDateTime();
  888. Assert.Equal(date.ToUniversalTime(), actual.ToUniversalTime());
  889. Assert.Equal(date.ToLocalTime(), actual.ToLocalTime());
  890. }
  891. [Fact]
  892. public void UtcShouldUseUtc()
  893. {
  894. var customTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central Europe Standard Time");
  895. var engine = new Engine(cfg => cfg.LocalTimeZone(customTimeZone));
  896. var result = engine.Execute("Date.UTC(1970,0,1)").GetCompletionValue().AsNumber();
  897. Assert.Equal(0, result);
  898. }
  899. #if NET451
  900. [Fact]
  901. #else
  902. [Fact(Skip = "CreateCustomTimeZone not available on netstandard")]
  903. #endif
  904. public void ShouldUseLocalTimeZoneOverride()
  905. {
  906. #if NET451
  907. const string customName = "Custom Time";
  908. var customTimeZone = TimeZoneInfo.CreateCustomTimeZone(customName, new TimeSpan(0, 11, 0), customName, customName, customName, null, false);
  909. #else
  910. var customTimeZone = TimeZoneInfo.Utc;
  911. #endif
  912. var engine = new Engine(cfg => cfg.LocalTimeZone(customTimeZone));
  913. var epochGetLocalMinutes = engine.Execute("var d = new Date(0); d.getMinutes();").GetCompletionValue().AsNumber();
  914. Assert.Equal(11, epochGetLocalMinutes);
  915. var localEpochGetUtcMinutes = engine.Execute("var d = new Date(1970,0,1); d.getUTCMinutes();").GetCompletionValue().AsNumber();
  916. Assert.Equal(-11, localEpochGetUtcMinutes);
  917. var parseLocalEpoch = engine.Execute("Date.parse('January 1, 1970');").GetCompletionValue().AsNumber();
  918. Assert.Equal(-11 * 60 * 1000, parseLocalEpoch);
  919. var epochToLocalString = engine.Execute("var d = new Date(0); d.toString();").GetCompletionValue().AsString();
  920. Assert.Equal("Thu Jan 01 1970 00:11:00 GMT+00:11", epochToLocalString);
  921. var epochToUTCString = engine.Execute("var d = new Date(0); d.toUTCString();").GetCompletionValue().AsString();
  922. Assert.Equal("Thu Jan 01 1970 00:00:00 GMT", epochToUTCString);
  923. }
  924. [Theory]
  925. [InlineData("1970")]
  926. [InlineData("1970-01")]
  927. [InlineData("1970-01-01")]
  928. [InlineData("1970-01-01T00:00")]
  929. [InlineData("1970-01-01T00:00:00")]
  930. [InlineData("1970-01-01T00:00:00.000")]
  931. [InlineData("1970Z")]
  932. [InlineData("1970-1Z")]
  933. [InlineData("1970-1-1Z")]
  934. [InlineData("1970-1-1T0:0Z")]
  935. [InlineData("1970-1-1T0:0:0Z")]
  936. [InlineData("1970-1-1T0:0:0.0Z")]
  937. [InlineData("1970/1Z")]
  938. [InlineData("1970/1/1Z")]
  939. [InlineData("1970/1/1 0:0Z")]
  940. [InlineData("1970/1/1 0:0:0Z")]
  941. [InlineData("1970/1/1 0:0:0.0Z")]
  942. [InlineData("January 1, 1970 GMT")]
  943. [InlineData("1970-01-01T00:00:00.000-00:00")]
  944. public void ShouldParseAsUtc(string date)
  945. {
  946. #if NET451
  947. const string customName = "Custom Time";
  948. var customTimeZone = TimeZoneInfo.CreateCustomTimeZone(customName, new TimeSpan(7, 11, 0), customName, customName, customName, null, false);
  949. #else
  950. var customTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Tonga Standard Time");
  951. #endif
  952. var engine = new Engine(cfg => cfg.LocalTimeZone(customTimeZone));
  953. engine.SetValue("d", date);
  954. var result = engine.Execute("Date.parse(d);").GetCompletionValue().AsNumber();
  955. Assert.Equal(0, result);
  956. }
  957. #if NET451
  958. [Theory]
  959. #else
  960. [Theory(Skip = "CreateCustomTimeZone not available on netstandard")]
  961. #endif
  962. [InlineData("1970/01")]
  963. [InlineData("1970/01/01")]
  964. [InlineData("1970/01/01T00:00")]
  965. [InlineData("1970/01/01 00:00")]
  966. [InlineData("1970-1")]
  967. [InlineData("1970-1-1")]
  968. [InlineData("1970-1-1T0:0")]
  969. [InlineData("1970-1-1 0:0")]
  970. [InlineData("1970/1")]
  971. [InlineData("1970/1/1")]
  972. [InlineData("1970/1/1T0:0")]
  973. [InlineData("1970/1/1 0:0")]
  974. [InlineData("01-1970")]
  975. [InlineData("01-01-1970")]
  976. [InlineData("January 1, 1970")]
  977. [InlineData("1970-01-01T00:00:00.000+00:11")]
  978. public void ShouldParseAsLocalTime(string date)
  979. {
  980. const int timespanMinutes = 11;
  981. const int msPriorMidnight = -timespanMinutes * 60 * 1000;
  982. #if NET451
  983. const string customName = "Custom Time";
  984. var customTimeZone = TimeZoneInfo.CreateCustomTimeZone(customName, new TimeSpan(0, timespanMinutes, 0), customName, customName, customName, null, false);
  985. #else
  986. var customTimeZone = TimeZoneInfo.Utc;
  987. #endif
  988. var engine = new Engine(cfg => cfg.LocalTimeZone(customTimeZone)).SetValue("d", date);
  989. var result = engine.Execute("Date.parse(d);").GetCompletionValue().AsNumber();
  990. Assert.Equal(msPriorMidnight, result);
  991. }
  992. public static System.Collections.Generic.IEnumerable<object[]> TestDates
  993. {
  994. get
  995. {
  996. yield return new object[] { new DateTime(2000, 1, 1) };
  997. yield return new object[] { new DateTime(2000, 1, 1, 0, 15, 15, 15) };
  998. yield return new object[] { new DateTime(2000, 6, 1, 0, 15, 15, 15) };
  999. yield return new object[] { new DateTime(1900, 1, 1) };
  1000. yield return new object[] { new DateTime(1900, 1, 1, 0, 15, 15, 15) };
  1001. yield return new object[] { new DateTime(1900, 6, 1, 0, 15, 15, 15) };
  1002. }
  1003. }
  1004. [Theory, MemberData("TestDates")]
  1005. public void TestDateToISOStringFormat(DateTime testDate)
  1006. {
  1007. var customTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Tonga Standard Time");
  1008. var engine = new Engine(ctx => ctx.LocalTimeZone(customTimeZone));
  1009. var testDateTimeOffset = new DateTimeOffset(testDate, customTimeZone.GetUtcOffset(testDate));
  1010. engine.Execute(
  1011. 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));
  1012. Assert.Equal(testDateTimeOffset.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'"), engine.Execute("d.toISOString();").GetCompletionValue().ToString());
  1013. }
  1014. [Theory, MemberData("TestDates")]
  1015. public void TestDateToStringFormat(DateTime testDate)
  1016. {
  1017. var customTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Tonga Standard Time");
  1018. var engine = new Engine(ctx => ctx.LocalTimeZone(customTimeZone));
  1019. var testDateTimeOffset = new DateTimeOffset(testDate, customTimeZone.GetUtcOffset(testDate));
  1020. engine.Execute(
  1021. 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));
  1022. var expected = testDateTimeOffset.ToString("ddd MMM dd yyyy HH:mm:ss 'GMT'zzz");
  1023. var actual = engine.Execute("d.toString();").GetCompletionValue().ToString();
  1024. Assert.Equal(expected, actual);
  1025. }
  1026. #endregion
  1027. //DateParsingAndStrings
  1028. [Fact]
  1029. public void EmptyStringShouldMatchRegex()
  1030. {
  1031. RunTest(@"
  1032. var regex = /^(?:$)/g;
  1033. assert(''.match(regex) instanceof Array);
  1034. ");
  1035. }
  1036. [Fact]
  1037. public void ShouldExecuteHandlebars()
  1038. {
  1039. var content = GetEmbeddedFile("handlebars.js");
  1040. RunTest(content);
  1041. RunTest(@"
  1042. var source = 'Hello {{name}}';
  1043. var template = Handlebars.compile(source);
  1044. var context = {name: 'Paul'};
  1045. var html = template(context);
  1046. assert('Hello Paul' == html);
  1047. ");
  1048. }
  1049. [Fact]
  1050. public void DateParseReturnsNaN()
  1051. {
  1052. RunTest(@"
  1053. var d = Date.parse('not a date');
  1054. assert(isNaN(d));
  1055. ");
  1056. }
  1057. [Fact]
  1058. public void ShouldIgnoreHtmlComments()
  1059. {
  1060. RunTest(@"
  1061. var d = Date.parse('not a date'); <!-- a comment -->
  1062. assert(isNaN(d));
  1063. ");
  1064. }
  1065. [Fact]
  1066. public void DateShouldAllowEntireDotNetDateRange()
  1067. {
  1068. var engine = new Engine();
  1069. var minValue = engine.Execute("new Date('0001-01-01T00:00:00.000')").GetCompletionValue().ToObject();
  1070. Assert.Equal(new DateTime(1, 1, 1, 0, 0, 0, DateTimeKind.Utc), minValue);
  1071. var maxValue = engine.Execute("new Date('9999-12-31T23:59:59.999')").GetCompletionValue().ToObject();
  1072. Assert.Equal(new DateTime(9999, 12, 31, 23, 59, 59, 999, DateTimeKind.Utc), maxValue);
  1073. }
  1074. [Fact]
  1075. public void ShouldConstructNewArrayWithInteger()
  1076. {
  1077. RunTest(@"
  1078. var a = new Array(3);
  1079. assert(a.length === 3);
  1080. assert(a[0] == undefined);
  1081. assert(a[1] == undefined);
  1082. assert(a[2] == undefined);
  1083. ");
  1084. }
  1085. [Fact]
  1086. public void ShouldConstructNewArrayWithString()
  1087. {
  1088. RunTest(@"
  1089. var a = new Array('foo');
  1090. assert(a.length === 1);
  1091. assert(a[0] === 'foo');
  1092. ");
  1093. }
  1094. [Fact]
  1095. public void ShouldThrowRangeExceptionWhenConstructedWithNonInteger()
  1096. {
  1097. RunTest(@"
  1098. var result = false;
  1099. try {
  1100. var a = new Array(3.4);
  1101. }
  1102. catch(e) {
  1103. result = e instanceof RangeError;
  1104. }
  1105. assert(result);
  1106. ");
  1107. }
  1108. [Fact]
  1109. public void ShouldInitializeArrayWithSingleIngegerValue()
  1110. {
  1111. RunTest(@"
  1112. var a = [3];
  1113. assert(a.length === 1);
  1114. assert(a[0] === 3);
  1115. ");
  1116. }
  1117. [Fact]
  1118. public void ShouldInitializeJsonObjectArrayWithSingleIntegerValue()
  1119. {
  1120. RunTest(@"
  1121. var x = JSON.parse('{ ""a"": [3] }');
  1122. assert(x.a.length === 1);
  1123. assert(x.a[0] === 3);
  1124. ");
  1125. }
  1126. [Fact]
  1127. public void ShouldInitializeJsonArrayWithSingleIntegerValue()
  1128. {
  1129. RunTest(@"
  1130. var a = JSON.parse('[3]');
  1131. assert(a.length === 1);
  1132. assert(a[0] === 3);
  1133. ");
  1134. }
  1135. [Fact]
  1136. public void ShouldReturnTrueForEmptyIsNaNStatement()
  1137. {
  1138. RunTest(@"
  1139. assert(true === isNaN());
  1140. ");
  1141. }
  1142. [Theory]
  1143. [InlineData(4d, 0, "4")]
  1144. [InlineData(4d, 1, "4.0")]
  1145. [InlineData(4d, 2, "4.00")]
  1146. [InlineData(28.995, 2, "29.00")]
  1147. [InlineData(-28.995, 2, "-29.00")]
  1148. [InlineData(-28.495, 2, "-28.50")]
  1149. [InlineData(-28.445, 2, "-28.45")]
  1150. [InlineData(28.445, 2, "28.45")]
  1151. [InlineData(10.995, 0, "11")]
  1152. public void ShouldRoundToFixedDecimal(double number, int fractionDigits, string result)
  1153. {
  1154. var engine = new Engine();
  1155. var value = engine.Execute(
  1156. String.Format("new Number({0}).toFixed({1})",
  1157. number.ToString(CultureInfo.InvariantCulture),
  1158. fractionDigits.ToString(CultureInfo.InvariantCulture)))
  1159. .GetCompletionValue().ToObject();
  1160. Assert.Equal(value, result);
  1161. }
  1162. [Fact]
  1163. public void ShouldSortArrayWhenCompareFunctionReturnsFloatingPointNumber()
  1164. {
  1165. RunTest(@"
  1166. var nums = [1, 1.1, 1.2, 2, 2, 2.1, 2.2];
  1167. nums.sort(function(a,b){return b-a;});
  1168. assert(nums[0] === 2.2);
  1169. assert(nums[1] === 2.1);
  1170. assert(nums[2] === 2);
  1171. assert(nums[3] === 2);
  1172. assert(nums[4] === 1.2);
  1173. assert(nums[5] === 1.1);
  1174. assert(nums[6] === 1);
  1175. ");
  1176. }
  1177. [Fact]
  1178. public void ShouldBreakWhenBreakpointIsReached()
  1179. {
  1180. countBreak = 0;
  1181. stepMode = StepMode.None;
  1182. var engine = new Engine(options => options.DebugMode());
  1183. engine.Break += EngineStep;
  1184. engine.BreakPoints.Add(new BreakPoint(1, 1));
  1185. engine.Execute(@"var local = true;
  1186. if (local === true)
  1187. {}");
  1188. engine.Break -= EngineStep;
  1189. Assert.Equal(1, countBreak);
  1190. }
  1191. [Fact]
  1192. public void ShouldExecuteStepByStep()
  1193. {
  1194. countBreak = 0;
  1195. stepMode = StepMode.Into;
  1196. var engine = new Engine(options => options.DebugMode());
  1197. engine.Step += EngineStep;
  1198. engine.Execute(@"var local = true;
  1199. var creatingSomeOtherLine = 0;
  1200. var lastOneIPromise = true");
  1201. engine.Step -= EngineStep;
  1202. Assert.Equal(3, countBreak);
  1203. }
  1204. [Fact]
  1205. public void ShouldNotBreakTwiceIfSteppingOverBreakpoint()
  1206. {
  1207. countBreak = 0;
  1208. stepMode = StepMode.Into;
  1209. var engine = new Engine(options => options.DebugMode());
  1210. engine.BreakPoints.Add(new BreakPoint(1, 1));
  1211. engine.Step += EngineStep;
  1212. engine.Break += EngineStep;
  1213. engine.Execute(@"var local = true;");
  1214. engine.Step -= EngineStep;
  1215. engine.Break -= EngineStep;
  1216. Assert.Equal(1, countBreak);
  1217. }
  1218. private StepMode EngineStep(object sender, DebugInformation debugInfo)
  1219. {
  1220. Assert.NotNull(sender);
  1221. Assert.IsType(typeof(Engine), sender);
  1222. Assert.NotNull(debugInfo);
  1223. countBreak++;
  1224. return stepMode;
  1225. }
  1226. [Fact]
  1227. public void ShouldShowProperDebugInformation()
  1228. {
  1229. countBreak = 0;
  1230. stepMode = StepMode.None;
  1231. var engine = new Engine(options => options.DebugMode());
  1232. engine.BreakPoints.Add(new BreakPoint(5, 0));
  1233. engine.Break += EngineStepVerifyDebugInfo;
  1234. engine.Execute(@"var global = true;
  1235. function func1()
  1236. {
  1237. var local = false;
  1238. ;
  1239. }
  1240. func1();");
  1241. engine.Break -= EngineStepVerifyDebugInfo;
  1242. Assert.Equal(1, countBreak);
  1243. }
  1244. private StepMode EngineStepVerifyDebugInfo(object sender, DebugInformation debugInfo)
  1245. {
  1246. Assert.NotNull(sender);
  1247. Assert.IsType(typeof(Engine), sender);
  1248. Assert.NotNull(debugInfo);
  1249. Assert.NotNull(debugInfo.CallStack);
  1250. Assert.NotNull(debugInfo.CurrentStatement);
  1251. Assert.NotNull(debugInfo.Locals);
  1252. Assert.Equal(1, debugInfo.CallStack.Count);
  1253. Assert.Equal("func1()", debugInfo.CallStack.Peek());
  1254. Assert.Contains(debugInfo.Globals, kvp => kvp.Key.Equals("global", StringComparison.Ordinal) && kvp.Value.AsBoolean() == true);
  1255. Assert.Contains(debugInfo.Globals, kvp => kvp.Key.Equals("local", StringComparison.Ordinal) && kvp.Value.AsBoolean() == false);
  1256. Assert.Contains(debugInfo.Locals, kvp => kvp.Key.Equals("local", StringComparison.Ordinal) && kvp.Value.AsBoolean() == false);
  1257. Assert.DoesNotContain(debugInfo.Locals, kvp => kvp.Key.Equals("global", StringComparison.Ordinal));
  1258. countBreak++;
  1259. return stepMode;
  1260. }
  1261. [Fact]
  1262. public void ShouldBreakWhenConditionIsMatched()
  1263. {
  1264. countBreak = 0;
  1265. stepMode = StepMode.None;
  1266. var engine = new Engine(options => options.DebugMode());
  1267. engine.Break += EngineStep;
  1268. engine.BreakPoints.Add(new BreakPoint(5, 16, "condition === true"));
  1269. engine.BreakPoints.Add(new BreakPoint(6, 16, "condition === false"));
  1270. engine.Execute(@"var local = true;
  1271. var condition = true;
  1272. if (local === true)
  1273. {
  1274. ;
  1275. ;
  1276. }");
  1277. engine.Break -= EngineStep;
  1278. Assert.Equal(1, countBreak);
  1279. }
  1280. [Fact]
  1281. public void ShouldNotStepInSameLevelStatementsWhenStepOut()
  1282. {
  1283. countBreak = 0;
  1284. stepMode = StepMode.Out;
  1285. var engine = new Engine(options => options.DebugMode());
  1286. engine.Step += EngineStep;
  1287. engine.Execute(@"function func() // first step - then stepping out
  1288. {
  1289. ; // shall not step
  1290. ; // not even here
  1291. }
  1292. func(); // shall not step
  1293. ; // shall not step ");
  1294. engine.Step -= EngineStep;
  1295. Assert.Equal(1, countBreak);
  1296. }
  1297. [Fact]
  1298. public void ShouldNotStepInIfRequiredToStepOut()
  1299. {
  1300. countBreak = 0;
  1301. var engine = new Engine(options => options.DebugMode());
  1302. engine.Step += EngineStepOutWhenInsideFunction;
  1303. engine.Execute(@"function func() // first step
  1304. {
  1305. ; // third step - now stepping out
  1306. ; // it should not step here
  1307. }
  1308. func(); // second step
  1309. ; // fourth step ");
  1310. engine.Step -= EngineStepOutWhenInsideFunction;
  1311. Assert.Equal(4, countBreak);
  1312. }
  1313. private StepMode EngineStepOutWhenInsideFunction(object sender, DebugInformation debugInfo)
  1314. {
  1315. Assert.NotNull(sender);
  1316. Assert.IsType(typeof(Engine), sender);
  1317. Assert.NotNull(debugInfo);
  1318. countBreak++;
  1319. if (debugInfo.CallStack.Count > 0)
  1320. return StepMode.Out;
  1321. return StepMode.Into;
  1322. }
  1323. [Fact]
  1324. public void ShouldBreakWhenStatementIsMultiLine()
  1325. {
  1326. countBreak = 0;
  1327. stepMode = StepMode.None;
  1328. var engine = new Engine(options => options.DebugMode());
  1329. engine.BreakPoints.Add(new BreakPoint(4, 33));
  1330. engine.Break += EngineStep;
  1331. engine.Execute(@"var global = true;
  1332. function func1()
  1333. {
  1334. var local =
  1335. false;
  1336. }
  1337. func1();");
  1338. engine.Break -= EngineStep;
  1339. Assert.Equal(1, countBreak);
  1340. }
  1341. [Fact]
  1342. public void ShouldNotStepInsideIfRequiredToStepOver()
  1343. {
  1344. countBreak = 0;
  1345. var engine = new Engine(options => options.DebugMode());
  1346. stepMode = StepMode.Over;
  1347. engine.Step += EngineStep;
  1348. engine.Execute(@"function func() // first step
  1349. {
  1350. ; // third step - it shall not step here
  1351. ; // it shall not step here
  1352. }
  1353. func(); // second step
  1354. ; // third step ");
  1355. engine.Step -= EngineStep;
  1356. Assert.Equal(3, countBreak);
  1357. }
  1358. [Fact]
  1359. public void ShouldStepAllStatementsWithoutInvocationsIfStepOver()
  1360. {
  1361. countBreak = 0;
  1362. var engine = new Engine(options => options.DebugMode());
  1363. stepMode = StepMode.Over;
  1364. engine.Step += EngineStep;
  1365. engine.Execute(@"var step1 = 1; // first step
  1366. var step2 = 2; // second step
  1367. if (step1 !== step2) // third step
  1368. { // fourth step
  1369. ; // fifth step
  1370. }");
  1371. engine.Step -= EngineStep;
  1372. Assert.Equal(5, countBreak);
  1373. }
  1374. [Fact]
  1375. public void ShouldEvaluateVariableAssignmentFromLeftToRight()
  1376. {
  1377. RunTest(@"
  1378. var keys = ['a']
  1379. , source = { a: 3}
  1380. , target = {}
  1381. , key
  1382. , i = 0;
  1383. target[key = keys[i++]] = source[key];
  1384. assert(i == 1);
  1385. assert(key == 'a');
  1386. assert(target[key] == 3);
  1387. ");
  1388. }
  1389. [Fact]
  1390. public void ObjectShouldBeExtensible()
  1391. {
  1392. RunTest(@"
  1393. try {
  1394. Object.defineProperty(Object.defineProperty, 'foo', { value: 1 });
  1395. }
  1396. catch(e) {
  1397. assert(false);
  1398. }
  1399. ");
  1400. }
  1401. [Fact]
  1402. public void ArrayIndexShouldBeConvertedToUint32()
  1403. {
  1404. // This is missing from ECMA tests suite
  1405. // http://www.ecma-international.org/ecma-262/5.1/#sec-15.4
  1406. RunTest(@"
  1407. var a = [ 'foo' ];
  1408. assert(a[0] === 'foo');
  1409. assert(a['0'] === 'foo');
  1410. assert(a['00'] === undefined);
  1411. ");
  1412. }
  1413. [Fact]
  1414. public void DatePrototypeFunctionWorkOnDateOnly()
  1415. {
  1416. RunTest(@"
  1417. try {
  1418. var myObj = Object.create(Date.prototype);
  1419. myObj.toDateString();
  1420. } catch (e) {
  1421. assert(e instanceof TypeError);
  1422. }
  1423. ");
  1424. }
  1425. [Fact]
  1426. public void DateToStringMethodsShouldUseCurrentTimeZoneAndCulture()
  1427. {
  1428. // Forcing to PDT and FR for tests
  1429. // var PDT = TimeZoneInfo.CreateCustomTimeZone("Pacific Daylight Time", new TimeSpan(-7, 0, 0), "Pacific Daylight Time", "Pacific Daylight Time");
  1430. var PDT = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
  1431. var FR = new CultureInfo("fr-FR");
  1432. var engine = new Engine(options => options.LocalTimeZone(PDT).Culture(FR))
  1433. .SetValue("log", new Action<object>(Console.WriteLine))
  1434. .SetValue("assert", new Action<bool>(Assert.True))
  1435. .SetValue("equal", new Action<object, object>(Assert.Equal))
  1436. ;
  1437. engine.Execute(@"
  1438. var d = new Date(1433160000000);
  1439. equal('Mon Jun 01 2015 05:00:00 GMT-07:00', d.toString());
  1440. equal('Mon Jun 01 2015', d.toDateString());
  1441. equal('05:00:00 GMT-07:00', d.toTimeString());
  1442. equal('lundi 1 juin 2015 05:00:00', d.toLocaleString());
  1443. equal('lundi 1 juin 2015', d.toLocaleDateString());
  1444. equal('05:00:00', d.toLocaleTimeString());
  1445. ");
  1446. }
  1447. [Fact]
  1448. public void DateShouldHonorTimezoneDaylightSavingRules()
  1449. {
  1450. var EST = TimeZoneInfo.FindSystemTimeZoneById("US Eastern Standard Time");
  1451. var engine = new Engine(options => options.LocalTimeZone(EST))
  1452. .SetValue("log", new Action<object>(Console.WriteLine))
  1453. .SetValue("assert", new Action<bool>(Assert.True))
  1454. .SetValue("equal", new Action<object, object>(Assert.Equal))
  1455. ;
  1456. engine.Execute(@"
  1457. var d = new Date(2016, 8, 1);
  1458. equal('Thu Sep 01 2016 00:00:00 GMT-04:00', d.toString());
  1459. equal('Thu Sep 01 2016', d.toDateString());
  1460. ");
  1461. }
  1462. [Fact]
  1463. public void DateShouldParseToString()
  1464. {
  1465. // Forcing to PDT and FR for tests
  1466. // var PDT = TimeZoneInfo.CreateCustomTimeZone("Pacific Daylight Time", new TimeSpan(-7, 0, 0), "Pacific Daylight Time", "Pacific Daylight Time");
  1467. var PDT = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
  1468. var FR = new CultureInfo("fr-FR");
  1469. new Engine(options => options.LocalTimeZone(PDT).Culture(FR))
  1470. .SetValue("log", new Action<object>(Console.WriteLine))
  1471. .SetValue("assert", new Action<bool>(Assert.True))
  1472. .SetValue("equal", new Action<object, object>(Assert.Equal))
  1473. .Execute(@"
  1474. var d = new Date(1433160000000);
  1475. equal(Date.parse(d.toString()), d.valueOf());
  1476. equal(Date.parse(d.toLocaleString()), d.valueOf());
  1477. ");
  1478. }
  1479. [Fact]
  1480. public void LocaleNumberShouldUseLocalCulture()
  1481. {
  1482. // Forcing to PDT and FR for tests
  1483. // var PDT = TimeZoneInfo.CreateCustomTimeZone("Pacific Daylight Time", new TimeSpan(-7, 0, 0), "Pacific Daylight Time", "Pacific Daylight Time");
  1484. var PDT = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
  1485. var FR = new CultureInfo("fr-FR");
  1486. new Engine(options => options.LocalTimeZone(PDT).Culture(FR))
  1487. .SetValue("log", new Action<object>(Console.WriteLine))
  1488. .SetValue("assert", new Action<bool>(Assert.True))
  1489. .SetValue("equal", new Action<object, object>(Assert.Equal))
  1490. .Execute(@"
  1491. var d = new Number(-1.23);
  1492. equal('-1.23', d.toString());
  1493. equal('-1,23', d.toLocaleString());
  1494. ");
  1495. }
  1496. [Fact]
  1497. public void DateCtorShouldAcceptDate()
  1498. {
  1499. RunTest(@"
  1500. var a = new Date();
  1501. var b = new Date(a);
  1502. assert(String(a) === String(b));
  1503. ");
  1504. }
  1505. [Fact]
  1506. public void RegExpResultIsMutable()
  1507. {
  1508. RunTest(@"
  1509. var match = /quick\s(brown).+?(jumps)/ig.exec('The Quick Brown Fox Jumps Over The Lazy Dog');
  1510. var result = match.shift();
  1511. assert(result === 'Quick Brown Fox Jumps');
  1512. ");
  1513. }
  1514. [Fact]
  1515. public void RegExpSupportsMultiline()
  1516. {
  1517. RunTest(@"
  1518. var rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg;
  1519. var headersString = 'X-AspNetMvc-Version: 4.0\r\nX-Powered-By: ASP.NET\r\n\r\n';
  1520. match = rheaders.exec(headersString);
  1521. assert('X-AspNetMvc-Version' === match[1]);
  1522. assert('4.0' === match[2]);
  1523. ");
  1524. RunTest(@"
  1525. var rheaders = /^(.*?):[ \t]*(.*?)$/mg;
  1526. var headersString = 'X-AspNetMvc-Version: 4.0\r\nX-Powered-By: ASP.NET\r\n\r\n';
  1527. match = rheaders.exec(headersString);
  1528. assert('X-AspNetMvc-Version' === match[1]);
  1529. assert('4.0' === match[2]);
  1530. ");
  1531. RunTest(@"
  1532. var rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg;
  1533. var headersString = 'X-AspNetMvc-Version: 4.0\nX-Powered-By: ASP.NET\n\n';
  1534. match = rheaders.exec(headersString);
  1535. assert('X-AspNetMvc-Version' === match[1]);
  1536. assert('4.0' === match[2]);
  1537. ");
  1538. }
  1539. [Fact]
  1540. public void ShouldSetYearBefore1970()
  1541. {
  1542. RunTest(@"
  1543. var d = new Date('1969-01-01T08:17:00');
  1544. d.setYear(2015);
  1545. equal('2015-01-01T08:17:00.000Z', d.toISOString());
  1546. ");
  1547. }
  1548. [Fact]
  1549. public void ExceptionShouldHaveLocationOfInnerFunction()
  1550. {
  1551. try
  1552. {
  1553. new Engine()
  1554. .Execute(@"
  1555. function test(s) {
  1556. o.boom();
  1557. }
  1558. test('arg');
  1559. ");
  1560. }
  1561. catch (JavaScriptException ex)
  1562. {
  1563. Assert.Equal(3, ex.LineNumber);
  1564. }
  1565. }
  1566. }
  1567. }