InteropTests.cs 63 KB

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