2
0

EngineTests.cs 107 KB

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