InteropTests.cs 112 KB

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