InteropTests.cs 94 KB

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