InteropTests.cs 106 KB

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