2
0

InteropTests.cs 106 KB

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