EngineTests.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  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 Xunit;
  11. using Xunit.Extensions;
  12. namespace Jint.Tests.Runtime
  13. {
  14. public class EngineTests : IDisposable
  15. {
  16. private readonly Engine _engine;
  17. public EngineTests()
  18. {
  19. _engine = new Engine()
  20. .SetValue("log", new Action<object>(Console.WriteLine))
  21. .SetValue("assert", new Action<bool>(Assert.True))
  22. ;
  23. }
  24. void IDisposable.Dispose()
  25. {
  26. }
  27. private void RunTest(string source)
  28. {
  29. _engine.Execute(source);
  30. }
  31. [Theory]
  32. [InlineData("Scratch.js")]
  33. public void ShouldInterpretScriptFile(string file)
  34. {
  35. const string prefix = "Jint.Tests.Runtime.Scripts.";
  36. var assembly = Assembly.GetExecutingAssembly();
  37. var scriptPath = prefix + file;
  38. using (var stream = assembly.GetManifestResourceStream(scriptPath))
  39. if (stream != null)
  40. using (var sr = new StreamReader(stream))
  41. {
  42. var source = sr.ReadToEnd();
  43. RunTest(source);
  44. }
  45. }
  46. [Theory]
  47. [InlineData(42d, "42")]
  48. [InlineData("Hello", "'Hello'")]
  49. public void ShouldInterpretLiterals(object expected, string source)
  50. {
  51. var engine = new Engine();
  52. var result = engine.Execute(source).GetCompletionValue().ToObject();
  53. Assert.Equal(expected, result);
  54. }
  55. [Fact]
  56. public void ShouldInterpretVariableDeclaration()
  57. {
  58. var engine = new Engine();
  59. var result = engine
  60. .Execute("var foo = 'bar'; foo;")
  61. .GetCompletionValue()
  62. .ToObject();
  63. Assert.Equal("bar", result);
  64. }
  65. [Theory]
  66. [InlineData(4d, "1 + 3")]
  67. [InlineData(-2d, "1 - 3")]
  68. [InlineData(3d, "1 * 3")]
  69. [InlineData(2d, "6 / 3")]
  70. [InlineData(9d, "15 & 9")]
  71. [InlineData(15d, "15 | 9")]
  72. [InlineData(6d, "15 ^ 9")]
  73. [InlineData(36d, "9 << 2")]
  74. [InlineData(2d, "9 >> 2")]
  75. [InlineData(4d, "19 >>> 2")]
  76. public void ShouldInterpretBinaryExpression(object expected, string source)
  77. {
  78. var engine = new Engine();
  79. var result = engine.Execute(source).GetCompletionValue().ToObject();
  80. Assert.Equal(expected, result);
  81. }
  82. [Fact]
  83. public void ShouldEvaluateHasOwnProperty()
  84. {
  85. RunTest(@"
  86. var x = {};
  87. x.Bar = 42;
  88. assert(x.hasOwnProperty('Bar'));
  89. ");
  90. }
  91. [Fact]
  92. public void FunctionConstructorsShouldCreateNewObjects()
  93. {
  94. RunTest(@"
  95. var Vehicle = function () {};
  96. var vehicle = new Vehicle();
  97. assert(vehicle != undefined);
  98. ");
  99. }
  100. [Fact]
  101. public void NewObjectsInheritFunctionConstructorProperties()
  102. {
  103. RunTest(@"
  104. var Vehicle = function () {};
  105. var vehicle = new Vehicle();
  106. Vehicle.prototype.wheelCount = 4;
  107. assert(vehicle.wheelCount == 4);
  108. assert((new Vehicle()).wheelCount == 4);
  109. ");
  110. }
  111. [Fact]
  112. public void PrototypeFunctionIsInherited()
  113. {
  114. RunTest(@"
  115. function Body(mass){
  116. this.mass = mass;
  117. }
  118. Body.prototype.offsetMass = function(dm) {
  119. this.mass += dm;
  120. return this;
  121. }
  122. var b = new Body(36);
  123. b.offsetMass(6);
  124. assert(b.mass == 42);
  125. ");
  126. }
  127. [Fact]
  128. public void FunctionConstructorCall()
  129. {
  130. RunTest(@"
  131. function Body(mass){
  132. this.mass = mass;
  133. }
  134. var john = new Body(36);
  135. assert(john.mass == 36);
  136. ");
  137. }
  138. [Fact]
  139. public void NewObjectsShouldUsePrivateProperties()
  140. {
  141. RunTest(@"
  142. var Vehicle = function (color) {
  143. this.color = color;
  144. };
  145. var vehicle = new Vehicle('tan');
  146. assert(vehicle.color == 'tan');
  147. ");
  148. }
  149. [Fact]
  150. public void FunctionConstructorsShouldDefinePrototypeChain()
  151. {
  152. RunTest(@"
  153. function Vehicle() {};
  154. var vehicle = new Vehicle();
  155. assert(vehicle.hasOwnProperty('constructor') == false);
  156. ");
  157. }
  158. [Fact]
  159. public void NewObjectsConstructorIsObject()
  160. {
  161. RunTest(@"
  162. var o = new Object();
  163. assert(o.constructor == Object);
  164. ");
  165. }
  166. [Fact]
  167. public void NewObjectsIntanceOfConstructorObject()
  168. {
  169. RunTest(@"
  170. var o = new Object();
  171. assert(o instanceof Object);
  172. ");
  173. }
  174. [Fact]
  175. public void NewObjectsConstructorShouldBeConstructorObject()
  176. {
  177. RunTest(@"
  178. var Vehicle = function () {};
  179. var vehicle = new Vehicle();
  180. assert(vehicle.constructor == Vehicle);
  181. ");
  182. }
  183. [Fact]
  184. public void NewObjectsIntanceOfConstructorFunction()
  185. {
  186. RunTest(@"
  187. var Vehicle = function () {};
  188. var vehicle = new Vehicle();
  189. assert(vehicle instanceof Vehicle);
  190. ");
  191. }
  192. [Fact]
  193. public void ShouldEvaluateForLoops()
  194. {
  195. RunTest(@"
  196. var foo = 0;
  197. for (var i = 0; i < 5; i++) {
  198. foo += i;
  199. }
  200. assert(foo == 10);
  201. ");
  202. }
  203. [Fact]
  204. public void ShouldEvaluateRecursiveFunctions()
  205. {
  206. RunTest(@"
  207. function fib(n) {
  208. if (n < 2) {
  209. return n;
  210. }
  211. return fib(n - 1) + fib(n - 2);
  212. }
  213. var result = fib(6);
  214. assert(result == 8);
  215. ");
  216. }
  217. [Fact]
  218. public void ShouldAccessObjectProperties()
  219. {
  220. RunTest(@"
  221. var o = {};
  222. o.Foo = 'bar';
  223. o.Baz = 42;
  224. o.Blah = o.Foo + o.Baz;
  225. assert(o.Blah == 'bar42');
  226. ");
  227. }
  228. [Fact]
  229. public void ShouldConstructArray()
  230. {
  231. RunTest(@"
  232. var o = [];
  233. assert(o.length == 0);
  234. ");
  235. }
  236. [Fact]
  237. public void ArrayPushShouldIncrementLength()
  238. {
  239. RunTest(@"
  240. var o = [];
  241. o.push(1);
  242. assert(o.length == 1);
  243. ");
  244. }
  245. [Fact]
  246. public void ArrayFunctionInitializesLength()
  247. {
  248. RunTest(@"
  249. assert(Array(3).length == 3);
  250. assert(Array('3').length == 1);
  251. ");
  252. }
  253. [Fact]
  254. public void ArrayIndexerIsAssigned()
  255. {
  256. RunTest(@"
  257. var n = 8;
  258. var o = Array(n);
  259. for (var i = 0; i < n; i++) o[i] = i;
  260. assert(o[0] == 0);
  261. assert(o[7] == 7);
  262. ");
  263. }
  264. [Fact]
  265. public void ArrayPopShouldDecrementLength()
  266. {
  267. RunTest(@"
  268. var o = [42, 'foo'];
  269. var pop = o.pop();
  270. assert(o.length == 1);
  271. assert(pop == 'foo');
  272. ");
  273. }
  274. [Fact]
  275. public void ArrayConstructor()
  276. {
  277. RunTest(@"
  278. var o = [];
  279. assert(o.constructor == Array);
  280. ");
  281. }
  282. [Fact]
  283. public void DateConstructor()
  284. {
  285. RunTest(@"
  286. var o = new Date();
  287. assert(o.constructor == Date);
  288. assert(o.hasOwnProperty('constructor') == false);
  289. ");
  290. }
  291. [Fact]
  292. public void ShouldConvertDateToNumber()
  293. {
  294. RunTest(@"
  295. assert(Number(new Date(0)) === 0);
  296. ");
  297. }
  298. [Fact]
  299. public void DatePrimitiveValueShouldBeNaN()
  300. {
  301. RunTest(@"
  302. assert(isNaN(Date.prototype.valueOf()));
  303. ");
  304. }
  305. [Fact]
  306. public void MathObjectIsDefined()
  307. {
  308. RunTest(@"
  309. var o = Math.abs(-1)
  310. assert(o == 1);
  311. ");
  312. }
  313. [Fact]
  314. public void VoidShouldReturnUndefined()
  315. {
  316. RunTest(@"
  317. assert(void 0 === undefined);
  318. var x = '1';
  319. assert(void x === undefined);
  320. x = 'x';
  321. assert (isNaN(void x) === true);
  322. x = new String('-1');
  323. assert (void x === undefined);
  324. ");
  325. }
  326. [Fact]
  327. public void TypeofObjectShouldReturnString()
  328. {
  329. RunTest(@"
  330. assert(typeof x === 'undefined');
  331. assert(typeof 0 === 'number');
  332. var x = 0;
  333. assert (typeof x === 'number');
  334. var x = new Object();
  335. assert (typeof x === 'object');
  336. ");
  337. }
  338. [Fact]
  339. public void MathAbsReturnsAbsolute()
  340. {
  341. RunTest(@"
  342. assert(1 == Math.abs(-1));
  343. ");
  344. }
  345. [Fact]
  346. public void NaNIsNan()
  347. {
  348. RunTest(@"
  349. var x = NaN;
  350. assert(isNaN(NaN));
  351. assert(isNaN(Math.abs(x)));
  352. ");
  353. }
  354. [Fact]
  355. public void ToNumberHandlesStringObject()
  356. {
  357. RunTest(@"
  358. x = new String('1');
  359. x *= undefined;
  360. assert(isNaN(x));
  361. ");
  362. }
  363. [Fact]
  364. public void FunctionScopesAreChained()
  365. {
  366. RunTest(@"
  367. var x = 0;
  368. function f1(){
  369. function f2(){
  370. return x;
  371. };
  372. return f2();
  373. var x = 1;
  374. }
  375. assert(f1() === undefined);
  376. ");
  377. }
  378. [Fact]
  379. public void EvalFunctionParseAndExecuteCode()
  380. {
  381. RunTest(@"
  382. var x = 0;
  383. eval('assert(x == 0)');
  384. ");
  385. }
  386. [Fact]
  387. public void ForInStatement()
  388. {
  389. RunTest(@"
  390. var x, y, str = '';
  391. for(var z in this) {
  392. str += z;
  393. }
  394. assert(str == 'xystrz');
  395. ");
  396. }
  397. [Fact]
  398. public void WithStatement()
  399. {
  400. RunTest(@"
  401. with (Math) {
  402. assert(cos(0) == 1);
  403. }
  404. ");
  405. }
  406. [Fact]
  407. public void ObjectExpression()
  408. {
  409. RunTest(@"
  410. var o = { x: 1 };
  411. assert(o.x == 1);
  412. ");
  413. }
  414. [Fact]
  415. public void StringFunctionCreatesString()
  416. {
  417. RunTest(@"
  418. assert(String(NaN) === 'NaN');
  419. ");
  420. }
  421. [Fact]
  422. public void ScopeChainInWithStatement()
  423. {
  424. RunTest(@"
  425. var x = 0;
  426. var myObj = {x : 'obj'};
  427. function f1(){
  428. var x = 1;
  429. function f2(){
  430. with(myObj){
  431. return x;
  432. }
  433. };
  434. return f2();
  435. }
  436. assert(f1() === 'obj');
  437. ");
  438. }
  439. [Fact]
  440. public void TryCatchBlockStatement()
  441. {
  442. RunTest(@"
  443. var x, y, z;
  444. try {
  445. x = 1;
  446. throw new TypeError();
  447. x = 2;
  448. }
  449. catch(e) {
  450. assert(x == 1);
  451. assert(e instanceof TypeError);
  452. y = 1;
  453. }
  454. finally {
  455. assert(x == 1);
  456. z = 1;
  457. }
  458. assert(x == 1);
  459. assert(y == 1);
  460. assert(z == 1);
  461. ");
  462. }
  463. [Fact]
  464. public void FunctionsCanBeAssigned()
  465. {
  466. RunTest(@"
  467. var sin = Math.sin;
  468. assert(sin(0) == 0);
  469. ");
  470. }
  471. [Fact]
  472. public void FunctionArgumentsIsDefined()
  473. {
  474. RunTest(@"
  475. function f() {
  476. assert(arguments.length > 0);
  477. }
  478. f(42);
  479. ");
  480. }
  481. [Fact]
  482. public void PrimitiveValueFunctions()
  483. {
  484. RunTest(@"
  485. var s = (1).toString();
  486. assert(s == '1');
  487. ");
  488. }
  489. [Theory]
  490. [InlineData(true, "'ab' == 'a' + 'b'")]
  491. public void OperatorsPrecedence(object expected, string source)
  492. {
  493. var engine = new Engine();
  494. var result = engine.Execute(source).GetCompletionValue().ToObject();
  495. Assert.Equal(expected, result);
  496. }
  497. [Fact]
  498. public void FunctionPrototypeShouldHaveApplyMethod()
  499. {
  500. RunTest(@"
  501. var numbers = [5, 6, 2, 3, 7];
  502. var max = Math.max.apply(null, numbers);
  503. assert(max == 7);
  504. ");
  505. }
  506. [Theory]
  507. [InlineData(double.NaN, "parseInt(NaN)")]
  508. [InlineData(double.NaN, "parseInt(null)")]
  509. [InlineData(double.NaN, "parseInt(undefined)")]
  510. [InlineData(double.NaN, "parseInt(new Boolean(true))")]
  511. [InlineData(double.NaN, "parseInt(Infinity)")]
  512. [InlineData(-1d, "parseInt(-1)")]
  513. [InlineData(-1d, "parseInt('-1')")]
  514. public void ShouldEvaluateParseInt(object expected, string source)
  515. {
  516. var engine = new Engine();
  517. var result = engine.Execute(source).GetCompletionValue().ToObject();
  518. Assert.Equal(expected, result);
  519. }
  520. [Fact]
  521. public void ShouldNotExecuteDebuggerStatement()
  522. {
  523. new Engine().Execute("debugger");
  524. }
  525. [Fact]
  526. public void ShouldThrowStatementCountOverflow()
  527. {
  528. Assert.Throws<StatementsCountOverflowException>(
  529. () => new Engine(cfg => cfg.MaxStatements(100)).Execute("while(true);")
  530. );
  531. }
  532. [Fact]
  533. public void ShouldDiscardRecursion()
  534. {
  535. var script = @"var factorial = function(n) {
  536. if (n>1) {
  537. return n * factorial(n - 1);
  538. }
  539. };
  540. var result = factorial(500);
  541. ";
  542. Assert.Throws<RecursionDiscardedException>(
  543. () => new Engine(cfg => cfg.DiscardRecursion()).Execute(script)
  544. );
  545. }
  546. [Fact]
  547. public void ShouldDiscardHiddenRecursion()
  548. {
  549. var script = @"var renamedFunc;
  550. var exec = function(callback) {
  551. renamedFunc = callback;
  552. callback();
  553. };
  554. var result = exec(function() {
  555. renamedFunc();
  556. });
  557. ";
  558. Assert.Throws<RecursionDiscardedException>(
  559. () => new Engine(cfg => cfg.DiscardRecursion()).Execute(script)
  560. );
  561. }
  562. [Fact]
  563. public void ShouldRecognizeAndDiscardChainedRecursion()
  564. {
  565. var script = @" var funcRoot, funcA, funcB, funcC, funcD;
  566. var funcRoot = function() {
  567. funcA();
  568. };
  569. var funcA = function() {
  570. funcB();
  571. };
  572. var funcB = function() {
  573. funcC();
  574. };
  575. var funcC = function() {
  576. funcD();
  577. };
  578. var funcD = function() {
  579. funcRoot();
  580. };
  581. funcRoot();
  582. ";
  583. Assert.Throws<RecursionDiscardedException>(
  584. () => new Engine(cfg => cfg.DiscardRecursion()).Execute(script)
  585. );
  586. }
  587. [Fact]
  588. public void ShouldProvideCallChainWhenDiscardRecursion()
  589. {
  590. var script = @" var funcRoot, funcA, funcB, funcC, funcD;
  591. var funcRoot = function() {
  592. funcA();
  593. };
  594. var funcA = function() {
  595. funcB();
  596. };
  597. var funcB = function() {
  598. funcC();
  599. };
  600. var funcC = function() {
  601. funcD();
  602. };
  603. var funcD = function() {
  604. funcRoot();
  605. };
  606. funcRoot();
  607. ";
  608. RecursionDiscardedException exception = null;
  609. try
  610. {
  611. new Engine(cfg => cfg.DiscardRecursion()).Execute(script);
  612. }
  613. catch (RecursionDiscardedException ex)
  614. {
  615. exception = ex;
  616. }
  617. Assert.NotNull(exception);
  618. Assert.Equal("funcRoot->funcA->funcB->funcC->funcD", exception.CallChain);
  619. Assert.Equal("funcRoot", exception.CallExpressionReference);
  620. }
  621. [Fact]
  622. public void ShouldConvertDoubleToStringWithoutLosingPrecision()
  623. {
  624. RunTest(@"
  625. assert(String(14.915832707045631) === '14.915832707045631');
  626. assert(String(-14.915832707045631) === '-14.915832707045631');
  627. assert(String(0.5) === '0.5');
  628. assert(String(0.00000001) === '1e-8');
  629. assert(String(0.000001) === '0.000001');
  630. assert(String(-1.0) === '-1');
  631. assert(String(30.0) === '30');
  632. assert(String(0.2388906159889881) === '0.2388906159889881');
  633. ");
  634. }
  635. [Fact]
  636. public void ShouldWriteNumbersUsingBases()
  637. {
  638. RunTest(@"
  639. assert(15.0.toString() === '15');
  640. assert(15.0.toString(2) === '1111');
  641. assert(15.0.toString(8) === '17');
  642. assert(15.0.toString(16) === 'f');
  643. assert(15.0.toString(17) === 'f');
  644. assert(15.0.toString(36) === 'f');
  645. assert(15.1.toString(36) === 'f.3llllllllkau6snqkpygsc3di');
  646. ");
  647. }
  648. [Fact]
  649. public void ShouldNotAlterSlashesInRegex()
  650. {
  651. RunTest(@"
  652. assert(new RegExp('/').toString() === '///');
  653. ");
  654. }
  655. [Fact]
  656. public void ShouldHandleEscapedSlashesInRegex()
  657. {
  658. RunTest(@"
  659. var regex = /[a-z]\/[a-z]/;
  660. assert(regex.test('a/b') === true);
  661. assert(regex.test('a\\/b') === false);
  662. ");
  663. }
  664. [Fact]
  665. public void ShouldComputeFractionInBase()
  666. {
  667. Assert.Equal("011", NumberPrototype.ToFractionBase(0.375, 2));
  668. Assert.Equal("14141414141414141414141414141414141414141414141414", NumberPrototype.ToFractionBase(0.375, 5));
  669. }
  670. [Fact]
  671. public void ShouldInvokeAFunctionValue()
  672. {
  673. RunTest(@"
  674. function add(x, y) { return x + y; }
  675. ");
  676. var add = _engine.GetValue("add");
  677. Assert.Equal(3, add.Invoke(1, 2));
  678. }
  679. [Fact]
  680. public void ShouldNotInvokeNonFunctionValue()
  681. {
  682. RunTest(@"
  683. var x= 10;
  684. ");
  685. var x = _engine.GetValue("x");
  686. Assert.Throws<ArgumentException>(() => x.Invoke(1, 2));
  687. }
  688. [Theory]
  689. [InlineData("0", 0, 16)]
  690. [InlineData("1", 1, 16)]
  691. [InlineData("100", 100, 10)]
  692. [InlineData("1100100", 100, 2)]
  693. [InlineData("2s", 100, 36)]
  694. [InlineData("2qgpckvng1s", 10000000000000000L, 36)]
  695. public void ShouldConvertNumbersToDifferentBase(string expected, long number, int radix)
  696. {
  697. var result = NumberPrototype.ToBase(number, radix);
  698. Assert.Equal(expected, result);
  699. }
  700. [Fact]
  701. public void ShouldBeCultureInvariant()
  702. {
  703. // decimals in french are separated by commas
  704. Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("fr-FR");
  705. var engine = new Engine();
  706. var result = engine.Execute("1.2 + 2.1").GetCompletionValue().AsNumber();
  707. Assert.Equal(3.3d, result);
  708. result = engine.Execute("JSON.parse('{\"x\" : 3.3}').x").GetCompletionValue().AsNumber();
  709. Assert.Equal(3.3d, result);
  710. }
  711. [Fact]
  712. public void ShouldGetTheLastSyntaxNode()
  713. {
  714. var engine = new Engine();
  715. engine.Execute("1.2");
  716. var result = engine.GetLastSyntaxNode();
  717. Assert.Equal(SyntaxNodes.Literal, result.Type);
  718. }
  719. [Fact]
  720. public void ShouldGetParseErrorLocation()
  721. {
  722. var engine = new Engine();
  723. try
  724. {
  725. engine.Execute("1.2+ new", new ParserOptions { Source = "jQuery.js" });
  726. }
  727. catch (ParserException e)
  728. {
  729. Assert.Equal(1, e.LineNumber);
  730. Assert.Equal(9, e.Column);
  731. Assert.Equal("jQuery.js", e.Source);
  732. }
  733. }
  734. }
  735. }