InteropTests.cs 88 KB

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