2
0

InteropTests.cs 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230
  1. using System.Collections;
  2. using System.Globalization;
  3. using System.Reflection;
  4. using System.Runtime.CompilerServices;
  5. using Jint.Native;
  6. using Jint.Native.Object;
  7. using Jint.Native.Symbol;
  8. using Jint.Runtime;
  9. using Jint.Runtime.Interop;
  10. using Jint.Tests.Runtime.Converters;
  11. using Jint.Tests.Runtime.Domain;
  12. using Jint.Tests.Runtime.TestClasses;
  13. using MongoDB.Bson;
  14. using Shapes;
  15. namespace Jint.Tests.Runtime
  16. {
  17. public partial class InteropTests : IDisposable
  18. {
  19. private readonly Engine _engine;
  20. public InteropTests()
  21. {
  22. _engine = new Engine(cfg => cfg.AllowClr(
  23. typeof(Shape).GetTypeInfo().Assembly,
  24. typeof(Console).GetTypeInfo().Assembly,
  25. typeof(File).GetTypeInfo().Assembly))
  26. .SetValue("log", new Action<object>(Console.WriteLine))
  27. .SetValue("assert", new Action<bool>(Assert.True))
  28. .SetValue("equal", new Action<object, object>(Assert.Equal))
  29. ;
  30. }
  31. void IDisposable.Dispose()
  32. {
  33. }
  34. private void RunTest(string source)
  35. {
  36. _engine.Execute(source);
  37. }
  38. public class Foo
  39. {
  40. public static Bar GetBar()
  41. {
  42. return new Bar();
  43. }
  44. }
  45. public class Bar
  46. {
  47. public string Test { get; set; } = "123";
  48. }
  49. [Fact]
  50. public void ShouldStringifyNetObjects()
  51. {
  52. _engine.SetValue("foo", new Foo());
  53. var json = _engine.Evaluate("JSON.stringify(foo.GetBar())").AsString();
  54. Assert.Equal("{\"Test\":\"123\"}", json);
  55. }
  56. [Fact]
  57. public void EngineShouldStringifyADictionary()
  58. {
  59. var engine = new Engine();
  60. var d = new Hashtable();
  61. d["Values"] = 1;
  62. engine.SetValue("d", d);
  63. Assert.Equal("{\"Values\":1}", engine.Evaluate($"JSON.stringify(d)").AsString());
  64. }
  65. [Fact]
  66. public void EngineShouldStringifyADictionaryOfStringAndObjectCorrectly()
  67. {
  68. var engine = new Engine();
  69. var dictionary = new Dictionary<string, object>
  70. {
  71. { "foo", 5 },
  72. { "bar", "A string" }
  73. };
  74. engine.SetValue(nameof(dictionary), dictionary);
  75. var result = engine.Evaluate($"JSON.stringify({nameof(dictionary)})").AsString();
  76. Assert.Equal("{\"foo\":5,\"bar\":\"A string\"}", result);
  77. }
  78. [Fact]
  79. public void EngineShouldRoundtripParsedJSONBackToStringCorrectly()
  80. {
  81. var engine = new Engine();
  82. const string json = "{\"foo\":5,\"bar\":\"A string\"}";
  83. var parsed = engine.Evaluate($"JSON.parse('{json}')").ToObject();
  84. engine.SetValue(nameof(parsed), parsed);
  85. var result = engine.Evaluate($"JSON.stringify({nameof(parsed)})").AsString();
  86. Assert.Equal(json, result);
  87. }
  88. [Fact]
  89. public void PrimitiveTypesCanBeSet()
  90. {
  91. _engine.SetValue("x", 10);
  92. _engine.SetValue("y", true);
  93. _engine.SetValue("z", "foo");
  94. RunTest(@"
  95. assert(x === 10);
  96. assert(y === true);
  97. assert(z === 'foo');
  98. ");
  99. }
  100. [Fact]
  101. public void TypePropertyAccess()
  102. {
  103. var userClass = new Person();
  104. var result = new Engine()
  105. .SetValue("userclass", userClass)
  106. .Evaluate("userclass.TypeProperty.Name;")
  107. .AsString();
  108. Assert.Equal("Person", result);
  109. }
  110. [Fact]
  111. public void CanAccessMemberNamedItem()
  112. {
  113. _engine.Execute(@"
  114. function item2(arg) {
  115. return arg.item2
  116. }
  117. function item1(arg) {
  118. return arg.item
  119. }
  120. function item3(arg) {
  121. return arg.Item
  122. }
  123. ");
  124. var argument = new Dictionary<string, object>
  125. {
  126. { "item2", "item2 value" },
  127. { "item", "item value" },
  128. { "Item", "Item value" }
  129. };
  130. Assert.Equal("item2 value", _engine.Invoke("item2", argument));
  131. Assert.Equal("item value", _engine.Invoke("item1", argument));
  132. Assert.Equal("Item value", _engine.Invoke("item3", argument));
  133. var company = new Company("Acme Ltd");
  134. _engine.SetValue("c", company);
  135. Assert.Equal("item thingie", _engine.Evaluate("c.Item"));
  136. Assert.Equal("item thingie", _engine.Evaluate("c.item"));
  137. Assert.Equal("value", _engine.Evaluate("c['key']"));
  138. }
  139. [Fact]
  140. public void DelegatesCanBeSet()
  141. {
  142. _engine.SetValue("square", new Func<double, double>(x => x * x));
  143. RunTest(@"
  144. assert(square(10) === 100);
  145. ");
  146. }
  147. [Fact]
  148. public void DelegateWithNullableParameterCanBePassedANull()
  149. {
  150. _engine.SetValue("isnull", new Func<double?, bool>(x => x == null));
  151. RunTest(@"
  152. assert(isnull(null) === true);
  153. ");
  154. }
  155. [Fact]
  156. public void DelegateWithObjectParameterCanBePassedANull()
  157. {
  158. _engine.SetValue("isnull", new Func<object, bool>(x => x == null));
  159. RunTest(@"
  160. assert(isnull(null) === true);
  161. ");
  162. }
  163. [Fact]
  164. public void DelegateWithNullableParameterCanBePassedAnUndefined()
  165. {
  166. _engine.SetValue("isnull", new Func<double?, bool>(x => x == null));
  167. RunTest(@"
  168. assert(isnull(undefined) === true);
  169. ");
  170. }
  171. [Fact]
  172. public void DelegateWithObjectParameterCanBePassedAnUndefined()
  173. {
  174. _engine.SetValue("isnull", new Func<object, bool>(x => x == null));
  175. RunTest(@"
  176. assert(isnull(undefined) === true);
  177. ");
  178. }
  179. [Fact]
  180. public void DelegateWithNullableParameterCanBeExcluded()
  181. {
  182. _engine.SetValue("isnull", new Func<double?, bool>(x => x == null));
  183. RunTest(@"
  184. assert(isnull() === true);
  185. ");
  186. }
  187. [Fact]
  188. public void DelegateWithObjectParameterCanBeExcluded()
  189. {
  190. _engine.SetValue("isnull", new Func<object, bool>(x => x == null));
  191. RunTest(@"
  192. assert(isnull() === true);
  193. ");
  194. }
  195. [Fact]
  196. public void DynamicDelegateCanBeSet()
  197. {
  198. #if NETFRAMEWORK
  199. var parameters = new[]
  200. {
  201. System.Linq.Expressions.Expression.Parameter(typeof(int)),
  202. System.Linq.Expressions.Expression.Parameter(typeof(int))
  203. };
  204. var exp = System.Linq.Expressions.Expression.Add(parameters[0], parameters[1]);
  205. var del = System.Linq.Expressions.Expression.Lambda(exp, parameters).Compile();
  206. _engine.SetValue("add", del);
  207. RunTest(@"
  208. assert(add(1,1) === 2);
  209. ");
  210. #endif
  211. }
  212. [Fact]
  213. public void ExtraParametersAreIgnored()
  214. {
  215. _engine.SetValue("passNumber", new Func<int, int>(x => x));
  216. RunTest(@"
  217. assert(passNumber(123,'test',{},[],null) === 123);
  218. ");
  219. }
  220. private delegate string callParams(params object[] values);
  221. private delegate string callArgumentAndParams(string firstParam, params object[] values);
  222. [Fact]
  223. public void DelegatesWithParamsParameterCanBeInvoked()
  224. {
  225. var a = new A();
  226. _engine.SetValue("callParams", new callParams(a.Call13));
  227. _engine.SetValue("callArgumentAndParams", new callArgumentAndParams(a.Call14));
  228. RunTest(@"
  229. assert(callParams('1','2','3') === '1,2,3');
  230. assert(callParams('1') === '1');
  231. assert(callParams() === '');
  232. assert(callArgumentAndParams('a','1','2','3') === 'a:1,2,3');
  233. assert(callArgumentAndParams('a','1') === 'a:1');
  234. assert(callArgumentAndParams('a') === 'a:');
  235. assert(callArgumentAndParams() === ':');
  236. ");
  237. }
  238. [Fact]
  239. public void CanGetObjectProperties()
  240. {
  241. var p = new Person
  242. {
  243. Name = "Mickey Mouse"
  244. };
  245. _engine.SetValue("p", p);
  246. RunTest(@"
  247. assert(p.Name === 'Mickey Mouse');
  248. ");
  249. }
  250. [Fact]
  251. public void CanInvokeObjectMethods()
  252. {
  253. var p = new Person
  254. {
  255. Name = "Mickey Mouse"
  256. };
  257. _engine.SetValue("p", p);
  258. RunTest(@"
  259. assert(p.ToString() === 'Mickey Mouse');
  260. ");
  261. }
  262. [Fact]
  263. public void CanInvokeObjectMethodsWithPascalCase()
  264. {
  265. var p = new Person
  266. {
  267. Name = "Mickey Mouse"
  268. };
  269. _engine.SetValue("p", p);
  270. RunTest(@"
  271. assert(p.toString() === 'Mickey Mouse');
  272. ");
  273. }
  274. [Fact]
  275. public void CanSetObjectProperties()
  276. {
  277. var p = new Person
  278. {
  279. Name = "Mickey Mouse"
  280. };
  281. _engine.SetValue("p", p);
  282. RunTest(@"
  283. p.Name = 'Donald Duck';
  284. assert(p.Name === 'Donald Duck');
  285. ");
  286. Assert.Equal("Donald Duck", p.Name);
  287. }
  288. [Fact]
  289. public void CanGetIndexUsingStringKey()
  290. {
  291. var dictionary = new Dictionary<string, Person>();
  292. dictionary.Add("person1", new Person { Name = "Mickey Mouse" });
  293. dictionary.Add("person2", new Person { Name = "Goofy" });
  294. _engine.SetValue("dictionary", dictionary);
  295. RunTest(@"
  296. assert(dictionary['person1'].Name === 'Mickey Mouse');
  297. assert(dictionary['person2'].Name === 'Goofy');
  298. ");
  299. }
  300. [Fact]
  301. public void CanSetIndexUsingStringKey()
  302. {
  303. var dictionary = new Dictionary<string, Person>();
  304. dictionary.Add("person1", new Person { Name = "Mickey Mouse" });
  305. dictionary.Add("person2", new Person { Name = "Goofy" });
  306. _engine.SetValue("dictionary", dictionary);
  307. RunTest(@"
  308. dictionary['person2'].Name = 'Donald Duck';
  309. assert(dictionary['person2'].Name === 'Donald Duck');
  310. ");
  311. Assert.Equal("Donald Duck", dictionary["person2"].Name);
  312. }
  313. [Fact]
  314. public void CanGetIndexUsingIntegerKey()
  315. {
  316. var dictionary = new Dictionary<int, string>();
  317. dictionary.Add(1, "Mickey Mouse");
  318. dictionary.Add(2, "Goofy");
  319. _engine.SetValue("dictionary", dictionary);
  320. RunTest(@"
  321. assert(dictionary[1] === 'Mickey Mouse');
  322. assert(dictionary[2] === 'Goofy');
  323. ");
  324. }
  325. [Fact]
  326. public void CanSetIndexUsingIntegerKey()
  327. {
  328. var dictionary = new Dictionary<int, string>();
  329. dictionary.Add(1, "Mickey Mouse");
  330. dictionary.Add(2, "Goofy");
  331. _engine.SetValue("dictionary", dictionary);
  332. RunTest(@"
  333. dictionary[2] = 'Donald Duck';
  334. assert(dictionary[2] === 'Donald Duck');
  335. ");
  336. Assert.Equal("Mickey Mouse", dictionary[1]);
  337. Assert.Equal("Donald Duck", dictionary[2]);
  338. }
  339. private class DoubleIndexedClass
  340. {
  341. public int this[int index] => index;
  342. public string this[string index] => index;
  343. }
  344. [Fact]
  345. public void CanGetIndexUsingBothIntAndStringIndex()
  346. {
  347. var dictionary = new DoubleIndexedClass();
  348. _engine.SetValue("dictionary", dictionary);
  349. RunTest(@"
  350. assert(dictionary[1] === 1);
  351. assert(dictionary['test'] === 'test');
  352. ");
  353. }
  354. [Fact]
  355. public void CanUseGenericMethods()
  356. {
  357. var dictionary = new Dictionary<int, string>();
  358. dictionary.Add(1, "Mickey Mouse");
  359. _engine.SetValue("dictionary", dictionary);
  360. RunTest(@"
  361. dictionary.Add(2, 'Goofy');
  362. assert(dictionary[2] === 'Goofy');
  363. ");
  364. Assert.Equal("Mickey Mouse", dictionary[1]);
  365. Assert.Equal("Goofy", dictionary[2]);
  366. }
  367. [Fact]
  368. public void CanUseMultiGenericTypes()
  369. {
  370. RunTest(@"
  371. var type = System.Collections.Generic.Dictionary(System.Int32, System.String);
  372. var dictionary = new type();
  373. dictionary.Add(1, 'Mickey Mouse');
  374. dictionary.Add(2, 'Goofy');
  375. assert(dictionary[2] === 'Goofy');
  376. ");
  377. }
  378. [Fact]
  379. public void CanUseIndexOnCollection()
  380. {
  381. var collection = new System.Collections.ObjectModel.Collection<string>();
  382. collection.Add("Mickey Mouse");
  383. collection.Add("Goofy");
  384. _engine.SetValue("dictionary", collection);
  385. RunTest(@"
  386. dictionary[1] = 'Donald Duck';
  387. assert(dictionary[1] === 'Donald Duck');
  388. ");
  389. Assert.Equal("Mickey Mouse", collection[0]);
  390. Assert.Equal("Donald Duck", collection[1]);
  391. }
  392. [Fact]
  393. public void CanUseIndexOnList()
  394. {
  395. var list = new List<object>(2);
  396. list.Add("Mickey Mouse");
  397. list.Add("Goofy");
  398. _engine.SetValue("list", list);
  399. _engine.Evaluate("list[1] = 'Donald Duck';");
  400. Assert.Equal("Donald Duck", _engine.Evaluate("list[1]").AsString());
  401. Assert.Equal("Mickey Mouse", list[0]);
  402. Assert.Equal("Donald Duck", list[1]);
  403. }
  404. [Fact]
  405. public void ShouldForOfOnLists()
  406. {
  407. _engine.SetValue("list", new List<string> { "a", "b" });
  408. var result = _engine.Evaluate("var l = ''; for (var x of list) l += x; return l;").AsString();
  409. Assert.Equal("ab", result);
  410. }
  411. [Fact]
  412. public void ShouldForOfOnArrays()
  413. {
  414. _engine.SetValue("arr", new[] { "a", "b" });
  415. var result = _engine.Evaluate("var l = ''; for (var x of arr) l += x; return l;").AsString();
  416. Assert.Equal("ab", result);
  417. }
  418. [Fact]
  419. public void ShouldForOfOnDictionaries()
  420. {
  421. _engine.SetValue("dict", new Dictionary<string, string> { { "a", "1" }, { "b", "2" } });
  422. var result = _engine.Evaluate("var l = ''; for (var x of dict) l += x; return l;").AsString();
  423. Assert.Equal("a,1b,2", result);
  424. }
  425. [Fact]
  426. public void ShouldForOfOnEnumerable()
  427. {
  428. _engine.SetValue("c", new Company("name"));
  429. var result = _engine.Evaluate("var l = ''; for (var x of c.getNameChars()) l += x + ','; return l;").AsString();
  430. Assert.Equal("n,a,m,e,", result);
  431. }
  432. [Fact]
  433. public void ShouldThrowWhenForOfOnObject()
  434. {
  435. // normal objects are not iterable in javascript
  436. var o = new { A = 1, B = 2 };
  437. _engine.SetValue("anonymous", o);
  438. var ex = Assert.Throws<JavaScriptException>(() => _engine.Evaluate("for (var x of anonymous) {}"));
  439. Assert.Equal("The value is not iterable", ex.Message);
  440. }
  441. [Fact]
  442. public void CanAccessAnonymousObject()
  443. {
  444. var p = new
  445. {
  446. Name = "Mickey Mouse"
  447. };
  448. _engine.SetValue("p", p);
  449. RunTest(@"
  450. assert(p.Name === 'Mickey Mouse');
  451. ");
  452. }
  453. [Fact]
  454. public void CanAccessAnonymousObjectProperties()
  455. {
  456. var p = new
  457. {
  458. Address = new
  459. {
  460. City = "Mouseton"
  461. }
  462. };
  463. _engine.SetValue("p", p);
  464. RunTest(@"
  465. assert(p.Address.City === 'Mouseton');
  466. ");
  467. }
  468. [Fact]
  469. public void PocosCanReturnJsValueDirectly()
  470. {
  471. var o = new
  472. {
  473. x = new JsNumber(1),
  474. y = new JsString("string")
  475. };
  476. _engine.SetValue("o", o);
  477. RunTest(@"
  478. assert(o.x === 1);
  479. assert(o.y === 'string');
  480. ");
  481. }
  482. [Fact]
  483. public void PocosCanReturnObjectInstanceDirectly()
  484. {
  485. var x = new JsObject(_engine);
  486. x.Set("foo", new JsString("bar"));
  487. var o = new
  488. {
  489. x
  490. };
  491. _engine.SetValue("o", o);
  492. RunTest(@"
  493. assert(o.x.foo === 'bar');
  494. ");
  495. }
  496. [Fact]
  497. public void DateTimeIsConvertedToDate()
  498. {
  499. var o = new
  500. {
  501. z = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
  502. };
  503. _engine.SetValue("o", o);
  504. RunTest(@"
  505. assert(o.z.valueOf() === 0);
  506. ");
  507. }
  508. [Fact]
  509. public void DateTimeOffsetIsConvertedToDate()
  510. {
  511. var o = new
  512. {
  513. z = new DateTimeOffset(1970, 1, 1, 0, 0, 0, new TimeSpan())
  514. };
  515. _engine.SetValue("o", o);
  516. RunTest(@"
  517. assert(o.z.valueOf() === 0);
  518. ");
  519. }
  520. [Fact]
  521. public void EcmaValuesAreAutomaticallyConvertedWhenSetInPoco()
  522. {
  523. var p = new Person
  524. {
  525. Name = "foo"
  526. };
  527. _engine.SetValue("p", p);
  528. RunTest(@"
  529. assert(p.Name === 'foo');
  530. assert(p.Age === 0);
  531. p.Name = 'bar';
  532. p.Age = 10;
  533. ");
  534. Assert.Equal("bar", p.Name);
  535. Assert.Equal(10, p.Age);
  536. }
  537. [Fact]
  538. public void EcmaValuesAreAutomaticallyConvertedToBestMatchWhenSetInPoco()
  539. {
  540. var p = new Person
  541. {
  542. Name = "foo"
  543. };
  544. _engine.SetValue("p", p);
  545. RunTest(@"
  546. p.Name = 10;
  547. p.Age = '20';
  548. ");
  549. Assert.Equal("10", p.Name);
  550. Assert.Equal(20, p.Age);
  551. }
  552. [Fact]
  553. public void ShouldCallInstanceMethodWithoutArgument()
  554. {
  555. _engine.SetValue("a", new A());
  556. RunTest(@"
  557. assert(a.Call1() === 0);
  558. ");
  559. }
  560. [Fact]
  561. public void ShouldCallInstanceMethodOverloadArgument()
  562. {
  563. _engine.SetValue("a", new A());
  564. RunTest(@"
  565. assert(a.Call1(1) === 1);
  566. ");
  567. }
  568. [Fact]
  569. public void ShouldCallInstanceMethodWithString()
  570. {
  571. var p = new Person();
  572. _engine.SetValue("a", new A());
  573. _engine.SetValue("p", p);
  574. RunTest(@"
  575. p.Name = a.Call2('foo');
  576. assert(p.Name === 'foo');
  577. ");
  578. Assert.Equal("foo", p.Name);
  579. }
  580. [Fact]
  581. public void CanUseTrim()
  582. {
  583. var p = new Person { Name = "Mickey Mouse " };
  584. _engine.SetValue("p", p);
  585. RunTest(@"
  586. assert(p.Name === 'Mickey Mouse ');
  587. p.Name = p.Name.trim();
  588. assert(p.Name === 'Mickey Mouse');
  589. ");
  590. Assert.Equal("Mickey Mouse", p.Name);
  591. }
  592. [Fact]
  593. public void CanUseMathFloor()
  594. {
  595. var p = new Person();
  596. _engine.SetValue("p", p);
  597. RunTest(@"
  598. p.Age = Math.floor(1.6);p
  599. assert(p.Age === 1);
  600. ");
  601. Assert.Equal(1, p.Age);
  602. }
  603. [Fact]
  604. public void CanUseDelegateAsFunction()
  605. {
  606. var even = new Func<int, bool>(x => x % 2 == 0);
  607. _engine.SetValue("even", even);
  608. RunTest(@"
  609. assert(even(2) === true);
  610. ");
  611. }
  612. private struct TestStruct
  613. {
  614. public int Value;
  615. public TestStruct(int value)
  616. {
  617. Value = value;
  618. }
  619. }
  620. private class TestClass
  621. {
  622. public string String { get; set; }
  623. public int Int { get; set; }
  624. public int? NullableInt { get; set; }
  625. public DateTime? NullableDate { get; set; }
  626. public bool? NullableBool { get; set; }
  627. public bool Bool { get; set; }
  628. public TestEnumInt32? NullableEnum { get; set; }
  629. public TestStruct? NullableStruct { get; set; }
  630. public void SetBool(bool value)
  631. {
  632. Bool = value;
  633. }
  634. public void SetInt(int value)
  635. {
  636. Int = value;
  637. }
  638. public void SetString(string value)
  639. {
  640. String = value;
  641. }
  642. }
  643. [Fact]
  644. public void CanSetNullablePropertiesOnPocos()
  645. {
  646. var instance = new TestClass();
  647. _engine.SetValue("instance", instance);
  648. _engine.SetValue("TestStruct", typeof(TestStruct));
  649. RunTest(@"
  650. instance.NullableInt = 2;
  651. instance.NullableDate = new Date();
  652. instance.NullableBool = true;
  653. instance.NullableEnum = 1;
  654. instance.NullableStruct = new TestStruct(5);
  655. assert(instance.NullableInt===2);
  656. assert(instance.NullableDate!=null);
  657. assert(instance.NullableBool===true);
  658. assert(instance.NullableEnum===1);
  659. assert(instance.NullableStruct.Value===5);
  660. ");
  661. }
  662. private class ReadOnlyList : IReadOnlyList<Person>
  663. {
  664. private readonly Person[] _data;
  665. public ReadOnlyList(params Person[] data)
  666. {
  667. _data = data;
  668. }
  669. public IEnumerator<Person> GetEnumerator()
  670. {
  671. return ((IEnumerable<Person>) _data).GetEnumerator();
  672. }
  673. IEnumerator IEnumerable.GetEnumerator()
  674. {
  675. return _data.GetEnumerator();
  676. }
  677. public int Count => _data.Length;
  678. public Person this[int index] => _data[index];
  679. }
  680. [Fact]
  681. public void CanAddArrayPrototypeForArrayLikeClrObjects()
  682. {
  683. var e = new Engine(cfg => cfg
  684. .AllowClr(typeof(Person).Assembly)
  685. .SetWrapObjectHandler((engine, target) =>
  686. {
  687. var instance = new ObjectWrapper(engine, target);
  688. if (instance.IsArrayLike)
  689. {
  690. instance.SetPrototypeOf(engine.Realm.Intrinsics.Array.PrototypeObject);
  691. }
  692. return instance;
  693. })
  694. );
  695. var person = new Person
  696. {
  697. Age = 12,
  698. Name = "John"
  699. };
  700. dynamic obj = new
  701. {
  702. values = new ReadOnlyList(person)
  703. };
  704. e.SetValue("o", obj);
  705. var name = e.Evaluate("o.values.filter(x => x.age == 12)[0].name").ToString();
  706. Assert.Equal("John", name);
  707. }
  708. [Fact]
  709. public void CanSetIsConcatSpreadableForArrays()
  710. {
  711. var engine = new Engine(opt =>
  712. {
  713. opt.SetWrapObjectHandler((eng, obj) =>
  714. {
  715. var wrapper = new ObjectWrapper(eng, obj);
  716. if (wrapper.IsArrayLike)
  717. {
  718. wrapper.SetPrototypeOf(eng.Realm.Intrinsics.Array.PrototypeObject);
  719. wrapper.Set(GlobalSymbolRegistry.IsConcatSpreadable, true);
  720. }
  721. return wrapper;
  722. });
  723. });
  724. engine
  725. .SetValue("list1", new List<string> { "A", "B", "C" })
  726. .SetValue("list2", new List<string> { "D", "E", "F" })
  727. .Execute("var array1 = ['A', 'B', 'C'];")
  728. .Execute("var array2 = ['D', 'E', 'F'];");
  729. Assert.True(engine.Evaluate("list1[Symbol.isConcatSpreadable] = true; list1[Symbol.isConcatSpreadable];").AsBoolean());
  730. Assert.True(engine.Evaluate("list2[Symbol.isConcatSpreadable] = true; list2[Symbol.isConcatSpreadable];").AsBoolean());
  731. Assert.Equal("[\"A\",\"B\",\"C\"]", engine.Evaluate("JSON.stringify(array1);"));
  732. Assert.Equal("[\"D\",\"E\",\"F\"]", engine.Evaluate("JSON.stringify(array2);"));
  733. Assert.Equal("[\"A\",\"B\",\"C\"]", engine.Evaluate("JSON.stringify(list1);"));
  734. Assert.Equal("[\"D\",\"E\",\"F\"]", engine.Evaluate("JSON.stringify(list2);"));
  735. const string Concatenated = "[\"A\",\"B\",\"C\",\"D\",\"E\",\"F\"]";
  736. Assert.Equal(Concatenated, engine.Evaluate("JSON.stringify(array1.concat(array2));"));
  737. Assert.Equal(Concatenated, engine.Evaluate("JSON.stringify(array1.concat(list2));"));
  738. Assert.Equal(Concatenated, engine.Evaluate("JSON.stringify(list1.concat(array2));"));
  739. Assert.Equal(Concatenated, engine.Evaluate("JSON.stringify(list1.concat(list2));"));
  740. Assert.False(engine.Evaluate("list1[Symbol.isConcatSpreadable] = false; list1[Symbol.isConcatSpreadable];").AsBoolean());
  741. Assert.False(engine.Evaluate("list2[Symbol.isConcatSpreadable] = false; list2[Symbol.isConcatSpreadable];").AsBoolean());
  742. Assert.Equal("[[\"A\",\"B\",\"C\"]]", engine.Evaluate("JSON.stringify([].concat(list1));"));
  743. Assert.Equal("[[\"A\",\"B\",\"C\"],[\"D\",\"E\",\"F\"]]", engine.Evaluate("JSON.stringify(list1.concat(list2));"));
  744. }
  745. [Fact]
  746. public void ShouldConvertArrayToArrayInstance()
  747. {
  748. var result = _engine
  749. .SetValue("values", new[] { 1, 2, 3, 4, 5, 6 })
  750. .Evaluate("values.filter(function(x){ return x % 2 == 0; })");
  751. var parts = result.ToObject();
  752. Assert.True(parts.GetType().IsArray);
  753. Assert.Equal(3, ((object[]) parts).Length);
  754. Assert.Equal(2d, ((object[]) parts)[0]);
  755. Assert.Equal(4d, ((object[]) parts)[1]);
  756. Assert.Equal(6d, ((object[]) parts)[2]);
  757. }
  758. [Fact]
  759. public void ShouldConvertListsToArrayInstance()
  760. {
  761. var result = _engine
  762. .SetValue("values", new List<object> { 1, 2, 3, 4, 5, 6 })
  763. .Evaluate("new Array(values).filter(function(x){ return x % 2 == 0; })");
  764. var parts = result.ToObject();
  765. Assert.True(parts.GetType().IsArray);
  766. Assert.Equal(3, ((object[]) parts).Length);
  767. Assert.Equal(2d, ((object[]) parts)[0]);
  768. Assert.Equal(4d, ((object[]) parts)[1]);
  769. Assert.Equal(6d, ((object[]) parts)[2]);
  770. }
  771. [Fact]
  772. public void ShouldConvertArrayInstanceToArray()
  773. {
  774. var parts = _engine.Evaluate("'[email protected]'.split('@');").ToObject();
  775. Assert.True(parts.GetType().IsArray);
  776. Assert.Equal(2, ((object[]) parts).Length);
  777. Assert.Equal("foo", ((object[]) parts)[0]);
  778. Assert.Equal("bar.com", ((object[]) parts)[1]);
  779. }
  780. [Fact]
  781. public void ShouldLoopWithNativeEnumerator()
  782. {
  783. JsValue adder(JsValue argValue)
  784. {
  785. var args = argValue.AsArray();
  786. double sum = 0;
  787. foreach (var item in args)
  788. {
  789. if (item.IsNumber())
  790. {
  791. sum += item.AsNumber();
  792. }
  793. }
  794. return sum;
  795. }
  796. var result = _engine.SetValue("getSum", new Func<JsValue, JsValue>(adder))
  797. .Evaluate("getSum([1,2,3]);");
  798. Assert.True(result == 6);
  799. }
  800. [Fact]
  801. public void ShouldConvertBooleanInstanceToBool()
  802. {
  803. var value = _engine.Evaluate("new Boolean(true)").ToObject();
  804. Assert.Equal(typeof(bool), value.GetType());
  805. Assert.Equal(true, value);
  806. }
  807. [Fact]
  808. public void ShouldAllowBooleanCoercion()
  809. {
  810. var engine = new Engine(options => { options.Interop.ValueCoercion = ValueCoercionType.Boolean; });
  811. engine.SetValue("o", new TestClass());
  812. Assert.True(engine.Evaluate("o.Bool = 1; return o.Bool;").AsBoolean());
  813. Assert.True(engine.Evaluate("o.Bool = 'dog'; return o.Bool;").AsBoolean());
  814. Assert.True(engine.Evaluate("o.Bool = {}; return o.Bool;").AsBoolean());
  815. Assert.False(engine.Evaluate("o.Bool = 0; return o.Bool;").AsBoolean());
  816. Assert.False(engine.Evaluate("o.Bool = ''; return o.Bool;").AsBoolean());
  817. Assert.False(engine.Evaluate("o.Bool = null; return o.Bool;").AsBoolean());
  818. Assert.False(engine.Evaluate("o.Bool = undefined; return o.Bool;").AsBoolean());
  819. engine.Evaluate("class MyClass { valueOf() { return 42; } }");
  820. Assert.Equal(true, engine.Evaluate("let obj = new MyClass(); o.Bool = obj; return o.Bool;").AsBoolean());
  821. engine.SetValue("func3", new Action<bool, bool, bool>((param1, param2, param3) =>
  822. {
  823. Assert.True(param1);
  824. Assert.True(param2);
  825. Assert.True(param3);
  826. }));
  827. engine.Evaluate("func3(true, obj, [ 1, 2, 3])");
  828. Assert.Equal(true, engine.Evaluate("o.SetBool(42); return o.Bool;").AsBoolean());
  829. Assert.Equal(true, engine.Evaluate("o.SetBool(obj); return o.Bool;").AsBoolean());
  830. Assert.Equal(true, engine.Evaluate("o.SetBool([ 1, 2, 3].length); return o.Bool;").AsBoolean());
  831. }
  832. [Fact]
  833. public void ShouldAllowNumberCoercion()
  834. {
  835. var engine = new Engine(options => { options.Interop.ValueCoercion = ValueCoercionType.Number; });
  836. engine.SetValue("o", new TestClass());
  837. Assert.Equal(1, engine.Evaluate("o.Int = true; return o.Int;").AsNumber());
  838. Assert.Equal(0, engine.Evaluate("o.Int = false; return o.Int;").AsNumber());
  839. engine.Evaluate("class MyClass { valueOf() { return 42; } }");
  840. Assert.Equal(42, engine.Evaluate("let obj = new MyClass(); o.Int = obj; return o.Int;").AsNumber());
  841. // but null and undefined should be injected as nulls to nullable objects
  842. Assert.True(engine.Evaluate("o.NullableInt = null; return o.NullableInt;").IsNull());
  843. Assert.True(engine.Evaluate("o.NullableInt = undefined; return o.NullableInt;").IsNull());
  844. engine.SetValue("func3", new Action<int, double, long>((param1, param2, param3) =>
  845. {
  846. Assert.Equal(1, param1);
  847. Assert.Equal(42, param2);
  848. Assert.Equal(3, param3);
  849. }));
  850. engine.Evaluate("func3(true, obj, [ 1, 2, 3].length)");
  851. Assert.Equal(1, engine.Evaluate("o.SetInt(true); return o.Int;").AsNumber());
  852. Assert.Equal(42, engine.Evaluate("o.SetInt(obj); return o.Int;").AsNumber());
  853. Assert.Equal(3, engine.Evaluate("o.SetInt([ 1, 2, 3].length); return o.Int;").AsNumber());
  854. }
  855. [Fact]
  856. public void ShouldAllowStringCoercion()
  857. {
  858. var engine = new Engine(options => { options.Interop.ValueCoercion = ValueCoercionType.String; });
  859. // basic premise, booleans in JS are lower-case, so should the the toString under interop
  860. Assert.Equal("true", engine.Evaluate("'' + true").AsString());
  861. engine.SetValue("o", new TestClass());
  862. Assert.Equal("false", engine.Evaluate("'' + o.Bool").AsString());
  863. Assert.Equal("true", engine.Evaluate("o.Bool = true; o.String = o.Bool; return o.String;").AsString());
  864. Assert.Equal("true", engine.Evaluate("o.String = true; return o.String;").AsString());
  865. engine.SetValue("func1", new Func<bool>(() => true));
  866. Assert.Equal("true", engine.Evaluate("'' + func1()").AsString());
  867. engine.SetValue("func2", new Func<JsValue>(() => JsBoolean.True));
  868. Assert.Equal("true", engine.Evaluate("'' + func2()").AsString());
  869. // but null and undefined should be injected as nulls to c# objects
  870. Assert.True(engine.Evaluate("o.String = null; return o.String;").IsNull());
  871. Assert.True(engine.Evaluate("o.String = undefined; return o.String;").IsNull());
  872. Assert.Equal("1,2,3", engine.Evaluate("o.String = [ 1, 2, 3 ]; return o.String;").AsString());
  873. engine.Evaluate("class MyClass { toString() { return 'hello world'; } }");
  874. Assert.Equal("hello world", engine.Evaluate("let obj = new MyClass(); o.String = obj; return o.String;").AsString());
  875. engine.SetValue("func3", new Action<string, string, string>((param1, param2, param3) =>
  876. {
  877. Assert.Equal("true", param1);
  878. Assert.Equal("hello world", param2);
  879. Assert.Equal("1,2,3", param3);
  880. }));
  881. engine.Evaluate("func3(true, obj, [ 1, 2, 3])");
  882. Assert.Equal("true", engine.Evaluate("o.SetString(true); return o.String;").AsString());
  883. Assert.Equal("hello world", engine.Evaluate("o.SetString(obj); return o.String;").AsString());
  884. Assert.Equal("1,2,3", engine.Evaluate("o.SetString([ 1, 2, 3]); return o.String;").AsString());
  885. }
  886. [Fact]
  887. public void ShouldConvertDateInstanceToDateTime()
  888. {
  889. var result = _engine.Evaluate("new Date(0)");
  890. var value = result.ToObject() is DateTime ? (DateTime) result.ToObject() : default;
  891. Assert.Equal(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), value);
  892. Assert.Equal(DateTimeKind.Utc, value.Kind);
  893. }
  894. [Fact]
  895. public void ShouldConvertDateInstanceToLocalDateTime()
  896. {
  897. TimeZoneInfo timeZone;
  898. try
  899. {
  900. timeZone = TimeZoneInfo.FindSystemTimeZoneById("Europe/Helsinki");
  901. }
  902. catch (TimeZoneNotFoundException)
  903. {
  904. timeZone = TimeZoneInfo.FindSystemTimeZoneById("FLE Standard Time");
  905. }
  906. var engine = new Engine(options =>
  907. {
  908. options.TimeZone = timeZone;
  909. options.Interop.DateTimeKind = DateTimeKind.Local;
  910. });
  911. var result = engine.Evaluate("new Date(0)");
  912. var value = result.ToObject() is DateTime ? (DateTime) result.ToObject() : default;
  913. Assert.Equal(new DateTime(1970, 1, 1, 2, 0, 0, DateTimeKind.Local), value);
  914. Assert.Equal(DateTimeKind.Local, value.Kind);
  915. }
  916. [Fact]
  917. public void ShouldConvertNumberInstanceToDouble()
  918. {
  919. var result = _engine.Evaluate("new Number(10)");
  920. var value = result.ToObject();
  921. Assert.Equal(typeof(double), value.GetType());
  922. Assert.Equal(10d, value);
  923. }
  924. [Fact]
  925. public void ShouldConvertStringInstanceToString()
  926. {
  927. var value = _engine.Evaluate("new String('foo')").ToObject();
  928. Assert.Equal(typeof(string), value.GetType());
  929. Assert.Equal("foo", value);
  930. }
  931. [Fact]
  932. public void ShouldNotTryToConvertCompatibleTypes()
  933. {
  934. _engine.SetValue("a", new A());
  935. RunTest(@"
  936. assert(a.Call3('foo') === 'foo');
  937. assert(a.Call3(1) === '1');
  938. ");
  939. }
  940. [Fact]
  941. public void ShouldNotTryToConvertDerivedTypes()
  942. {
  943. _engine.SetValue("a", new A());
  944. _engine.SetValue("p", new Person { Name = "Mickey" });
  945. RunTest(@"
  946. assert(a.Call4(p) === 'Mickey');
  947. ");
  948. }
  949. [Fact]
  950. public void ShouldExecuteFunctionCallBackAsDelegate()
  951. {
  952. _engine.SetValue("a", new A());
  953. RunTest(@"
  954. assert(a.Call5(function(a,b){ return a+b }) === '1foo');
  955. ");
  956. }
  957. [Fact]
  958. public void ShouldExecuteFunctionCallBackAsFuncAndThisCanBeAssigned()
  959. {
  960. _engine.SetValue("a", new A());
  961. RunTest(@"
  962. assert(a.Call6(function(a,b){ return this+a+b }) === 'bar1foo');
  963. ");
  964. }
  965. [Fact]
  966. public void ShouldExecuteFunctionCallBackAsPredicate()
  967. {
  968. _engine.SetValue("a", new A());
  969. // Func<>
  970. RunTest(@"
  971. assert(a.Call8(function(){ return 'foo'; }) === 'foo');
  972. ");
  973. }
  974. [Fact]
  975. public void ShouldExecuteFunctionWithParameterCallBackAsPredicate()
  976. {
  977. _engine.SetValue("a", new A());
  978. // Func<,>
  979. RunTest(@"
  980. assert(a.Call7('foo', function(a){ return a === 'foo'; }) === true);
  981. ");
  982. }
  983. [Fact]
  984. public void ShouldExecuteActionCallBackAsPredicate()
  985. {
  986. _engine.SetValue("a", new A());
  987. // Action
  988. RunTest(@"
  989. var value;
  990. a.Call9(function(){ value = 'foo'; });
  991. assert(value === 'foo');
  992. ");
  993. }
  994. [Fact]
  995. public void ShouldExecuteActionWithParameterCallBackAsPredicate()
  996. {
  997. _engine.SetValue("a", new A());
  998. // Action<>
  999. RunTest(@"
  1000. var value;
  1001. a.Call10('foo', function(b){ value = b; });
  1002. assert(value === 'foo');
  1003. ");
  1004. }
  1005. [Fact]
  1006. public void ShouldExecuteActionWithMultipleParametersCallBackAsPredicate()
  1007. {
  1008. _engine.SetValue("a", new A());
  1009. // Action<,>
  1010. RunTest(@"
  1011. var value;
  1012. a.Call11('foo', 'bar', function(a,b){ value = a + b; });
  1013. assert(value === 'foobar');
  1014. ");
  1015. }
  1016. [Fact]
  1017. public void ShouldExecuteFunc()
  1018. {
  1019. _engine.SetValue("a", new A());
  1020. // Func<int, int>
  1021. RunTest(@"
  1022. var result = a.Call12(42, function(a){ return a + a; });
  1023. assert(result === 84);
  1024. ");
  1025. }
  1026. [Fact]
  1027. public void ShouldExecuteActionCallbackOnEventChanged()
  1028. {
  1029. var collection = new System.Collections.ObjectModel.ObservableCollection<string>();
  1030. Assert.True(collection.Count == 0);
  1031. _engine.SetValue("collection", collection);
  1032. RunTest(@"
  1033. var callCount = 0;
  1034. var handler = function(sender, eventArgs) { callCount++; } ;
  1035. collection.add_CollectionChanged(handler);
  1036. collection.Add('test');
  1037. collection.remove_CollectionChanged(handler);
  1038. collection.Add('test');
  1039. var json = JSON.stringify(Object.keys(handler));
  1040. ");
  1041. var callCount = (int) _engine.GetValue("callCount").AsNumber();
  1042. Assert.Equal(1, callCount);
  1043. Assert.Equal(2, collection.Count);
  1044. // make sure our delegate holder is hidden
  1045. Assert.Equal("[]", _engine.Evaluate("json"));
  1046. }
  1047. [Fact]
  1048. public void ShouldUseSystemIO()
  1049. {
  1050. RunTest(@"
  1051. var filename = System.IO.Path.GetTempFileName();
  1052. var sw = System.IO.File.CreateText(filename);
  1053. sw.Write('Hello World');
  1054. sw.Dispose();
  1055. var content = System.IO.File.ReadAllText(filename);
  1056. System.Console.WriteLine(content);
  1057. assert(content === 'Hello World');
  1058. ");
  1059. }
  1060. [Fact]
  1061. public void ShouldImportNamespace()
  1062. {
  1063. RunTest(@"
  1064. var Shapes = importNamespace('Shapes');
  1065. var circle = new Shapes.Circle();
  1066. assert(circle.Radius === 0);
  1067. assert(circle.Perimeter() === 0);
  1068. ");
  1069. }
  1070. [Fact]
  1071. public void ShouldConstructReferenceTypeWithParameters()
  1072. {
  1073. RunTest(@"
  1074. var Shapes = importNamespace('Shapes');
  1075. var circle = new Shapes.Circle(1);
  1076. assert(circle.Radius === 1);
  1077. assert(circle.Perimeter() === Math.PI);
  1078. ");
  1079. }
  1080. [Fact]
  1081. public void ShouldConstructValueTypeWithoutParameters()
  1082. {
  1083. RunTest(@"
  1084. var guid = new System.Guid();
  1085. assert('00000000-0000-0000-0000-000000000000' === guid.ToString());
  1086. ");
  1087. }
  1088. [Fact]
  1089. public void ShouldInvokeAFunctionByName()
  1090. {
  1091. RunTest(@"
  1092. function add(x, y) { return x + y; }
  1093. ");
  1094. Assert.Equal(3, _engine.Invoke("add", 1, 2));
  1095. }
  1096. [Fact]
  1097. public void ShouldNotInvokeNonFunctionValue()
  1098. {
  1099. RunTest(@"
  1100. var x= 10;
  1101. ");
  1102. Assert.Throws<JavaScriptException>(() => _engine.Invoke("x", 1, 2));
  1103. }
  1104. [Fact]
  1105. public void CanGetField()
  1106. {
  1107. var o = new ClassWithField
  1108. {
  1109. Field = "Mickey Mouse"
  1110. };
  1111. _engine.SetValue("o", o);
  1112. RunTest(@"
  1113. assert(o.Field === 'Mickey Mouse');
  1114. ");
  1115. }
  1116. [Fact]
  1117. public void CanSetField()
  1118. {
  1119. var o = new ClassWithField();
  1120. _engine.SetValue("o", o);
  1121. RunTest(@"
  1122. o.Field = 'Mickey Mouse';
  1123. assert(o.Field === 'Mickey Mouse');
  1124. ");
  1125. Assert.Equal("Mickey Mouse", o.Field);
  1126. }
  1127. [Fact]
  1128. public void CanGetStaticField()
  1129. {
  1130. RunTest(@"
  1131. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1132. var statics = domain.ClassWithStaticFields;
  1133. assert(statics.Get == 'Get');
  1134. ");
  1135. }
  1136. [Fact]
  1137. public void CanSetStaticField()
  1138. {
  1139. RunTest(@"
  1140. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1141. var statics = domain.ClassWithStaticFields;
  1142. statics.Set = 'hello';
  1143. assert(statics.Set == 'hello');
  1144. ");
  1145. Assert.Equal(ClassWithStaticFields.Set, "hello");
  1146. }
  1147. [Fact]
  1148. public void CanGetStaticAccessor()
  1149. {
  1150. RunTest(@"
  1151. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1152. var statics = domain.ClassWithStaticFields;
  1153. assert(statics.Getter == 'Getter');
  1154. ");
  1155. }
  1156. [Fact]
  1157. public void CanSetStaticAccessor()
  1158. {
  1159. RunTest(@"
  1160. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1161. var statics = domain.ClassWithStaticFields;
  1162. statics.Setter = 'hello';
  1163. assert(statics.Setter == 'hello');
  1164. ");
  1165. Assert.Equal(ClassWithStaticFields.Setter, "hello");
  1166. }
  1167. [Fact]
  1168. public void CantSetStaticReadonly()
  1169. {
  1170. RunTest(@"
  1171. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1172. var statics = domain.ClassWithStaticFields;
  1173. statics.Readonly = 'hello';
  1174. assert(statics.Readonly == 'Readonly');
  1175. ");
  1176. Assert.Equal(ClassWithStaticFields.Readonly, "Readonly");
  1177. }
  1178. [Fact]
  1179. public void CanSetCustomConverters()
  1180. {
  1181. var engine1 = new Engine();
  1182. engine1.SetValue("p", new { Test = true });
  1183. engine1.Execute("var result = p.Test;");
  1184. Assert.True((bool) engine1.GetValue("result").ToObject());
  1185. var engine2 = new Engine(o => o.AddObjectConverter(new NegateBoolConverter()));
  1186. engine2.SetValue("p", new { Test = true });
  1187. engine2.Execute("var result = p.Test;");
  1188. Assert.False((bool) engine2.GetValue("result").ToObject());
  1189. }
  1190. [Fact]
  1191. public void CanConvertEnumsToString()
  1192. {
  1193. var engine1 = new Engine(o => o.AddObjectConverter(new EnumsToStringConverter()))
  1194. .SetValue("assert", new Action<bool>(Assert.True));
  1195. engine1.SetValue("p", new { Comparison = StringComparison.CurrentCulture });
  1196. engine1.Execute("assert(p.Comparison === 'CurrentCulture');");
  1197. engine1.Execute("var result = p.Comparison;");
  1198. Assert.Equal("CurrentCulture", (string) engine1.GetValue("result").ToObject());
  1199. }
  1200. [Fact]
  1201. public void CanUserIncrementOperator()
  1202. {
  1203. var p = new Person
  1204. {
  1205. Age = 1
  1206. };
  1207. _engine.SetValue("p", p);
  1208. RunTest(@"
  1209. assert(++p.Age === 2);
  1210. ");
  1211. Assert.Equal(2, p.Age);
  1212. }
  1213. [Fact]
  1214. public void CanOverwriteValues()
  1215. {
  1216. _engine.SetValue("x", 3);
  1217. _engine.SetValue("x", 4);
  1218. RunTest(@"
  1219. assert(x === 4);
  1220. ");
  1221. }
  1222. [Fact]
  1223. public void ShouldCreateGenericType()
  1224. {
  1225. RunTest(@"
  1226. var ListOfString = System.Collections.Generic.List(System.String);
  1227. var list = new ListOfString();
  1228. list.Add('foo');
  1229. list.Add(1);
  1230. assert(2 === list.Count);
  1231. ");
  1232. }
  1233. [Fact]
  1234. public void EnumComparesByName()
  1235. {
  1236. var o = new
  1237. {
  1238. r = Colors.Red,
  1239. b = Colors.Blue,
  1240. g = Colors.Green,
  1241. b2 = Colors.Red
  1242. };
  1243. _engine.SetValue("o", o);
  1244. _engine.SetValue("assertFalse", new Action<bool>(Assert.False));
  1245. RunTest(@"
  1246. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1247. var colors = domain.Colors;
  1248. assert(o.r === colors.Red);
  1249. assert(o.g === colors.Green);
  1250. assert(o.b === colors.Blue);
  1251. assertFalse(o.b2 === colors.Blue);
  1252. ");
  1253. }
  1254. [Fact]
  1255. public void ShouldSetEnumProperty()
  1256. {
  1257. var s = new Circle
  1258. {
  1259. Color = Colors.Red
  1260. };
  1261. _engine.SetValue("s", s);
  1262. RunTest(@"
  1263. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1264. var colors = domain.Colors;
  1265. s.Color = colors.Blue;
  1266. assert(s.Color === colors.Blue);
  1267. ");
  1268. _engine.SetValue("s", s);
  1269. RunTest(@"
  1270. s.Color = colors.Blue | colors.Green;
  1271. assert(s.Color === colors.Blue | colors.Green);
  1272. ");
  1273. Assert.Equal(Colors.Blue | Colors.Green, s.Color);
  1274. }
  1275. private enum TestEnumInt32 : int
  1276. {
  1277. None,
  1278. One = 1,
  1279. Min = int.MaxValue,
  1280. Max = int.MaxValue
  1281. }
  1282. private enum TestEnumUInt32 : uint
  1283. {
  1284. None,
  1285. One = 1,
  1286. Min = uint.MaxValue,
  1287. Max = uint.MaxValue
  1288. }
  1289. private enum TestEnumInt64 : long
  1290. {
  1291. None,
  1292. One = 1,
  1293. Min = long.MaxValue,
  1294. Max = long.MaxValue
  1295. }
  1296. private enum TestEnumUInt64 : ulong
  1297. {
  1298. None,
  1299. One = 1,
  1300. Min = ulong.MaxValue,
  1301. Max = ulong.MaxValue
  1302. }
  1303. private void TestEnum<T>(T enumValue)
  1304. {
  1305. var i = Convert.ChangeType(enumValue, Enum.GetUnderlyingType(typeof(T)));
  1306. var s = Convert.ToString(i, CultureInfo.InvariantCulture);
  1307. var o = new Tuple<T>(enumValue);
  1308. _engine.SetValue("o", o);
  1309. RunTest("assert(o.Item1 === " + s + ");");
  1310. }
  1311. [Fact]
  1312. public void ShouldWorkWithEnumInt32()
  1313. {
  1314. TestEnum(TestEnumInt32.None);
  1315. TestEnum(TestEnumInt32.One);
  1316. TestEnum(TestEnumInt32.Min);
  1317. TestEnum(TestEnumInt32.Max);
  1318. }
  1319. [Fact]
  1320. public void ShouldWorkWithEnumUInt32()
  1321. {
  1322. TestEnum(TestEnumUInt32.None);
  1323. TestEnum(TestEnumUInt32.One);
  1324. TestEnum(TestEnumUInt32.Min);
  1325. TestEnum(TestEnumUInt32.Max);
  1326. }
  1327. [Fact]
  1328. public void ShouldWorkWithEnumInt64()
  1329. {
  1330. TestEnum(TestEnumInt64.None);
  1331. TestEnum(TestEnumInt64.One);
  1332. TestEnum(TestEnumInt64.Min);
  1333. TestEnum(TestEnumInt64.Max);
  1334. }
  1335. [Fact]
  1336. public void ShouldWorkWithEnumUInt64()
  1337. {
  1338. TestEnum(TestEnumUInt64.None);
  1339. TestEnum(TestEnumUInt64.One);
  1340. TestEnum(TestEnumUInt64.Min);
  1341. TestEnum(TestEnumUInt64.Max);
  1342. }
  1343. [Fact]
  1344. public void EnumIsConvertedToNumber()
  1345. {
  1346. var o = new
  1347. {
  1348. r = Colors.Red,
  1349. b = Colors.Blue,
  1350. g = Colors.Green
  1351. };
  1352. _engine.SetValue("o", o);
  1353. RunTest(@"
  1354. assert(o.r === 0);
  1355. assert(o.g === 1);
  1356. assert(o.b === 10);
  1357. ");
  1358. }
  1359. [Fact]
  1360. public void ShouldConvertToEnum()
  1361. {
  1362. var s = new Circle
  1363. {
  1364. Color = Colors.Red
  1365. };
  1366. _engine.SetValue("s", s);
  1367. RunTest(@"
  1368. assert(s.Color === 0);
  1369. s.Color = 10;
  1370. assert(s.Color === 10);
  1371. ");
  1372. _engine.SetValue("s", s);
  1373. RunTest(@"
  1374. s.Color = 11;
  1375. assert(s.Color === 11);
  1376. ");
  1377. Assert.Equal(Colors.Blue | Colors.Green, s.Color);
  1378. }
  1379. [Fact]
  1380. public void ShouldUseExplicitPropertyGetter()
  1381. {
  1382. _engine.SetValue("c", new Company("ACME"));
  1383. RunTest(@"
  1384. assert(c.Name === 'ACME');
  1385. ");
  1386. }
  1387. [Fact]
  1388. public void ShouldUseExplicitIndexerPropertyGetter()
  1389. {
  1390. var company = new Company("ACME");
  1391. ((ICompany) company)["Foo"] = "Bar";
  1392. _engine.SetValue("c", company);
  1393. RunTest(@"
  1394. assert(c.Foo === 'Bar');
  1395. ");
  1396. }
  1397. [Fact]
  1398. public void ShouldUseExplicitPropertySetter()
  1399. {
  1400. _engine.SetValue("c", new Company("ACME"));
  1401. RunTest(@"
  1402. c.Name = 'Foo';
  1403. assert(c.Name === 'Foo');
  1404. ");
  1405. }
  1406. [Fact]
  1407. public void ShouldUseExplicitIndexerPropertySetter()
  1408. {
  1409. var company = new Company("ACME");
  1410. ((ICompany) company)["Foo"] = "Bar";
  1411. _engine.SetValue("c", company);
  1412. RunTest(@"
  1413. c.Foo = 'Baz';
  1414. assert(c.Foo === 'Baz');
  1415. ");
  1416. }
  1417. [Fact]
  1418. public void ShouldUseExplicitMethod()
  1419. {
  1420. _engine.SetValue("c", new Company("ACME"));
  1421. RunTest(@"
  1422. assert(0 === c.CompareTo(c));
  1423. ");
  1424. }
  1425. [Fact]
  1426. public void ShouldCallInstanceMethodWithParams()
  1427. {
  1428. _engine.SetValue("a", new A());
  1429. RunTest(@"
  1430. assert(a.Call13('1','2','3') === '1,2,3');
  1431. assert(a.Call13('1') === '1');
  1432. assert(a.Call13(1) === '1');
  1433. assert(a.Call13() === '');
  1434. assert(a.Call14('a','1','2','3') === 'a:1,2,3');
  1435. assert(a.Call14('a','1') === 'a:1');
  1436. assert(a.Call14('a') === 'a:');
  1437. function call13wrapper(){ return a.Call13.apply(a, Array.prototype.slice.call(arguments)); }
  1438. assert(call13wrapper('1','2','3') === '1,2,3');
  1439. assert(a.Call13('1','2','3') === a.Call13(['1','2','3']));
  1440. ");
  1441. }
  1442. [Fact]
  1443. public void ShouldCallInstanceMethodWithJsValueParams()
  1444. {
  1445. _engine.SetValue("a", new A());
  1446. RunTest(@"
  1447. assert(a.Call16('1','2','3') === '1,2,3');
  1448. assert(a.Call16('1') === '1');
  1449. assert(a.Call16(1) === '1');
  1450. assert(a.Call16() === '');
  1451. assert(a.Call16('1','2','3') === a.Call16(['1','2','3']));
  1452. ");
  1453. }
  1454. [Fact]
  1455. public void NullValueAsArgumentShouldWork()
  1456. {
  1457. _engine.SetValue("a", new A());
  1458. RunTest(@"
  1459. var x = a.Call2(null);
  1460. assert(x === null);
  1461. ");
  1462. }
  1463. [Fact]
  1464. public void ShouldSetPropertyToNull()
  1465. {
  1466. var p = new Person { Name = "Mickey" };
  1467. _engine.SetValue("p", p);
  1468. RunTest(@"
  1469. assert(p.Name != null);
  1470. p.Name = null;
  1471. assert(p.Name == null);
  1472. ");
  1473. Assert.True(p.Name == null);
  1474. }
  1475. [Fact]
  1476. public void ShouldCallMethodWithNull()
  1477. {
  1478. _engine.SetValue("a", new A());
  1479. RunTest(@"
  1480. a.Call15(null);
  1481. var result = a.Call2(null);
  1482. assert(result == null);
  1483. ");
  1484. }
  1485. [Fact]
  1486. public void ShouldReturnUndefinedProperty()
  1487. {
  1488. _engine.SetValue("uo", new { foo = "bar" });
  1489. _engine.SetValue("ud", new Dictionary<string, object> { { "foo", "bar" } });
  1490. _engine.SetValue("ul", new List<string> { "foo", "bar" });
  1491. RunTest(@"
  1492. assert(!uo.undefinedProperty);
  1493. assert(!ul[5]);
  1494. assert(!ud.undefinedProperty);
  1495. ");
  1496. }
  1497. private class FailingObject2
  1498. {
  1499. public int this[int index] => throw new ArgumentException("index is bad", nameof(index));
  1500. }
  1501. [Fact]
  1502. public void ShouldPropagateIndexerExceptions()
  1503. {
  1504. var engine = new Engine();
  1505. engine.Execute(@"function f2(obj) { return obj[1]; }");
  1506. var failingObject = new FailingObject2();
  1507. Assert.Throws<ArgumentException>(() => engine.Invoke("f2", failingObject));
  1508. }
  1509. [Fact]
  1510. public void ShouldAutomaticallyConvertArraysToFindBestInteropResolution()
  1511. {
  1512. _engine.SetValue("a", new ArrayConverterTestClass());
  1513. _engine.SetValue("item1", new ArrayConverterItem(1));
  1514. _engine.SetValue("item2", new ArrayConverterItem(2));
  1515. RunTest(@"
  1516. assert(a.MethodAcceptsArrayOfInt([false, '1', 2]) === a.MethodAcceptsArrayOfInt([0, 1, 2]));
  1517. assert(a.MethodAcceptsArrayOfStrings(['1', 2]) === a.MethodAcceptsArrayOfStrings([1, 2]));
  1518. assert(a.MethodAcceptsArrayOfBool(['1', 0]) === a.MethodAcceptsArrayOfBool([true, false]));
  1519. assert(a.MethodAcceptsArrayOfStrings([item1, item2]) === a.MethodAcceptsArrayOfStrings(['1', '2']));
  1520. assert(a.MethodAcceptsArrayOfInt([item1, item2]) === a.MethodAcceptsArrayOfInt([1, 2]));
  1521. ");
  1522. }
  1523. [Fact]
  1524. public void ShouldImportNamespaceNestedType()
  1525. {
  1526. RunTest(@"
  1527. var shapes = importNamespace('Shapes.Circle');
  1528. var kinds = shapes.Kind;
  1529. assert(kinds.Unit === 0);
  1530. assert(kinds.Ellipse === 1);
  1531. assert(kinds.Round === 5);
  1532. ");
  1533. }
  1534. [Fact]
  1535. public void ShouldImportNamespaceNestedNestedType()
  1536. {
  1537. RunTest(@"
  1538. var meta = importNamespace('Shapes.Circle.Meta');
  1539. var usages = meta.Usage;
  1540. assert(usages.Public === 0);
  1541. assert(usages.Private === 1);
  1542. assert(usages.Internal === 11);
  1543. ");
  1544. }
  1545. [Fact]
  1546. public void ShouldGetNestedNestedProp()
  1547. {
  1548. RunTest(@"
  1549. var meta = importNamespace('Shapes.Circle');
  1550. var m = new meta.Meta();
  1551. assert(m.Description === 'descp');
  1552. ");
  1553. }
  1554. [Fact]
  1555. public void ShouldSetNestedNestedProp()
  1556. {
  1557. RunTest(@"
  1558. var meta = importNamespace('Shapes.Circle');
  1559. var m = new meta.Meta();
  1560. m.Description = 'hello';
  1561. assert(m.Description === 'hello');
  1562. ");
  1563. }
  1564. [Fact]
  1565. public void CanGetStaticNestedField()
  1566. {
  1567. RunTest(@"
  1568. var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
  1569. var statics = domain.ClassWithStaticFields;
  1570. assert(statics.Get == 'Get');
  1571. ");
  1572. }
  1573. [Fact]
  1574. public void CanSetStaticNestedField()
  1575. {
  1576. RunTest(@"
  1577. var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
  1578. var statics = domain.ClassWithStaticFields;
  1579. statics.Set = 'hello';
  1580. assert(statics.Set == 'hello');
  1581. ");
  1582. Assert.Equal(Nested.ClassWithStaticFields.Set, "hello");
  1583. }
  1584. [Fact]
  1585. public void CanGetStaticNestedAccessor()
  1586. {
  1587. RunTest(@"
  1588. var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
  1589. var statics = domain.ClassWithStaticFields;
  1590. assert(statics.Getter == 'Getter');
  1591. ");
  1592. }
  1593. [Fact]
  1594. public void CanSetStaticNestedAccessor()
  1595. {
  1596. RunTest(@"
  1597. var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
  1598. var statics = domain.ClassWithStaticFields;
  1599. statics.Setter = 'hello';
  1600. assert(statics.Setter == 'hello');
  1601. ");
  1602. Assert.Equal(Nested.ClassWithStaticFields.Setter, "hello");
  1603. }
  1604. [Fact]
  1605. public void CantSetStaticNestedReadonly()
  1606. {
  1607. RunTest(@"
  1608. var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
  1609. var statics = domain.ClassWithStaticFields;
  1610. statics.Readonly = 'hello';
  1611. assert(statics.Readonly == 'Readonly');
  1612. ");
  1613. Assert.Equal(Nested.ClassWithStaticFields.Readonly, "Readonly");
  1614. }
  1615. [Fact]
  1616. public void ShouldExecuteFunctionWithValueTypeParameterCorrectly()
  1617. {
  1618. _engine.SetValue("a", new A());
  1619. // Func<int, int>
  1620. RunTest(@"
  1621. assert(a.Call17(function(value){ return value; }) === 17);
  1622. ");
  1623. }
  1624. [Fact]
  1625. public void ShouldExecuteActionWithValueTypeParameterCorrectly()
  1626. {
  1627. _engine.SetValue("a", new A());
  1628. // Action<int>
  1629. RunTest(@"
  1630. a.Call18(function(value){ assert(value === 18); });
  1631. ");
  1632. }
  1633. [Fact]
  1634. public void ShouldConvertToJsValue()
  1635. {
  1636. RunTest(@"
  1637. var now = System.DateTime.Now;
  1638. assert(new String(now) == now.toString());
  1639. var zero = System.Int32.MaxValue;
  1640. assert(new String(zero) == zero.toString());
  1641. ");
  1642. }
  1643. [Fact]
  1644. public void ShouldNotCatchClrExceptions()
  1645. {
  1646. var engine = new Engine()
  1647. .SetValue("throwMyException", new Action(() => { throw new NotSupportedException(); }))
  1648. .SetValue("Thrower", typeof(Thrower))
  1649. .Execute(@"
  1650. function throwException1(){
  1651. try {
  1652. throwMyException();
  1653. return;
  1654. }
  1655. catch(e) {
  1656. return;
  1657. }
  1658. }
  1659. function throwException2(){
  1660. try {
  1661. new Thrower().ThrowNotSupportedException();
  1662. return;
  1663. }
  1664. catch(e) {
  1665. return;
  1666. }
  1667. }
  1668. ");
  1669. Assert.ThrowsAny<NotSupportedException>(() => engine.Invoke("throwException1"));
  1670. Assert.ThrowsAny<NotSupportedException>(() => engine.Invoke("throwException2"));
  1671. }
  1672. [Fact]
  1673. public void ShouldCatchAllClrExceptions()
  1674. {
  1675. var exceptionMessage = "myExceptionMessage";
  1676. var engine = new Engine(o => o.CatchClrExceptions())
  1677. .SetValue("throwMyException", new Action(() => { throw new Exception(exceptionMessage); }))
  1678. .SetValue("Thrower", typeof(Thrower))
  1679. .Execute(@"
  1680. function throwException1(){
  1681. try {
  1682. throwMyException();
  1683. return '';
  1684. }
  1685. catch(e) {
  1686. return e.message;
  1687. }
  1688. }
  1689. function throwException2(){
  1690. try {
  1691. new Thrower().ThrowExceptionWithMessage('myExceptionMessage');
  1692. return;
  1693. }
  1694. catch(e) {
  1695. return e.message;
  1696. }
  1697. }
  1698. ");
  1699. Assert.Equal(engine.Invoke("throwException1").AsString(), exceptionMessage);
  1700. Assert.Equal(engine.Invoke("throwException2").AsString(), exceptionMessage);
  1701. }
  1702. private class MemberExceptionTest
  1703. {
  1704. public MemberExceptionTest(bool throwOnCreate)
  1705. {
  1706. if (throwOnCreate)
  1707. {
  1708. throw new InvalidOperationException("thrown as requested");
  1709. }
  1710. }
  1711. public JsValue ThrowingProperty1
  1712. {
  1713. get => throw new InvalidOperationException();
  1714. set => throw new InvalidOperationException();
  1715. }
  1716. public object ThrowingProperty2
  1717. {
  1718. get => throw new InvalidOperationException();
  1719. set => throw new InvalidOperationException();
  1720. }
  1721. public void ThrowingFunction()
  1722. {
  1723. throw new InvalidOperationException();
  1724. }
  1725. }
  1726. [Fact]
  1727. public void ShouldCatchClrMemberExceptions()
  1728. {
  1729. var engine = new Engine(cfg =>
  1730. {
  1731. cfg.AllowClr();
  1732. cfg.CatchClrExceptions();
  1733. });
  1734. engine.SetValue("assert", new Action<bool>(Assert.True));
  1735. engine.SetValue("log", new Action<object>(Console.WriteLine));
  1736. engine.SetValue("create", typeof(MemberExceptionTest));
  1737. engine.SetValue("instance", new MemberExceptionTest(false));
  1738. // Test calling a constructor that throws an exception
  1739. engine.Execute(@"
  1740. try
  1741. {
  1742. create(true);
  1743. assert(false);
  1744. }
  1745. catch (e)
  1746. {
  1747. assert(true);
  1748. }
  1749. ");
  1750. // Test calling a member function that throws an exception
  1751. engine.Execute(@"
  1752. try
  1753. {
  1754. instance.ThrowingFunction();
  1755. assert(false);
  1756. }
  1757. catch (e)
  1758. {
  1759. assert(true);
  1760. }
  1761. ");
  1762. // Test using a property getter that throws an exception
  1763. engine.Execute(@"
  1764. try
  1765. {
  1766. log(o.ThrowingProperty);
  1767. assert(false);
  1768. }
  1769. catch (e)
  1770. {
  1771. assert(true);
  1772. }
  1773. ");
  1774. // Test using a property setter that throws an exception
  1775. engine.Execute(@"
  1776. try
  1777. {
  1778. instance.ThrowingProperty1 = 123;
  1779. assert(false);
  1780. }
  1781. catch (e)
  1782. {
  1783. assert(true);
  1784. }
  1785. try
  1786. {
  1787. instance.ThrowingProperty2 = 456;
  1788. assert(false);
  1789. }
  1790. catch (e)
  1791. {
  1792. assert(true);
  1793. }
  1794. ");
  1795. }
  1796. [Fact]
  1797. public void ShouldCatchSomeExceptions()
  1798. {
  1799. var exceptionMessage = "myExceptionMessage";
  1800. var engine = new Engine(o => o.CatchClrExceptions(e => e is NotSupportedException))
  1801. .SetValue("throwMyException1", new Action(() => { throw new NotSupportedException(exceptionMessage); }))
  1802. .SetValue("throwMyException2", new Action(() => { throw new ArgumentNullException(); }))
  1803. .SetValue("Thrower", typeof(Thrower))
  1804. .Execute(@"
  1805. function throwException1(){
  1806. try {
  1807. throwMyException1();
  1808. return '';
  1809. }
  1810. catch(e) {
  1811. return e.message;
  1812. }
  1813. }
  1814. function throwException2(){
  1815. try {
  1816. throwMyException2();
  1817. return '';
  1818. }
  1819. catch(e) {
  1820. return e.message;
  1821. }
  1822. }
  1823. function throwException3(){
  1824. try {
  1825. new Thrower().ThrowNotSupportedExceptionWithMessage('myExceptionMessage');
  1826. return '';
  1827. }
  1828. catch(e) {
  1829. return e.message;
  1830. }
  1831. }
  1832. function throwException4(){
  1833. try {
  1834. new Thrower().ThrowArgumentNullException();
  1835. return '';
  1836. }
  1837. catch(e) {
  1838. return e.message;
  1839. }
  1840. }
  1841. ");
  1842. Assert.Equal(engine.Invoke("throwException1").AsString(), exceptionMessage);
  1843. Assert.Throws<ArgumentNullException>(() => engine.Invoke("throwException2"));
  1844. Assert.Equal(engine.Invoke("throwException3").AsString(), exceptionMessage);
  1845. Assert.Throws<ArgumentNullException>(() => engine.Invoke("throwException4"));
  1846. }
  1847. [Fact]
  1848. public void ArrayFromShouldConvertListToArrayLike()
  1849. {
  1850. var list = new List<Person>
  1851. {
  1852. new Person { Name = "Mike" },
  1853. new Person { Name = "Mika" }
  1854. };
  1855. _engine.SetValue("a", list);
  1856. RunTest(@"
  1857. var arr = new Array(a);
  1858. assert(arr.length === 2);
  1859. assert(arr[0].Name === 'Mike');
  1860. assert(arr[1].Name === 'Mika');
  1861. ");
  1862. RunTest(@"
  1863. var arr = Array.from(a);
  1864. assert(arr.length === 2);
  1865. assert(arr[0].Name === 'Mike');
  1866. assert(arr[1].Name === 'Mika');
  1867. ");
  1868. }
  1869. [Fact]
  1870. public void ArrayFromShouldConvertArrayToArrayLike()
  1871. {
  1872. var list = new[]
  1873. {
  1874. new Person { Name = "Mike" },
  1875. new Person { Name = "Mika" }
  1876. };
  1877. _engine.SetValue("a", list);
  1878. RunTest(@"
  1879. var arr = new Array(a);
  1880. assert(arr.length === 2);
  1881. assert(arr[0].Name === 'Mike');
  1882. assert(arr[1].Name === 'Mika');
  1883. ");
  1884. RunTest(@"
  1885. var arr = Array.from(a);
  1886. assert(arr.length === 2);
  1887. assert(arr[0].Name === 'Mike');
  1888. assert(arr[1].Name === 'Mika');
  1889. ");
  1890. }
  1891. [Fact]
  1892. public void ArrayFromShouldConvertIEnumerable()
  1893. {
  1894. var enumerable = new[]
  1895. {
  1896. new Person { Name = "Mike" },
  1897. new Person { Name = "Mika" }
  1898. }.Select(x => x);
  1899. _engine.SetValue("a", enumerable);
  1900. RunTest(@"
  1901. var arr = new Array(a);
  1902. assert(arr.length === 2);
  1903. assert(arr[0].Name === 'Mike');
  1904. assert(arr[1].Name === 'Mika');
  1905. ");
  1906. RunTest(@"
  1907. var arr = Array.from(a);
  1908. assert(arr.length === 2);
  1909. assert(arr[0].Name === 'Mike');
  1910. assert(arr[1].Name === 'Mika');
  1911. ");
  1912. }
  1913. [Fact]
  1914. public void ShouldBeAbleToPlusAssignStringProperty()
  1915. {
  1916. var p = new Person();
  1917. var engine = new Engine();
  1918. engine.SetValue("P", p);
  1919. engine.Evaluate("P.Name = 'b';");
  1920. engine.Evaluate("P.Name += 'c';");
  1921. Assert.Equal("bc", p.Name);
  1922. }
  1923. [Fact]
  1924. public void ShouldNotResolveToPrimitiveSymbol()
  1925. {
  1926. var engine = new Engine(options =>
  1927. options.AllowClr(typeof(FloatIndexer).GetTypeInfo().Assembly));
  1928. var c = engine.Evaluate(@"
  1929. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1930. return new domain.FloatIndexer();
  1931. ");
  1932. Assert.NotNull(c.ToString());
  1933. Assert.Equal((uint) 0, c.As<ObjectInstance>().Length);
  1934. }
  1935. private class DictionaryWrapper
  1936. {
  1937. public IDictionary<string, object> Values { get; set; }
  1938. }
  1939. private class DictionaryTest
  1940. {
  1941. public void Test1(IDictionary<string, object> values)
  1942. {
  1943. Assert.Equal(1, Convert.ToInt32(values["a"]));
  1944. }
  1945. public void Test2(DictionaryWrapper dictionaryObject)
  1946. {
  1947. Assert.Equal(1, Convert.ToInt32(dictionaryObject.Values["a"]));
  1948. }
  1949. }
  1950. [Fact]
  1951. public void ShouldBeAbleToPassDictionaryToMethod()
  1952. {
  1953. var engine = new Engine();
  1954. engine.SetValue("dictionaryTest", new DictionaryTest());
  1955. engine.Evaluate("dictionaryTest.test1({ a: 1 });");
  1956. }
  1957. [Fact]
  1958. public void ShouldBeAbleToPassDictionaryInObjectToMethod()
  1959. {
  1960. var engine = new Engine();
  1961. engine.SetValue("dictionaryTest", new DictionaryTest());
  1962. engine.Evaluate("dictionaryTest.test2({ values: { a: 1 } });");
  1963. }
  1964. [Fact]
  1965. public void ShouldSupportSpreadForDictionary()
  1966. {
  1967. var engine = new Engine();
  1968. var state = new Dictionary<string, object>
  1969. {
  1970. { "invoice", new Dictionary<string, object> { ["number"] = "42" } }
  1971. };
  1972. engine.SetValue("state", state);
  1973. var result = (IDictionary<string, object>) engine
  1974. .Evaluate("({ supplier: 'S1', ...state.invoice })")
  1975. .ToObject();
  1976. Assert.Equal("S1", result["supplier"]);
  1977. Assert.Equal("42", result["number"]);
  1978. }
  1979. [Fact]
  1980. public void ShouldSupportSpreadForDictionary2()
  1981. {
  1982. var engine = new Engine();
  1983. var state = new Dictionary<string, object>
  1984. {
  1985. { "invoice", new Dictionary<string, object> { ["number"] = "42" } }
  1986. };
  1987. engine.SetValue("state", state);
  1988. var result = (IDictionary<string, object>) engine
  1989. .Execute("function getValue() { return {supplier: 'S1', ...state.invoice}; }")
  1990. .Invoke("getValue")
  1991. .ToObject();
  1992. Assert.Equal("S1", result["supplier"]);
  1993. Assert.Equal("42", result["number"]);
  1994. }
  1995. [Fact]
  1996. public void ShouldSupportSpreadForObject()
  1997. {
  1998. var engine = new Engine();
  1999. var person = new Person
  2000. {
  2001. Name = "Mike",
  2002. Age = 20
  2003. };
  2004. engine.SetValue("p", person);
  2005. var result = (IDictionary<string, object>) engine
  2006. .Evaluate("({ supplier: 'S1', ...p })")
  2007. .ToObject();
  2008. Assert.Equal("S1", result["supplier"]);
  2009. Assert.Equal("Mike", result["Name"]);
  2010. Assert.Equal(20d, result["Age"]);
  2011. }
  2012. [Fact]
  2013. public void ShouldBeAbleToJsonStringifyClrObjects()
  2014. {
  2015. var engine = new Engine();
  2016. engine.Evaluate("var jsObj = { 'key1' :'value1', 'key2' : 'value2' }");
  2017. engine.SetValue("netObj", new Dictionary<string, object>
  2018. {
  2019. { "key1", "value1" },
  2020. { "key2", "value2" }
  2021. });
  2022. var jsValue = engine.Evaluate("jsObj['key1']").AsString();
  2023. var clrValue = engine.Evaluate("netObj['key1']").AsString();
  2024. Assert.Equal(jsValue, clrValue);
  2025. jsValue = engine.Evaluate("JSON.stringify(jsObj)").AsString();
  2026. clrValue = engine.Evaluate("JSON.stringify(netObj)").AsString();
  2027. Assert.Equal(jsValue, clrValue);
  2028. // Write properties on screen using showProps function defined on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
  2029. engine.Execute(@"function showProps(obj, objName) {
  2030. var result = """";
  2031. for (var i in obj) {
  2032. if (obj.hasOwnProperty(i)) {
  2033. result += objName + ""."" + i + "" = "" + obj[i] + ""\n"";
  2034. }
  2035. }
  2036. return result;
  2037. }");
  2038. jsValue = engine.Evaluate("showProps(jsObj, 'theObject')").AsString();
  2039. clrValue = engine.Evaluate("showProps(jsObj, 'theObject')").AsString();
  2040. Assert.Equal(jsValue, clrValue);
  2041. }
  2042. [Fact]
  2043. public void SettingValueViaIntegerIndexer()
  2044. {
  2045. var engine = new Engine(cfg => cfg.AllowClr(typeof(FloatIndexer).GetTypeInfo().Assembly));
  2046. engine.SetValue("log", new Action<object>(Console.WriteLine));
  2047. engine.Execute(@"
  2048. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  2049. var fia = new domain.IntegerIndexer();
  2050. log(fia[0]);
  2051. ");
  2052. Assert.Equal(123, engine.Evaluate("fia[0]").AsNumber());
  2053. engine.Evaluate("fia[0] = 678;");
  2054. Assert.Equal(678, engine.Evaluate("fia[0]").AsNumber());
  2055. }
  2056. [Fact]
  2057. public void IndexingBsonProperties()
  2058. {
  2059. const string jsonAnimals = @" { ""Animals"": [ { ""Id"": 1, ""Type"": ""Cat"" } ] }";
  2060. var bsonAnimals = BsonDocument.Parse(jsonAnimals);
  2061. _engine.SetValue("animals", bsonAnimals["Animals"]);
  2062. // weak equality does conversions from native types
  2063. Assert.True(_engine.Evaluate("animals[0].Type == 'Cat'").AsBoolean());
  2064. Assert.True(_engine.Evaluate("animals[0].Id == 1").AsBoolean());
  2065. }
  2066. [Fact]
  2067. public void IntegerAndFloatInFunctionOverloads()
  2068. {
  2069. var engine = new Engine(options => options.AllowClr(GetType().Assembly));
  2070. engine.SetValue("a", new OverLoading());
  2071. Assert.Equal("int-val", engine.Evaluate("a.testFunc(123);").AsString());
  2072. Assert.Equal("float-val", engine.Evaluate("a.testFunc(12.3);").AsString());
  2073. }
  2074. [Fact]
  2075. public void TypeConversionWithTemporaryInvalidValuesShouldNotCache()
  2076. {
  2077. var engine = new Engine(options => options.AllowClr());
  2078. engine.SetValue("IntValueInput", TypeReference.CreateTypeReference(engine, typeof(IntValueInput)));
  2079. var ex = Assert.Throws<JavaScriptException>(() => engine.Evaluate("new IntValueInput().testFunc(NaN);").AsString());
  2080. Assert.Equal("No public methods with the specified arguments were found.", ex.Message);
  2081. Assert.Equal(123, engine.Evaluate("new IntValueInput().testFunc(123);").AsNumber());
  2082. }
  2083. [Fact]
  2084. public void CanConvertFloatingPointToIntegerWithoutError()
  2085. {
  2086. var engine = new Engine(options => options.AllowClr());
  2087. engine.SetValue("IntValueInput", TypeReference.CreateTypeReference(engine, typeof(IntValueInput)));
  2088. Assert.Equal(12, engine.Evaluate("new IntValueInput().testFunc(12.3);").AsNumber());
  2089. }
  2090. public class IntValueInput
  2091. {
  2092. public int TestFunc(int value) => value;
  2093. }
  2094. public class TestItem
  2095. {
  2096. public double Cost { get; set; }
  2097. public double Age { get; set; }
  2098. public string Name { get; set; }
  2099. }
  2100. public class TestItemList : List<TestItem>
  2101. {
  2102. public double Sum(Func<TestItem, double> calc)
  2103. {
  2104. double rc = 0;
  2105. foreach (var item in this)
  2106. {
  2107. rc += calc(item);
  2108. }
  2109. return rc;
  2110. }
  2111. public TestItemList Where(Func<TestItem, bool> cond)
  2112. {
  2113. var rc = new TestItemList();
  2114. foreach (var item in this)
  2115. {
  2116. if (cond(item))
  2117. {
  2118. rc.Add(item);
  2119. }
  2120. }
  2121. return rc;
  2122. }
  2123. }
  2124. [Fact]
  2125. public void DelegateCanReturnValue()
  2126. {
  2127. var engine = new Engine(options => options.AllowClr(GetType().Assembly));
  2128. var lst = new TestItemList();
  2129. lst.Add(new TestItem() { Name = "a", Cost = 1, Age = 10 });
  2130. lst.Add(new TestItem() { Name = "a", Cost = 1, Age = 10 });
  2131. lst.Add(new TestItem() { Name = "b", Cost = 1, Age = 10 });
  2132. lst.Add(new TestItem() { Name = "b", Cost = 1, Age = 10 });
  2133. lst.Add(new TestItem() { Name = "b", Cost = 1, Age = 10 });
  2134. engine.SetValue("lst", lst);
  2135. Assert.Equal(5, engine.Evaluate("lst.Sum(x => x.Cost);").AsNumber());
  2136. Assert.Equal(50, engine.Evaluate("lst.Sum(x => x.Age);").AsNumber());
  2137. Assert.Equal(3, engine.Evaluate("lst.Where(x => x.Name == 'b').Count;").AsNumber());
  2138. Assert.Equal(30, engine.Evaluate("lst.Where(x => x.Name == 'b').Sum(x => x.Age);").AsNumber());
  2139. }
  2140. [Fact]
  2141. public void ObjectWrapperOverridingEquality()
  2142. {
  2143. // equality same via name
  2144. _engine.SetValue("a", new Person { Name = "Name" });
  2145. _engine.SetValue("b", new Person { Name = "Name" });
  2146. _engine.Evaluate("const arr = [ null, a, undefined ];");
  2147. Assert.Equal(1, _engine.Evaluate("arr.filter(x => x == b).length").AsNumber());
  2148. Assert.Equal(1, _engine.Evaluate("arr.filter(x => x === b).length").AsNumber());
  2149. Assert.True(_engine.Evaluate("arr.find(x => x == b) === a").AsBoolean());
  2150. Assert.True(_engine.Evaluate("arr.find(x => x === b) == a").AsBoolean());
  2151. Assert.Equal(1, _engine.Evaluate("arr.findIndex(x => x == b)").AsNumber());
  2152. Assert.Equal(1, _engine.Evaluate("arr.findIndex(x => x === b)").AsNumber());
  2153. Assert.Equal(1, _engine.Evaluate("arr.indexOf(b)").AsNumber());
  2154. Assert.True(_engine.Evaluate("arr.includes(b)").AsBoolean());
  2155. }
  2156. [Fact]
  2157. public void ObjectWrapperWrappingDictionaryShouldNotBeArrayLike()
  2158. {
  2159. var wrapper = new ObjectWrapper(_engine, new Dictionary<string, object>());
  2160. Assert.False(wrapper.IsArrayLike);
  2161. }
  2162. [Fact]
  2163. public void ShouldHandleCyclicReferences()
  2164. {
  2165. var engine = new Engine();
  2166. static void Test(string message, object value)
  2167. {
  2168. Console.WriteLine(message);
  2169. }
  2170. engine.Realm.GlobalObject.FastSetDataProperty("global", engine.Realm.GlobalObject);
  2171. engine.Realm.GlobalObject.FastSetDataProperty("test", new DelegateWrapper(engine, (Action<string, object>) Test));
  2172. {
  2173. var ex = Assert.Throws<JavaScriptException>(() => engine.Realm.GlobalObject.ToObject());
  2174. Assert.Equal("Cyclic reference detected.", ex.Message);
  2175. }
  2176. {
  2177. var ex = Assert.Throws<JavaScriptException>(() =>
  2178. engine.Execute(@"
  2179. var demo={};
  2180. demo.value=1;
  2181. test('Test 1', demo.value===1);
  2182. test('Test 2', demo.value);
  2183. demo.demo=demo;
  2184. test('Test 3', demo);
  2185. test('Test 4', global);"
  2186. )
  2187. );
  2188. Assert.Equal("Cyclic reference detected.", ex.Message);
  2189. }
  2190. }
  2191. [Fact]
  2192. public void CanConfigurePropertyNameMatcher()
  2193. {
  2194. // defaults
  2195. var e = new Engine();
  2196. e.SetValue("a", new A());
  2197. Assert.True(e.Evaluate("a.call1").IsObject());
  2198. Assert.True(e.Evaluate("a.Call1").IsObject());
  2199. Assert.True(e.Evaluate("a.CALL1").IsUndefined());
  2200. e = new Engine(options =>
  2201. {
  2202. options.SetTypeResolver(new TypeResolver
  2203. {
  2204. MemberNameComparer = StringComparer.Ordinal
  2205. });
  2206. });
  2207. e.SetValue("a", new A());
  2208. Assert.True(e.Evaluate("a.call1").IsUndefined());
  2209. Assert.True(e.Evaluate("a.Call1").IsObject());
  2210. Assert.True(e.Evaluate("a.CALL1").IsUndefined());
  2211. e = new Engine(options =>
  2212. {
  2213. options.SetTypeResolver(new TypeResolver
  2214. {
  2215. MemberNameComparer = StringComparer.OrdinalIgnoreCase
  2216. });
  2217. });
  2218. e.SetValue("a", new A());
  2219. Assert.True(e.Evaluate("a.call1").IsObject());
  2220. Assert.True(e.Evaluate("a.Call1").IsObject());
  2221. Assert.True(e.Evaluate("a.CALL1").IsObject());
  2222. }
  2223. [Fact]
  2224. public void ShouldNotEnumerateClassMethods()
  2225. {
  2226. var engine = new Engine();
  2227. var dictionary = new Dictionary<string, object>
  2228. {
  2229. { "foo", 5 },
  2230. { "bar", "A string" }
  2231. };
  2232. engine.SetValue("dictionary", dictionary);
  2233. var result = engine.Evaluate($"Object.keys(dictionary).join(',')").AsString();
  2234. Assert.Equal("foo,bar", result);
  2235. engine.Execute("dictionary.ContainsKey('foo')");
  2236. result = engine.Evaluate($"Object.keys(dictionary).join(',')").AsString();
  2237. Assert.Equal("foo,bar", result);
  2238. }
  2239. [Fact]
  2240. public void ShouldNotEnumerateExtensionMethods()
  2241. {
  2242. var engine = new Engine(cfg => cfg.AddExtensionMethods(typeof(Enumerable)));
  2243. var result = engine.Evaluate("Object.keys({ ...[1,2,3] }).join(',')").AsString();
  2244. Assert.Equal("0,1,2", result);
  2245. var script = @"
  2246. var arr = [1,2,3];
  2247. var keys = [];
  2248. for(var index in arr) keys.push(index);
  2249. keys.join(',');
  2250. ";
  2251. result = engine.Evaluate(script).ToString();
  2252. Assert.Equal("0,1,2", result);
  2253. }
  2254. [Fact]
  2255. public void CanCheckIfCallable()
  2256. {
  2257. var engine = new Engine();
  2258. engine.Evaluate("var f = () => true;");
  2259. var result = engine.GetValue("f");
  2260. Assert.True(result.IsCallable);
  2261. Assert.True(result.Call(Array.Empty<JsValue>()).AsBoolean());
  2262. Assert.True(result.Call().AsBoolean());
  2263. }
  2264. [Fact]
  2265. public void CanGiveCustomNameToInteropMembers()
  2266. {
  2267. static IEnumerable<string> MemberNameCreator(MemberInfo prop)
  2268. {
  2269. var attributes = prop.GetCustomAttributes(typeof(CustomNameAttribute), true);
  2270. if (attributes.Length > 0)
  2271. {
  2272. foreach (CustomNameAttribute attribute in attributes)
  2273. {
  2274. yield return attribute.Name;
  2275. }
  2276. }
  2277. else
  2278. {
  2279. yield return prop.Name;
  2280. }
  2281. }
  2282. var customTypeResolver = new TypeResolver
  2283. {
  2284. MemberNameCreator = MemberNameCreator
  2285. };
  2286. var engine = new Engine(options =>
  2287. {
  2288. options.SetTypeResolver(customTypeResolver);
  2289. options.AddExtensionMethods(typeof(CustomNamedExtensions));
  2290. });
  2291. engine.SetValue("o", new CustomNamed());
  2292. Assert.Equal("StringField", engine.Evaluate("o.jsStringField").AsString());
  2293. Assert.Equal("StringField", engine.Evaluate("o.jsStringField2").AsString());
  2294. Assert.Equal("StaticStringField", engine.Evaluate("o.jsStaticStringField").AsString());
  2295. Assert.Equal("StringProperty", engine.Evaluate("o.jsStringProperty").AsString());
  2296. Assert.Equal("Method", engine.Evaluate("o.jsMethod()").AsString());
  2297. Assert.Equal("StaticMethod", engine.Evaluate("o.jsStaticMethod()").AsString());
  2298. Assert.Equal("InterfaceStringProperty", engine.Evaluate("o.jsInterfaceStringProperty").AsString());
  2299. Assert.Equal("InterfaceMethod", engine.Evaluate("o.jsInterfaceMethod()").AsString());
  2300. Assert.Equal("ExtensionMethod", engine.Evaluate("o.jsExtensionMethod()").AsString());
  2301. engine.SetValue("XmlHttpRequest", typeof(CustomNamedEnum));
  2302. engine.Evaluate("o.jsEnumProperty = XmlHttpRequest.HEADERS_RECEIVED;");
  2303. Assert.Equal((int) CustomNamedEnum.HeadersReceived, engine.Evaluate("o.jsEnumProperty").AsNumber());
  2304. }
  2305. [Fact]
  2306. public void ShouldBeAbleToHandleInvalidClrConversionViaCatchClrExceptions()
  2307. {
  2308. var engine = new Engine(cfg => cfg.CatchClrExceptions());
  2309. engine.SetValue("a", new Person());
  2310. var ex = Assert.Throws<JavaScriptException>(() => engine.Execute("a.age = \"It won't work, but it's normal\""));
  2311. Assert.Equal("Input string was not in a correct format.", ex.Message);
  2312. }
  2313. [Fact]
  2314. public void ShouldLetNotSupportedExceptionBubble()
  2315. {
  2316. _engine.SetValue("profile", new Profile());
  2317. var ex = Assert.Throws<NotSupportedException>(() => _engine.Evaluate("profile.AnyProperty"));
  2318. Assert.Equal("NOT SUPPORTED", ex.Message);
  2319. }
  2320. [Fact]
  2321. public void ShouldBeAbleToUseConvertibleStructAsMethodParameter()
  2322. {
  2323. _engine.SetValue("test", new DiscordTestClass());
  2324. _engine.SetValue("id", new DiscordId("12345"));
  2325. Assert.Equal("12345", _engine.Evaluate("String(id)").AsString());
  2326. Assert.Equal("12345", _engine.Evaluate("test.echo('12345')").AsString());
  2327. Assert.Equal("12345", _engine.Evaluate("test.create(12345)").AsString());
  2328. }
  2329. [Fact]
  2330. public void ShouldGetIteratorForListAndDictionary()
  2331. {
  2332. const string Script = @"
  2333. var it = collection[Symbol.iterator]();
  2334. var result = it.next();
  2335. var str = """";
  2336. while (!result.done) {
  2337. str += result.value;
  2338. result = it.next();
  2339. }
  2340. return str;";
  2341. _engine.SetValue("collection", new List<string> { "a", "b", "c" });
  2342. Assert.Equal("abc", _engine.Evaluate(Script));
  2343. _engine.SetValue("collection", new Dictionary<string, object> { { "a", 1 }, { "b", 2 }, { "c", 3 } });
  2344. Assert.Equal("a,1b,2c,3", _engine.Evaluate(Script));
  2345. }
  2346. [Fact]
  2347. public void ShouldNotIntroduceNewPropertiesWhenTraversing()
  2348. {
  2349. _engine.SetValue("x", new Dictionary<string, int> { { "First", 1 }, { "Second", 2 } });
  2350. Assert.Equal("[\"First\",\"Second\"]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));
  2351. Assert.Equal("x['First']: 1", _engine.Evaluate("\"x['First']: \" + x['First']"));
  2352. Assert.Equal("[\"First\",\"Second\"]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));
  2353. Assert.Equal("x['Third']: undefined", _engine.Evaluate("\"x['Third']: \" + x['Third']"));
  2354. Assert.Equal("[\"First\",\"Second\"]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));
  2355. Assert.Equal(JsValue.Undefined, _engine.Evaluate("x.length"));
  2356. Assert.Equal("[\"First\",\"Second\"]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));
  2357. Assert.Equal(2, _engine.Evaluate("x.Count").AsNumber());
  2358. Assert.Equal("[\"First\",\"Second\"]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));
  2359. _engine.Evaluate("x.Clear();");
  2360. Assert.Equal("[]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));
  2361. _engine.Evaluate("x['Fourth'] = 4;");
  2362. Assert.Equal("[\"Fourth\"]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));
  2363. Assert.False(_engine.Evaluate("Object.prototype.hasOwnProperty.call(x, 'Third')").AsBoolean());
  2364. }
  2365. [Fact]
  2366. public void CanConfigureCustomObjectTypeForJsToClrConversion()
  2367. {
  2368. var engine = new Engine(options =>
  2369. {
  2370. options.Interop.CreateClrObject = oi => new Dictionary<string, object>((int) oi.Length);
  2371. });
  2372. object capture = null;
  2373. var callback = (object value) => capture = value;
  2374. engine.SetValue("callback", callback);
  2375. engine.Evaluate("callback(({'a': 'b'}));");
  2376. Assert.IsType<Dictionary<string, object>>(capture);
  2377. var dictionary = (Dictionary<string, object>) capture;
  2378. Assert.Equal("b", dictionary["a"]);
  2379. }
  2380. [Fact]
  2381. public void ArrayPrototypeIndexOfWithInteropList()
  2382. {
  2383. var engine = new Jint.Engine();
  2384. engine.SetValue("list", new List<string> { "A", "B", "C" });
  2385. Assert.Equal(1, engine.Evaluate("list.indexOf('B')"));
  2386. Assert.Equal(1, engine.Evaluate("list.lastIndexOf('B')"));
  2387. Assert.Equal(1, engine.Evaluate("Array.prototype.indexOf.call(list, 'B')"));
  2388. Assert.Equal(1, engine.Evaluate("Array.prototype.lastIndexOf.call(list, 'B')"));
  2389. }
  2390. [Fact]
  2391. public void ShouldBeJavaScriptException()
  2392. {
  2393. var engine = new Engine(cfg => cfg.AllowClr().AllowOperatorOverloading().CatchClrExceptions());
  2394. engine.SetValue("Dimensional", typeof(Dimensional));
  2395. engine.Execute(@"
  2396. function Eval(param0, param1)
  2397. {
  2398. var result = param0 + param1;
  2399. return result;
  2400. }");
  2401. // checking working custom type
  2402. Assert.Equal(new Dimensional("kg", 90), (new Dimensional("kg", 30) + new Dimensional("kg", 60)));
  2403. Assert.Equal(new Dimensional("kg", 90), engine.Invoke("Eval", new object[] { new Dimensional("kg", 30), new Dimensional("kg", 60) }).ToObject());
  2404. Assert.Throws<InvalidOperationException>(() => new Dimensional("kg", 30) + new Dimensional("piece", 70));
  2405. // checking throwing exception in override operator
  2406. string errorMsg = string.Empty;
  2407. errorMsg = Assert.Throws<JavaScriptException>(() => engine.Invoke("Eval", new object[] { new Dimensional("kg", 30), new Dimensional("piece", 70) })).Message;
  2408. Assert.Equal("Dimensionals with different measure types are non-summable", errorMsg);
  2409. }
  2410. private class Profile
  2411. {
  2412. public int AnyProperty => throw new NotSupportedException("NOT SUPPORTED");
  2413. }
  2414. [Fact]
  2415. public void GenericParameterResolutionShouldWorkWithNulls()
  2416. {
  2417. var result = new Engine()
  2418. .SetValue("JintCommon", new JintCommon())
  2419. .Evaluate("JintCommon.sum(1, null)")
  2420. .AsNumber();
  2421. Assert.Equal(2, result);
  2422. }
  2423. public class JintCommon
  2424. {
  2425. public int Sum(int a, int? b) => a + b.GetValueOrDefault(1);
  2426. }
  2427. private delegate void ParamsTestDelegate(params Action[] callbacks);
  2428. [Fact]
  2429. public void CanUseParamsActions()
  2430. {
  2431. var engine = new Engine();
  2432. engine.SetValue("print", new Action<string>(_ => { }));
  2433. engine.SetValue("callAll", new DelegateWrapper(engine, new ParamsTestDelegate(ParamsTest)));
  2434. engine.Execute(@"
  2435. callAll(
  2436. function() { print('a'); },
  2437. function() { print('b'); },
  2438. function() { print('c'); }
  2439. );
  2440. ");
  2441. }
  2442. private static void ParamsTest(params Action[] callbacks)
  2443. {
  2444. foreach (var callback in callbacks)
  2445. {
  2446. callback.Invoke();
  2447. }
  2448. }
  2449. [Fact]
  2450. public void ObjectWrapperIdentityIsMaintained()
  2451. {
  2452. // run in separate method so stack won't keep reference
  2453. var reference = RunWeakReferenceTest();
  2454. GC.Collect();
  2455. // make sure no dangling reference is left
  2456. Assert.False(reference.IsAlive);
  2457. }
  2458. [MethodImpl(MethodImplOptions.NoInlining)]
  2459. private static WeakReference RunWeakReferenceTest()
  2460. {
  2461. var o = new object();
  2462. var engine = new Engine()
  2463. .SetValue("o", o);
  2464. var wrapper1 = (ObjectWrapper) engine.GetValue("o");
  2465. var reference = new WeakReference(wrapper1);
  2466. Assert.Same(wrapper1, engine.GetValue("o"));
  2467. Assert.Same(o, wrapper1.Target);
  2468. // reset
  2469. engine.Realm.GlobalObject.RemoveOwnProperty("o");
  2470. return reference;
  2471. }
  2472. [Fact]
  2473. public void CanUseClrFunction()
  2474. {
  2475. var engine = new Engine();
  2476. engine.SetValue("fn", new ClrFunctionInstance(engine, "fn", (_, args) => (JsValue) (args[0].AsInteger() + 1)));
  2477. var result = engine.Evaluate("fn(1)");
  2478. Assert.Equal(2, result);
  2479. }
  2480. [Fact]
  2481. public void ShouldAllowClrExceptionsThrough()
  2482. {
  2483. var engine = new Engine(opts => opts.CatchClrExceptions(exc => false));
  2484. engine.SetValue("fn", new ClrFunctionInstance(engine, "fn", (_, _) => throw new InvalidOperationException("This is a C# error")));
  2485. const string Source = @"
  2486. function wrap() {
  2487. fn();
  2488. }
  2489. wrap();
  2490. ";
  2491. Assert.Throws<InvalidOperationException>(() => engine.Execute(Source));
  2492. }
  2493. [Fact]
  2494. public void ShouldConvertClrExceptionsToErrors()
  2495. {
  2496. var engine = new Engine(opts => opts.CatchClrExceptions(exc => exc is InvalidOperationException));
  2497. engine.SetValue("fn", new ClrFunctionInstance(engine, "fn", (_, _) => throw new InvalidOperationException("This is a C# error")));
  2498. const string Source = @"
  2499. function wrap() {
  2500. fn();
  2501. }
  2502. wrap();
  2503. ";
  2504. var exc = Assert.Throws<JavaScriptException>(() => engine.Execute(Source));
  2505. Assert.Equal(exc.Message, "This is a C# error");
  2506. }
  2507. [Fact]
  2508. public void ShouldAllowCatchingConvertedClrExceptions()
  2509. {
  2510. var engine = new Engine(opts => opts.CatchClrExceptions(exc => exc is InvalidOperationException));
  2511. engine.SetValue("fn", new ClrFunctionInstance(engine, "fn", (_, _) => throw new InvalidOperationException("This is a C# error")));
  2512. const string Source = @"
  2513. try {
  2514. fn();
  2515. } catch (e) {
  2516. throw new Error('Caught: ' + e.message);
  2517. }
  2518. ";
  2519. var exc = Assert.Throws<JavaScriptException>(() => engine.Execute(Source));
  2520. Assert.Equal(exc.Message, "Caught: This is a C# error");
  2521. }
  2522. class Baz
  2523. {
  2524. public int DisposeCalls { get; private set; }
  2525. public IEnumerable<int> Enumerator
  2526. {
  2527. get
  2528. {
  2529. try
  2530. {
  2531. for (int i = 0; i < 10; i++) yield return i;
  2532. }
  2533. finally // finally clause is translated into IDisposable.Dispose in underlying IEnumerator
  2534. {
  2535. ++DisposeCalls;
  2536. }
  2537. }
  2538. }
  2539. }
  2540. [Fact]
  2541. public void ShouldCallEnumeratorDisposeOnNormalTermination()
  2542. {
  2543. var engine = new Engine();
  2544. var baz = new Baz();
  2545. engine.SetValue("baz", baz);
  2546. const string Source = @"
  2547. for (let i of baz.Enumerator) {
  2548. }";
  2549. engine.Execute(Source);
  2550. Assert.Equal(1, baz.DisposeCalls);
  2551. }
  2552. [Fact]
  2553. public void ShouldCallEnumeratorDisposeOnBreak()
  2554. {
  2555. var engine = new Engine();
  2556. var baz = new Baz();
  2557. engine.SetValue("baz", baz);
  2558. const string Source = @"
  2559. for (let i of baz.Enumerator) {
  2560. if (i == 2) break;
  2561. }";
  2562. engine.Execute(Source);
  2563. Assert.Equal(1, baz.DisposeCalls);
  2564. }
  2565. [Fact]
  2566. public void ShouldCallEnumeratorDisposeOnException()
  2567. {
  2568. var engine = new Engine();
  2569. var baz = new Baz();
  2570. engine.SetValue("baz", baz);
  2571. const string Source = @"
  2572. try {
  2573. for (let i of baz.Enumerator) {
  2574. if (i == 2) throw 'exception';
  2575. }
  2576. } catch (e) {
  2577. }";
  2578. engine.Execute(Source);
  2579. Assert.Equal(1, baz.DisposeCalls);
  2580. }
  2581. public class PropertyTestClass
  2582. {
  2583. public object Value;
  2584. }
  2585. [Fact]
  2586. public void PropertiesOfJsObjectPassedToClrShouldBeReadable()
  2587. {
  2588. _engine.SetValue("MyClass", typeof(PropertyTestClass));
  2589. RunTest(@"
  2590. var obj = new MyClass();
  2591. obj.Value = { foo: 'bar' };
  2592. equal('bar', obj.Value.foo);
  2593. ");
  2594. }
  2595. [Fact]
  2596. public void ShouldBeAbleToDeleteDictionaryEntries()
  2597. {
  2598. var engine = new Engine(options => options.Strict());
  2599. var dictionary = new Dictionary<string, int>
  2600. {
  2601. { "a", 1 },
  2602. { "b", 2 }
  2603. };
  2604. engine.SetValue("data", dictionary);
  2605. Assert.True(engine.Evaluate("Object.hasOwn(data, 'a')").AsBoolean());
  2606. Assert.True(engine.Evaluate("data['a'] === 1").AsBoolean());
  2607. engine.Evaluate("data['a'] = 42");
  2608. Assert.True(engine.Evaluate("data['a'] === 42").AsBoolean());
  2609. Assert.Equal(42, dictionary["a"]);
  2610. engine.Execute("delete data['a'];");
  2611. Assert.False(engine.Evaluate("Object.hasOwn(data, 'a')").AsBoolean());
  2612. Assert.False(engine.Evaluate("data['a'] === 42").AsBoolean());
  2613. Assert.False(dictionary.ContainsKey("a"));
  2614. var engineNoWrite = new Engine(options => options.Strict().AllowClrWrite(false));
  2615. dictionary = new Dictionary<string, int>
  2616. {
  2617. { "a", 1 },
  2618. { "b", 2 }
  2619. };
  2620. engineNoWrite.SetValue("data", dictionary);
  2621. var ex1 = Assert.Throws<JavaScriptException>(() => engineNoWrite.Evaluate("data['a'] = 42"));
  2622. Assert.Equal("Cannot assign to read only property 'a' of System.Collections.Generic.Dictionary`2[System.String,System.Int32]", ex1.Message);
  2623. // no changes
  2624. Assert.True(engineNoWrite.Evaluate("data['a'] === 1").AsBoolean());
  2625. var ex2 = Assert.Throws<JavaScriptException>(() => engineNoWrite.Execute("delete data['a'];"));
  2626. Assert.Equal("Cannot delete property 'a' of System.Collections.Generic.Dictionary`2[System.String,System.Int32]", ex2.Message);
  2627. }
  2628. public record RecordTestClass(object Value = null);
  2629. public class RecordTestClassContext
  2630. {
  2631. public object Method(RecordTestClass recordTest)
  2632. {
  2633. return recordTest.Value;
  2634. }
  2635. }
  2636. private class ClassWithIndexerAndProperty
  2637. {
  2638. public string MyProp { get; } = "from property";
  2639. public string this[string name] => name != nameof(MyProp) ? "from indexer" : null;
  2640. }
  2641. [Fact]
  2642. public void CanToStringObjectWithoutToPrimitiveSymbol()
  2643. {
  2644. var engine = new Engine();
  2645. engine.SetValue("obj", new ClassWithIndexerAndProperty());
  2646. Assert.Equal("Jint.Tests.Runtime.InteropTests+ClassWithIndexerAndProperty", engine.Evaluate("obj + ''").AsString());
  2647. engine.SetValue("obj", new Company("name"));
  2648. Assert.Equal("Jint.Tests.Runtime.Domain.Company", engine.Evaluate("obj + ''").AsString());
  2649. }
  2650. [Fact]
  2651. public void CanConstructOptionalRecordClass()
  2652. {
  2653. _engine.SetValue("Context", new RecordTestClassContext());
  2654. Assert.Equal(null, _engine.Evaluate("Context.method({});").ToObject());
  2655. Assert.Equal(5, _engine.Evaluate("Context.method({ value: 5 });").AsInteger());
  2656. }
  2657. [Fact]
  2658. public void CanPassDateTimeMinAndMaxViaInterop()
  2659. {
  2660. var engine = new Engine(cfg => cfg.AllowClrWrite());
  2661. var dt = DateTime.UtcNow;
  2662. engine.SetValue("capture", new Action<object>(o => dt = (DateTime) o));
  2663. engine.SetValue("minDate", DateTime.MinValue);
  2664. engine.Execute("capture(minDate);");
  2665. Assert.Equal(DateTime.MinValue, dt);
  2666. engine.SetValue("maxDate", DateTime.MaxValue);
  2667. engine.Execute("capture(maxDate);");
  2668. Assert.Equal(DateTime.MaxValue, dt);
  2669. }
  2670. }
  2671. }