EngineTests.cs 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817
  1. using System;
  2. using System.Globalization;
  3. using System.IO;
  4. using System.Reflection;
  5. using Esprima;
  6. using Esprima.Ast;
  7. using Jint.Native;
  8. using Jint.Native.Array;
  9. using Jint.Native.Object;
  10. using Jint.Runtime;
  11. using Jint.Runtime.Debugger;
  12. using Xunit;
  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 ShouldHaveProperReferenceErrorMessage()
  95. {
  96. RunTest(@"
  97. 'use strict';
  98. var arr = [1, 2];
  99. try {
  100. for (i in arr) { }
  101. assert(false);
  102. }
  103. catch (ex) {
  104. assert(ex.message === 'i is not defined');
  105. }
  106. ");
  107. }
  108. [Fact]
  109. public void ShouldHaveProperNotAFunctionErrorMessage()
  110. {
  111. RunTest(@"
  112. try {
  113. var example = {};
  114. example();
  115. assert(false);
  116. }
  117. catch (ex) {
  118. assert(ex.message === 'example is not a function');
  119. }
  120. ");
  121. }
  122. [Fact]
  123. public void ShouldEvaluateHasOwnProperty()
  124. {
  125. RunTest(@"
  126. var x = {};
  127. x.Bar = 42;
  128. assert(x.hasOwnProperty('Bar'));
  129. ");
  130. }
  131. [Fact]
  132. public void FunctionConstructorsShouldCreateNewObjects()
  133. {
  134. RunTest(@"
  135. var Vehicle = function () {};
  136. var vehicle = new Vehicle();
  137. assert(vehicle != undefined);
  138. ");
  139. }
  140. [Fact]
  141. public void NewObjectsInheritFunctionConstructorProperties()
  142. {
  143. RunTest(@"
  144. var Vehicle = function () {};
  145. var vehicle = new Vehicle();
  146. Vehicle.prototype.wheelCount = 4;
  147. assert(vehicle.wheelCount == 4);
  148. assert((new Vehicle()).wheelCount == 4);
  149. ");
  150. }
  151. [Fact]
  152. public void PrototypeFunctionIsInherited()
  153. {
  154. RunTest(@"
  155. function Body(mass){
  156. this.mass = mass;
  157. }
  158. Body.prototype.offsetMass = function(dm) {
  159. this.mass += dm;
  160. return this;
  161. }
  162. var b = new Body(36);
  163. b.offsetMass(6);
  164. assert(b.mass == 42);
  165. ");
  166. }
  167. [Fact]
  168. public void FunctionConstructorCall()
  169. {
  170. RunTest(@"
  171. function Body(mass){
  172. this.mass = mass;
  173. }
  174. var john = new Body(36);
  175. assert(john.mass == 36);
  176. ");
  177. }
  178. [Fact]
  179. public void ArrowFunctionCall()
  180. {
  181. RunTest(@"
  182. var add = (a, b) => {
  183. return a + b;
  184. }
  185. var x = add(1, 2);
  186. assert(x == 3);
  187. ");
  188. }
  189. [Fact]
  190. public void ArrowFunctionExpressionCall()
  191. {
  192. RunTest(@"
  193. var add = (a, b) => a + b;
  194. var x = add(1, 2);
  195. assert(x === 3);
  196. ");
  197. }
  198. [Fact]
  199. public void ArrowFunctionScope()
  200. {
  201. RunTest(@"
  202. var bob = {
  203. _name: ""Bob"",
  204. _friends: [""Alice""],
  205. printFriends() {
  206. this._friends.forEach(f => assert(this._name === ""Bob"" && f === ""Alice""))
  207. }
  208. };
  209. bob.printFriends();
  210. ");
  211. }
  212. [Fact]
  213. public void NewObjectsShouldUsePrivateProperties()
  214. {
  215. RunTest(@"
  216. var Vehicle = function (color) {
  217. this.color = color;
  218. };
  219. var vehicle = new Vehicle('tan');
  220. assert(vehicle.color == 'tan');
  221. ");
  222. }
  223. [Fact]
  224. public void FunctionConstructorsShouldDefinePrototypeChain()
  225. {
  226. RunTest(@"
  227. function Vehicle() {};
  228. var vehicle = new Vehicle();
  229. assert(vehicle.hasOwnProperty('constructor') == false);
  230. ");
  231. }
  232. [Fact]
  233. public void NewObjectsConstructorIsObject()
  234. {
  235. RunTest(@"
  236. var o = new Object();
  237. assert(o.constructor == Object);
  238. ");
  239. }
  240. [Fact]
  241. public void NewObjectsIntanceOfConstructorObject()
  242. {
  243. RunTest(@"
  244. var o = new Object();
  245. assert(o instanceof Object);
  246. ");
  247. }
  248. [Fact]
  249. public void NewObjectsConstructorShouldBeConstructorObject()
  250. {
  251. RunTest(@"
  252. var Vehicle = function () {};
  253. var vehicle = new Vehicle();
  254. assert(vehicle.constructor == Vehicle);
  255. ");
  256. }
  257. [Fact]
  258. public void NewObjectsIntanceOfConstructorFunction()
  259. {
  260. RunTest(@"
  261. var Vehicle = function () {};
  262. var vehicle = new Vehicle();
  263. assert(vehicle instanceof Vehicle);
  264. ");
  265. }
  266. [Fact]
  267. public void ShouldEvaluateForLoops()
  268. {
  269. RunTest(@"
  270. var foo = 0;
  271. for (var i = 0; i < 5; i++) {
  272. foo += i;
  273. }
  274. assert(foo == 10);
  275. ");
  276. }
  277. [Fact]
  278. public void ShouldEvaluateRecursiveFunctions()
  279. {
  280. RunTest(@"
  281. function fib(n) {
  282. if (n < 2) {
  283. return n;
  284. }
  285. return fib(n - 1) + fib(n - 2);
  286. }
  287. var result = fib(6);
  288. assert(result == 8);
  289. ");
  290. }
  291. [Fact]
  292. public void ShouldAccessObjectProperties()
  293. {
  294. RunTest(@"
  295. var o = {};
  296. o.Foo = 'bar';
  297. o.Baz = 42;
  298. o.Blah = o.Foo + o.Baz;
  299. assert(o.Blah == 'bar42');
  300. ");
  301. }
  302. [Fact]
  303. public void ShouldConstructArray()
  304. {
  305. RunTest(@"
  306. var o = [];
  307. assert(o.length == 0);
  308. ");
  309. }
  310. [Fact]
  311. public void ArrayPushShouldIncrementLength()
  312. {
  313. RunTest(@"
  314. var o = [];
  315. o.push(1);
  316. assert(o.length == 1);
  317. ");
  318. }
  319. [Fact]
  320. public void ArrayFunctionInitializesLength()
  321. {
  322. RunTest(@"
  323. assert(Array(3).length == 3);
  324. assert(Array('3').length == 1);
  325. ");
  326. }
  327. [Fact]
  328. public void ArrayIndexerIsAssigned()
  329. {
  330. RunTest(@"
  331. var n = 8;
  332. var o = Array(n);
  333. for (var i = 0; i < n; i++) o[i] = i;
  334. assert(o[0] == 0);
  335. assert(o[7] == 7);
  336. ");
  337. }
  338. [Fact]
  339. public void DenseArrayTurnsToSparseArrayWhenSizeGrowsTooMuch()
  340. {
  341. RunTest(@"
  342. var n = 1024*10+2;
  343. var o = Array(n);
  344. for (var i = 0; i < n; i++) o[i] = i;
  345. assert(o[0] == 0);
  346. assert(o[n - 1] == n -1);
  347. ");
  348. }
  349. [Fact]
  350. public void DenseArrayTurnsToSparseArrayWhenSparseIndexed()
  351. {
  352. RunTest(@"
  353. var o = Array();
  354. o[100] = 1;
  355. assert(o[100] == 1);
  356. ");
  357. }
  358. [Fact]
  359. public void ArrayPopShouldDecrementLength()
  360. {
  361. RunTest(@"
  362. var o = [42, 'foo'];
  363. var pop = o.pop();
  364. assert(o.length == 1);
  365. assert(pop == 'foo');
  366. ");
  367. }
  368. [Fact]
  369. public void ArrayConstructor()
  370. {
  371. RunTest(@"
  372. var o = [];
  373. assert(o.constructor == Array);
  374. ");
  375. }
  376. [Fact]
  377. public void DateConstructor()
  378. {
  379. RunTest(@"
  380. var o = new Date();
  381. assert(o.constructor == Date);
  382. assert(o.hasOwnProperty('constructor') == false);
  383. ");
  384. }
  385. [Fact]
  386. public void DateConstructorWithInvalidParameters()
  387. {
  388. Assert.Throws<JavaScriptException>(() => RunTest("new Date (1, Infinity);"));
  389. }
  390. [Fact]
  391. public void ShouldConvertDateToNumber()
  392. {
  393. RunTest(@"
  394. assert(Number(new Date(0)) === 0);
  395. ");
  396. }
  397. [Fact]
  398. public void DatePrimitiveValueShouldBeNaN()
  399. {
  400. RunTest(@"
  401. assert(isNaN(Date.prototype.valueOf()));
  402. ");
  403. }
  404. [Fact]
  405. public void MathObjectIsDefined()
  406. {
  407. RunTest(@"
  408. var o = Math.abs(-1)
  409. assert(o == 1);
  410. ");
  411. }
  412. [Fact]
  413. public void VoidShouldReturnUndefined()
  414. {
  415. RunTest(@"
  416. assert(void 0 === undefined);
  417. var x = '1';
  418. assert(void x === undefined);
  419. x = 'x';
  420. assert (isNaN(void x) === true);
  421. x = new String('-1');
  422. assert (void x === undefined);
  423. ");
  424. }
  425. [Fact]
  426. public void TypeofObjectShouldReturnString()
  427. {
  428. RunTest(@"
  429. assert(typeof x === 'undefined');
  430. assert(typeof 0 === 'number');
  431. var x = 0;
  432. assert (typeof x === 'number');
  433. var x = new Object();
  434. assert (typeof x === 'object');
  435. ");
  436. }
  437. [Fact]
  438. public void MathAbsReturnsAbsolute()
  439. {
  440. RunTest(@"
  441. assert(1 == Math.abs(-1));
  442. ");
  443. }
  444. [Fact]
  445. public void NaNIsNan()
  446. {
  447. RunTest(@"
  448. var x = NaN;
  449. assert(isNaN(NaN));
  450. assert(isNaN(Math.abs(x)));
  451. ");
  452. }
  453. [Fact]
  454. public void ToNumberHandlesStringObject()
  455. {
  456. RunTest(@"
  457. x = new String('1');
  458. x *= undefined;
  459. assert(isNaN(x));
  460. ");
  461. }
  462. [Fact]
  463. public void FunctionScopesAreChained()
  464. {
  465. RunTest(@"
  466. var x = 0;
  467. function f1(){
  468. function f2(){
  469. return x;
  470. };
  471. return f2();
  472. var x = 1;
  473. }
  474. assert(f1() === undefined);
  475. ");
  476. }
  477. [Fact]
  478. public void EvalFunctionParseAndExecuteCode()
  479. {
  480. RunTest(@"
  481. var x = 0;
  482. eval('assert(x == 0)');
  483. ");
  484. }
  485. [Fact]
  486. public void ForInStatement()
  487. {
  488. RunTest(@"
  489. var x, y, str = '';
  490. for(var z in this) {
  491. str += z;
  492. }
  493. assert(str == 'xystrz');
  494. ");
  495. }
  496. [Fact]
  497. public void ForInStatementEnumeratesKeys()
  498. {
  499. RunTest(@"
  500. for(var i in 'abc');
  501. log(i);
  502. assert(i === '2');
  503. ");
  504. }
  505. [Fact]
  506. public void WithStatement()
  507. {
  508. RunTest(@"
  509. with (Math) {
  510. assert(cos(0) == 1);
  511. }
  512. ");
  513. }
  514. [Fact]
  515. public void ObjectExpression()
  516. {
  517. RunTest(@"
  518. var o = { x: 1 };
  519. assert(o.x == 1);
  520. ");
  521. }
  522. [Fact]
  523. public void StringFunctionCreatesString()
  524. {
  525. RunTest(@"
  526. assert(String(NaN) === 'NaN');
  527. ");
  528. }
  529. [Fact]
  530. public void ScopeChainInWithStatement()
  531. {
  532. RunTest(@"
  533. var x = 0;
  534. var myObj = {x : 'obj'};
  535. function f1(){
  536. var x = 1;
  537. function f2(){
  538. with(myObj){
  539. return x;
  540. }
  541. };
  542. return f2();
  543. }
  544. assert(f1() === 'obj');
  545. ");
  546. }
  547. [Fact]
  548. public void TryCatchBlockStatement()
  549. {
  550. RunTest(@"
  551. var x, y, z;
  552. try {
  553. x = 1;
  554. throw new TypeError();
  555. x = 2;
  556. }
  557. catch(e) {
  558. assert(x == 1);
  559. assert(e instanceof TypeError);
  560. y = 1;
  561. }
  562. finally {
  563. assert(x == 1);
  564. z = 1;
  565. }
  566. assert(x == 1);
  567. assert(y == 1);
  568. assert(z == 1);
  569. ");
  570. }
  571. [Fact]
  572. public void FunctionsCanBeAssigned()
  573. {
  574. RunTest(@"
  575. var sin = Math.sin;
  576. assert(sin(0) == 0);
  577. ");
  578. }
  579. [Fact]
  580. public void FunctionArgumentsIsDefined()
  581. {
  582. RunTest(@"
  583. function f() {
  584. assert(arguments.length > 0);
  585. }
  586. f(42);
  587. ");
  588. }
  589. [Fact]
  590. public void PrimitiveValueFunctions()
  591. {
  592. RunTest(@"
  593. var s = (1).toString();
  594. assert(s == '1');
  595. ");
  596. }
  597. [Theory]
  598. [InlineData(true, "'ab' == 'a' + 'b'")]
  599. public void OperatorsPrecedence(object expected, string source)
  600. {
  601. var engine = new Engine();
  602. var result = engine.Execute(source).GetCompletionValue().ToObject();
  603. Assert.Equal(expected, result);
  604. }
  605. [Fact]
  606. public void FunctionPrototypeShouldHaveApplyMethod()
  607. {
  608. RunTest(@"
  609. var numbers = [5, 6, 2, 3, 7];
  610. var max = Math.max.apply(null, numbers);
  611. assert(max == 7);
  612. ");
  613. }
  614. [Theory]
  615. [InlineData(double.NaN, "parseInt(NaN)")]
  616. [InlineData(double.NaN, "parseInt(null)")]
  617. [InlineData(double.NaN, "parseInt(undefined)")]
  618. [InlineData(double.NaN, "parseInt(new Boolean(true))")]
  619. [InlineData(double.NaN, "parseInt(Infinity)")]
  620. [InlineData(-1d, "parseInt(-1)")]
  621. [InlineData(-1d, "parseInt('-1')")]
  622. public void ShouldEvaluateParseInt(object expected, string source)
  623. {
  624. var engine = new Engine();
  625. var result = engine.Execute(source).GetCompletionValue().ToObject();
  626. Assert.Equal(expected, result);
  627. }
  628. [Fact]
  629. public void ShouldNotExecuteDebuggerStatement()
  630. {
  631. new Engine().Execute("debugger");
  632. }
  633. [Fact]
  634. public void ShouldThrowStatementCountOverflow()
  635. {
  636. Assert.Throws<StatementsCountOverflowException>(
  637. () => new Engine(cfg => cfg.MaxStatements(100)).Execute("while(true);")
  638. );
  639. }
  640. [Fact]
  641. public void ShouldThrowMemoryLimitExceeded()
  642. {
  643. Assert.Throws<MemoryLimitExceededException>(
  644. () => new Engine(cfg => cfg.LimitMemory(2048)).Execute("a=[]; while(true){ a.push(0); }")
  645. );
  646. }
  647. [Fact]
  648. public void ShouldThrowTimeout()
  649. {
  650. Assert.Throws<TimeoutException>(
  651. () => new Engine(cfg => cfg.TimeoutInterval(new TimeSpan(0, 0, 0, 0, 500))).Execute("while(true);")
  652. );
  653. }
  654. [Fact]
  655. public void CanDiscardRecursion()
  656. {
  657. var script = @"var factorial = function(n) {
  658. if (n>1) {
  659. return n * factorial(n - 1);
  660. }
  661. };
  662. var result = factorial(500);
  663. ";
  664. Assert.Throws<RecursionDepthOverflowException>(
  665. () => new Engine(cfg => cfg.LimitRecursion()).Execute(script)
  666. );
  667. }
  668. [Fact]
  669. public void ShouldDiscardHiddenRecursion()
  670. {
  671. var script = @"var renamedFunc;
  672. var exec = function(callback) {
  673. renamedFunc = callback;
  674. callback();
  675. };
  676. var result = exec(function() {
  677. renamedFunc();
  678. });
  679. ";
  680. Assert.Throws<RecursionDepthOverflowException>(
  681. () => new Engine(cfg => cfg.LimitRecursion()).Execute(script)
  682. );
  683. }
  684. [Fact]
  685. public void ShouldRecognizeAndDiscardChainedRecursion()
  686. {
  687. var script = @" var funcRoot, funcA, funcB, funcC, funcD;
  688. var funcRoot = function() {
  689. funcA();
  690. };
  691. var funcA = function() {
  692. funcB();
  693. };
  694. var funcB = function() {
  695. funcC();
  696. };
  697. var funcC = function() {
  698. funcD();
  699. };
  700. var funcD = function() {
  701. funcRoot();
  702. };
  703. funcRoot();
  704. ";
  705. Assert.Throws<RecursionDepthOverflowException>(
  706. () => new Engine(cfg => cfg.LimitRecursion()).Execute(script)
  707. );
  708. }
  709. [Fact]
  710. public void ShouldProvideCallChainWhenDiscardRecursion()
  711. {
  712. var script = @" var funcRoot, funcA, funcB, funcC, funcD;
  713. var funcRoot = function() {
  714. funcA();
  715. };
  716. var funcA = function() {
  717. funcB();
  718. };
  719. var funcB = function() {
  720. funcC();
  721. };
  722. var funcC = function() {
  723. funcD();
  724. };
  725. var funcD = function() {
  726. funcRoot();
  727. };
  728. funcRoot();
  729. ";
  730. RecursionDepthOverflowException exception = null;
  731. try
  732. {
  733. new Engine(cfg => cfg.LimitRecursion()).Execute(script);
  734. }
  735. catch (RecursionDepthOverflowException ex)
  736. {
  737. exception = ex;
  738. }
  739. Assert.NotNull(exception);
  740. Assert.Equal("funcRoot->funcA->funcB->funcC->funcD", exception.CallChain);
  741. Assert.Equal("funcRoot", exception.CallExpressionReference);
  742. }
  743. [Fact]
  744. public void ShouldAllowShallowRecursion()
  745. {
  746. var script = @"var factorial = function(n) {
  747. if (n>1) {
  748. return n * factorial(n - 1);
  749. }
  750. };
  751. var result = factorial(8);
  752. ";
  753. new Engine(cfg => cfg.LimitRecursion(20)).Execute(script);
  754. }
  755. [Fact]
  756. public void ShouldDiscardDeepRecursion()
  757. {
  758. var script = @"var factorial = function(n) {
  759. if (n>1) {
  760. return n * factorial(n - 1);
  761. }
  762. };
  763. var result = factorial(38);
  764. ";
  765. Assert.Throws<RecursionDepthOverflowException>(
  766. () => new Engine(cfg => cfg.LimitRecursion(20)).Execute(script)
  767. );
  768. }
  769. [Fact]
  770. public void ShouldConvertDoubleToStringWithoutLosingPrecision()
  771. {
  772. RunTest(@"
  773. assert(String(14.915832707045631) === '14.915832707045631');
  774. assert(String(-14.915832707045631) === '-14.915832707045631');
  775. assert(String(0.5) === '0.5');
  776. assert(String(0.00000001) === '1e-8');
  777. assert(String(0.000001) === '0.000001');
  778. assert(String(-1.0) === '-1');
  779. assert(String(30.0) === '30');
  780. assert(String(0.2388906159889881) === '0.2388906159889881');
  781. ");
  782. }
  783. [Fact]
  784. public void ShouldWriteNumbersUsingBases()
  785. {
  786. RunTest(@"
  787. assert(15.0.toString() === '15');
  788. assert(15.0.toString(2) === '1111');
  789. assert(15.0.toString(8) === '17');
  790. assert(15.0.toString(16) === 'f');
  791. assert(15.0.toString(17) === 'f');
  792. assert(15.0.toString(36) === 'f');
  793. assert(15.1.toString(36) === 'f.3llllllllkau6snqkpygsc3di');
  794. ");
  795. }
  796. [Fact]
  797. public void ShouldNotAlterSlashesInRegex()
  798. {
  799. RunTest(@"
  800. assert(new RegExp('/').toString() === '///');
  801. ");
  802. }
  803. [Fact]
  804. public void ShouldHandleEscapedSlashesInRegex()
  805. {
  806. RunTest(@"
  807. var regex = /[a-z]\/[a-z]/;
  808. assert(regex.test('a/b') === true);
  809. assert(regex.test('a\\/b') === false);
  810. ");
  811. }
  812. [Fact]
  813. public void ShouldComputeFractionInBase()
  814. {
  815. Assert.Equal("011", _engine.Number.PrototypeObject.ToFractionBase(0.375, 2));
  816. Assert.Equal("14141414141414141414141414141414141414141414141414", _engine.Number.PrototypeObject.ToFractionBase(0.375, 5));
  817. }
  818. [Fact]
  819. public void ShouldInvokeAFunctionValue()
  820. {
  821. RunTest(@"
  822. function add(x, y) { return x + y; }
  823. ");
  824. var add = _engine.GetValue("add");
  825. Assert.Equal(3, add.Invoke(1, 2));
  826. }
  827. [Fact]
  828. public void ShouldAllowInvokeAFunctionValueWithNullValueAsArgument()
  829. {
  830. RunTest(@"
  831. function get(x) { return x; }
  832. ");
  833. var add = _engine.GetValue("get");
  834. string str = null;
  835. Assert.Equal(Native.JsValue.Null, add.Invoke(str));
  836. }
  837. [Fact]
  838. public void ShouldNotInvokeNonFunctionValue()
  839. {
  840. RunTest(@"
  841. var x= 10;
  842. ");
  843. var x = _engine.GetValue("x");
  844. Assert.Throws<ArgumentException>(() => x.Invoke(1, 2));
  845. }
  846. [Fact]
  847. public void ShouldInvokeAFunctionValueThatBelongsToAnObject()
  848. {
  849. RunTest(@"
  850. var obj = { foo: 5, getFoo: function (bar) { return 'foo is ' + this.foo + ', bar is ' + bar; } };
  851. ");
  852. var obj = _engine.GetValue("obj").AsObject();
  853. var getFoo = obj.Get("getFoo");
  854. Assert.Equal("foo is 5, bar is 7", _engine.Invoke(getFoo, obj, new object[] { 7 }).AsString());
  855. }
  856. [Fact]
  857. public void ShouldNotInvokeNonFunctionValueThatBelongsToAnObject()
  858. {
  859. RunTest(@"
  860. var obj = { foo: 2 };
  861. ");
  862. var obj = _engine.GetValue("obj").AsObject();
  863. var foo = obj.Get("foo");
  864. Assert.Throws<ArgumentException>(() => _engine.Invoke(foo, obj, new object[] { }));
  865. }
  866. [Fact]
  867. public void ShouldNotAllowModifyingSharedUndefinedDescriptor()
  868. {
  869. var e = new Engine();
  870. e.Execute("var x = { literal: true };");
  871. var pd = e.GetValue("x").AsObject().GetProperty("doesNotExist");
  872. Assert.Throws<InvalidOperationException>(() => pd.Value = "oh no, assigning this breaks things");
  873. }
  874. [Theory]
  875. [InlineData("0", 0, 16)]
  876. [InlineData("1", 1, 16)]
  877. [InlineData("100", 100, 10)]
  878. [InlineData("1100100", 100, 2)]
  879. [InlineData("2s", 100, 36)]
  880. [InlineData("2qgpckvng1s", 10000000000000000L, 36)]
  881. public void ShouldConvertNumbersToDifferentBase(string expected, long number, int radix)
  882. {
  883. var result = _engine.Number.PrototypeObject.ToBase(number, radix);
  884. Assert.Equal(expected, result);
  885. }
  886. [Fact]
  887. public void JsonParserShouldParseNegativeNumber()
  888. {
  889. RunTest(@"
  890. var a = JSON.parse('{ ""x"":-1 }');
  891. assert(a.x === -1);
  892. var b = JSON.parse('{ ""x"": -1 }');
  893. assert(b.x === -1);
  894. ");
  895. }
  896. [Fact]
  897. public void JsonParserShouldUseToString()
  898. {
  899. RunTest(@"
  900. var a = JSON.parse(null); // Equivalent to JSON.parse('null')
  901. assert(a === null);
  902. ");
  903. RunTest(@"
  904. var a = JSON.parse(true); // Equivalent to JSON.parse('true')
  905. assert(a === true);
  906. ");
  907. RunTest(@"
  908. var a = JSON.parse(false); // Equivalent to JSON.parse('false')
  909. assert(a === false);
  910. ");
  911. RunTest(@"
  912. try {
  913. JSON.parse(undefined); // Equivalent to JSON.parse('undefined')
  914. assert(false);
  915. }
  916. catch(ex) {
  917. assert(ex instanceof SyntaxError);
  918. }
  919. ");
  920. RunTest(@"
  921. try {
  922. JSON.parse({}); // Equivalent to JSON.parse('[object Object]')
  923. assert(false);
  924. }
  925. catch(ex) {
  926. assert(ex instanceof SyntaxError);
  927. }
  928. ");
  929. RunTest(@"
  930. try {
  931. JSON.parse(function() { }); // Equivalent to JSON.parse('function () {}')
  932. assert(false);
  933. }
  934. catch(ex) {
  935. assert(ex instanceof SyntaxError);
  936. }
  937. ");
  938. }
  939. [Fact]
  940. public void JsonParserShouldDetectInvalidNegativeNumberSyntax()
  941. {
  942. RunTest(@"
  943. try {
  944. JSON.parse('{ ""x"": -.1 }'); // Not allowed
  945. assert(false);
  946. }
  947. catch(ex) {
  948. assert(ex instanceof SyntaxError);
  949. }
  950. ");
  951. RunTest(@"
  952. try {
  953. JSON.parse('{ ""x"": - 1 }'); // Not allowed
  954. assert(false);
  955. }
  956. catch(ex) {
  957. assert(ex instanceof SyntaxError);
  958. }
  959. ");
  960. }
  961. [Fact]
  962. public void JsonParserShouldUseReviverFunction()
  963. {
  964. RunTest(@"
  965. var jsonObj = JSON.parse('{""p"": 5}', function (key, value){
  966. return typeof value === 'number' ? value * 2 : value;
  967. });
  968. assert(jsonObj.p === 10);
  969. ");
  970. RunTest(@"
  971. var expectedKeys = [""1"", ""2"", ""4"", ""6"", ""5"", ""3"", """"];
  972. var actualKeys = [];
  973. JSON.parse('{""1"": 1, ""2"": 2, ""3"": {""4"": 4, ""5"": {""6"": 6}}}', function (key, value){
  974. actualKeys.push(key);
  975. return value;// return the unchanged property value.
  976. });
  977. expectedKeys.forEach(function (val, i){
  978. assert(actualKeys[i] === val);
  979. });
  980. ");
  981. }
  982. [Fact]
  983. [ReplaceCulture("fr-FR")]
  984. public void ShouldBeCultureInvariant()
  985. {
  986. // decimals in french are separated by commas
  987. var engine = new Engine();
  988. var result = engine.Execute("1.2 + 2.1").GetCompletionValue().AsNumber();
  989. Assert.Equal(3.3d, result);
  990. result = engine.Execute("JSON.parse('{\"x\" : 3.3}').x").GetCompletionValue().AsNumber();
  991. Assert.Equal(3.3d, result);
  992. }
  993. [Fact]
  994. public void ShouldGetTheLastSyntaxNode()
  995. {
  996. var engine = new Engine();
  997. engine.Execute("1.2");
  998. var result = engine.GetLastSyntaxNode();
  999. Assert.Equal(Nodes.Literal, result.Type);
  1000. }
  1001. [Fact]
  1002. public void ShouldGetParseErrorLocation()
  1003. {
  1004. var engine = new Engine();
  1005. try
  1006. {
  1007. engine.Execute("1.2+ new", new ParserOptions(source: "jQuery.js"));
  1008. }
  1009. catch (ParserException e)
  1010. {
  1011. Assert.Equal(1, e.LineNumber);
  1012. Assert.Equal(9, e.Column);
  1013. Assert.Equal("jQuery.js", e.SourceText);
  1014. }
  1015. }
  1016. #region DateParsingAndStrings
  1017. [Fact]
  1018. public void ParseShouldReturnNumber()
  1019. {
  1020. var engine = new Engine();
  1021. var result = engine.Execute("Date.parse('1970-01-01');").GetCompletionValue().AsNumber();
  1022. Assert.Equal(0, result);
  1023. }
  1024. [Fact]
  1025. public void TimeWithinDayShouldHandleNegativeValues()
  1026. {
  1027. RunTest(@"
  1028. // using a date < 1970 so that the primitive value is negative
  1029. var d = new Date(1958, 0, 1);
  1030. d.setMonth(-1);
  1031. assert(d.getDate() == 1);
  1032. ");
  1033. }
  1034. [Fact]
  1035. public void LocalDateTimeShouldNotLoseTimezone()
  1036. {
  1037. var date = new DateTime(2016, 1, 1, 13, 0, 0, DateTimeKind.Local);
  1038. var engine = new Engine().SetValue("localDate", date);
  1039. engine.Execute(@"localDate");
  1040. var actual = engine.GetCompletionValue().AsDate().ToDateTime();
  1041. Assert.Equal(date.ToUniversalTime(), actual.ToUniversalTime());
  1042. Assert.Equal(date.ToLocalTime(), actual.ToLocalTime());
  1043. }
  1044. [Fact]
  1045. public void UtcShouldUseUtc()
  1046. {
  1047. var customTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central Europe Standard Time");
  1048. var engine = new Engine(cfg => cfg.LocalTimeZone(customTimeZone));
  1049. var result = engine.Execute("Date.UTC(1970,0,1)").GetCompletionValue().AsNumber();
  1050. Assert.Equal(0, result);
  1051. }
  1052. [Fact]
  1053. public void ShouldUseLocalTimeZoneOverride()
  1054. {
  1055. const string customName = "Custom Time";
  1056. var customTimeZone = TimeZoneInfo.CreateCustomTimeZone(customName, new TimeSpan(0, 11, 0), customName, customName, customName, null, false);
  1057. var engine = new Engine(cfg => cfg.LocalTimeZone(customTimeZone));
  1058. var epochGetLocalMinutes = engine.Execute("var d = new Date(0); d.getMinutes();").GetCompletionValue().AsNumber();
  1059. Assert.Equal(11, epochGetLocalMinutes);
  1060. var localEpochGetUtcMinutes = engine.Execute("var d = new Date(1970,0,1); d.getUTCMinutes();").GetCompletionValue().AsNumber();
  1061. Assert.Equal(49, localEpochGetUtcMinutes);
  1062. var parseLocalEpoch = engine.Execute("Date.parse('January 1, 1970');").GetCompletionValue().AsNumber();
  1063. Assert.Equal(-11 * 60 * 1000, parseLocalEpoch);
  1064. var epochToLocalString = engine.Execute("var d = new Date(0); d.toString();").GetCompletionValue().AsString();
  1065. Assert.Equal("Thu Jan 01 1970 00:11:00 GMT+00:11", epochToLocalString);
  1066. var epochToUTCString = engine.Execute("var d = new Date(0); d.toUTCString();").GetCompletionValue().AsString();
  1067. Assert.Equal("Thu Jan 01 1970 00:00:00 GMT", epochToUTCString);
  1068. }
  1069. [Theory]
  1070. [InlineData("1970")]
  1071. [InlineData("1970-01")]
  1072. [InlineData("1970-01-01")]
  1073. [InlineData("1970-01-01T00:00")]
  1074. [InlineData("1970-01-01T00:00:00")]
  1075. [InlineData("1970-01-01T00:00:00.000")]
  1076. [InlineData("1970Z")]
  1077. [InlineData("1970-1Z")]
  1078. [InlineData("1970-1-1Z")]
  1079. [InlineData("1970-1-1T0:0Z")]
  1080. [InlineData("1970-1-1T0:0:0Z")]
  1081. [InlineData("1970-1-1T0:0:0.0Z")]
  1082. [InlineData("1970/1Z")]
  1083. [InlineData("1970/1/1Z")]
  1084. [InlineData("1970/1/1 0:0Z")]
  1085. [InlineData("1970/1/1 0:0:0Z")]
  1086. [InlineData("1970/1/1 0:0:0.0Z")]
  1087. [InlineData("January 1, 1970 GMT")]
  1088. [InlineData("1970-01-01T00:00:00.000-00:00")]
  1089. public void ShouldParseAsUtc(string date)
  1090. {
  1091. #if NET451
  1092. const string customName = "Custom Time";
  1093. var customTimeZone = TimeZoneInfo.CreateCustomTimeZone(customName, new TimeSpan(7, 11, 0), customName, customName, customName, null, false);
  1094. #else
  1095. var customTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Tonga Standard Time");
  1096. #endif
  1097. var engine = new Engine(cfg => cfg.LocalTimeZone(customTimeZone));
  1098. engine.SetValue("d", date);
  1099. var result = engine.Execute("Date.parse(d);").GetCompletionValue().AsNumber();
  1100. Assert.Equal(0, result);
  1101. }
  1102. [Theory]
  1103. [InlineData("1970/01")]
  1104. [InlineData("1970/01/01")]
  1105. [InlineData("1970/01/01T00:00")]
  1106. [InlineData("1970/01/01 00:00")]
  1107. [InlineData("1970-1")]
  1108. [InlineData("1970-1-1")]
  1109. [InlineData("1970-1-1T0:0")]
  1110. [InlineData("1970-1-1 0:0")]
  1111. [InlineData("1970/1")]
  1112. [InlineData("1970/1/1")]
  1113. [InlineData("1970/1/1T0:0")]
  1114. [InlineData("1970/1/1 0:0")]
  1115. [InlineData("01-1970")]
  1116. [InlineData("01-01-1970")]
  1117. [InlineData("January 1, 1970")]
  1118. [InlineData("1970-01-01T00:00:00.000+00:11")]
  1119. public void ShouldParseAsLocalTime(string date)
  1120. {
  1121. const int timespanMinutes = 11;
  1122. const int msPriorMidnight = -timespanMinutes * 60 * 1000;
  1123. const string customName = "Custom Time";
  1124. var customTimeZone = TimeZoneInfo.CreateCustomTimeZone(customName, new TimeSpan(0, timespanMinutes, 0), customName, customName, customName, null, false);
  1125. var engine = new Engine(cfg => cfg.LocalTimeZone(customTimeZone)).SetValue("d", date);
  1126. var result = engine.Execute("Date.parse(d);").GetCompletionValue().AsNumber();
  1127. Assert.Equal(msPriorMidnight, result);
  1128. }
  1129. public static System.Collections.Generic.IEnumerable<object[]> TestDates
  1130. {
  1131. get
  1132. {
  1133. yield return new object[] { new DateTime(2000, 1, 1) };
  1134. yield return new object[] { new DateTime(2000, 1, 1, 0, 15, 15, 15) };
  1135. yield return new object[] { new DateTime(2000, 6, 1, 0, 15, 15, 15) };
  1136. yield return new object[] { new DateTime(1900, 1, 1) };
  1137. yield return new object[] { new DateTime(1900, 1, 1, 0, 15, 15, 15) };
  1138. yield return new object[] { new DateTime(1900, 6, 1, 0, 15, 15, 15) };
  1139. }
  1140. }
  1141. [Theory, MemberData("TestDates")]
  1142. public void TestDateToISOStringFormat(DateTime testDate)
  1143. {
  1144. var customTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Tonga Standard Time");
  1145. var engine = new Engine(ctx => ctx.LocalTimeZone(customTimeZone));
  1146. var testDateTimeOffset = new DateTimeOffset(testDate, customTimeZone.GetUtcOffset(testDate));
  1147. engine.Execute(
  1148. 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));
  1149. Assert.Equal(testDateTimeOffset.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture), engine.Execute("d.toISOString();").GetCompletionValue().ToString());
  1150. }
  1151. [Theory, MemberData("TestDates")]
  1152. public void TestDateToStringFormat(DateTime testDate)
  1153. {
  1154. var customTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Tonga Standard Time");
  1155. var engine = new Engine(ctx => ctx.LocalTimeZone(customTimeZone));
  1156. var testDateTimeOffset = new DateTimeOffset(testDate, customTimeZone.GetUtcOffset(testDate));
  1157. engine.Execute(
  1158. 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));
  1159. var expected = testDateTimeOffset.ToString("ddd MMM dd yyyy HH:mm:ss 'GMT'zzz", CultureInfo.InvariantCulture);
  1160. var actual = engine.Execute("d.toString();").GetCompletionValue().ToString();
  1161. Assert.Equal(expected, actual);
  1162. }
  1163. #endregion
  1164. //DateParsingAndStrings
  1165. [Fact]
  1166. public void EmptyStringShouldMatchRegex()
  1167. {
  1168. RunTest(@"
  1169. var regex = /^(?:$)/g;
  1170. assert(''.match(regex) instanceof Array);
  1171. ");
  1172. }
  1173. [Fact]
  1174. public void ShouldExecuteHandlebars()
  1175. {
  1176. var content = GetEmbeddedFile("handlebars.js");
  1177. RunTest(content);
  1178. RunTest(@"
  1179. var source = 'Hello {{name}}';
  1180. var template = Handlebars.compile(source);
  1181. var context = {name: 'Paul'};
  1182. var html = template(context);
  1183. assert('Hello Paul' == html);
  1184. ");
  1185. }
  1186. [Fact]
  1187. public void ShouldExecuteDromaeoBase64()
  1188. {
  1189. RunTest(@"
  1190. var startTest = function () { };
  1191. var test = function (name, fn) { fn(); };
  1192. var endTest = function () { };
  1193. var prep = function (fn) { fn(); };
  1194. ");
  1195. var content = GetEmbeddedFile("dromaeo-string-base64.js");
  1196. RunTest(content);
  1197. }
  1198. [Fact]
  1199. public void ShouldExecuteKnockoutWithErrorWhenIntolerant()
  1200. {
  1201. var content = GetEmbeddedFile("knockout-3.4.0.js");
  1202. var ex = Assert.Throws<ParserException>(() => _engine.Execute(content, new ParserOptions { Tolerant = false }));
  1203. Assert.Contains("Duplicate __proto__ fields are not allowed in object literals", ex.Message);
  1204. }
  1205. [Fact]
  1206. public void ShouldExecuteKnockoutWithoutErrorWhenTolerant()
  1207. {
  1208. var content = GetEmbeddedFile("knockout-3.4.0.js");
  1209. _engine.Execute(content, new ParserOptions { Tolerant = true });
  1210. }
  1211. [Fact]
  1212. public void ShouldExecuteLodash()
  1213. {
  1214. var content = GetEmbeddedFile("lodash.min.js");
  1215. RunTest(content);
  1216. }
  1217. [Fact]
  1218. public void DateParseReturnsNaN()
  1219. {
  1220. RunTest(@"
  1221. var d = Date.parse('not a date');
  1222. assert(isNaN(d));
  1223. ");
  1224. }
  1225. [Fact]
  1226. public void ShouldIgnoreHtmlComments()
  1227. {
  1228. RunTest(@"
  1229. var d = Date.parse('not a date'); <!-- a comment -->
  1230. assert(isNaN(d));
  1231. ");
  1232. }
  1233. [Fact]
  1234. public void DateShouldAllowEntireDotNetDateRange()
  1235. {
  1236. var engine = new Engine();
  1237. var minValue = engine.Execute("new Date('0001-01-01T00:00:00.000')").GetCompletionValue().ToObject();
  1238. Assert.Equal(new DateTime(1, 1, 1, 0, 0, 0, DateTimeKind.Utc), minValue);
  1239. var maxValue = engine.Execute("new Date('9999-12-31T23:59:59.999')").GetCompletionValue().ToObject();
  1240. Assert.Equal(new DateTime(9999, 12, 31, 23, 59, 59, 999, DateTimeKind.Utc), maxValue);
  1241. }
  1242. [Fact]
  1243. public void ShouldConstructNewArrayWithInteger()
  1244. {
  1245. RunTest(@"
  1246. var a = new Array(3);
  1247. assert(a.length === 3);
  1248. assert(a[0] == undefined);
  1249. assert(a[1] == undefined);
  1250. assert(a[2] == undefined);
  1251. ");
  1252. }
  1253. [Fact]
  1254. public void ShouldConstructNewArrayWithString()
  1255. {
  1256. RunTest(@"
  1257. var a = new Array('foo');
  1258. assert(a.length === 1);
  1259. assert(a[0] === 'foo');
  1260. ");
  1261. }
  1262. [Fact]
  1263. public void ShouldThrowRangeExceptionWhenConstructedWithNonInteger()
  1264. {
  1265. RunTest(@"
  1266. var result = false;
  1267. try {
  1268. var a = new Array(3.4);
  1269. }
  1270. catch(e) {
  1271. result = e instanceof RangeError;
  1272. }
  1273. assert(result);
  1274. ");
  1275. }
  1276. [Fact]
  1277. public void ShouldInitializeArrayWithSingleIngegerValue()
  1278. {
  1279. RunTest(@"
  1280. var a = [3];
  1281. assert(a.length === 1);
  1282. assert(a[0] === 3);
  1283. ");
  1284. }
  1285. [Fact]
  1286. public void ShouldInitializeJsonObjectArrayWithSingleIntegerValue()
  1287. {
  1288. RunTest(@"
  1289. var x = JSON.parse('{ ""a"": [3] }');
  1290. assert(x.a.length === 1);
  1291. assert(x.a[0] === 3);
  1292. ");
  1293. }
  1294. [Fact]
  1295. public void ShouldInitializeJsonArrayWithSingleIntegerValue()
  1296. {
  1297. RunTest(@"
  1298. var a = JSON.parse('[3]');
  1299. assert(a.length === 1);
  1300. assert(a[0] === 3);
  1301. ");
  1302. }
  1303. [Fact]
  1304. public void ShouldReturnTrueForEmptyIsNaNStatement()
  1305. {
  1306. RunTest(@"
  1307. assert(true === isNaN());
  1308. ");
  1309. }
  1310. [Theory]
  1311. [InlineData(4d, 0, "4")]
  1312. [InlineData(4d, 1, "4.0")]
  1313. [InlineData(4d, 2, "4.00")]
  1314. [InlineData(28.995, 2, "29.00")]
  1315. [InlineData(-28.995, 2, "-29.00")]
  1316. [InlineData(-28.495, 2, "-28.50")]
  1317. [InlineData(-28.445, 2, "-28.45")]
  1318. [InlineData(28.445, 2, "28.45")]
  1319. [InlineData(10.995, 0, "11")]
  1320. public void ShouldRoundToFixedDecimal(double number, int fractionDigits, string result)
  1321. {
  1322. var engine = new Engine();
  1323. var value = engine.Execute(
  1324. String.Format("new Number({0}).toFixed({1})",
  1325. number.ToString(CultureInfo.InvariantCulture),
  1326. fractionDigits.ToString(CultureInfo.InvariantCulture)))
  1327. .GetCompletionValue().ToObject();
  1328. Assert.Equal(value, result);
  1329. }
  1330. [Fact]
  1331. public void ShouldSortArrayWhenCompareFunctionReturnsFloatingPointNumber()
  1332. {
  1333. RunTest(@"
  1334. var nums = [1, 1.1, 1.2, 2, 2, 2.1, 2.2];
  1335. nums.sort(function(a,b){return b-a;});
  1336. assert(nums[0] === 2.2);
  1337. assert(nums[1] === 2.1);
  1338. assert(nums[2] === 2);
  1339. assert(nums[3] === 2);
  1340. assert(nums[4] === 1.2);
  1341. assert(nums[5] === 1.1);
  1342. assert(nums[6] === 1);
  1343. ");
  1344. }
  1345. [Fact]
  1346. public void ShouldBreakWhenBreakpointIsReached()
  1347. {
  1348. countBreak = 0;
  1349. stepMode = StepMode.None;
  1350. var engine = new Engine(options => options.DebugMode());
  1351. engine.Break += EngineStep;
  1352. engine.BreakPoints.Add(new BreakPoint(1, 1));
  1353. engine.Execute(@"var local = true;
  1354. if (local === true)
  1355. {}");
  1356. engine.Break -= EngineStep;
  1357. Assert.Equal(1, countBreak);
  1358. }
  1359. [Fact]
  1360. public void ShouldExecuteStepByStep()
  1361. {
  1362. countBreak = 0;
  1363. stepMode = StepMode.Into;
  1364. var engine = new Engine(options => options.DebugMode());
  1365. engine.Step += EngineStep;
  1366. engine.Execute(@"var local = true;
  1367. var creatingSomeOtherLine = 0;
  1368. var lastOneIPromise = true");
  1369. engine.Step -= EngineStep;
  1370. Assert.Equal(3, countBreak);
  1371. }
  1372. [Fact]
  1373. public void ShouldNotBreakTwiceIfSteppingOverBreakpoint()
  1374. {
  1375. countBreak = 0;
  1376. stepMode = StepMode.Into;
  1377. var engine = new Engine(options => options.DebugMode());
  1378. engine.BreakPoints.Add(new BreakPoint(1, 1));
  1379. engine.Step += EngineStep;
  1380. engine.Break += EngineStep;
  1381. engine.Execute(@"var local = true;");
  1382. engine.Step -= EngineStep;
  1383. engine.Break -= EngineStep;
  1384. Assert.Equal(1, countBreak);
  1385. }
  1386. private StepMode EngineStep(object sender, DebugInformation debugInfo)
  1387. {
  1388. Assert.NotNull(sender);
  1389. Assert.IsType(typeof(Engine), sender);
  1390. Assert.NotNull(debugInfo);
  1391. countBreak++;
  1392. return stepMode;
  1393. }
  1394. [Fact]
  1395. public void ShouldShowProperDebugInformation()
  1396. {
  1397. countBreak = 0;
  1398. stepMode = StepMode.None;
  1399. var engine = new Engine(options => options.DebugMode());
  1400. engine.BreakPoints.Add(new BreakPoint(5, 0));
  1401. engine.Break += EngineStepVerifyDebugInfo;
  1402. engine.Execute(@"var global = true;
  1403. function func1()
  1404. {
  1405. var local = false;
  1406. ;
  1407. }
  1408. func1();");
  1409. engine.Break -= EngineStepVerifyDebugInfo;
  1410. Assert.Equal(1, countBreak);
  1411. }
  1412. private StepMode EngineStepVerifyDebugInfo(object sender, DebugInformation debugInfo)
  1413. {
  1414. Assert.NotNull(sender);
  1415. Assert.IsType(typeof(Engine), sender);
  1416. Assert.NotNull(debugInfo);
  1417. Assert.NotNull(debugInfo.CallStack);
  1418. Assert.NotNull(debugInfo.CurrentStatement);
  1419. Assert.NotNull(debugInfo.Locals);
  1420. Assert.Single(debugInfo.CallStack);
  1421. Assert.Equal("func1()", debugInfo.CallStack.Peek());
  1422. Assert.Contains(debugInfo.Globals, kvp => kvp.Key.Equals("global", StringComparison.Ordinal) && kvp.Value.AsBoolean() == true);
  1423. Assert.Contains(debugInfo.Globals, kvp => kvp.Key.Equals("local", StringComparison.Ordinal) && kvp.Value.AsBoolean() == false);
  1424. Assert.Contains(debugInfo.Locals, kvp => kvp.Key.Equals("local", StringComparison.Ordinal) && kvp.Value.AsBoolean() == false);
  1425. Assert.DoesNotContain(debugInfo.Locals, kvp => kvp.Key.Equals("global", StringComparison.Ordinal));
  1426. countBreak++;
  1427. return stepMode;
  1428. }
  1429. [Fact]
  1430. public void ShouldBreakWhenConditionIsMatched()
  1431. {
  1432. countBreak = 0;
  1433. stepMode = StepMode.None;
  1434. var engine = new Engine(options => options.DebugMode());
  1435. engine.Break += EngineStep;
  1436. engine.BreakPoints.Add(new BreakPoint(5, 16, "condition === true"));
  1437. engine.BreakPoints.Add(new BreakPoint(6, 16, "condition === false"));
  1438. engine.Execute(@"var local = true;
  1439. var condition = true;
  1440. if (local === true)
  1441. {
  1442. ;
  1443. ;
  1444. }");
  1445. engine.Break -= EngineStep;
  1446. Assert.Equal(1, countBreak);
  1447. }
  1448. [Fact]
  1449. public void ShouldNotStepInSameLevelStatementsWhenStepOut()
  1450. {
  1451. countBreak = 0;
  1452. stepMode = StepMode.Out;
  1453. var engine = new Engine(options => options.DebugMode());
  1454. engine.Step += EngineStep;
  1455. engine.Execute(@"function func() // first step - then stepping out
  1456. {
  1457. ; // shall not step
  1458. ; // not even here
  1459. }
  1460. func(); // shall not step
  1461. ; // shall not step ");
  1462. engine.Step -= EngineStep;
  1463. Assert.Equal(1, countBreak);
  1464. }
  1465. [Fact]
  1466. public void ShouldNotStepInIfRequiredToStepOut()
  1467. {
  1468. countBreak = 0;
  1469. var engine = new Engine(options => options.DebugMode());
  1470. engine.Step += EngineStepOutWhenInsideFunction;
  1471. engine.Execute(@"function func() // first step
  1472. {
  1473. ; // third step - now stepping out
  1474. ; // it should not step here
  1475. }
  1476. func(); // second step
  1477. ; // fourth step ");
  1478. engine.Step -= EngineStepOutWhenInsideFunction;
  1479. Assert.Equal(4, countBreak);
  1480. }
  1481. private StepMode EngineStepOutWhenInsideFunction(object sender, DebugInformation debugInfo)
  1482. {
  1483. Assert.NotNull(sender);
  1484. Assert.IsType(typeof(Engine), sender);
  1485. Assert.NotNull(debugInfo);
  1486. countBreak++;
  1487. if (debugInfo.CallStack.Count > 0)
  1488. return StepMode.Out;
  1489. return StepMode.Into;
  1490. }
  1491. [Fact]
  1492. public void ShouldBreakWhenStatementIsMultiLine()
  1493. {
  1494. countBreak = 0;
  1495. stepMode = StepMode.None;
  1496. var engine = new Engine(options => options.DebugMode());
  1497. engine.BreakPoints.Add(new BreakPoint(4, 33));
  1498. engine.Break += EngineStep;
  1499. engine.Execute(@"var global = true;
  1500. function func1()
  1501. {
  1502. var local =
  1503. false;
  1504. }
  1505. func1();");
  1506. engine.Break -= EngineStep;
  1507. Assert.Equal(1, countBreak);
  1508. }
  1509. [Fact]
  1510. public void ShouldNotStepInsideIfRequiredToStepOver()
  1511. {
  1512. countBreak = 0;
  1513. var engine = new Engine(options => options.DebugMode());
  1514. stepMode = StepMode.Over;
  1515. engine.Step += EngineStep;
  1516. engine.Execute(@"function func() // first step
  1517. {
  1518. ; // third step - it shall not step here
  1519. ; // it shall not step here
  1520. }
  1521. func(); // second step
  1522. ; // third step ");
  1523. engine.Step -= EngineStep;
  1524. Assert.Equal(3, countBreak);
  1525. }
  1526. [Fact]
  1527. public void ShouldStepAllStatementsWithoutInvocationsIfStepOver()
  1528. {
  1529. countBreak = 0;
  1530. var engine = new Engine(options => options.DebugMode());
  1531. stepMode = StepMode.Over;
  1532. engine.Step += EngineStep;
  1533. engine.Execute(@"var step1 = 1; // first step
  1534. var step2 = 2; // second step
  1535. if (step1 !== step2) // third step
  1536. { // fourth step
  1537. ; // fifth step
  1538. }");
  1539. engine.Step -= EngineStep;
  1540. Assert.Equal(5, countBreak);
  1541. }
  1542. [Fact]
  1543. public void ShouldEvaluateVariableAssignmentFromLeftToRight()
  1544. {
  1545. RunTest(@"
  1546. var keys = ['a']
  1547. , source = { a: 3}
  1548. , target = {}
  1549. , key
  1550. , i = 0;
  1551. target[key = keys[i++]] = source[key];
  1552. assert(i == 1);
  1553. assert(key == 'a');
  1554. assert(target[key] == 3);
  1555. ");
  1556. }
  1557. [Fact]
  1558. public void ObjectShouldBeExtensible()
  1559. {
  1560. RunTest(@"
  1561. try {
  1562. Object.defineProperty(Object.defineProperty, 'foo', { value: 1 });
  1563. }
  1564. catch(e) {
  1565. assert(false);
  1566. }
  1567. ");
  1568. }
  1569. [Fact]
  1570. public void ArrayIndexShouldBeConvertedToUint32()
  1571. {
  1572. // This is missing from ECMA tests suite
  1573. // http://www.ecma-international.org/ecma-262/5.1/#sec-15.4
  1574. RunTest(@"
  1575. var a = [ 'foo' ];
  1576. assert(a[0] === 'foo');
  1577. assert(a['0'] === 'foo');
  1578. assert(a['00'] === undefined);
  1579. ");
  1580. }
  1581. [Fact]
  1582. public void DatePrototypeFunctionWorkOnDateOnly()
  1583. {
  1584. RunTest(@"
  1585. try {
  1586. var myObj = Object.create(Date.prototype);
  1587. myObj.toDateString();
  1588. } catch (e) {
  1589. assert(e instanceof TypeError);
  1590. }
  1591. ");
  1592. }
  1593. [Fact]
  1594. public void DateToStringMethodsShouldUseCurrentTimeZoneAndCulture()
  1595. {
  1596. // Forcing to PDT and FR for tests
  1597. // var PDT = TimeZoneInfo.CreateCustomTimeZone("Pacific Daylight Time", new TimeSpan(-7, 0, 0), "Pacific Daylight Time", "Pacific Daylight Time");
  1598. var PDT = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
  1599. var FR = new CultureInfo("fr-FR");
  1600. var engine = new Engine(options => options.LocalTimeZone(PDT).Culture(FR))
  1601. .SetValue("log", new Action<object>(Console.WriteLine))
  1602. .SetValue("assert", new Action<bool>(Assert.True))
  1603. .SetValue("equal", new Action<object, object>(Assert.Equal))
  1604. ;
  1605. engine.Execute(@"
  1606. var d = new Date(1433160000000);
  1607. equal('Mon Jun 01 2015 05:00:00 GMT-07:00', d.toString());
  1608. equal('Mon Jun 01 2015', d.toDateString());
  1609. equal('05:00:00 GMT-07:00', d.toTimeString());
  1610. equal('lundi 1 juin 2015 05:00:00', d.toLocaleString());
  1611. equal('lundi 1 juin 2015', d.toLocaleDateString());
  1612. equal('05:00:00', d.toLocaleTimeString());
  1613. ");
  1614. }
  1615. [Fact]
  1616. public void DateShouldHonorTimezoneDaylightSavingRules()
  1617. {
  1618. var EST = TimeZoneInfo.FindSystemTimeZoneById("US Eastern Standard Time");
  1619. var engine = new Engine(options => options.LocalTimeZone(EST))
  1620. .SetValue("log", new Action<object>(Console.WriteLine))
  1621. .SetValue("assert", new Action<bool>(Assert.True))
  1622. .SetValue("equal", new Action<object, object>(Assert.Equal))
  1623. ;
  1624. engine.Execute(@"
  1625. var d = new Date(2016, 8, 1);
  1626. equal('Thu Sep 01 2016 00:00:00 GMT-04:00', d.toString());
  1627. equal('Thu Sep 01 2016', d.toDateString());
  1628. ");
  1629. }
  1630. [Fact]
  1631. public void DateShouldParseToString()
  1632. {
  1633. // Forcing to PDT and FR for tests
  1634. // var PDT = TimeZoneInfo.CreateCustomTimeZone("Pacific Daylight Time", new TimeSpan(-7, 0, 0), "Pacific Daylight Time", "Pacific Daylight Time");
  1635. var PDT = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
  1636. var FR = new CultureInfo("fr-FR");
  1637. new Engine(options => options.LocalTimeZone(PDT).Culture(FR))
  1638. .SetValue("log", new Action<object>(Console.WriteLine))
  1639. .SetValue("assert", new Action<bool>(Assert.True))
  1640. .SetValue("equal", new Action<object, object>(Assert.Equal))
  1641. .Execute(@"
  1642. var d = new Date(1433160000000);
  1643. equal(Date.parse(d.toString()), d.valueOf());
  1644. equal(Date.parse(d.toLocaleString()), d.valueOf());
  1645. ");
  1646. }
  1647. [Fact]
  1648. public void LocaleNumberShouldUseLocalCulture()
  1649. {
  1650. // Forcing to PDT and FR for tests
  1651. // var PDT = TimeZoneInfo.CreateCustomTimeZone("Pacific Daylight Time", new TimeSpan(-7, 0, 0), "Pacific Daylight Time", "Pacific Daylight Time");
  1652. var PDT = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
  1653. var FR = new CultureInfo("fr-FR");
  1654. new Engine(options => options.LocalTimeZone(PDT).Culture(FR))
  1655. .SetValue("log", new Action<object>(Console.WriteLine))
  1656. .SetValue("assert", new Action<bool>(Assert.True))
  1657. .SetValue("equal", new Action<object, object>(Assert.Equal))
  1658. .Execute(@"
  1659. var d = new Number(-1.23);
  1660. equal('-1.23', d.toString());
  1661. equal('-1,23', d.toLocaleString());
  1662. ");
  1663. }
  1664. [Fact]
  1665. public void DateCtorShouldAcceptDate()
  1666. {
  1667. RunTest(@"
  1668. var a = new Date();
  1669. var b = new Date(a);
  1670. assert(String(a) === String(b));
  1671. ");
  1672. }
  1673. [Fact]
  1674. public void RegExpResultIsMutable()
  1675. {
  1676. RunTest(@"
  1677. var match = /quick\s(brown).+?(jumps)/ig.exec('The Quick Brown Fox Jumps Over The Lazy Dog');
  1678. var result = match.shift();
  1679. assert(result === 'Quick Brown Fox Jumps');
  1680. ");
  1681. }
  1682. [Fact]
  1683. public void RegExpSupportsMultiline()
  1684. {
  1685. RunTest(@"
  1686. var rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg;
  1687. var headersString = 'X-AspNetMvc-Version: 4.0\r\nX-Powered-By: ASP.NET\r\n\r\n';
  1688. match = rheaders.exec(headersString);
  1689. assert('X-AspNetMvc-Version' === match[1]);
  1690. assert('4.0' === match[2]);
  1691. ");
  1692. RunTest(@"
  1693. var rheaders = /^(.*?):[ \t]*(.*?)$/mg;
  1694. var headersString = 'X-AspNetMvc-Version: 4.0\r\nX-Powered-By: ASP.NET\r\n\r\n';
  1695. match = rheaders.exec(headersString);
  1696. assert('X-AspNetMvc-Version' === match[1]);
  1697. assert('4.0' === match[2]);
  1698. ");
  1699. RunTest(@"
  1700. var rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg;
  1701. var headersString = 'X-AspNetMvc-Version: 4.0\nX-Powered-By: ASP.NET\n\n';
  1702. match = rheaders.exec(headersString);
  1703. assert('X-AspNetMvc-Version' === match[1]);
  1704. assert('4.0' === match[2]);
  1705. ");
  1706. }
  1707. [Fact]
  1708. public void RegExpPrototypeToString()
  1709. {
  1710. RunTest("assert(RegExp.prototype.toString() === '/(?:)/');");
  1711. }
  1712. [Fact]
  1713. public void ShouldSetYearBefore1970()
  1714. {
  1715. RunTest(@"
  1716. var d = new Date('1969-01-01T08:17:00');
  1717. d.setYear(2015);
  1718. equal('2015-01-01T08:17:00.000Z', d.toISOString());
  1719. ");
  1720. }
  1721. [Fact]
  1722. public void ShouldUseReplaceMarkers()
  1723. {
  1724. RunTest(@"
  1725. var re = /a/g;
  1726. var str = 'abab';
  1727. var newstr = str.replace(re, '$\'x');
  1728. equal('babxbbxb', newstr);
  1729. ");
  1730. }
  1731. [Fact]
  1732. public void ExceptionShouldHaveLocationOfInnerFunction()
  1733. {
  1734. try
  1735. {
  1736. new Engine()
  1737. .Execute(@"
  1738. function test(s) {
  1739. o.boom();
  1740. }
  1741. test('arg');
  1742. ");
  1743. }
  1744. catch (JavaScriptException ex)
  1745. {
  1746. Assert.Equal(3, ex.LineNumber);
  1747. }
  1748. }
  1749. [Fact]
  1750. public void GlobalRegexLiteralShouldNotKeepState()
  1751. {
  1752. RunTest(@"
  1753. var url = 'https://www.example.com';
  1754. assert(isAbsolutePath(url));
  1755. assert(isAbsolutePath(url));
  1756. assert(isAbsolutePath(url));
  1757. function isAbsolutePath(path) {
  1758. return /\.+/g.test(path);
  1759. }
  1760. ");
  1761. }
  1762. [Fact]
  1763. public void ShouldCompareInnerValueOfClrInstances()
  1764. {
  1765. var engine = new Engine();
  1766. // Create two separate Guid with identical inner values.
  1767. var guid1 = Guid.NewGuid();
  1768. var guid2 = new Guid(guid1.ToString());
  1769. engine.SetValue("guid1", guid1);
  1770. engine.SetValue("guid2", guid2);
  1771. var result = engine.Execute("guid1 == guid2").GetCompletionValue().AsBoolean();
  1772. Assert.True(result);
  1773. }
  1774. [Fact]
  1775. public void CanStringifyToConsole()
  1776. {
  1777. var engine = new Engine(options => options.AllowClr(typeof(Console).Assembly));
  1778. engine.Execute("System.Console.WriteLine(JSON.stringify({x:12, y:14}));");
  1779. }
  1780. [Fact]
  1781. public void ShouldNotCompareClrInstancesWithObjects()
  1782. {
  1783. var engine = new Engine();
  1784. var guid1 = Guid.NewGuid();
  1785. engine.SetValue("guid1", guid1);
  1786. var result = engine.Execute("guid1 == {}").GetCompletionValue().AsBoolean();
  1787. Assert.False(result);
  1788. }
  1789. [Fact]
  1790. public void ShouldStringifyNumWithoutV8DToA()
  1791. {
  1792. // 53.6841659 cannot be converted by V8's DToA => "old" DToA code will be used.
  1793. var engine = new Engine();
  1794. var val = engine.Execute("JSON.stringify(53.6841659)").GetCompletionValue();
  1795. Assert.Equal("53.6841659", val.AsString());
  1796. }
  1797. [Fact]
  1798. public void ShouldStringifyObjectWithPropertiesToSameRef()
  1799. {
  1800. var engine = new Engine();
  1801. var res = engine.Execute(@"
  1802. var obj = {
  1803. a : [],
  1804. a1 : ['str'],
  1805. a2 : {},
  1806. a3 : { 'prop' : 'val' }
  1807. };
  1808. obj.b = obj.a;
  1809. obj.b1 = obj.a1;
  1810. JSON.stringify(obj);
  1811. ").GetCompletionValue();
  1812. Assert.True(res == "{\"a\":[],\"a1\":[\"str\"],\"a2\":{},\"a3\":{\"prop\":\"val\"},\"b\":[],\"b1\":[\"str\"]}");
  1813. }
  1814. [Fact]
  1815. public void ShouldThrowOnSerializingCyclicRefObject()
  1816. {
  1817. var engine = new Engine();
  1818. var res = engine.Execute(@"
  1819. (function(){
  1820. try{
  1821. a = [];
  1822. a[0] = a;
  1823. my_text = JSON.stringify(a);
  1824. }
  1825. catch(ex){
  1826. return ex.message;
  1827. }
  1828. })();
  1829. ").GetCompletionValue();
  1830. Assert.True(res == "Cyclic reference detected.");
  1831. }
  1832. [Theory]
  1833. [InlineData("", "escape('')")]
  1834. [InlineData("%u0100%u0101%u0102", "escape('\u0100\u0101\u0102')")]
  1835. [InlineData("%uFFFD%uFFFE%uFFFF", "escape('\ufffd\ufffe\uffff')")]
  1836. [InlineData("%uD834%uDF06", "escape('\ud834\udf06')")]
  1837. [InlineData("%00%01%02%03", "escape('\x00\x01\x02\x03')")]
  1838. [InlineData("%2C", "escape(',')")]
  1839. [InlineData("%3A%3B%3C%3D%3E%3F", "escape(':;<=>?')")]
  1840. [InlineData("%60", "escape('`')")]
  1841. [InlineData("%7B%7C%7D%7E%7F%80", "escape('{|}~\x7f\x80')")]
  1842. [InlineData("%FD%FE%FF", "escape('\xfd\xfe\xff')")]
  1843. [InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./", "escape('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./')")]
  1844. public void ShouldEvaluateEscape(object expected, string source)
  1845. {
  1846. var engine = new Engine();
  1847. var result = engine.Execute(source).GetCompletionValue().ToObject();
  1848. Assert.Equal(expected, result);
  1849. }
  1850. [Theory]
  1851. //https://github.com/tc39/test262/blob/master/test/annexB/built-ins/unescape/empty-string.js
  1852. [InlineData("", "unescape('')")]
  1853. //https://github.com/tc39/test262/blob/master/test/annexB/built-ins/unescape/four-ignore-bad-u.js
  1854. [InlineData("%U0000", "unescape('%U0000')")]
  1855. [InlineData("%t0000", "unescape('%t0000')")]
  1856. [InlineData("%v0000", "unescape('%v0000')")]
  1857. [InlineData("%" + "\x00" + "00", "unescape('%%0000')")]
  1858. //https://github.com/tc39/test262/blob/master/test/annexB/built-ins/unescape/four-ignore-end-str.js
  1859. [InlineData("%u", "unescape('%u')")]
  1860. [InlineData("%u0", "unescape('%u0')")]
  1861. [InlineData("%u1", "unescape('%u1')")]
  1862. [InlineData("%u2", "unescape('%u2')")]
  1863. [InlineData("%u3", "unescape('%u3')")]
  1864. [InlineData("%u4", "unescape('%u4')")]
  1865. [InlineData("%u5", "unescape('%u5')")]
  1866. [InlineData("%u6", "unescape('%u6')")]
  1867. [InlineData("%u7", "unescape('%u7')")]
  1868. [InlineData("%u8", "unescape('%u8')")]
  1869. [InlineData("%u9", "unescape('%u9')")]
  1870. [InlineData("%ua", "unescape('%ua')")]
  1871. [InlineData("%uA", "unescape('%uA')")]
  1872. [InlineData("%ub", "unescape('%ub')")]
  1873. [InlineData("%uB", "unescape('%uB')")]
  1874. [InlineData("%uc", "unescape('%uc')")]
  1875. [InlineData("%uC", "unescape('%uC')")]
  1876. [InlineData("%ud", "unescape('%ud')")]
  1877. [InlineData("%uD", "unescape('%uD')")]
  1878. [InlineData("%ue", "unescape('%ue')")]
  1879. [InlineData("%uE", "unescape('%uE')")]
  1880. [InlineData("%uf", "unescape('%uf')")]
  1881. [InlineData("%uF", "unescape('%uF')")]
  1882. [InlineData("%u01", "unescape('%u01')")]
  1883. [InlineData("%u02", "unescape('%u02')")]
  1884. [InlineData("%u03", "unescape('%u03')")]
  1885. [InlineData("%u04", "unescape('%u04')")]
  1886. [InlineData("%u05", "unescape('%u05')")]
  1887. [InlineData("%u06", "unescape('%u06')")]
  1888. [InlineData("%u07", "unescape('%u07')")]
  1889. [InlineData("%u08", "unescape('%u08')")]
  1890. [InlineData("%u09", "unescape('%u09')")]
  1891. [InlineData("%u0a", "unescape('%u0a')")]
  1892. [InlineData("%u0A", "unescape('%u0A')")]
  1893. [InlineData("%u0b", "unescape('%u0b')")]
  1894. [InlineData("%u0B", "unescape('%u0B')")]
  1895. [InlineData("%u0c", "unescape('%u0c')")]
  1896. [InlineData("%u0C", "unescape('%u0C')")]
  1897. [InlineData("%u0d", "unescape('%u0d')")]
  1898. [InlineData("%u0D", "unescape('%u0D')")]
  1899. [InlineData("%u0e", "unescape('%u0e')")]
  1900. [InlineData("%u0E", "unescape('%u0E')")]
  1901. [InlineData("%u0f", "unescape('%u0f')")]
  1902. [InlineData("%u0F", "unescape('%u0F')")]
  1903. [InlineData("%u000", "unescape('%u000')")]
  1904. [InlineData("%u001", "unescape('%u001')")]
  1905. [InlineData("%u002", "unescape('%u002')")]
  1906. [InlineData("%u003", "unescape('%u003')")]
  1907. [InlineData("%u004", "unescape('%u004')")]
  1908. [InlineData("%u005", "unescape('%u005')")]
  1909. [InlineData("%u006", "unescape('%u006')")]
  1910. [InlineData("%u007", "unescape('%u007')")]
  1911. [InlineData("%u008", "unescape('%u008')")]
  1912. [InlineData("%u009", "unescape('%u009')")]
  1913. [InlineData("%u00a", "unescape('%u00a')")]
  1914. [InlineData("%u00A", "unescape('%u00A')")]
  1915. [InlineData("%u00b", "unescape('%u00b')")]
  1916. [InlineData("%u00B", "unescape('%u00B')")]
  1917. [InlineData("%u00c", "unescape('%u00c')")]
  1918. [InlineData("%u00C", "unescape('%u00C')")]
  1919. [InlineData("%u00d", "unescape('%u00d')")]
  1920. [InlineData("%u00D", "unescape('%u00D')")]
  1921. [InlineData("%u00e", "unescape('%u00e')")]
  1922. [InlineData("%u00E", "unescape('%u00E')")]
  1923. [InlineData("%u00f", "unescape('%u00f')")]
  1924. [InlineData("%u00F", "unescape('%u00F')")]
  1925. //https://github.com/tc39/test262/blob/master/test/annexB/built-ins/unescape/four-ignore-non-hex.js
  1926. [InlineData("%u000%0", "unescape('%u000%0')")]
  1927. [InlineData("%u000g0", "unescape('%u000g0')")]
  1928. [InlineData("%u000G0", "unescape('%u000G0')")]
  1929. [InlineData("%u00g00", "unescape('%u00g00')")]
  1930. [InlineData("%u00G00", "unescape('%u00G00')")]
  1931. [InlineData("%u0g000", "unescape('%u0g000')")]
  1932. [InlineData("%u0G000", "unescape('%u0G000')")]
  1933. [InlineData("%ug0000", "unescape('%ug0000')")]
  1934. [InlineData("%uG0000", "unescape('%uG0000')")]
  1935. [InlineData("%u000u0", "unescape('%u000u0')")]
  1936. [InlineData("%u000U0", "unescape('%u000U0')")]
  1937. [InlineData("%u00u00", "unescape('%u00u00')")]
  1938. [InlineData("%u00U00", "unescape('%u00U00')")]
  1939. [InlineData("%u0u000", "unescape('%u0u000')")]
  1940. [InlineData("%u0U000", "unescape('%u0U000')")]
  1941. [InlineData("%uu0000", "unescape('%uu0000')")]
  1942. [InlineData("%uU0000", "unescape('%uU0000')")]
  1943. //https://github.com/tc39/test262/blob/master/test/annexB/built-ins/unescape/four.js
  1944. [InlineData("%0" + "\x00" + "0", "unescape('%0%u00000')")]
  1945. [InlineData("%0" + "\x01" + "0", "unescape('%0%u00010')")]
  1946. [InlineData("%0)0", "unescape('%0%u00290')")]
  1947. [InlineData("%0*0", "unescape('%0%u002a0')")]
  1948. [InlineData("%0*0", "unescape('%0%u002A0')")]
  1949. [InlineData("%0+0", "unescape('%0%u002b0')")]
  1950. [InlineData("%0+0", "unescape('%0%u002B0')")]
  1951. [InlineData("%0,0", "unescape('%0%u002c0')")]
  1952. [InlineData("%0,0", "unescape('%0%u002C0')")]
  1953. [InlineData("%0-0", "unescape('%0%u002d0')")]
  1954. [InlineData("%0-0", "unescape('%0%u002D0')")]
  1955. [InlineData("%090", "unescape('%0%u00390')")]
  1956. [InlineData("%0:0", "unescape('%0%u003a0')")]
  1957. [InlineData("%0:0", "unescape('%0%u003A0')")]
  1958. [InlineData("%0?0", "unescape('%0%u003f0')")]
  1959. [InlineData("%0?0", "unescape('%0%u003F0')")]
  1960. [InlineData("%0@0", "unescape('%0%u00400')")]
  1961. [InlineData("%0Z0", "unescape('%0%u005a0')")]
  1962. [InlineData("%0Z0", "unescape('%0%u005A0')")]
  1963. [InlineData("%0[0", "unescape('%0%u005b0')")]
  1964. [InlineData("%0[0", "unescape('%0%u005B0')")]
  1965. [InlineData("%0^0", "unescape('%0%u005e0')")]
  1966. [InlineData("%0^0", "unescape('%0%u005E0')")]
  1967. [InlineData("%0_0", "unescape('%0%u005f0')")]
  1968. [InlineData("%0_0", "unescape('%0%u005F0')")]
  1969. [InlineData("%0`0", "unescape('%0%u00600')")]
  1970. [InlineData("%0a0", "unescape('%0%u00610')")]
  1971. [InlineData("%0z0", "unescape('%0%u007a0')")]
  1972. [InlineData("%0z0", "unescape('%0%u007A0')")]
  1973. [InlineData("%0{0", "unescape('%0%u007b0')")]
  1974. [InlineData("%0{0", "unescape('%0%u007B0')")]
  1975. [InlineData("%0" + "\ufffe" + "0", "unescape('%0%ufffe0')")]
  1976. [InlineData("%0" + "\ufffe" + "0", "unescape('%0%uFffe0')")]
  1977. [InlineData("%0" + "\ufffe" + "0", "unescape('%0%ufFfe0')")]
  1978. [InlineData("%0" + "\ufffe" + "0", "unescape('%0%uffFe0')")]
  1979. [InlineData("%0" + "\ufffe" + "0", "unescape('%0%ufffE0')")]
  1980. [InlineData("%0" + "\ufffe" + "0", "unescape('%0%uFFFE0')")]
  1981. [InlineData("%0" + "\uffff" + "0", "unescape('%0%uffff0')")]
  1982. [InlineData("%0" + "\uffff" + "0", "unescape('%0%uFfff0')")]
  1983. [InlineData("%0" + "\uffff" + "0", "unescape('%0%ufFff0')")]
  1984. [InlineData("%0" + "\uffff" + "0", "unescape('%0%uffFf0')")]
  1985. [InlineData("%0" + "\uffff" + "0", "unescape('%0%ufffF0')")]
  1986. [InlineData("%0" + "\uffff" + "0", "unescape('%0%uFFFF0')")]
  1987. //https://github.com/tc39/test262/blob/master/test/annexB/built-ins/unescape/two-ignore-end-str.js
  1988. [InlineData("%", "unescape('%')")]
  1989. [InlineData("%0", "unescape('%0')")]
  1990. [InlineData("%1", "unescape('%1')")]
  1991. [InlineData("%2", "unescape('%2')")]
  1992. [InlineData("%3", "unescape('%3')")]
  1993. [InlineData("%4", "unescape('%4')")]
  1994. [InlineData("%5", "unescape('%5')")]
  1995. [InlineData("%6", "unescape('%6')")]
  1996. [InlineData("%7", "unescape('%7')")]
  1997. [InlineData("%8", "unescape('%8')")]
  1998. [InlineData("%9", "unescape('%9')")]
  1999. [InlineData("%a", "unescape('%a')")]
  2000. [InlineData("%A", "unescape('%A')")]
  2001. [InlineData("%b", "unescape('%b')")]
  2002. [InlineData("%B", "unescape('%B')")]
  2003. [InlineData("%c", "unescape('%c')")]
  2004. [InlineData("%C", "unescape('%C')")]
  2005. [InlineData("%d", "unescape('%d')")]
  2006. [InlineData("%D", "unescape('%D')")]
  2007. [InlineData("%e", "unescape('%e')")]
  2008. [InlineData("%E", "unescape('%E')")]
  2009. [InlineData("%f", "unescape('%f')")]
  2010. [InlineData("%F", "unescape('%F')")]
  2011. //https://github.com/tc39/test262/blob/master/test/annexB/built-ins/unescape/two-ignore-non-hex.js
  2012. [InlineData("%0%0", "unescape('%0%0')")]
  2013. [InlineData("%0g0", "unescape('%0g0')")]
  2014. [InlineData("%0G0", "unescape('%0G0')")]
  2015. [InlineData("%g00", "unescape('%g00')")]
  2016. [InlineData("%G00", "unescape('%G00')")]
  2017. [InlineData("%0u0", "unescape('%0u0')")]
  2018. [InlineData("%0U0", "unescape('%0U0')")]
  2019. [InlineData("%u00", "unescape('%u00')")]
  2020. [InlineData("%U00", "unescape('%U00')")]
  2021. //https://github.com/tc39/test262/blob/master/test/annexB/built-ins/unescape/two.js
  2022. [InlineData("%0" + "\x00" + "00", "unescape('%0%0000')")]
  2023. [InlineData("%0" + "\x01" + "00", "unescape('%0%0100')")]
  2024. [InlineData("%0)00", "unescape('%0%2900')")]
  2025. [InlineData("%0*00", "unescape('%0%2a00')")]
  2026. [InlineData("%0*00", "unescape('%0%2A00')")]
  2027. [InlineData("%0+00", "unescape('%0%2b00')")]
  2028. [InlineData("%0+00", "unescape('%0%2B00')")]
  2029. [InlineData("%0,00", "unescape('%0%2c00')")]
  2030. [InlineData("%0,00", "unescape('%0%2C00')")]
  2031. [InlineData("%0-00", "unescape('%0%2d00')")]
  2032. [InlineData("%0-00", "unescape('%0%2D00')")]
  2033. [InlineData("%0900", "unescape('%0%3900')")]
  2034. [InlineData("%0:00", "unescape('%0%3a00')")]
  2035. [InlineData("%0:00", "unescape('%0%3A00')")]
  2036. [InlineData("%0?00", "unescape('%0%3f00')")]
  2037. [InlineData("%0?00", "unescape('%0%3F00')")]
  2038. [InlineData("%0@00", "unescape('%0%4000')")]
  2039. [InlineData("%0Z00", "unescape('%0%5a00')")]
  2040. [InlineData("%0Z00", "unescape('%0%5A00')")]
  2041. [InlineData("%0[00", "unescape('%0%5b00')")]
  2042. [InlineData("%0[00", "unescape('%0%5B00')")]
  2043. [InlineData("%0^00", "unescape('%0%5e00')")]
  2044. [InlineData("%0^00", "unescape('%0%5E00')")]
  2045. [InlineData("%0_00", "unescape('%0%5f00')")]
  2046. [InlineData("%0_00", "unescape('%0%5F00')")]
  2047. [InlineData("%0`00", "unescape('%0%6000')")]
  2048. [InlineData("%0a00", "unescape('%0%6100')")]
  2049. [InlineData("%0z00", "unescape('%0%7a00')")]
  2050. [InlineData("%0z00", "unescape('%0%7A00')")]
  2051. [InlineData("%0{00", "unescape('%0%7b00')")]
  2052. [InlineData("%0{00", "unescape('%0%7B00')")]
  2053. public void ShouldEvaluateUnescape(object expected, string source)
  2054. {
  2055. var engine = new Engine();
  2056. var result = engine.Execute(source).GetCompletionValue().ToObject();
  2057. Assert.Equal(expected, result);
  2058. }
  2059. [Theory]
  2060. [InlineData("new Date(1969,0,1,19,45,30,500).getHours()", 19)]
  2061. [InlineData("new Date(1970,0,1,19,45,30,500).getHours()", 19)]
  2062. [InlineData("new Date(1971,0,1,19,45,30,500).getHours()", 19)]
  2063. [InlineData("new Date(1969,0,1,19,45,30,500).getMinutes()", 45)]
  2064. [InlineData("new Date(1970,0,1,19,45,30,500).getMinutes()", 45)]
  2065. [InlineData("new Date(1971,0,1,19,45,30,500).getMinutes()", 45)]
  2066. [InlineData("new Date(1969,0,1,19,45,30,500).getSeconds()", 30)]
  2067. [InlineData("new Date(1970,0,1,19,45,30,500).getSeconds()", 30)]
  2068. [InlineData("new Date(1971,0,1,19,45,30,500).getSeconds()", 30)]
  2069. //[InlineData("new Date(1969,0,1,19,45,30,500).getMilliseconds()", 500)]
  2070. //[InlineData("new Date(1970,0,1,19,45,30,500).getMilliseconds()", 500)]
  2071. //[InlineData("new Date(1971,0,1,19,45,30,500).getMilliseconds()", 500)]
  2072. public void ShouldExtractDateParts(string source, double expected)
  2073. {
  2074. var engine = new Engine();
  2075. var result = engine.Execute(source).GetCompletionValue().ToObject();
  2076. Assert.Equal(expected, result);
  2077. }
  2078. [Theory]
  2079. [InlineData("'abc'.padStart(10)", " abc")]
  2080. [InlineData("'abc'.padStart(10, \"foo\")", "foofoofabc")]
  2081. [InlineData("'abc'.padStart(6, \"123456\")", "123abc")]
  2082. [InlineData("'abc'.padStart(8, \"0\")", "00000abc")]
  2083. [InlineData("'abc'.padStart(1)", "abc")]
  2084. public void ShouldPadStart(string source, object expected)
  2085. {
  2086. var engine = new Engine();
  2087. var result = engine.Execute(source).GetCompletionValue().ToObject();
  2088. Assert.Equal(expected, result);
  2089. }
  2090. [Theory]
  2091. [InlineData("'abc'.padEnd(10)", "abc ")]
  2092. [InlineData("'abc'.padEnd(10, \"foo\")", "abcfoofoof")]
  2093. [InlineData("'abc'.padEnd(6, \"123456\")", "abc123")]
  2094. [InlineData("'abc'.padEnd(1)", "abc")]
  2095. public void ShouldPadEnd(string source, object expected)
  2096. {
  2097. var engine = new Engine();
  2098. var result = engine.Execute(source).GetCompletionValue().ToObject();
  2099. Assert.Equal(expected, result);
  2100. }
  2101. /// <summary>
  2102. /// Tests for startsWith - tests created from MDN and https://github.com/mathiasbynens/String.prototype.startsWith/blob/master/tests/tests.js
  2103. /// </summary>
  2104. [Theory]
  2105. [InlineData("'To be, or not to be, that is the question.'.startsWith('To be')", true)]
  2106. [InlineData("'To be, or not to be, that is the question.'.startsWith('not to be')", false)]
  2107. [InlineData("'To be, or not to be, that is the question.'.startsWith()", false)]
  2108. [InlineData("'To be, or not to be, that is the question.'.startsWith('not to be', 10)", true)]
  2109. [InlineData("'undefined'.startsWith()", true)]
  2110. [InlineData("'undefined'.startsWith(undefined)", true)]
  2111. [InlineData("'undefined'.startsWith(null)", false)]
  2112. [InlineData("'null'.startsWith()", false)]
  2113. [InlineData("'null'.startsWith(undefined)", false)]
  2114. [InlineData("'null'.startsWith(null)", true)]
  2115. [InlineData("'abc'.startsWith()", false)]
  2116. [InlineData("'abc'.startsWith('')", true)]
  2117. [InlineData("'abc'.startsWith('\0')", false)]
  2118. [InlineData("'abc'.startsWith('a')", true)]
  2119. [InlineData("'abc'.startsWith('b')", false)]
  2120. [InlineData("'abc'.startsWith('ab')", true)]
  2121. [InlineData("'abc'.startsWith('bc')", false)]
  2122. [InlineData("'abc'.startsWith('abc')", true)]
  2123. [InlineData("'abc'.startsWith('bcd')", false)]
  2124. [InlineData("'abc'.startsWith('abcd')", false)]
  2125. [InlineData("'abc'.startsWith('bcde')", false)]
  2126. [InlineData("'abc'.startsWith('', 1)", true)]
  2127. [InlineData("'abc'.startsWith('\0', 1)", false)]
  2128. [InlineData("'abc'.startsWith('a', 1)", false)]
  2129. [InlineData("'abc'.startsWith('b', 1)", true)]
  2130. [InlineData("'abc'.startsWith('ab', 1)", false)]
  2131. [InlineData("'abc'.startsWith('bc', 1)", true)]
  2132. [InlineData("'abc'.startsWith('abc', 1)", false)]
  2133. [InlineData("'abc'.startsWith('bcd', 1)", false)]
  2134. [InlineData("'abc'.startsWith('abcd', 1)", false)]
  2135. [InlineData("'abc'.startsWith('bcde', 1)", false)]
  2136. public void ShouldStartWith(string source, object expected)
  2137. {
  2138. var engine = new Engine();
  2139. var result = engine.Execute(source).GetCompletionValue().ToObject();
  2140. Assert.Equal(expected, result);
  2141. }
  2142. [Theory]
  2143. [InlineData("throw {}", "undefined")]
  2144. [InlineData("throw {message:null}", "null")]
  2145. [InlineData("throw {message:''}", "")]
  2146. [InlineData("throw {message:2}", "2")]
  2147. public void ShouldAllowNonStringMessage(string source, string expected)
  2148. {
  2149. var engine = new Engine();
  2150. var ex = Assert.Throws<JavaScriptException>(() => engine.Execute(source));
  2151. Assert.Equal(expected, ex.Message);
  2152. }
  2153. [Theory]
  2154. //Months
  2155. [InlineData("new Date(2017, 0, 1, 0, 0, 0)", "new Date(2016, 12, 1, 0, 0, 0)")]
  2156. [InlineData("new Date(2016, 0, 1, 23, 59, 59)", "new Date(2015, 12, 1, 23, 59, 59)")]
  2157. [InlineData("new Date(2013, 0, 1, 0, 0, 0)", "new Date(2012, 12, 1, 0, 0, 0)")]
  2158. [InlineData("new Date(2013, 0, 29, 23, 59, 59)", "new Date(2012, 12, 29, 23, 59, 59)")]
  2159. [InlineData("new Date(2015, 11, 1, 0, 0, 0)", "new Date(2016, -1, 1, 0, 0, 0)")]
  2160. [InlineData("new Date(2014, 11, 1, 23, 59, 59)", "new Date(2015, -1, 1, 23, 59, 59)")]
  2161. [InlineData("new Date(2011, 11, 1, 0, 0, 0)", "new Date(2012, -1, 1, 0, 0, 0)")]
  2162. [InlineData("new Date(2011, 11, 29, 23, 59, 59)", "new Date(2012, -1, 29, 23, 59, 59)")]
  2163. [InlineData("new Date(2015, 1, 1, 0, 0, 0)", "new Date(2016, -11, 1, 0, 0, 0)")]
  2164. [InlineData("new Date(2014, 1, 1, 23, 59, 59)", "new Date(2015, -11, 1, 23, 59, 59)")]
  2165. [InlineData("new Date(2011, 1, 1, 0, 0, 0)", "new Date(2012, -11, 1, 0, 0, 0)")]
  2166. [InlineData("new Date(2011, 2, 1, 23, 59, 59)", "new Date(2012, -11, 29, 23, 59, 59)")]
  2167. [InlineData("new Date(2015, 0, 1, 0, 0, 0)", "new Date(2016, -12, 1, 0, 0, 0)")]
  2168. [InlineData("new Date(2014, 0, 1, 23, 59, 59)", "new Date(2015, -12, 1, 23, 59, 59)")]
  2169. [InlineData("new Date(2011, 0, 1, 0, 0, 0)", "new Date(2012, -12, 1, 0, 0, 0)")]
  2170. [InlineData("new Date(2011, 0, 29, 23, 59, 59)", "new Date(2012, -12, 29, 23, 59, 59)")]
  2171. [InlineData("new Date(2014, 11, 1, 0, 0, 0)", "new Date(2016, -13, 1, 0, 0, 0)")]
  2172. [InlineData("new Date(2013, 11, 1, 23, 59, 59)", "new Date(2015, -13, 1, 23, 59, 59)")]
  2173. [InlineData("new Date(2010, 11, 1, 0, 0, 0)", "new Date(2012, -13, 1, 0, 0, 0)")]
  2174. [InlineData("new Date(2010, 11, 29, 23, 59, 59)", "new Date(2012, -13, 29, 23, 59, 59)")]
  2175. [InlineData("new Date(2013, 11, 1, 0, 0, 0)", "new Date(2016, -25, 1, 0, 0, 0)")]
  2176. [InlineData("new Date(2012, 11, 1, 23, 59, 59)", "new Date(2015, -25, 1, 23, 59, 59)")]
  2177. [InlineData("new Date(2009, 11, 1, 0, 0, 0)", "new Date(2012, -25, 1, 0, 0, 0)")]
  2178. [InlineData("new Date(2009, 11, 29, 23, 59, 59)", "new Date(2012, -25, 29, 23, 59, 59)")]
  2179. //Days
  2180. [InlineData("new Date(2016, 1, 11, 0, 0, 0)", "new Date(2016, 0, 42, 0, 0, 0)")]
  2181. [InlineData("new Date(2016, 0, 11, 23, 59, 59)", "new Date(2015, 11, 42, 23, 59, 59)")]
  2182. [InlineData("new Date(2012, 3, 11, 0, 0, 0)", "new Date(2012, 2, 42, 0, 0, 0)")]
  2183. [InlineData("new Date(2012, 2, 13, 23, 59, 59)", "new Date(2012, 1, 42, 23, 59, 59)")]
  2184. [InlineData("new Date(2015, 11, 31, 0, 0, 0)", "new Date(2016, 0, 0, 0, 0, 0)")]
  2185. [InlineData("new Date(2015, 10, 30, 23, 59, 59)", "new Date(2015, 11, 0, 23, 59, 59)")]
  2186. [InlineData("new Date(2012, 1, 29, 0, 0, 0)", "new Date(2012, 2, 0, 0, 0, 0)")]
  2187. [InlineData("new Date(2012, 0, 31, 23, 59, 59)", "new Date(2012, 1, 0, 23, 59, 59)")]
  2188. [InlineData("new Date(2015, 10, 24, 0, 0, 0)", "new Date(2016, 0, -37, 0, 0, 0)")]
  2189. [InlineData("new Date(2015, 9, 24, 23, 59, 59)", "new Date(2015, 11, -37, 23, 59, 59)")]
  2190. [InlineData("new Date(2012, 0, 23, 0, 0, 0)", "new Date(2012, 2, -37, 0, 0, 0)")]
  2191. [InlineData("new Date(2011, 11, 25, 23, 59, 59)", "new Date(2012, 1, -37, 23, 59, 59)")]
  2192. //Hours
  2193. [InlineData("new Date(2016, 0, 2, 1, 0, 0)", "new Date(2016, 0, 1, 25, 0, 0)")]
  2194. [InlineData("new Date(2015, 11, 2, 1, 59, 59)", "new Date(2015, 11, 1, 25, 59, 59)")]
  2195. [InlineData("new Date(2012, 2, 2, 1, 0, 0)", "new Date(2012, 2, 1, 25, 0, 0)")]
  2196. [InlineData("new Date(2012, 2, 1, 1, 59, 59)", "new Date(2012, 1, 29, 25, 59, 59)")]
  2197. [InlineData("new Date(2016, 0, 19, 3, 0, 0)", "new Date(2016, 0, 1, 435, 0, 0)")]
  2198. [InlineData("new Date(2015, 11, 19, 3, 59, 59)", "new Date(2015, 11, 1, 435, 59, 59)")]
  2199. [InlineData("new Date(2012, 2, 19, 3, 0, 0)", "new Date(2012, 2, 1, 435, 0, 0)")]
  2200. [InlineData("new Date(2012, 2, 18, 3, 59, 59)", "new Date(2012, 1, 29, 435, 59, 59)")]
  2201. [InlineData("new Date(2015, 11, 31, 23, 0, 0)", "new Date(2016, 0, 1, -1, 0, 0)")]
  2202. [InlineData("new Date(2015, 10, 30, 23, 59, 59)", "new Date(2015, 11, 1, -1, 59, 59)")]
  2203. [InlineData("new Date(2012, 1, 29, 23, 0, 0)", "new Date(2012, 2, 1, -1, 0, 0)")]
  2204. [InlineData("new Date(2012, 1, 28, 23, 59, 59)", "new Date(2012, 1, 29, -1, 59, 59)")]
  2205. [InlineData("new Date(2015, 11, 3, 18, 0, 0)", "new Date(2016, 0, 1, -678, 0, 0)")]
  2206. [InlineData("new Date(2015, 10, 2, 18, 59, 59)", "new Date(2015, 11, 1, -678, 59, 59)")]
  2207. [InlineData("new Date(2012, 1, 1, 18, 0, 0)", "new Date(2012, 2, 1, -678, 0, 0)")]
  2208. [InlineData("new Date(2012, 0, 31, 18, 59, 59)", "new Date(2012, 1, 29, -678, 59, 59)")]
  2209. // Minutes
  2210. [InlineData("new Date(2016, 0, 1, 1, 0, 0)", "new Date(2016, 0, 1, 0, 60, 0)")]
  2211. [InlineData("new Date(2015, 11, 2, 0, 0, 59)", "new Date(2015, 11, 1, 23, 60, 59)")]
  2212. [InlineData("new Date(2012, 2, 1, 1, 0, 0)", "new Date(2012, 2, 1, 0, 60, 0)")]
  2213. [InlineData("new Date(2012, 2, 1, 0, 0, 59)", "new Date(2012, 1, 29, 23, 60, 59)")]
  2214. [InlineData("new Date(2015, 11, 31, 23, 59, 0)", "new Date(2016, 0, 1, 0, -1, 0)")]
  2215. [InlineData("new Date(2015, 11, 1, 22, 59, 59)", "new Date(2015, 11, 1, 23, -1, 59)")]
  2216. [InlineData("new Date(2012, 1, 29, 23, 59, 0)", "new Date(2012, 2, 1, 0, -1, 0)")]
  2217. [InlineData("new Date(2012, 1, 29, 22, 59, 59)", "new Date(2012, 1, 29, 23, -1, 59)")]
  2218. [InlineData("new Date(2016, 0, 2, 15, 5, 0)", "new Date(2016, 0, 1, 0, 2345, 0)")]
  2219. [InlineData("new Date(2015, 11, 3, 14, 5, 59)", "new Date(2015, 11, 1, 23, 2345, 59)")]
  2220. [InlineData("new Date(2012, 2, 2, 15, 5, 0)", "new Date(2012, 2, 1, 0, 2345, 0)")]
  2221. [InlineData("new Date(2012, 2, 2, 14, 5, 59)", "new Date(2012, 1, 29, 23, 2345, 59)")]
  2222. [InlineData("new Date(2015, 11, 25, 18, 24, 0)", "new Date(2016, 0, 1, 0, -8976, 0)")]
  2223. [InlineData("new Date(2015, 10, 25, 17, 24, 59)", "new Date(2015, 11, 1, 23, -8976, 59)")]
  2224. [InlineData("new Date(2012, 1, 23, 18, 24, 0)", "new Date(2012, 2, 1, 0, -8976, 0)")]
  2225. [InlineData("new Date(2012, 1, 23, 17, 24, 59)", "new Date(2012, 1, 29, 23, -8976, 59)")]
  2226. // Seconds
  2227. [InlineData("new Date(2016, 0, 1, 0, 1, 0)", "new Date(2016, 0, 1, 0, 0, 60)")]
  2228. [InlineData("new Date(2015, 11, 2, 0, 0, 0)", "new Date(2015, 11, 1, 23, 59, 60)")]
  2229. [InlineData("new Date(2012, 2, 1, 0, 1, 0)", "new Date(2012, 2, 1, 0, 0, 60)")]
  2230. [InlineData("new Date(2012, 2, 1, 0, 0, 0)", "new Date(2012, 1, 29, 23, 59, 60)")]
  2231. [InlineData("new Date(2015, 11, 31, 23, 59, 59)", "new Date(2016, 0, 1, 0, 0, -1)")]
  2232. [InlineData("new Date(2015, 11, 1, 23, 58, 59)", "new Date(2015, 11, 1, 23, 59, -1)")]
  2233. [InlineData("new Date(2012, 1, 29, 23, 59, 59)", "new Date(2012, 2, 1, 0, 0, -1)")]
  2234. [InlineData("new Date(2012, 1, 29, 23, 58, 59)", "new Date(2012, 1, 29, 23, 59, -1)")]
  2235. [InlineData("new Date(2016, 0, 3, 17, 9, 58)", "new Date(2016, 0, 1, 0, 0, 234598)")]
  2236. [InlineData("new Date(2015, 11, 4, 17, 8, 58)", "new Date(2015, 11, 1, 23, 59, 234598)")]
  2237. [InlineData("new Date(2012, 2, 3, 17, 9, 58)", "new Date(2012, 2, 1, 0, 0, 234598)")]
  2238. [InlineData("new Date(2012, 2, 3, 17, 8, 58)", "new Date(2012, 1, 29, 23, 59, 234598)")]
  2239. [InlineData("new Date(2015, 11, 21, 14, 39, 15)", "new Date(2016, 0, 1, 0, 0, -897645)")]
  2240. [InlineData("new Date(2015, 10, 21, 14, 38, 15)", "new Date(2015, 11, 1, 23, 59, -897645)")]
  2241. [InlineData("new Date(2012, 1, 19, 14, 39, 15)", "new Date(2012, 2, 1, 0, 0, -897645)")]
  2242. [InlineData("new Date(2012, 1, 19, 14, 38, 15)", "new Date(2012, 1, 29, 23, 59, -897645)")]
  2243. public void ShouldSupportDateConsturctorWithArgumentOutOfRange(string expected, string actual)
  2244. {
  2245. var engine = new Engine(o => o.LocalTimeZone(TimeZoneInfo.Utc));
  2246. var expectedValue = engine.Execute(expected).GetCompletionValue().ToObject();
  2247. var actualValue = engine.Execute(actual).GetCompletionValue().ToObject();
  2248. Assert.Equal(expectedValue, actualValue);
  2249. }
  2250. [Fact]
  2251. public void ShouldReturnCorrectConcatenatedStrings()
  2252. {
  2253. RunTest(@"
  2254. function concat(x, a, b) {
  2255. x += a;
  2256. x += b;
  2257. return x;
  2258. }");
  2259. var concat = _engine.GetValue("concat");
  2260. var result = concat.Invoke("concat", "well", "done").ToObject() as string;
  2261. Assert.Equal("concatwelldone", result);
  2262. }
  2263. [Fact]
  2264. public void ComplexMappingAndReducing()
  2265. {
  2266. const string program = @"
  2267. Object.map = function (o, f, ctx) {
  2268. ctx = ctx || this;
  2269. var result = [];
  2270. Object.keys(o).forEach(function(k) {
  2271. result.push(f.call(ctx, o[k], k));
  2272. });
  2273. return result;
  2274. };
  2275. var x1 = {""Value"":1.0,""Elements"":[{""Name"":""a"",""Value"":""b"",""Decimal"":3.2},{""Name"":""a"",""Value"":""b"",""Decimal"": 3.5}],""Values"":{""test"": 2,""test1"":3,""test2"": 4}}
  2276. var x2 = {""Value"":2.0,""Elements"":[{""Name"":""aa"",""Value"":""ba"",""Decimal"":3.5}],""Values"":{""test"":1,""test1"":2,""test2"":3}};
  2277. function output(x) {
  2278. var elements = x.Elements.map(function(a){return a.Decimal;});
  2279. var values = x.Values;
  2280. var generated = x.Elements.reduce(function(_obj, _cur) {_obj[(function(a){return a.Name;})(_cur)] = (function(a){return a.Decimal;})(_cur);return _obj;}, {});
  2281. return {
  2282. TestDictionary1 : values,
  2283. TestDictionary2 : x.Values,
  2284. TestDictionaryDirectAccess1 : Object.keys(x.Values).length,
  2285. TestDictionaryDirectAccess2 : Object.keys(x.Values),
  2286. TestDictionaryDirectAccess4 : Object.keys(x.Values).map(function(a){return x.Values[a];}),
  2287. TestDictionarySum1 : Object.keys(values).map(function(a){return{Key: a,Value:values[a]};}).map(function(a){return a.Value;}).reduce(function(a, b) { return a + b; }, 0),
  2288. TestDictionarySum2 : Object.keys(x.Values).map(function(a){return{Key: a,Value:x.Values[a]};}).map(function(a){return a.Value;}).reduce(function(a, b) { return a + b; }, 0),
  2289. TestDictionarySum3 : Object.keys(x.Values).map(function(a){return x.Values[a];}).reduce(function(a, b) { return a + b; }, 0),
  2290. TestDictionaryAverage1 : Object.keys(values).map(function(a){return{Key: a,Value:values[a]};}).map(function(a){return a.Value;}).reduce(function(a, b) { return a + b; }, 0)/(Object.keys(values).length||1),
  2291. TestDictionaryAverage2 : Object.keys(x.Values).map(function(a){return{Key: a,Value:x.Values[a]};}).map(function(a){return a.Value;}).reduce(function(a, b) { return a + b; }, 0)/(Object.keys(x.Values).length||1),
  2292. TestDictionaryAverage3 : Object.keys(x.Values).map(function(a){return x.Values[a];}).reduce(function(a, b) { return a + b; }, 0)/(Object.keys(x.Values).map(function(a){return x.Values[a];}).length||1),
  2293. TestDictionaryFunc1 : Object.keys(x.Values).length,
  2294. TestDictionaryFunc2 : Object.map(x.Values, function(v, k){ return v;}),
  2295. TestGeneratedDictionary1 : generated,
  2296. TestGeneratedDictionary2 : x.Elements.reduce(function(_obj, _cur) {_obj[(function(a){return a.Name;})(_cur)] = (function(a){return a.Decimal;})(_cur);return _obj;}, {}),
  2297. TestGeneratedDictionary3 : Object.keys(generated).length,
  2298. TestGeneratedDictionarySum1 : Object.keys(generated).map(function(a){return{Key: a,Value:generated[a]};}).map(function(a){return a.Value;}).reduce(function(a, b) { return a + b; }, 0),
  2299. TestGeneratedDictionarySum2 : Object.keys(x.Elements.reduce(function(_obj, _cur) {_obj[(function(a){return a.Name;})(_cur)] = (function(a){return a.Decimal;})(_cur);return _obj;}, {})).map(function(a){return{Key: a,Value:x.Elements.reduce(function(_obj, _cur) {_obj[(function(a){return a.Name;})(_cur)] = (function(a){return a.Decimal;})(_cur);return _obj;}, {})[a]};}).map(function(a){return a.Value;}).reduce(function(a, b) { return a + b; }, 0),
  2300. TestGeneratedDictionaryAverage1 : Object.keys(generated).map(function(a){return{Key: a,Value:generated[a]};}).map(function(a){return a.Value;}).reduce(function(a, b) { return a + b; }, 0)/(Object.keys(generated).length||1),
  2301. TestGeneratedDictionaryAverage2 : Object.keys(x.Elements.reduce(function(_obj, _cur) {_obj[(function(a){return a.Name;})(_cur)] = (function(a){return a.Decimal;})(_cur);return _obj;}, {})).map(function(a){return{Key: a,Value:x.Elements.reduce(function(_obj, _cur) {_obj[(function(a){return a.Name;})(_cur)] = (function(a){return a.Decimal;})(_cur);return _obj;}, {})[a]};}).map(function(a){return a.Value;}).reduce(function(a, b) { return a + b; }, 0)/(Object.keys(x.Elements.reduce(function(_obj, _cur) {_obj[(function(a){return a.Name;})(_cur)] = (function(a){return a.Decimal;})(_cur);return _obj;}, {})).length||1),
  2302. TestGeneratedDictionaryDirectAccess1 : Object.keys(generated),
  2303. TestGeneratedDictionaryDirectAccess2 : Object.keys(generated).map(function(a){return generated[a];}),
  2304. TestGeneratedDictionaryDirectAccess3 : Object.keys(generated).length,
  2305. TestList1 : elements.reduce(function(a, b) { return a + b; }, 0),
  2306. TestList2 : x.Elements.map(function(a){return a.Decimal;}).reduce(function(a, b) { return a + b; }, 0),
  2307. TestList3 : x.Elements.map(function(a){return a.Decimal;}).reduce(function(a, b) { return a + b; }, 0),
  2308. TestList4 : x.Elements.map(function(a){return a.Decimal;}).reduce(function(a, b) { return a + b; }, 0)/(x.Elements.length||1),
  2309. TestList5 : x.Elements.map(function(a){return a.Decimal;}).reduce(function(a, b) { return a + b; }, 0)/(x.Elements.map((function(a){return a.Decimal;})).length||1)
  2310. };
  2311. };
  2312. ";
  2313. _engine.Execute(program);
  2314. var result1 = (ObjectInstance)_engine.Execute("output(x1)").GetCompletionValue();
  2315. var result2 = (ObjectInstance)_engine.Execute("output(x2)").GetCompletionValue();
  2316. Assert.Equal(9, TypeConverter.ToNumber(result1.Get("TestDictionarySum1")));
  2317. Assert.Equal(9, TypeConverter.ToNumber(result1.Get("TestDictionarySum2")));
  2318. Assert.Equal(9, TypeConverter.ToNumber(result1.Get("TestDictionarySum3")));
  2319. Assert.Equal(3, TypeConverter.ToNumber(result1.Get("TestDictionaryAverage1")));
  2320. Assert.Equal(3, TypeConverter.ToNumber(result1.Get("TestDictionaryAverage2")));
  2321. Assert.Equal(3, TypeConverter.ToNumber(result1.Get("TestDictionaryAverage3")));
  2322. Assert.Equal(3, TypeConverter.ToNumber(result1.Get("TestDictionaryFunc1")));
  2323. Assert.Equal(1, TypeConverter.ToNumber(result1.Get("TestGeneratedDictionary3")));
  2324. Assert.Equal(3.5, TypeConverter.ToNumber(result1.Get("TestGeneratedDictionarySum1")));
  2325. Assert.Equal(3.5, TypeConverter.ToNumber(result1.Get("TestGeneratedDictionarySum2")));
  2326. Assert.Equal(3.5, TypeConverter.ToNumber(result1.Get("TestGeneratedDictionaryAverage1")));
  2327. Assert.Equal(3.5, TypeConverter.ToNumber(result1.Get("TestGeneratedDictionaryAverage2")));
  2328. Assert.Equal(1, TypeConverter.ToNumber(result1.Get("TestGeneratedDictionaryDirectAccess3")));
  2329. Assert.Equal(6.7, TypeConverter.ToNumber(result1.Get("TestList1")));
  2330. Assert.Equal(6.7, TypeConverter.ToNumber(result1.Get("TestList2")));
  2331. Assert.Equal(6.7, TypeConverter.ToNumber(result1.Get("TestList3")));
  2332. Assert.Equal(3.35, TypeConverter.ToNumber(result1.Get("TestList4")));
  2333. Assert.Equal(3.35, TypeConverter.ToNumber(result1.Get("TestList5")));
  2334. Assert.Equal(6, TypeConverter.ToNumber(result2.Get("TestDictionarySum1")));
  2335. Assert.Equal(6, TypeConverter.ToNumber(result2.Get("TestDictionarySum2")));
  2336. Assert.Equal(6, TypeConverter.ToNumber(result2.Get("TestDictionarySum3")));
  2337. Assert.Equal(2, TypeConverter.ToNumber(result2.Get("TestDictionaryAverage1")));
  2338. Assert.Equal(2, TypeConverter.ToNumber(result2.Get("TestDictionaryAverage2")));
  2339. Assert.Equal(2, TypeConverter.ToNumber(result2.Get("TestDictionaryAverage3")));
  2340. }
  2341. [Fact]
  2342. public void ShouldBeAbleToSpreadArrayLiteralsAndFunctionParameters()
  2343. {
  2344. RunTest(@"
  2345. function concat(x, a, b) {
  2346. x += a;
  2347. x += b;
  2348. return x;
  2349. }
  2350. var s = [...'abc'];
  2351. var c = concat(1, ...'ab');
  2352. var arr1 = [1, 2];
  2353. var arr2 = [3, 4 ];
  2354. var r = [...arr2, ...arr1];
  2355. ");
  2356. var arrayInstance = (ArrayInstance)_engine.GetValue("r");
  2357. Assert.Equal(arrayInstance[0], 3);
  2358. Assert.Equal(arrayInstance[1], 4);
  2359. Assert.Equal(arrayInstance[2], 1);
  2360. Assert.Equal(arrayInstance[3], 2);
  2361. arrayInstance = (ArrayInstance)_engine.GetValue("s");
  2362. Assert.Equal(arrayInstance[0], 'a');
  2363. Assert.Equal(arrayInstance[1], 'b');
  2364. Assert.Equal(arrayInstance[2], 'c');
  2365. var c = _engine.GetValue("c").ToString();
  2366. Assert.Equal("1ab", c);
  2367. }
  2368. [Fact]
  2369. public void ShouldSupportDefaultsInFunctionParameters()
  2370. {
  2371. RunTest(@"
  2372. function f(x, y=12) {
  2373. // y is 12 if not passed (or passed as undefined)
  2374. return x + y;
  2375. }
  2376. ");
  2377. var function = _engine.GetValue("f");
  2378. var result = function.Invoke(3).ToString();
  2379. Assert.Equal("15", result);
  2380. result = function.Invoke(3, JsValue.Undefined).ToString();
  2381. Assert.Equal("15", result);
  2382. }
  2383. [Fact]
  2384. public void ShouldReportErrorForInvalidJson()
  2385. {
  2386. var engine = new Engine();
  2387. var ex = Assert.Throws<JavaScriptException>(() => engine.Execute("JSON.parse('[01]')"));
  2388. Assert.Equal("Unexpected token '1'", ex.Message);
  2389. var voidCompletion = engine.Execute("try { JSON.parse('01') } catch (e) {}").GetCompletionValue();
  2390. Assert.Equal(JsValue.Undefined, voidCompletion);
  2391. }
  2392. [Fact]
  2393. public void ShouldParseAnonymousToTypeObject()
  2394. {
  2395. var obj = new Wrapper();
  2396. var engine = new Engine()
  2397. .SetValue("x", obj);
  2398. var js = @"
  2399. x.test = {
  2400. name: 'Testificate',
  2401. init (a, b) {
  2402. return a + b
  2403. }
  2404. }";
  2405. engine.Execute(js);
  2406. Assert.Equal("Testificate", obj.Test.Name);
  2407. Assert.Equal(5, obj.Test.Init(2, 3));
  2408. }
  2409. [Fact]
  2410. public void ShouldOverrideDefaultTypeConverter()
  2411. {
  2412. var engine = new Engine
  2413. {
  2414. ClrTypeConverter = new TestTypeConverter()
  2415. };
  2416. Assert.IsType<TestTypeConverter>(engine.ClrTypeConverter);
  2417. engine.SetValue("x", new Testificate());
  2418. Assert.Throws<JavaScriptException>(() => engine.Execute("c.Name"));
  2419. }
  2420. private class Wrapper
  2421. {
  2422. public Testificate Test { get; set; }
  2423. }
  2424. private class Testificate
  2425. {
  2426. public string Name { get; set; }
  2427. public Func<int, int, int> Init { get; set; }
  2428. }
  2429. private class TestTypeConverter : Jint.Runtime.Interop.ITypeConverter
  2430. {
  2431. public object Convert(object value, Type type, IFormatProvider formatProvider)
  2432. {
  2433. throw new NotImplementedException();
  2434. }
  2435. public bool TryConvert(object value, Type type, IFormatProvider formatProvider, out object converted)
  2436. {
  2437. throw new NotImplementedException();
  2438. }
  2439. }
  2440. }
  2441. }