InteropTests.cs 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269
  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.Interop;
  12. using Jint.Tests.Runtime.Converters;
  13. using Jint.Tests.Runtime.Domain;
  14. using Shapes;
  15. using Xunit;
  16. namespace Jint.Tests.Runtime
  17. {
  18. public class InteropTests : IDisposable
  19. {
  20. private readonly Engine _engine;
  21. public InteropTests()
  22. {
  23. _engine = new Engine(cfg => cfg.AllowClr(
  24. typeof(Shape).GetTypeInfo().Assembly,
  25. typeof(Console).GetTypeInfo().Assembly,
  26. typeof(System.IO.File).GetTypeInfo().Assembly))
  27. .SetValue("log", new Action<object>(Console.WriteLine))
  28. .SetValue("assert", new Action<bool>(Assert.True))
  29. .SetValue("equal", new Action<object, object>(Assert.Equal))
  30. ;
  31. }
  32. void IDisposable.Dispose()
  33. {
  34. }
  35. private void RunTest(string source)
  36. {
  37. _engine.Execute(source);
  38. }
  39. [Fact]
  40. public void PrimitiveTypesCanBeSet()
  41. {
  42. _engine.SetValue("x", 10);
  43. _engine.SetValue("y", true);
  44. _engine.SetValue("z", "foo");
  45. RunTest(@"
  46. assert(x === 10);
  47. assert(y === true);
  48. assert(z === 'foo');
  49. ");
  50. }
  51. [Fact]
  52. public void CanAccessMemberNamedItem()
  53. {
  54. _engine.Execute(@"
  55. function item2(arg) {
  56. return arg.item2
  57. }
  58. function item1(arg) {
  59. return arg.item
  60. }
  61. function item3(arg) {
  62. return arg.Item
  63. }
  64. ");
  65. var argument = new Dictionary<string, object>
  66. {
  67. {"item2", "item2 value"},
  68. {"item", "item value"},
  69. {"Item", "Item value"}
  70. };
  71. Assert.Equal("item2 value", _engine.Invoke("item2", argument));
  72. Assert.Equal("item value", _engine.Invoke("item1", argument));
  73. Assert.Equal("Item value", _engine.Invoke("item3", argument));
  74. var company = new Company("Acme Ltd");
  75. _engine.SetValue("c", company);
  76. Assert.Equal("item thingie", _engine.Execute("c.Item").GetCompletionValue());
  77. Assert.Equal("item thingie", _engine.Execute("c.item").GetCompletionValue());
  78. Assert.Equal("value", _engine.Execute("c['key']").GetCompletionValue());
  79. }
  80. [Fact]
  81. public void DelegatesCanBeSet()
  82. {
  83. _engine.SetValue("square", new Func<double, double>(x => x * x));
  84. RunTest(@"
  85. assert(square(10) === 100);
  86. ");
  87. }
  88. [Fact]
  89. public void DelegateWithNullableParameterCanBePassedANull()
  90. {
  91. _engine.SetValue("isnull", new Func<double?, bool>(x => x == null));
  92. RunTest(@"
  93. assert(isnull(null) === true);
  94. ");
  95. }
  96. [Fact]
  97. public void DelegateWithObjectParameterCanBePassedANull()
  98. {
  99. _engine.SetValue("isnull", new Func<object, bool>(x => x == null));
  100. RunTest(@"
  101. assert(isnull(null) === true);
  102. ");
  103. }
  104. [Fact]
  105. public void DelegateWithNullableParameterCanBePassedAnUndefined()
  106. {
  107. _engine.SetValue("isnull", new Func<double?, bool>(x => x == null));
  108. RunTest(@"
  109. assert(isnull(undefined) === true);
  110. ");
  111. }
  112. [Fact]
  113. public void DelegateWithObjectParameterCanBePassedAnUndefined()
  114. {
  115. _engine.SetValue("isnull", new Func<object, bool>(x => x == null));
  116. RunTest(@"
  117. assert(isnull(undefined) === true);
  118. ");
  119. }
  120. [Fact]
  121. public void DelegateWithNullableParameterCanBeExcluded()
  122. {
  123. _engine.SetValue("isnull", new Func<double?, bool>(x => x == null));
  124. RunTest(@"
  125. assert(isnull() === true);
  126. ");
  127. }
  128. [Fact]
  129. public void DelegateWithObjectParameterCanBeExcluded()
  130. {
  131. _engine.SetValue("isnull", new Func<object, bool>(x => x == null));
  132. RunTest(@"
  133. assert(isnull() === true);
  134. ");
  135. }
  136. [Fact]
  137. public void DynamicDelegateCanBeSet()
  138. {
  139. #if NETFRAMEWORK
  140. var parameters = new[]
  141. {
  142. System.Linq.Expressions.Expression.Parameter(typeof(int)),
  143. System.Linq.Expressions.Expression.Parameter(typeof(int))
  144. };
  145. var exp = System.Linq.Expressions.Expression.Add(parameters[0], parameters[1]);
  146. var del = System.Linq.Expressions.Expression.Lambda(exp, parameters).Compile();
  147. _engine.SetValue("add", del);
  148. RunTest(@"
  149. assert(add(1,1) === 2);
  150. ");
  151. #endif
  152. }
  153. [Fact]
  154. public void ExtraParametersAreIgnored()
  155. {
  156. _engine.SetValue("passNumber", new Func<int, int>(x => x));
  157. RunTest(@"
  158. assert(passNumber(123,'test',{},[],null) === 123);
  159. ");
  160. }
  161. private delegate string callParams(params object[] values);
  162. private delegate string callArgumentAndParams(string firstParam, params object[] values);
  163. [Fact]
  164. public void DelegatesWithParamsParameterCanBeInvoked()
  165. {
  166. var a = new A();
  167. _engine.SetValue("callParams", new callParams(a.Call13));
  168. _engine.SetValue("callArgumentAndParams", new callArgumentAndParams(a.Call14));
  169. RunTest(@"
  170. assert(callParams('1','2','3') === '1,2,3');
  171. assert(callParams('1') === '1');
  172. assert(callParams() === '');
  173. assert(callArgumentAndParams('a','1','2','3') === 'a:1,2,3');
  174. assert(callArgumentAndParams('a','1') === 'a:1');
  175. assert(callArgumentAndParams('a') === 'a:');
  176. assert(callArgumentAndParams() === ':');
  177. ");
  178. }
  179. [Fact]
  180. public void DelegateWithDefaultValueParametersCanBeInvoked()
  181. {
  182. var instance = new A();
  183. _engine.SetValue("Instance", instance);
  184. _engine.SetValue("Class", TypeReference.CreateTypeReference(_engine, typeof(A)));
  185. RunTest(@"
  186. assert(Instance.Call19() === 0);
  187. assert(Instance.Call19(1) === 1);
  188. assert(Instance.Call20(1) === 4);
  189. assert(Instance.Call20(1, 2) === 5);
  190. assert(Instance.Call20(1 , 2, 3) === 6);
  191. assert(Class.Call19Static() === 0);
  192. assert(Class.Call19Static(1) === 1);
  193. assert(Class.Call20Static(1) === 4);
  194. assert(Class.Call20Static(1, 2) === 5);
  195. assert(Class.Call20Static(1 , 2, 3) === 6);
  196. ");
  197. }
  198. [Fact]
  199. public void CanGetObjectProperties()
  200. {
  201. var p = new Person
  202. {
  203. Name = "Mickey Mouse"
  204. };
  205. _engine.SetValue("p", p);
  206. RunTest(@"
  207. assert(p.Name === 'Mickey Mouse');
  208. ");
  209. }
  210. [Fact]
  211. public void CanInvokeObjectMethods()
  212. {
  213. var p = new Person
  214. {
  215. Name = "Mickey Mouse"
  216. };
  217. _engine.SetValue("p", p);
  218. RunTest(@"
  219. assert(p.ToString() === 'Mickey Mouse');
  220. ");
  221. }
  222. [Fact]
  223. public void CanInvokeObjectMethodsWithPascalCase()
  224. {
  225. var p = new Person
  226. {
  227. Name = "Mickey Mouse"
  228. };
  229. _engine.SetValue("p", p);
  230. RunTest(@"
  231. assert(p.toString() === 'Mickey Mouse');
  232. ");
  233. }
  234. [Fact]
  235. public void CanSetObjectProperties()
  236. {
  237. var p = new Person
  238. {
  239. Name = "Mickey Mouse"
  240. };
  241. _engine.SetValue("p", p);
  242. RunTest(@"
  243. p.Name = 'Donald Duck';
  244. assert(p.Name === 'Donald Duck');
  245. ");
  246. Assert.Equal("Donald Duck", p.Name);
  247. }
  248. [Fact]
  249. public void CanGetIndexUsingStringKey()
  250. {
  251. var dictionary = new Dictionary<string, Person>();
  252. dictionary.Add("person1", new Person { Name = "Mickey Mouse" });
  253. dictionary.Add("person2", new Person { Name = "Goofy" });
  254. _engine.SetValue("dictionary", dictionary);
  255. RunTest(@"
  256. assert(dictionary['person1'].Name === 'Mickey Mouse');
  257. assert(dictionary['person2'].Name === 'Goofy');
  258. ");
  259. }
  260. [Fact]
  261. public void CanSetIndexUsingStringKey()
  262. {
  263. var dictionary = new Dictionary<string, Person>();
  264. dictionary.Add("person1", new Person { Name = "Mickey Mouse" });
  265. dictionary.Add("person2", new Person { Name = "Goofy" });
  266. _engine.SetValue("dictionary", dictionary);
  267. RunTest(@"
  268. dictionary['person2'].Name = 'Donald Duck';
  269. assert(dictionary['person2'].Name === 'Donald Duck');
  270. ");
  271. Assert.Equal("Donald Duck", dictionary["person2"].Name);
  272. }
  273. [Fact]
  274. public void CanGetIndexUsingIntegerKey()
  275. {
  276. var dictionary = new Dictionary<int, string>();
  277. dictionary.Add(1, "Mickey Mouse");
  278. dictionary.Add(2, "Goofy");
  279. _engine.SetValue("dictionary", dictionary);
  280. RunTest(@"
  281. assert(dictionary[1] === 'Mickey Mouse');
  282. assert(dictionary[2] === 'Goofy');
  283. ");
  284. }
  285. [Fact]
  286. public void CanSetIndexUsingIntegerKey()
  287. {
  288. var dictionary = new Dictionary<int, string>();
  289. dictionary.Add(1, "Mickey Mouse");
  290. dictionary.Add(2, "Goofy");
  291. _engine.SetValue("dictionary", dictionary);
  292. RunTest(@"
  293. dictionary[2] = 'Donald Duck';
  294. assert(dictionary[2] === 'Donald Duck');
  295. ");
  296. Assert.Equal("Mickey Mouse", dictionary[1]);
  297. Assert.Equal("Donald Duck", dictionary[2]);
  298. }
  299. private class DoubleIndexedClass
  300. {
  301. public int this[int index]
  302. {
  303. get { return index; }
  304. }
  305. public string this[string index]
  306. {
  307. get { return index; }
  308. }
  309. }
  310. [Fact]
  311. public void CanGetIndexUsingBothIntAndStringIndex()
  312. {
  313. var dictionary = new DoubleIndexedClass();
  314. _engine.SetValue("dictionary", dictionary);
  315. RunTest(@"
  316. assert(dictionary[1] === 1);
  317. assert(dictionary['test'] === 'test');
  318. ");
  319. }
  320. [Fact]
  321. public void CanUseGenericMethods()
  322. {
  323. var dictionary = new Dictionary<int, string>();
  324. dictionary.Add(1, "Mickey Mouse");
  325. _engine.SetValue("dictionary", dictionary);
  326. RunTest(@"
  327. dictionary.Add(2, 'Goofy');
  328. assert(dictionary[2] === 'Goofy');
  329. ");
  330. Assert.Equal("Mickey Mouse", dictionary[1]);
  331. Assert.Equal("Goofy", dictionary[2]);
  332. }
  333. [Fact]
  334. public void CanUseMultiGenericTypes()
  335. {
  336. RunTest(@"
  337. var type = System.Collections.Generic.Dictionary(System.Int32, System.String);
  338. var dictionary = new type();
  339. dictionary.Add(1, 'Mickey Mouse');
  340. dictionary.Add(2, 'Goofy');
  341. assert(dictionary[2] === 'Goofy');
  342. ");
  343. }
  344. [Fact]
  345. public void CanUseIndexOnCollection()
  346. {
  347. var collection = new System.Collections.ObjectModel.Collection<string>();
  348. collection.Add("Mickey Mouse");
  349. collection.Add("Goofy");
  350. _engine.SetValue("dictionary", collection);
  351. RunTest(@"
  352. dictionary[1] = 'Donald Duck';
  353. assert(dictionary[1] === 'Donald Duck');
  354. ");
  355. Assert.Equal("Mickey Mouse", collection[0]);
  356. Assert.Equal("Donald Duck", collection[1]);
  357. }
  358. [Fact]
  359. public void CanUseIndexOnList()
  360. {
  361. var list = new List<object>(2);
  362. list.Add("Mickey Mouse");
  363. list.Add("Goofy");
  364. _engine.SetValue("list", list);
  365. RunTest(@"
  366. list[1] = 'Donald Duck';
  367. assert(list[1] === 'Donald Duck');
  368. ");
  369. Assert.Equal("Mickey Mouse", list[0]);
  370. Assert.Equal("Donald Duck", list[1]);
  371. }
  372. [Fact]
  373. public void CanAccessAnonymousObject()
  374. {
  375. var p = new
  376. {
  377. Name = "Mickey Mouse",
  378. };
  379. _engine.SetValue("p", p);
  380. RunTest(@"
  381. assert(p.Name === 'Mickey Mouse');
  382. ");
  383. }
  384. [Fact]
  385. public void CanAccessAnonymousObjectProperties()
  386. {
  387. var p = new
  388. {
  389. Address = new
  390. {
  391. City = "Mouseton"
  392. }
  393. };
  394. _engine.SetValue("p", p);
  395. RunTest(@"
  396. assert(p.Address.City === 'Mouseton');
  397. ");
  398. }
  399. [Fact]
  400. public void PocosCanReturnJsValueDirectly()
  401. {
  402. var o = new
  403. {
  404. x = new JsNumber(1),
  405. y = new JsString("string"),
  406. };
  407. _engine.SetValue("o", o);
  408. RunTest(@"
  409. assert(o.x === 1);
  410. assert(o.y === 'string');
  411. ");
  412. }
  413. [Fact]
  414. public void PocosCanReturnObjectInstanceDirectly()
  415. {
  416. var x = new ObjectInstance(_engine);
  417. x.Set("foo", new JsString("bar"));
  418. var o = new
  419. {
  420. x
  421. };
  422. _engine.SetValue("o", o);
  423. RunTest(@"
  424. assert(o.x.foo === 'bar');
  425. ");
  426. }
  427. [Fact]
  428. public void DateTimeIsConvertedToDate()
  429. {
  430. var o = new
  431. {
  432. z = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
  433. };
  434. _engine.SetValue("o", o);
  435. RunTest(@"
  436. assert(o.z.valueOf() === 0);
  437. ");
  438. }
  439. [Fact]
  440. public void DateTimeOffsetIsConvertedToDate()
  441. {
  442. var o = new
  443. {
  444. z = new DateTimeOffset(1970, 1, 1, 0, 0, 0, new TimeSpan())
  445. };
  446. _engine.SetValue("o", o);
  447. RunTest(@"
  448. assert(o.z.valueOf() === 0);
  449. ");
  450. }
  451. [Fact]
  452. public void EcmaValuesAreAutomaticallyConvertedWhenSetInPoco()
  453. {
  454. var p = new Person
  455. {
  456. Name = "foo",
  457. };
  458. _engine.SetValue("p", p);
  459. RunTest(@"
  460. assert(p.Name === 'foo');
  461. assert(p.Age === 0);
  462. p.Name = 'bar';
  463. p.Age = 10;
  464. ");
  465. Assert.Equal("bar", p.Name);
  466. Assert.Equal(10, p.Age);
  467. }
  468. [Fact]
  469. public void EcmaValuesAreAutomaticallyConvertedToBestMatchWhenSetInPoco()
  470. {
  471. var p = new Person
  472. {
  473. Name = "foo",
  474. };
  475. _engine.SetValue("p", p);
  476. RunTest(@"
  477. p.Name = 10;
  478. p.Age = '20';
  479. ");
  480. Assert.Equal("10", p.Name);
  481. Assert.Equal(20, p.Age);
  482. }
  483. [Fact]
  484. public void ShouldCallInstanceMethodWithoutArgument()
  485. {
  486. _engine.SetValue("a", new A());
  487. RunTest(@"
  488. assert(a.Call1() === 0);
  489. ");
  490. }
  491. [Fact]
  492. public void ShouldCallInstanceMethodOverloadArgument()
  493. {
  494. _engine.SetValue("a", new A());
  495. RunTest(@"
  496. assert(a.Call1(1) === 1);
  497. ");
  498. }
  499. [Fact]
  500. public void ShouldCallInstanceMethodWithString()
  501. {
  502. var p = new Person();
  503. _engine.SetValue("a", new A());
  504. _engine.SetValue("p", p);
  505. RunTest(@"
  506. p.Name = a.Call2('foo');
  507. assert(p.Name === 'foo');
  508. ");
  509. Assert.Equal("foo", p.Name);
  510. }
  511. [Fact]
  512. public void CanUseTrim()
  513. {
  514. var p = new Person { Name = "Mickey Mouse "};
  515. _engine.SetValue("p", p);
  516. RunTest(@"
  517. assert(p.Name === 'Mickey Mouse ');
  518. p.Name = p.Name.trim();
  519. assert(p.Name === 'Mickey Mouse');
  520. ");
  521. Assert.Equal("Mickey Mouse", p.Name);
  522. }
  523. [Fact]
  524. public void CanUseMathFloor()
  525. {
  526. var p = new Person();
  527. _engine.SetValue("p", p);
  528. RunTest(@"
  529. p.Age = Math.floor(1.6);p
  530. assert(p.Age === 1);
  531. ");
  532. Assert.Equal(1, p.Age);
  533. }
  534. [Fact]
  535. public void CanUseDelegateAsFunction()
  536. {
  537. var even = new Func<int, bool>(x => x % 2 == 0);
  538. _engine.SetValue("even", even);
  539. RunTest(@"
  540. assert(even(2) === true);
  541. ");
  542. }
  543. private struct TestStruct
  544. {
  545. public int Value;
  546. public TestStruct(int value)
  547. {
  548. Value = value;
  549. }
  550. }
  551. private class TestClass
  552. {
  553. public int? NullableInt { get; set; }
  554. public DateTime? NullableDate { get; set; }
  555. public bool? NullableBool { get; set; }
  556. public TestEnumInt32? NullableEnum { get; set; }
  557. public TestStruct? NullableStruct { get; set; }
  558. }
  559. [Fact]
  560. public void CanSetNullablePropertiesOnPocos()
  561. {
  562. var instance = new TestClass();
  563. _engine.SetValue("instance", instance);
  564. _engine.SetValue("TestStruct", typeof(TestStruct));
  565. RunTest(@"
  566. instance.NullableInt = 2;
  567. instance.NullableDate = new Date();
  568. instance.NullableBool = true;
  569. instance.NullableEnum = 1;
  570. instance.NullableStruct = new TestStruct(5);
  571. assert(instance.NullableInt===2);
  572. assert(instance.NullableDate!=null);
  573. assert(instance.NullableBool===true);
  574. assert(instance.NullableEnum===1);
  575. assert(instance.NullableStruct.Value===5);
  576. ");
  577. }
  578. private class ReadOnlyList : IReadOnlyList<Person>
  579. {
  580. private readonly Person[] _data;
  581. public ReadOnlyList(params Person[] data)
  582. {
  583. _data = data;
  584. }
  585. public IEnumerator<Person> GetEnumerator()
  586. {
  587. return ((IEnumerable<Person>) _data).GetEnumerator();
  588. }
  589. IEnumerator IEnumerable.GetEnumerator()
  590. {
  591. return _data.GetEnumerator();
  592. }
  593. public int Count => _data.Length;
  594. public Person this[int index] => _data[index];
  595. }
  596. [Fact]
  597. public void CanAddArrayPrototypeForArrayLikeClrObjects()
  598. {
  599. var e = new Engine(cfg => cfg
  600. .AllowClr(typeof(Person).Assembly)
  601. .SetWrapObjectHandler((engine, target) =>
  602. {
  603. var instance = new ObjectWrapper(engine, target);
  604. if (instance.IsArrayLike)
  605. {
  606. instance.SetPrototypeOf(engine.Array.PrototypeObject);
  607. }
  608. return instance;
  609. })
  610. );
  611. var person = new Person
  612. {
  613. Age = 12,
  614. Name = "John"
  615. };
  616. dynamic obj = new
  617. {
  618. values = new ReadOnlyList(person)
  619. };
  620. e.SetValue("o", obj);
  621. var name = e.Execute("o.values.filter(x => x.age == 12)[0].name").GetCompletionValue().ToString();
  622. Assert.Equal("John", name);
  623. }
  624. [Fact]
  625. public void CanAccessExpandoObject()
  626. {
  627. var engine = new Engine();
  628. dynamic expando = new ExpandoObject();
  629. expando.Name = "test";
  630. engine.SetValue("expando", expando);
  631. Assert.Equal("test", engine.Execute("expando.Name").GetCompletionValue().ToString());
  632. }
  633. [Fact]
  634. public void ShouldConvertArrayToArrayInstance()
  635. {
  636. var result = _engine
  637. .SetValue("values", new[] { 1, 2, 3, 4, 5, 6 })
  638. .Execute("values.filter(function(x){ return x % 2 == 0; })");
  639. var parts = result.GetCompletionValue().ToObject();
  640. Assert.True(parts.GetType().IsArray);
  641. Assert.Equal(3, ((object[])parts).Length);
  642. Assert.Equal(2d, ((object[])parts)[0]);
  643. Assert.Equal(4d, ((object[])parts)[1]);
  644. Assert.Equal(6d, ((object[])parts)[2]);
  645. }
  646. [Fact]
  647. public void ShouldConvertListsToArrayInstance()
  648. {
  649. var result = _engine
  650. .SetValue("values", new List<object> { 1, 2, 3, 4, 5, 6 })
  651. .Execute("new Array(values).filter(function(x){ return x % 2 == 0; })");
  652. var parts = result.GetCompletionValue().ToObject();
  653. Assert.True(parts.GetType().IsArray);
  654. Assert.Equal(3, ((object[])parts).Length);
  655. Assert.Equal(2d, ((object[])parts)[0]);
  656. Assert.Equal(4d, ((object[])parts)[1]);
  657. Assert.Equal(6d, ((object[])parts)[2]);
  658. }
  659. [Fact]
  660. public void ShouldConvertArrayInstanceToArray()
  661. {
  662. var result = _engine.Execute("'[email protected]'.split('@');");
  663. var parts = result.GetCompletionValue().ToObject();
  664. Assert.True(parts.GetType().IsArray);
  665. Assert.Equal(2, ((object[])parts).Length);
  666. Assert.Equal("foo", ((object[])parts)[0]);
  667. Assert.Equal("bar.com", ((object[])parts)[1]);
  668. }
  669. [Fact]
  670. public void ShouldLoopWithNativeEnumerator()
  671. {
  672. JsValue adder(JsValue argValue)
  673. {
  674. ArrayInstance args = argValue.AsArray();
  675. double sum = 0;
  676. foreach (var item in args)
  677. {
  678. if (item.IsNumber())
  679. {
  680. sum += item.AsNumber();
  681. }
  682. }
  683. return sum;
  684. }
  685. var result = _engine.SetValue("getSum", new Func<JsValue, JsValue>(adder))
  686. .Execute("getSum([1,2,3]);");
  687. Assert.True(result.GetCompletionValue() == 6);
  688. }
  689. [Fact]
  690. public void ShouldConvertBooleanInstanceToBool()
  691. {
  692. var result = _engine.Execute("new Boolean(true)");
  693. var value = result.GetCompletionValue().ToObject();
  694. Assert.Equal(typeof(bool), value.GetType());
  695. Assert.Equal(true, value);
  696. }
  697. [Fact]
  698. public void ShouldConvertDateInstanceToDateTime()
  699. {
  700. var result = _engine.Execute("new Date(0)");
  701. var value = result.GetCompletionValue().ToObject();
  702. Assert.Equal(typeof(DateTime), value.GetType());
  703. Assert.Equal(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), value);
  704. }
  705. [Fact]
  706. public void ShouldConvertNumberInstanceToDouble()
  707. {
  708. var result = _engine.Execute("new Number(10)");
  709. var value = result.GetCompletionValue().ToObject();
  710. Assert.Equal(typeof(double), value.GetType());
  711. Assert.Equal(10d, value);
  712. }
  713. [Fact]
  714. public void ShouldConvertStringInstanceToString()
  715. {
  716. var result = _engine.Execute("new String('foo')");
  717. var value = result.GetCompletionValue().ToObject();
  718. Assert.Equal(typeof(string), value.GetType());
  719. Assert.Equal("foo", value);
  720. }
  721. [Fact]
  722. public void ShouldConvertObjectInstanceToExpando()
  723. {
  724. _engine.Execute("var o = {a: 1, b: 'foo'}");
  725. var result = _engine.GetValue("o");
  726. dynamic value = result.ToObject();
  727. Assert.Equal(1, value.a);
  728. Assert.Equal("foo", value.b);
  729. var dic = (IDictionary<string, object>)result.ToObject();
  730. Assert.Equal(1d, dic["a"]);
  731. Assert.Equal("foo", dic["b"]);
  732. }
  733. [Fact]
  734. public void ShouldNotTryToConvertCompatibleTypes()
  735. {
  736. _engine.SetValue("a", new A());
  737. RunTest(@"
  738. assert(a.Call3('foo') === 'foo');
  739. assert(a.Call3(1) === '1');
  740. ");
  741. }
  742. [Fact]
  743. public void ShouldNotTryToConvertDerivedTypes()
  744. {
  745. _engine.SetValue("a", new A());
  746. _engine.SetValue("p", new Person { Name = "Mickey" });
  747. RunTest(@"
  748. assert(a.Call4(p) === 'Mickey');
  749. ");
  750. }
  751. [Fact]
  752. public void ShouldExecuteFunctionCallBackAsDelegate()
  753. {
  754. _engine.SetValue("a", new A());
  755. RunTest(@"
  756. assert(a.Call5(function(a,b){ return a+b }) === '1foo');
  757. ");
  758. }
  759. [Fact]
  760. public void ShouldExecuteFunctionCallBackAsFuncAndThisCanBeAssigned()
  761. {
  762. _engine.SetValue("a", new A());
  763. RunTest(@"
  764. assert(a.Call6(function(a,b){ return this+a+b }) === 'bar1foo');
  765. ");
  766. }
  767. [Fact]
  768. public void ShouldExecuteFunctionCallBackAsPredicate()
  769. {
  770. _engine.SetValue("a", new A());
  771. // Func<>
  772. RunTest(@"
  773. assert(a.Call8(function(){ return 'foo'; }) === 'foo');
  774. ");
  775. }
  776. [Fact]
  777. public void ShouldExecuteFunctionWithParameterCallBackAsPredicate()
  778. {
  779. _engine.SetValue("a", new A());
  780. // Func<,>
  781. RunTest(@"
  782. assert(a.Call7('foo', function(a){ return a === 'foo'; }) === true);
  783. ");
  784. }
  785. [Fact]
  786. public void ShouldExecuteActionCallBackAsPredicate()
  787. {
  788. _engine.SetValue("a", new A());
  789. // Action
  790. RunTest(@"
  791. var value;
  792. a.Call9(function(){ value = 'foo'; });
  793. assert(value === 'foo');
  794. ");
  795. }
  796. [Fact]
  797. public void ShouldExecuteActionWithParameterCallBackAsPredicate()
  798. {
  799. _engine.SetValue("a", new A());
  800. // Action<>
  801. RunTest(@"
  802. var value;
  803. a.Call10('foo', function(b){ value = b; });
  804. assert(value === 'foo');
  805. ");
  806. }
  807. [Fact]
  808. public void ShouldExecuteActionWithMultipleParametersCallBackAsPredicate()
  809. {
  810. _engine.SetValue("a", new A());
  811. // Action<,>
  812. RunTest(@"
  813. var value;
  814. a.Call11('foo', 'bar', function(a,b){ value = a + b; });
  815. assert(value === 'foobar');
  816. ");
  817. }
  818. [Fact]
  819. public void ShouldExecuteFunc()
  820. {
  821. _engine.SetValue("a", new A());
  822. // Func<int, int>
  823. RunTest(@"
  824. var result = a.Call12(42, function(a){ return a + a; });
  825. assert(result === 84);
  826. ");
  827. }
  828. [Fact]
  829. public void ShouldExecuteActionCallbackOnEventChanged()
  830. {
  831. var collection = new System.Collections.ObjectModel.ObservableCollection<string>();
  832. Assert.True(collection.Count == 0);
  833. _engine.SetValue("collection", collection);
  834. RunTest(@"
  835. var eventAction;
  836. collection.add_CollectionChanged(function(sender, eventArgs) { eventAction = eventArgs.Action; } );
  837. collection.Add('test');
  838. ");
  839. var eventAction = _engine.GetValue("eventAction").AsNumber();
  840. Assert.True(eventAction == 0);
  841. Assert.True(collection.Count == 1);
  842. }
  843. [Fact]
  844. public void ShouldUseSystemIO()
  845. {
  846. RunTest(@"
  847. var filename = System.IO.Path.GetTempFileName();
  848. var sw = System.IO.File.CreateText(filename);
  849. sw.Write('Hello World');
  850. sw.Dispose();
  851. var content = System.IO.File.ReadAllText(filename);
  852. System.Console.WriteLine(content);
  853. assert(content === 'Hello World');
  854. ");
  855. }
  856. [Fact]
  857. public void ShouldBeInstanceOfTypeReferenceType()
  858. {
  859. _engine.SetValue("A", typeof(A));
  860. RunTest(@"
  861. var a = new A();
  862. assert(a instanceof A);
  863. ");
  864. }
  865. [Fact]
  866. public void ShouldImportNamespace()
  867. {
  868. RunTest(@"
  869. var Shapes = importNamespace('Shapes');
  870. var circle = new Shapes.Circle();
  871. assert(circle.Radius === 0);
  872. assert(circle.Perimeter() === 0);
  873. ");
  874. }
  875. [Fact]
  876. public void ShouldConstructReferenceTypeWithParameters()
  877. {
  878. RunTest(@"
  879. var Shapes = importNamespace('Shapes');
  880. var circle = new Shapes.Circle(1);
  881. assert(circle.Radius === 1);
  882. assert(circle.Perimeter() === Math.PI);
  883. ");
  884. }
  885. [Fact]
  886. public void ShouldConstructValueTypeWithoutParameters()
  887. {
  888. RunTest(@"
  889. var guid = new System.Guid();
  890. assert('00000000-0000-0000-0000-000000000000' === guid.ToString());
  891. ");
  892. }
  893. [Fact]
  894. public void ShouldInvokeAFunctionByName()
  895. {
  896. RunTest(@"
  897. function add(x, y) { return x + y; }
  898. ");
  899. Assert.Equal(3, _engine.Invoke("add", 1, 2));
  900. }
  901. [Fact]
  902. public void ShouldNotInvokeNonFunctionValue()
  903. {
  904. RunTest(@"
  905. var x= 10;
  906. ");
  907. Assert.Throws<ArgumentException>(() => _engine.Invoke("x", 1, 2));
  908. }
  909. [Fact]
  910. public void CanGetField()
  911. {
  912. var o = new ClassWithField
  913. {
  914. Field = "Mickey Mouse"
  915. };
  916. _engine.SetValue("o", o);
  917. RunTest(@"
  918. assert(o.Field === 'Mickey Mouse');
  919. ");
  920. }
  921. [Fact]
  922. public void CanSetField()
  923. {
  924. var o = new ClassWithField();
  925. _engine.SetValue("o", o);
  926. RunTest(@"
  927. o.Field = 'Mickey Mouse';
  928. assert(o.Field === 'Mickey Mouse');
  929. ");
  930. Assert.Equal("Mickey Mouse", o.Field);
  931. }
  932. [Fact]
  933. public void CanGetStaticField()
  934. {
  935. RunTest(@"
  936. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  937. var statics = domain.ClassWithStaticFields;
  938. assert(statics.Get == 'Get');
  939. ");
  940. }
  941. [Fact]
  942. public void CanSetStaticField()
  943. {
  944. RunTest(@"
  945. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  946. var statics = domain.ClassWithStaticFields;
  947. statics.Set = 'hello';
  948. assert(statics.Set == 'hello');
  949. ");
  950. Assert.Equal(ClassWithStaticFields.Set, "hello");
  951. }
  952. [Fact]
  953. public void CanGetStaticAccessor()
  954. {
  955. RunTest(@"
  956. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  957. var statics = domain.ClassWithStaticFields;
  958. assert(statics.Getter == 'Getter');
  959. ");
  960. }
  961. [Fact]
  962. public void CanSetStaticAccessor()
  963. {
  964. RunTest(@"
  965. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  966. var statics = domain.ClassWithStaticFields;
  967. statics.Setter = 'hello';
  968. assert(statics.Setter == 'hello');
  969. ");
  970. Assert.Equal(ClassWithStaticFields.Setter, "hello");
  971. }
  972. [Fact]
  973. public void CantSetStaticReadonly()
  974. {
  975. RunTest(@"
  976. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  977. var statics = domain.ClassWithStaticFields;
  978. statics.Readonly = 'hello';
  979. assert(statics.Readonly == 'Readonly');
  980. ");
  981. Assert.Equal(ClassWithStaticFields.Readonly, "Readonly");
  982. }
  983. [Fact]
  984. public void CanSetCustomConverters()
  985. {
  986. var engine1 = new Engine();
  987. engine1.SetValue("p", new { Test = true });
  988. engine1.Execute("var result = p.Test;");
  989. Assert.True((bool)engine1.GetValue("result").ToObject());
  990. var engine2 = new Engine(o => o.AddObjectConverter(new NegateBoolConverter()));
  991. engine2.SetValue("p", new { Test = true });
  992. engine2.Execute("var result = p.Test;");
  993. Assert.False((bool)engine2.GetValue("result").ToObject());
  994. }
  995. [Fact]
  996. public void CanConvertEnumsToString()
  997. {
  998. var engine1 = new Engine(o => o.AddObjectConverter(new EnumsToStringConverter()))
  999. .SetValue("assert", new Action<bool>(Assert.True));
  1000. engine1.SetValue("p", new { Comparison = StringComparison.CurrentCulture });
  1001. engine1.Execute("assert(p.Comparison === 'CurrentCulture');");
  1002. engine1.Execute("var result = p.Comparison;");
  1003. Assert.Equal("CurrentCulture", (string)engine1.GetValue("result").ToObject());
  1004. }
  1005. [Fact]
  1006. public void CanUserIncrementOperator()
  1007. {
  1008. var p = new Person
  1009. {
  1010. Age = 1,
  1011. };
  1012. _engine.SetValue("p", p);
  1013. RunTest(@"
  1014. assert(++p.Age === 2);
  1015. ");
  1016. Assert.Equal(2, p.Age);
  1017. }
  1018. [Fact]
  1019. public void CanOverwriteValues()
  1020. {
  1021. _engine.SetValue("x", 3);
  1022. _engine.SetValue("x", 4);
  1023. RunTest(@"
  1024. assert(x === 4);
  1025. ");
  1026. }
  1027. [Fact]
  1028. public void ShouldCreateGenericType()
  1029. {
  1030. RunTest(@"
  1031. var ListOfString = System.Collections.Generic.List(System.String);
  1032. var list = new ListOfString();
  1033. list.Add('foo');
  1034. list.Add(1);
  1035. assert(2 === list.Count);
  1036. ");
  1037. }
  1038. [Fact]
  1039. public void EnumComparesByName()
  1040. {
  1041. var o = new
  1042. {
  1043. r = Colors.Red,
  1044. b = Colors.Blue,
  1045. g = Colors.Green,
  1046. b2 = Colors.Red
  1047. };
  1048. _engine.SetValue("o", o);
  1049. _engine.SetValue("assertFalse", new Action<bool>(Assert.False));
  1050. RunTest(@"
  1051. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1052. var colors = domain.Colors;
  1053. assert(o.r === colors.Red);
  1054. assert(o.g === colors.Green);
  1055. assert(o.b === colors.Blue);
  1056. assertFalse(o.b2 === colors.Blue);
  1057. ");
  1058. }
  1059. [Fact]
  1060. public void ShouldSetEnumProperty()
  1061. {
  1062. var s = new Circle
  1063. {
  1064. Color = Colors.Red,
  1065. };
  1066. _engine.SetValue("s", s);
  1067. RunTest(@"
  1068. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1069. var colors = domain.Colors;
  1070. s.Color = colors.Blue;
  1071. assert(s.Color === colors.Blue);
  1072. ");
  1073. _engine.SetValue("s", s);
  1074. RunTest(@"
  1075. s.Color = colors.Blue | colors.Green;
  1076. assert(s.Color === colors.Blue | colors.Green);
  1077. ");
  1078. Assert.Equal(Colors.Blue | Colors.Green, s.Color);
  1079. }
  1080. enum TestEnumInt32 : int
  1081. {
  1082. None,
  1083. One = 1,
  1084. Min = int.MaxValue,
  1085. Max = int.MaxValue,
  1086. }
  1087. enum TestEnumUInt32 : uint
  1088. {
  1089. None,
  1090. One = 1,
  1091. Min = uint.MaxValue,
  1092. Max = uint.MaxValue,
  1093. }
  1094. enum TestEnumInt64 : long
  1095. {
  1096. None,
  1097. One = 1,
  1098. Min = long.MaxValue,
  1099. Max = long.MaxValue,
  1100. }
  1101. enum TestEnumUInt64 : ulong
  1102. {
  1103. None,
  1104. One = 1,
  1105. Min = ulong.MaxValue,
  1106. Max = ulong.MaxValue,
  1107. }
  1108. void TestEnum<T>(T enumValue)
  1109. {
  1110. object i = Convert.ChangeType(enumValue, Enum.GetUnderlyingType(typeof(T)));
  1111. string s = Convert.ToString(i, CultureInfo.InvariantCulture);
  1112. var o = new Tuple<T>(enumValue);
  1113. _engine.SetValue("o", o);
  1114. RunTest("assert(o.Item1 === " + s + ");");
  1115. }
  1116. [Fact]
  1117. public void ShouldWorkWithEnumInt32()
  1118. {
  1119. TestEnum(TestEnumInt32.None);
  1120. TestEnum(TestEnumInt32.One);
  1121. TestEnum(TestEnumInt32.Min);
  1122. TestEnum(TestEnumInt32.Max);
  1123. }
  1124. [Fact]
  1125. public void ShouldWorkWithEnumUInt32()
  1126. {
  1127. TestEnum(TestEnumUInt32.None);
  1128. TestEnum(TestEnumUInt32.One);
  1129. TestEnum(TestEnumUInt32.Min);
  1130. TestEnum(TestEnumUInt32.Max);
  1131. }
  1132. [Fact]
  1133. public void ShouldWorkWithEnumInt64()
  1134. {
  1135. TestEnum(TestEnumInt64.None);
  1136. TestEnum(TestEnumInt64.One);
  1137. TestEnum(TestEnumInt64.Min);
  1138. TestEnum(TestEnumInt64.Max);
  1139. }
  1140. [Fact]
  1141. public void ShouldWorkWithEnumUInt64()
  1142. {
  1143. TestEnum(TestEnumUInt64.None);
  1144. TestEnum(TestEnumUInt64.One);
  1145. TestEnum(TestEnumUInt64.Min);
  1146. TestEnum(TestEnumUInt64.Max);
  1147. }
  1148. [Fact]
  1149. public void EnumIsConvertedToNumber()
  1150. {
  1151. var o = new
  1152. {
  1153. r = Colors.Red,
  1154. b = Colors.Blue,
  1155. g = Colors.Green
  1156. };
  1157. _engine.SetValue("o", o);
  1158. RunTest(@"
  1159. assert(o.r === 0);
  1160. assert(o.g === 1);
  1161. assert(o.b === 10);
  1162. ");
  1163. }
  1164. [Fact]
  1165. public void ShouldConvertToEnum()
  1166. {
  1167. var s = new Circle
  1168. {
  1169. Color = Colors.Red,
  1170. };
  1171. _engine.SetValue("s", s);
  1172. RunTest(@"
  1173. assert(s.Color === 0);
  1174. s.Color = 10;
  1175. assert(s.Color === 10);
  1176. ");
  1177. _engine.SetValue("s", s);
  1178. RunTest(@"
  1179. s.Color = 11;
  1180. assert(s.Color === 11);
  1181. ");
  1182. Assert.Equal(Colors.Blue | Colors.Green, s.Color);
  1183. }
  1184. [Fact]
  1185. public void ShouldUseExplicitPropertyGetter()
  1186. {
  1187. _engine.SetValue("c", new Company("ACME"));
  1188. RunTest(@"
  1189. assert(c.Name === 'ACME');
  1190. ");
  1191. }
  1192. [Fact]
  1193. public void ShouldUseExplicitIndexerPropertyGetter()
  1194. {
  1195. var company = new Company("ACME");
  1196. ((ICompany)company)["Foo"] = "Bar";
  1197. _engine.SetValue("c", company);
  1198. RunTest(@"
  1199. assert(c.Foo === 'Bar');
  1200. ");
  1201. }
  1202. [Fact]
  1203. public void ShouldUseExplicitPropertySetter()
  1204. {
  1205. _engine.SetValue("c", new Company("ACME"));
  1206. RunTest(@"
  1207. c.Name = 'Foo';
  1208. assert(c.Name === 'Foo');
  1209. ");
  1210. }
  1211. [Fact]
  1212. public void ShouldUseExplicitIndexerPropertySetter()
  1213. {
  1214. var company = new Company("ACME");
  1215. ((ICompany)company)["Foo"] = "Bar";
  1216. _engine.SetValue("c", company);
  1217. RunTest(@"
  1218. c.Foo = 'Baz';
  1219. assert(c.Foo === 'Baz');
  1220. ");
  1221. }
  1222. [Fact]
  1223. public void ShouldUseExplicitMethod()
  1224. {
  1225. _engine.SetValue("c", new Company("ACME"));
  1226. RunTest(@"
  1227. assert(0 === c.CompareTo(c));
  1228. ");
  1229. }
  1230. [Fact]
  1231. public void ShouldCallInstanceMethodWithParams()
  1232. {
  1233. _engine.SetValue("a", new A());
  1234. RunTest(@"
  1235. assert(a.Call13('1','2','3') === '1,2,3');
  1236. assert(a.Call13('1') === '1');
  1237. assert(a.Call13(1) === '1');
  1238. assert(a.Call13() === '');
  1239. assert(a.Call14('a','1','2','3') === 'a:1,2,3');
  1240. assert(a.Call14('a','1') === 'a:1');
  1241. assert(a.Call14('a') === 'a:');
  1242. function call13wrapper(){ return a.Call13.apply(a, Array.prototype.slice.call(arguments)); }
  1243. assert(call13wrapper('1','2','3') === '1,2,3');
  1244. assert(a.Call13('1','2','3') === a.Call13(['1','2','3']));
  1245. ");
  1246. }
  1247. [Fact]
  1248. public void ShouldCallInstanceMethodWithJsValueParams()
  1249. {
  1250. _engine.SetValue("a", new A());
  1251. RunTest(@"
  1252. assert(a.Call16('1','2','3') === '1,2,3');
  1253. assert(a.Call16('1') === '1');
  1254. assert(a.Call16(1) === '1');
  1255. assert(a.Call16() === '');
  1256. assert(a.Call16('1','2','3') === a.Call16(['1','2','3']));
  1257. ");
  1258. }
  1259. [Fact]
  1260. public void NullValueAsArgumentShouldWork()
  1261. {
  1262. _engine.SetValue("a", new A());
  1263. RunTest(@"
  1264. var x = a.Call2(null);
  1265. assert(x === null);
  1266. ");
  1267. }
  1268. [Fact]
  1269. public void ShouldSetPropertyToNull()
  1270. {
  1271. var p = new Person { Name = "Mickey" };
  1272. _engine.SetValue("p", p);
  1273. RunTest(@"
  1274. assert(p.Name != null);
  1275. p.Name = null;
  1276. assert(p.Name == null);
  1277. ");
  1278. Assert.True(p.Name == null);
  1279. }
  1280. [Fact]
  1281. public void ShouldCallMethodWithNull()
  1282. {
  1283. _engine.SetValue("a", new A());
  1284. RunTest(@"
  1285. a.Call15(null);
  1286. var result = a.Call2(null);
  1287. assert(result == null);
  1288. ");
  1289. }
  1290. [Fact]
  1291. public void ShouldReturnUndefinedProperty()
  1292. {
  1293. _engine.SetValue("uo", new { foo = "bar" });
  1294. _engine.SetValue("ud", new Dictionary<string, object> { {"foo", "bar"} });
  1295. _engine.SetValue("ul", new List<string> { "foo", "bar" });
  1296. RunTest(@"
  1297. assert(!uo.undefinedProperty);
  1298. assert(!ul[5]);
  1299. assert(!ud.undefinedProperty);
  1300. ");
  1301. }
  1302. private class FailingObject2
  1303. {
  1304. public int this[int index] => throw new ArgumentException("index is bad", nameof(index));
  1305. }
  1306. [Fact]
  1307. public void ShouldPropagateIndexerExceptions()
  1308. {
  1309. var engine = new Engine();
  1310. engine.Execute(@"function f2(obj) { return obj[1]; }");
  1311. var failingObject = new FailingObject2();
  1312. Assert.Throws<ArgumentException>(() => engine.Invoke("f2", failingObject));
  1313. }
  1314. [Fact]
  1315. public void ShouldAutomaticallyConvertArraysToFindBestInteropResolution()
  1316. {
  1317. _engine.SetValue("a", new ArrayConverterTestClass());
  1318. _engine.SetValue("item1", new ArrayConverterItem(1));
  1319. _engine.SetValue("item2", new ArrayConverterItem(2));
  1320. RunTest(@"
  1321. assert(a.MethodAcceptsArrayOfInt([false, '1', 2]) === a.MethodAcceptsArrayOfInt([0, 1, 2]));
  1322. assert(a.MethodAcceptsArrayOfStrings(['1', 2]) === a.MethodAcceptsArrayOfStrings([1, 2]));
  1323. assert(a.MethodAcceptsArrayOfBool(['1', 0]) === a.MethodAcceptsArrayOfBool([true, false]));
  1324. assert(a.MethodAcceptsArrayOfStrings([item1, item2]) === a.MethodAcceptsArrayOfStrings(['1', '2']));
  1325. assert(a.MethodAcceptsArrayOfInt([item1, item2]) === a.MethodAcceptsArrayOfInt([1, 2]));
  1326. ");
  1327. }
  1328. [Fact]
  1329. public void ShouldImportNamespaceNestedType()
  1330. {
  1331. RunTest(@"
  1332. var shapes = importNamespace('Shapes.Circle');
  1333. var kinds = shapes.Kind;
  1334. assert(kinds.Unit === 0);
  1335. assert(kinds.Ellipse === 1);
  1336. assert(kinds.Round === 5);
  1337. ");
  1338. }
  1339. [Fact]
  1340. public void ShouldImportNamespaceNestedNestedType()
  1341. {
  1342. RunTest(@"
  1343. var meta = importNamespace('Shapes.Circle.Meta');
  1344. var usages = meta.Usage;
  1345. assert(usages.Public === 0);
  1346. assert(usages.Private === 1);
  1347. assert(usages.Internal === 11);
  1348. ");
  1349. }
  1350. [Fact]
  1351. public void ShouldGetNestedNestedProp()
  1352. {
  1353. RunTest(@"
  1354. var meta = importNamespace('Shapes.Circle');
  1355. var m = new meta.Meta();
  1356. assert(m.Description === 'descp');
  1357. ");
  1358. }
  1359. [Fact]
  1360. public void ShouldSetNestedNestedProp()
  1361. {
  1362. RunTest(@"
  1363. var meta = importNamespace('Shapes.Circle');
  1364. var m = new meta.Meta();
  1365. m.Description = 'hello';
  1366. assert(m.Description === 'hello');
  1367. ");
  1368. }
  1369. [Fact]
  1370. public void CanGetStaticNestedField()
  1371. {
  1372. RunTest(@"
  1373. var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
  1374. var statics = domain.ClassWithStaticFields;
  1375. assert(statics.Get == 'Get');
  1376. ");
  1377. }
  1378. [Fact]
  1379. public void CanSetStaticNestedField()
  1380. {
  1381. RunTest(@"
  1382. var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
  1383. var statics = domain.ClassWithStaticFields;
  1384. statics.Set = 'hello';
  1385. assert(statics.Set == 'hello');
  1386. ");
  1387. Assert.Equal(Nested.ClassWithStaticFields.Set, "hello");
  1388. }
  1389. [Fact]
  1390. public void CanGetStaticNestedAccessor()
  1391. {
  1392. RunTest(@"
  1393. var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
  1394. var statics = domain.ClassWithStaticFields;
  1395. assert(statics.Getter == 'Getter');
  1396. ");
  1397. }
  1398. [Fact]
  1399. public void CanSetStaticNestedAccessor()
  1400. {
  1401. RunTest(@"
  1402. var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
  1403. var statics = domain.ClassWithStaticFields;
  1404. statics.Setter = 'hello';
  1405. assert(statics.Setter == 'hello');
  1406. ");
  1407. Assert.Equal(Nested.ClassWithStaticFields.Setter, "hello");
  1408. }
  1409. [Fact]
  1410. public void CantSetStaticNestedReadonly()
  1411. {
  1412. RunTest(@"
  1413. var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
  1414. var statics = domain.ClassWithStaticFields;
  1415. statics.Readonly = 'hello';
  1416. assert(statics.Readonly == 'Readonly');
  1417. ");
  1418. Assert.Equal(Nested.ClassWithStaticFields.Readonly, "Readonly");
  1419. }
  1420. [Fact]
  1421. public void ShouldExecuteFunctionWithValueTypeParameterCorrectly()
  1422. {
  1423. _engine.SetValue("a", new A());
  1424. // Func<int, int>
  1425. RunTest(@"
  1426. assert(a.Call17(function(value){ return value; }) === 17);
  1427. ");
  1428. }
  1429. [Fact]
  1430. public void ShouldExecuteActionWithValueTypeParameterCorrectly()
  1431. {
  1432. _engine.SetValue("a", new A());
  1433. // Action<int>
  1434. RunTest(@"
  1435. a.Call18(function(value){ assert(value === 18); });
  1436. ");
  1437. }
  1438. [Fact]
  1439. public void ShouldConvertToJsValue()
  1440. {
  1441. RunTest(@"
  1442. var now = System.DateTime.Now;
  1443. assert(new String(now) == now.toString());
  1444. var zero = System.Int32.MaxValue;
  1445. assert(new String(zero) == zero.toString());
  1446. ");
  1447. }
  1448. [Fact]
  1449. public void ShouldNotCatchClrExceptions()
  1450. {
  1451. var engine = new Engine()
  1452. .SetValue("throwMyException", new Action(() => { throw new NotSupportedException(); }))
  1453. .SetValue("Thrower", typeof(Thrower))
  1454. .Execute(@"
  1455. function throwException1(){
  1456. try {
  1457. throwMyException();
  1458. return;
  1459. }
  1460. catch(e) {
  1461. return;
  1462. }
  1463. }
  1464. function throwException2(){
  1465. try {
  1466. new Thrower().ThrowNotSupportedException();
  1467. return;
  1468. }
  1469. catch(e) {
  1470. return;
  1471. }
  1472. }
  1473. ");
  1474. Assert.ThrowsAny<NotSupportedException>(() => engine.Invoke("throwException1"));
  1475. Assert.ThrowsAny<NotSupportedException>(() => engine.Invoke("throwException2"));
  1476. }
  1477. [Fact]
  1478. public void ShouldCatchAllClrExceptions()
  1479. {
  1480. string exceptionMessage = "myExceptionMessage";
  1481. var engine = new Engine(o => o.CatchClrExceptions())
  1482. .SetValue("throwMyException", new Action(() => { throw new Exception(exceptionMessage); }))
  1483. .SetValue("Thrower", typeof(Thrower))
  1484. .Execute(@"
  1485. function throwException1(){
  1486. try {
  1487. throwMyException();
  1488. return '';
  1489. }
  1490. catch(e) {
  1491. return e.message;
  1492. }
  1493. }
  1494. function throwException2(){
  1495. try {
  1496. new Thrower().ThrowExceptionWithMessage('myExceptionMessage');
  1497. return;
  1498. }
  1499. catch(e) {
  1500. return e.message;
  1501. }
  1502. }
  1503. ");
  1504. Assert.Equal(engine.Invoke("throwException1").AsString(), exceptionMessage);
  1505. Assert.Equal(engine.Invoke("throwException2").AsString(), exceptionMessage);
  1506. }
  1507. class MemberExceptionTest
  1508. {
  1509. public MemberExceptionTest(bool throwOnCreate)
  1510. {
  1511. if (throwOnCreate)
  1512. throw new InvalidOperationException();
  1513. }
  1514. public JsValue ThrowingProperty1
  1515. {
  1516. get { throw new InvalidOperationException(); }
  1517. set { throw new InvalidOperationException(); }
  1518. }
  1519. public object ThrowingProperty2
  1520. {
  1521. get { throw new InvalidOperationException(); }
  1522. set { throw new InvalidOperationException(); }
  1523. }
  1524. public void ThrowingFunction()
  1525. {
  1526. throw new InvalidOperationException();
  1527. }
  1528. }
  1529. [Fact]
  1530. public void ShouldCatchClrMemberExceptions()
  1531. {
  1532. var engine = new Engine(cfg =>
  1533. {
  1534. cfg.AllowClr();
  1535. cfg.CatchClrExceptions();
  1536. });
  1537. engine.SetValue("assert", new Action<bool>(Assert.True));
  1538. engine.SetValue("log", new Action<object>(Console.WriteLine));
  1539. engine.SetValue("create", typeof(MemberExceptionTest));
  1540. engine.SetValue("instance", new MemberExceptionTest(throwOnCreate: false));
  1541. // Test calling a constructor that throws an exception
  1542. engine.Execute(@"
  1543. try
  1544. {
  1545. create(true);
  1546. assert(false);
  1547. }
  1548. catch (e)
  1549. {
  1550. assert(true);
  1551. }
  1552. ");
  1553. // Test calling a member function that throws an exception
  1554. engine.Execute(@"
  1555. try
  1556. {
  1557. instance.ThrowingFunction();
  1558. assert(false);
  1559. }
  1560. catch (e)
  1561. {
  1562. assert(true);
  1563. }
  1564. ");
  1565. // Test using a property getter that throws an exception
  1566. engine.Execute(@"
  1567. try
  1568. {
  1569. log(o.ThrowingProperty);
  1570. assert(false);
  1571. }
  1572. catch (e)
  1573. {
  1574. assert(true);
  1575. }
  1576. ");
  1577. // Test using a property setter that throws an exception
  1578. engine.Execute(@"
  1579. try
  1580. {
  1581. instance.ThrowingProperty1 = 123;
  1582. assert(false);
  1583. }
  1584. catch (e)
  1585. {
  1586. assert(true);
  1587. }
  1588. try
  1589. {
  1590. instance.ThrowingProperty2 = 456;
  1591. assert(false);
  1592. }
  1593. catch (e)
  1594. {
  1595. assert(true);
  1596. }
  1597. ");
  1598. }
  1599. [Fact]
  1600. public void ShouldCatchSomeExceptions()
  1601. {
  1602. string exceptionMessage = "myExceptionMessage";
  1603. var engine = new Engine(o => o.CatchClrExceptions(e => e is NotSupportedException))
  1604. .SetValue("throwMyException1", new Action(() => { throw new NotSupportedException(exceptionMessage); }))
  1605. .SetValue("throwMyException2", new Action(() => { throw new ArgumentNullException(); }))
  1606. .SetValue("Thrower", typeof(Thrower))
  1607. .Execute(@"
  1608. function throwException1(){
  1609. try {
  1610. throwMyException1();
  1611. return '';
  1612. }
  1613. catch(e) {
  1614. return e.message;
  1615. }
  1616. }
  1617. function throwException2(){
  1618. try {
  1619. throwMyException2();
  1620. return '';
  1621. }
  1622. catch(e) {
  1623. return e.message;
  1624. }
  1625. }
  1626. function throwException3(){
  1627. try {
  1628. new Thrower().ThrowNotSupportedExceptionWithMessage('myExceptionMessage');
  1629. return '';
  1630. }
  1631. catch(e) {
  1632. return e.message;
  1633. }
  1634. }
  1635. function throwException4(){
  1636. try {
  1637. new Thrower().ThrowArgumentNullException();
  1638. return '';
  1639. }
  1640. catch(e) {
  1641. return e.message;
  1642. }
  1643. }
  1644. ");
  1645. Assert.Equal(engine.Invoke("throwException1").AsString(), exceptionMessage);
  1646. Assert.Throws<ArgumentNullException>(() => engine.Invoke("throwException2"));
  1647. Assert.Equal(engine.Invoke("throwException3").AsString(), exceptionMessage);
  1648. Assert.Throws<ArgumentNullException>(() => engine.Invoke("throwException4"));
  1649. }
  1650. [Fact]
  1651. public void ArrayFromShouldConvertListToArrayLike()
  1652. {
  1653. var list = new List<Person>
  1654. {
  1655. new Person {Name = "Mike"},
  1656. new Person {Name = "Mika"}
  1657. };
  1658. _engine.SetValue("a", list);
  1659. RunTest(@"
  1660. var arr = new Array(a);
  1661. assert(arr.length === 2);
  1662. assert(arr[0].Name === 'Mike');
  1663. assert(arr[1].Name === 'Mika');
  1664. ");
  1665. RunTest(@"
  1666. var arr = Array.from(a);
  1667. assert(arr.length === 2);
  1668. assert(arr[0].Name === 'Mike');
  1669. assert(arr[1].Name === 'Mika');
  1670. ");
  1671. }
  1672. [Fact]
  1673. public void ArrayFromShouldConvertArrayToArrayLike()
  1674. {
  1675. var list = new []
  1676. {
  1677. new Person {Name = "Mike"},
  1678. new Person {Name = "Mika"}
  1679. };
  1680. _engine.SetValue("a", list);
  1681. RunTest(@"
  1682. var arr = new Array(a);
  1683. assert(arr.length === 2);
  1684. assert(arr[0].Name === 'Mike');
  1685. assert(arr[1].Name === 'Mika');
  1686. ");
  1687. RunTest(@"
  1688. var arr = Array.from(a);
  1689. assert(arr.length === 2);
  1690. assert(arr[0].Name === 'Mike');
  1691. assert(arr[1].Name === 'Mika');
  1692. ");
  1693. }
  1694. [Fact]
  1695. public void ArrayFromShouldConvertIEnumerable()
  1696. {
  1697. var enumerable = new []
  1698. {
  1699. new Person {Name = "Mike"},
  1700. new Person {Name = "Mika"}
  1701. }.Select(x => x);
  1702. _engine.SetValue("a", enumerable);
  1703. RunTest(@"
  1704. var arr = new Array(a);
  1705. assert(arr.length === 2);
  1706. assert(arr[0].Name === 'Mike');
  1707. assert(arr[1].Name === 'Mika');
  1708. ");
  1709. RunTest(@"
  1710. var arr = Array.from(a);
  1711. assert(arr.length === 2);
  1712. assert(arr[0].Name === 'Mike');
  1713. assert(arr[1].Name === 'Mika');
  1714. ");
  1715. }
  1716. [Fact]
  1717. public void ShouldBeAbleToPlusAssignStringProperty()
  1718. {
  1719. var p = new Person();
  1720. var engine = new Engine();
  1721. engine.SetValue("P", p);
  1722. engine.Execute("P.Name = 'b';");
  1723. engine.Execute("P.Name += 'c';");
  1724. Assert.Equal("bc", p.Name);
  1725. }
  1726. [Fact]
  1727. public void ShouldNotResolveToPrimitiveSymbol()
  1728. {
  1729. var engine = new Engine(options =>
  1730. options.AllowClr(typeof(FloatIndexer).GetTypeInfo().Assembly));
  1731. var c = engine.Execute(@"
  1732. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1733. return new domain.FloatIndexer();
  1734. ").GetCompletionValue();
  1735. Assert.NotNull(c.ToString());
  1736. Assert.Equal((uint)0, c.As<ObjectInstance>().Length);
  1737. }
  1738. class DictionaryWrapper
  1739. {
  1740. public IDictionary<string, object> Values { get; set; }
  1741. }
  1742. class DictionaryTest
  1743. {
  1744. public void Test1(IDictionary<string, object> values)
  1745. {
  1746. Assert.Equal(1, Convert.ToInt32(values["a"]));
  1747. }
  1748. public void Test2(DictionaryWrapper dictionaryObject)
  1749. {
  1750. Assert.Equal(1, Convert.ToInt32(dictionaryObject.Values["a"]));
  1751. }
  1752. }
  1753. [Fact]
  1754. public void ShouldBeAbleToPassDictionaryToMethod()
  1755. {
  1756. var engine = new Engine();
  1757. engine.SetValue("dictionaryTest", new DictionaryTest());
  1758. engine.Execute("dictionaryTest.test1({ a: 1 });");
  1759. }
  1760. [Fact]
  1761. public void ShouldBeAbleToPassDictionaryInObjectToMethod()
  1762. {
  1763. var engine = new Engine();
  1764. engine.SetValue("dictionaryTest", new DictionaryTest());
  1765. engine.Execute("dictionaryTest.test2({ values: { a: 1 } });");
  1766. }
  1767. [Fact]
  1768. public void ShouldSupportSpreadForDictionary()
  1769. {
  1770. var engine = new Engine();
  1771. var state = new Dictionary<string, object>
  1772. {
  1773. {"invoice", new Dictionary<string, object> {["number"] = "42"}}
  1774. };
  1775. engine.SetValue("state", state);
  1776. var result = (IDictionary<string, object>) engine
  1777. .Execute("({ supplier: 'S1', ...state.invoice })")
  1778. .GetCompletionValue()
  1779. .ToObject();
  1780. Assert.Equal("S1", result["supplier"]);
  1781. Assert.Equal("42", result["number"]);
  1782. }
  1783. [Fact]
  1784. public void ShouldSupportSpreadForDictionary2()
  1785. {
  1786. var engine = new Engine();
  1787. var state = new Dictionary<string, object>
  1788. {
  1789. {"invoice", new Dictionary<string, object> {["number"] = "42"}}
  1790. };
  1791. engine.SetValue("state", state);
  1792. var result = (IDictionary<string, object>) engine
  1793. .Execute("function getValue() { return {supplier: 'S1', ...state.invoice}; }")
  1794. .Invoke("getValue")
  1795. .ToObject();
  1796. Assert.Equal("S1", result["supplier"]);
  1797. Assert.Equal("42", result["number"]);
  1798. }
  1799. [Fact]
  1800. public void ShouldSupportSpreadForObject()
  1801. {
  1802. var engine = new Engine();
  1803. var person = new Person
  1804. {
  1805. Name = "Mike",
  1806. Age = 20
  1807. };
  1808. engine.SetValue("p", person);
  1809. var result = (IDictionary<string, object>) engine
  1810. .Execute("({ supplier: 'S1', ...p })")
  1811. .GetCompletionValue()
  1812. .ToObject();
  1813. Assert.Equal("S1", result["supplier"]);
  1814. Assert.Equal("Mike", result["Name"]);
  1815. Assert.Equal(20d, result["Age"]);
  1816. }
  1817. [Fact]
  1818. public void ShouldBeAbleToJsonStringifyClrObjects()
  1819. {
  1820. var engine = new Engine();
  1821. engine.Execute("var jsObj = { 'key1' :'value1', 'key2' : 'value2' }");
  1822. engine.SetValue("netObj", new Dictionary<string, object>
  1823. {
  1824. {"key1", "value1"},
  1825. {"key2", "value2"},
  1826. });
  1827. var jsValue = engine.Execute("jsObj['key1']").GetCompletionValue().AsString();
  1828. var clrValue = engine.Execute("netObj['key1']").GetCompletionValue().AsString();
  1829. Assert.Equal(jsValue, clrValue);
  1830. jsValue = engine.Execute("JSON.stringify(jsObj)").GetCompletionValue().AsString();
  1831. clrValue = engine.Execute("JSON.stringify(netObj)").GetCompletionValue().AsString();
  1832. Assert.Equal(jsValue, clrValue);
  1833. // Write properties on screen using showProps function defined on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
  1834. engine.Execute(@"function showProps(obj, objName) {
  1835. var result = """";
  1836. for (var i in obj) {
  1837. if (obj.hasOwnProperty(i)) {
  1838. result += objName + ""."" + i + "" = "" + obj[i] + ""\n"";
  1839. }
  1840. }
  1841. return result;
  1842. }");
  1843. jsValue = engine.Execute("showProps(jsObj, 'theObject')").GetCompletionValue().AsString();
  1844. clrValue = engine.Execute("showProps(jsObj, 'theObject')").GetCompletionValue().AsString();
  1845. Assert.Equal(jsValue, clrValue);
  1846. }
  1847. [Fact]
  1848. public void ShouldHideSpecificMembers()
  1849. {
  1850. var engine = new Engine(options => options.SetMemberAccessor((e, target, member) =>
  1851. {
  1852. if (target is HiddenMembers)
  1853. {
  1854. if (member == nameof(HiddenMembers.Member2) || member == nameof(HiddenMembers.Method2))
  1855. {
  1856. return JsValue.Undefined;
  1857. }
  1858. }
  1859. return null;
  1860. }));
  1861. engine.SetValue("m", new HiddenMembers());
  1862. Assert.Equal("Member1", engine.Execute("m.Member1").GetCompletionValue().ToString());
  1863. Assert.Equal("undefined", engine.Execute("m.Member2").GetCompletionValue().ToString());
  1864. Assert.Equal("Method1", engine.Execute("m.Method1()").GetCompletionValue().ToString());
  1865. // check the method itself, not its invokation as it would mean invoking "undefined"
  1866. Assert.Equal("undefined", engine.Execute("m.Method2").GetCompletionValue().ToString());
  1867. }
  1868. [Fact]
  1869. public void ShouldOverrideMembers()
  1870. {
  1871. var engine = new Engine(options => options.SetMemberAccessor((e, target, member) =>
  1872. {
  1873. if (target is HiddenMembers && member == nameof(HiddenMembers.Member1))
  1874. {
  1875. return "Orange";
  1876. }
  1877. return null;
  1878. }));
  1879. engine.SetValue("m", new HiddenMembers());
  1880. Assert.Equal("Orange", engine.Execute("m.Member1").GetCompletionValue().ToString());
  1881. }
  1882. [Fact]
  1883. public void SettingValueViaIntegerIndexer()
  1884. {
  1885. var engine = new Engine(cfg => cfg.AllowClr(typeof(FloatIndexer).GetTypeInfo().Assembly));
  1886. engine.SetValue("log", new Action<object>(Console.WriteLine));
  1887. engine.Execute(@"
  1888. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1889. var fia = new domain.IntegerIndexer();
  1890. log(fia[0]);
  1891. ");
  1892. Assert.Equal(123, engine.Execute("fia[0]").GetCompletionValue().AsNumber());
  1893. engine.Execute("fia[0] = 678;");
  1894. Assert.Equal(678, engine.Execute("fia[0]").GetCompletionValue().AsNumber());
  1895. }
  1896. }
  1897. }