2
0

InteropTests.cs 69 KB

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