EngineTests.cs 110 KB

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