EngineTests.cs 42 KB

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