InteropTests.cs 114 KB

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