InteropTests.cs 92 KB

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