InteropTests.cs 106 KB

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