EngineTests.cs 109 KB

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