InteropTests.cs 72 KB

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