EngineTests.cs 104 KB

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