InteropTests.cs 113 KB

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