InteropTests.cs 102 KB

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