InteropTests.cs 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750
  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. private struct TestStruct
  635. {
  636. public int Value;
  637. public TestStruct(int value)
  638. {
  639. Value = value;
  640. }
  641. }
  642. private class TestClass
  643. {
  644. public string String { get; set; }
  645. public int Int { get; set; }
  646. public int? NullableInt { get; set; }
  647. public DateTime? NullableDate { get; set; }
  648. public bool? NullableBool { get; set; }
  649. public bool Bool { get; set; }
  650. public TestEnumInt32? NullableEnum { get; set; }
  651. public TestStruct? NullableStruct { get; set; }
  652. public void SetBool(bool value)
  653. {
  654. Bool = value;
  655. }
  656. public void SetInt(int value)
  657. {
  658. Int = value;
  659. }
  660. public void SetString(string value)
  661. {
  662. String = value;
  663. }
  664. }
  665. [Fact]
  666. public void CanSetNullablePropertiesOnPocos()
  667. {
  668. var instance = new TestClass();
  669. _engine.SetValue("instance", instance);
  670. _engine.SetValue("TestStruct", typeof(TestStruct));
  671. RunTest(@"
  672. instance.NullableInt = 2;
  673. instance.NullableDate = new Date();
  674. instance.NullableBool = true;
  675. instance.NullableEnum = 1;
  676. instance.NullableStruct = new TestStruct(5);
  677. assert(instance.NullableInt===2);
  678. assert(instance.NullableDate!=null);
  679. assert(instance.NullableBool===true);
  680. assert(instance.NullableEnum===1);
  681. assert(instance.NullableStruct.Value===5);
  682. ");
  683. }
  684. private class ReadOnlyList : IReadOnlyList<Person>
  685. {
  686. private readonly Person[] _data;
  687. public ReadOnlyList(params Person[] data)
  688. {
  689. _data = data;
  690. }
  691. public IEnumerator<Person> GetEnumerator()
  692. {
  693. return ((IEnumerable<Person>) _data).GetEnumerator();
  694. }
  695. IEnumerator IEnumerable.GetEnumerator()
  696. {
  697. return _data.GetEnumerator();
  698. }
  699. public int Count => _data.Length;
  700. public Person this[int index] => _data[index];
  701. }
  702. [Fact]
  703. public void CanAddArrayPrototypeForArrayLikeClrObjects()
  704. {
  705. var e = new Engine(cfg => cfg
  706. .AllowClr(typeof(Person).Assembly)
  707. .SetWrapObjectHandler((engine, target) =>
  708. {
  709. var instance = new ObjectWrapper(engine, target);
  710. if (instance.IsArrayLike)
  711. {
  712. instance.SetPrototypeOf(engine.Realm.Intrinsics.Array.PrototypeObject);
  713. }
  714. return instance;
  715. })
  716. );
  717. var person = new Person
  718. {
  719. Age = 12,
  720. Name = "John"
  721. };
  722. dynamic obj = new
  723. {
  724. values = new ReadOnlyList(person)
  725. };
  726. e.SetValue("o", obj);
  727. var name = e.Evaluate("o.values.filter(x => x.age == 12)[0].name").ToString();
  728. Assert.Equal("John", name);
  729. }
  730. [Fact]
  731. public void ShouldConvertArrayToArrayInstance()
  732. {
  733. var result = _engine
  734. .SetValue("values", new[] { 1, 2, 3, 4, 5, 6 })
  735. .Evaluate("values.filter(function(x){ return x % 2 == 0; })");
  736. var parts = result.ToObject();
  737. Assert.True(parts.GetType().IsArray);
  738. Assert.Equal(3, ((object[]) parts).Length);
  739. Assert.Equal(2d, ((object[]) parts)[0]);
  740. Assert.Equal(4d, ((object[]) parts)[1]);
  741. Assert.Equal(6d, ((object[]) parts)[2]);
  742. }
  743. [Fact]
  744. public void ShouldConvertListsToArrayInstance()
  745. {
  746. var result = _engine
  747. .SetValue("values", new List<object> { 1, 2, 3, 4, 5, 6 })
  748. .Evaluate("new Array(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 ShouldConvertArrayInstanceToArray()
  758. {
  759. var parts = _engine.Evaluate("'[email protected]'.split('@');").ToObject();
  760. Assert.True(parts.GetType().IsArray);
  761. Assert.Equal(2, ((object[]) parts).Length);
  762. Assert.Equal("foo", ((object[]) parts)[0]);
  763. Assert.Equal("bar.com", ((object[]) parts)[1]);
  764. }
  765. [Fact]
  766. public void ShouldLoopWithNativeEnumerator()
  767. {
  768. JsValue adder(JsValue argValue)
  769. {
  770. var args = argValue.AsArray();
  771. double sum = 0;
  772. foreach (var item in args)
  773. {
  774. if (item.IsNumber())
  775. {
  776. sum += item.AsNumber();
  777. }
  778. }
  779. return sum;
  780. }
  781. var result = _engine.SetValue("getSum", new Func<JsValue, JsValue>(adder))
  782. .Evaluate("getSum([1,2,3]);");
  783. Assert.True(result == 6);
  784. }
  785. [Fact]
  786. public void ShouldConvertBooleanInstanceToBool()
  787. {
  788. var value = _engine.Evaluate("new Boolean(true)").ToObject();
  789. Assert.Equal(typeof(bool), value.GetType());
  790. Assert.Equal(true, value);
  791. }
  792. [Fact]
  793. public void ShouldAllowBooleanCoercion()
  794. {
  795. var engine = new Engine(options => { options.Interop.ValueCoercion = ValueCoercionType.Boolean; });
  796. engine.SetValue("o", new TestClass());
  797. Assert.True(engine.Evaluate("o.Bool = 1; return o.Bool;").AsBoolean());
  798. Assert.True(engine.Evaluate("o.Bool = 'dog'; return o.Bool;").AsBoolean());
  799. Assert.True(engine.Evaluate("o.Bool = {}; return o.Bool;").AsBoolean());
  800. Assert.False(engine.Evaluate("o.Bool = 0; return o.Bool;").AsBoolean());
  801. Assert.False(engine.Evaluate("o.Bool = ''; return o.Bool;").AsBoolean());
  802. Assert.False(engine.Evaluate("o.Bool = null; return o.Bool;").AsBoolean());
  803. Assert.False(engine.Evaluate("o.Bool = undefined; return o.Bool;").AsBoolean());
  804. engine.Evaluate("class MyClass { valueOf() { return 42; } }");
  805. Assert.Equal(true, engine.Evaluate("let obj = new MyClass(); o.Bool = obj; return o.Bool;").AsBoolean());
  806. engine.SetValue("func3", new Action<bool, bool, bool>((param1, param2, param3) =>
  807. {
  808. Assert.True(param1);
  809. Assert.True(param2);
  810. Assert.True(param3);
  811. }));
  812. engine.Evaluate("func3(true, obj, [ 1, 2, 3])");
  813. Assert.Equal(true, engine.Evaluate("o.SetBool(42); return o.Bool;").AsBoolean());
  814. Assert.Equal(true, engine.Evaluate("o.SetBool(obj); return o.Bool;").AsBoolean());
  815. Assert.Equal(true, engine.Evaluate("o.SetBool([ 1, 2, 3].length); return o.Bool;").AsBoolean());
  816. }
  817. [Fact]
  818. public void ShouldAllowNumberCoercion()
  819. {
  820. var engine = new Engine(options => { options.Interop.ValueCoercion = ValueCoercionType.Number; });
  821. engine.SetValue("o", new TestClass());
  822. Assert.Equal(1, engine.Evaluate("o.Int = true; return o.Int;").AsNumber());
  823. Assert.Equal(0, engine.Evaluate("o.Int = false; return o.Int;").AsNumber());
  824. engine.Evaluate("class MyClass { valueOf() { return 42; } }");
  825. Assert.Equal(42, engine.Evaluate("let obj = new MyClass(); o.Int = obj; return o.Int;").AsNumber());
  826. // but null and undefined should be injected as nulls to nullable objects
  827. Assert.True(engine.Evaluate("o.NullableInt = null; return o.NullableInt;").IsNull());
  828. Assert.True(engine.Evaluate("o.NullableInt = undefined; return o.NullableInt;").IsNull());
  829. engine.SetValue("func3", new Action<int, double, long>((param1, param2, param3) =>
  830. {
  831. Assert.Equal(1, param1);
  832. Assert.Equal(42, param2);
  833. Assert.Equal(3, param3);
  834. }));
  835. engine.Evaluate("func3(true, obj, [ 1, 2, 3].length)");
  836. Assert.Equal(1, engine.Evaluate("o.SetInt(true); return o.Int;").AsNumber());
  837. Assert.Equal(42, engine.Evaluate("o.SetInt(obj); return o.Int;").AsNumber());
  838. Assert.Equal(3, engine.Evaluate("o.SetInt([ 1, 2, 3].length); return o.Int;").AsNumber());
  839. }
  840. [Fact]
  841. public void ShouldAllowStringCoercion()
  842. {
  843. var engine = new Engine(options => { options.Interop.ValueCoercion = ValueCoercionType.String; });
  844. // basic premise, booleans in JS are lower-case, so should the the toString under interop
  845. Assert.Equal("true", engine.Evaluate("'' + true").AsString());
  846. engine.SetValue("o", new TestClass());
  847. Assert.Equal("false", engine.Evaluate("'' + o.Bool").AsString());
  848. Assert.Equal("true", engine.Evaluate("o.Bool = true; o.String = o.Bool; return o.String;").AsString());
  849. Assert.Equal("true", engine.Evaluate("o.String = true; return o.String;").AsString());
  850. engine.SetValue("func1", new Func<bool>(() => true));
  851. Assert.Equal("true", engine.Evaluate("'' + func1()").AsString());
  852. engine.SetValue("func2", new Func<JsValue>(() => JsBoolean.True));
  853. Assert.Equal("true", engine.Evaluate("'' + func2()").AsString());
  854. // but null and undefined should be injected as nulls to c# objects
  855. Assert.True(engine.Evaluate("o.String = null; return o.String;").IsNull());
  856. Assert.True(engine.Evaluate("o.String = undefined; return o.String;").IsNull());
  857. Assert.Equal("1,2,3", engine.Evaluate("o.String = [ 1, 2, 3 ]; return o.String;").AsString());
  858. engine.Evaluate("class MyClass { toString() { return 'hello world'; } }");
  859. Assert.Equal("hello world", engine.Evaluate("let obj = new MyClass(); o.String = obj; return o.String;").AsString());
  860. engine.SetValue("func3", new Action<string, string, string>((param1, param2, param3) =>
  861. {
  862. Assert.Equal("true", param1);
  863. Assert.Equal("hello world", param2);
  864. Assert.Equal("1,2,3", param3);
  865. }));
  866. engine.Evaluate("func3(true, obj, [ 1, 2, 3])");
  867. Assert.Equal("true", engine.Evaluate("o.SetString(true); return o.String;").AsString());
  868. Assert.Equal("hello world", engine.Evaluate("o.SetString(obj); return o.String;").AsString());
  869. Assert.Equal("1,2,3", engine.Evaluate("o.SetString([ 1, 2, 3]); return o.String;").AsString());
  870. }
  871. [Fact]
  872. public void ShouldConvertDateInstanceToDateTime()
  873. {
  874. var result = _engine.Evaluate("new Date(0)");
  875. var value = result.ToObject();
  876. Assert.Equal(typeof(DateTime), value.GetType());
  877. Assert.Equal(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), value);
  878. }
  879. [Fact]
  880. public void ShouldConvertNumberInstanceToDouble()
  881. {
  882. var result = _engine.Evaluate("new Number(10)");
  883. var value = result.ToObject();
  884. Assert.Equal(typeof(double), value.GetType());
  885. Assert.Equal(10d, value);
  886. }
  887. [Fact]
  888. public void ShouldConvertStringInstanceToString()
  889. {
  890. var value = _engine.Evaluate("new String('foo')").ToObject();
  891. Assert.Equal(typeof(string), value.GetType());
  892. Assert.Equal("foo", value);
  893. }
  894. [Fact]
  895. public void ShouldNotTryToConvertCompatibleTypes()
  896. {
  897. _engine.SetValue("a", new A());
  898. RunTest(@"
  899. assert(a.Call3('foo') === 'foo');
  900. assert(a.Call3(1) === '1');
  901. ");
  902. }
  903. [Fact]
  904. public void ShouldNotTryToConvertDerivedTypes()
  905. {
  906. _engine.SetValue("a", new A());
  907. _engine.SetValue("p", new Person { Name = "Mickey" });
  908. RunTest(@"
  909. assert(a.Call4(p) === 'Mickey');
  910. ");
  911. }
  912. [Fact]
  913. public void ShouldExecuteFunctionCallBackAsDelegate()
  914. {
  915. _engine.SetValue("a", new A());
  916. RunTest(@"
  917. assert(a.Call5(function(a,b){ return a+b }) === '1foo');
  918. ");
  919. }
  920. [Fact]
  921. public void ShouldExecuteFunctionCallBackAsFuncAndThisCanBeAssigned()
  922. {
  923. _engine.SetValue("a", new A());
  924. RunTest(@"
  925. assert(a.Call6(function(a,b){ return this+a+b }) === 'bar1foo');
  926. ");
  927. }
  928. [Fact]
  929. public void ShouldExecuteFunctionCallBackAsPredicate()
  930. {
  931. _engine.SetValue("a", new A());
  932. // Func<>
  933. RunTest(@"
  934. assert(a.Call8(function(){ return 'foo'; }) === 'foo');
  935. ");
  936. }
  937. [Fact]
  938. public void ShouldExecuteFunctionWithParameterCallBackAsPredicate()
  939. {
  940. _engine.SetValue("a", new A());
  941. // Func<,>
  942. RunTest(@"
  943. assert(a.Call7('foo', function(a){ return a === 'foo'; }) === true);
  944. ");
  945. }
  946. [Fact]
  947. public void ShouldExecuteActionCallBackAsPredicate()
  948. {
  949. _engine.SetValue("a", new A());
  950. // Action
  951. RunTest(@"
  952. var value;
  953. a.Call9(function(){ value = 'foo'; });
  954. assert(value === 'foo');
  955. ");
  956. }
  957. [Fact]
  958. public void ShouldExecuteActionWithParameterCallBackAsPredicate()
  959. {
  960. _engine.SetValue("a", new A());
  961. // Action<>
  962. RunTest(@"
  963. var value;
  964. a.Call10('foo', function(b){ value = b; });
  965. assert(value === 'foo');
  966. ");
  967. }
  968. [Fact]
  969. public void ShouldExecuteActionWithMultipleParametersCallBackAsPredicate()
  970. {
  971. _engine.SetValue("a", new A());
  972. // Action<,>
  973. RunTest(@"
  974. var value;
  975. a.Call11('foo', 'bar', function(a,b){ value = a + b; });
  976. assert(value === 'foobar');
  977. ");
  978. }
  979. [Fact]
  980. public void ShouldExecuteFunc()
  981. {
  982. _engine.SetValue("a", new A());
  983. // Func<int, int>
  984. RunTest(@"
  985. var result = a.Call12(42, function(a){ return a + a; });
  986. assert(result === 84);
  987. ");
  988. }
  989. [Fact]
  990. public void ShouldExecuteActionCallbackOnEventChanged()
  991. {
  992. var collection = new System.Collections.ObjectModel.ObservableCollection<string>();
  993. Assert.True(collection.Count == 0);
  994. _engine.SetValue("collection", collection);
  995. RunTest(@"
  996. var eventAction;
  997. collection.add_CollectionChanged(function(sender, eventArgs) { eventAction = eventArgs.Action; } );
  998. collection.Add('test');
  999. ");
  1000. var eventAction = _engine.GetValue("eventAction").AsNumber();
  1001. Assert.True(eventAction == 0);
  1002. Assert.True(collection.Count == 1);
  1003. }
  1004. [Fact]
  1005. public void ShouldUseSystemIO()
  1006. {
  1007. RunTest(@"
  1008. var filename = System.IO.Path.GetTempFileName();
  1009. var sw = System.IO.File.CreateText(filename);
  1010. sw.Write('Hello World');
  1011. sw.Dispose();
  1012. var content = System.IO.File.ReadAllText(filename);
  1013. System.Console.WriteLine(content);
  1014. assert(content === 'Hello World');
  1015. ");
  1016. }
  1017. [Fact]
  1018. public void ShouldBeInstanceOfTypeReferenceType()
  1019. {
  1020. _engine.SetValue("A", typeof(A));
  1021. RunTest(@"
  1022. var a = new A();
  1023. assert(a instanceof A);
  1024. ");
  1025. }
  1026. [Fact]
  1027. public void ShouldImportNamespace()
  1028. {
  1029. RunTest(@"
  1030. var Shapes = importNamespace('Shapes');
  1031. var circle = new Shapes.Circle();
  1032. assert(circle.Radius === 0);
  1033. assert(circle.Perimeter() === 0);
  1034. ");
  1035. }
  1036. [Fact]
  1037. public void ShouldConstructReferenceTypeWithParameters()
  1038. {
  1039. RunTest(@"
  1040. var Shapes = importNamespace('Shapes');
  1041. var circle = new Shapes.Circle(1);
  1042. assert(circle.Radius === 1);
  1043. assert(circle.Perimeter() === Math.PI);
  1044. ");
  1045. }
  1046. [Fact]
  1047. public void ShouldConstructValueTypeWithoutParameters()
  1048. {
  1049. RunTest(@"
  1050. var guid = new System.Guid();
  1051. assert('00000000-0000-0000-0000-000000000000' === guid.ToString());
  1052. ");
  1053. }
  1054. [Fact]
  1055. public void ShouldInvokeAFunctionByName()
  1056. {
  1057. RunTest(@"
  1058. function add(x, y) { return x + y; }
  1059. ");
  1060. Assert.Equal(3, _engine.Invoke("add", 1, 2));
  1061. }
  1062. [Fact]
  1063. public void ShouldNotInvokeNonFunctionValue()
  1064. {
  1065. RunTest(@"
  1066. var x= 10;
  1067. ");
  1068. Assert.Throws<JavaScriptException>(() => _engine.Invoke("x", 1, 2));
  1069. }
  1070. [Fact]
  1071. public void CanGetField()
  1072. {
  1073. var o = new ClassWithField
  1074. {
  1075. Field = "Mickey Mouse"
  1076. };
  1077. _engine.SetValue("o", o);
  1078. RunTest(@"
  1079. assert(o.Field === 'Mickey Mouse');
  1080. ");
  1081. }
  1082. [Fact]
  1083. public void CanSetField()
  1084. {
  1085. var o = new ClassWithField();
  1086. _engine.SetValue("o", o);
  1087. RunTest(@"
  1088. o.Field = 'Mickey Mouse';
  1089. assert(o.Field === 'Mickey Mouse');
  1090. ");
  1091. Assert.Equal("Mickey Mouse", o.Field);
  1092. }
  1093. [Fact]
  1094. public void CanGetStaticField()
  1095. {
  1096. RunTest(@"
  1097. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1098. var statics = domain.ClassWithStaticFields;
  1099. assert(statics.Get == 'Get');
  1100. ");
  1101. }
  1102. [Fact]
  1103. public void CanSetStaticField()
  1104. {
  1105. RunTest(@"
  1106. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1107. var statics = domain.ClassWithStaticFields;
  1108. statics.Set = 'hello';
  1109. assert(statics.Set == 'hello');
  1110. ");
  1111. Assert.Equal(ClassWithStaticFields.Set, "hello");
  1112. }
  1113. [Fact]
  1114. public void CanGetStaticAccessor()
  1115. {
  1116. RunTest(@"
  1117. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1118. var statics = domain.ClassWithStaticFields;
  1119. assert(statics.Getter == 'Getter');
  1120. ");
  1121. }
  1122. [Fact]
  1123. public void CanSetStaticAccessor()
  1124. {
  1125. RunTest(@"
  1126. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1127. var statics = domain.ClassWithStaticFields;
  1128. statics.Setter = 'hello';
  1129. assert(statics.Setter == 'hello');
  1130. ");
  1131. Assert.Equal(ClassWithStaticFields.Setter, "hello");
  1132. }
  1133. [Fact]
  1134. public void CantSetStaticReadonly()
  1135. {
  1136. RunTest(@"
  1137. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1138. var statics = domain.ClassWithStaticFields;
  1139. statics.Readonly = 'hello';
  1140. assert(statics.Readonly == 'Readonly');
  1141. ");
  1142. Assert.Equal(ClassWithStaticFields.Readonly, "Readonly");
  1143. }
  1144. [Fact]
  1145. public void CanSetCustomConverters()
  1146. {
  1147. var engine1 = new Engine();
  1148. engine1.SetValue("p", new { Test = true });
  1149. engine1.Execute("var result = p.Test;");
  1150. Assert.True((bool) engine1.GetValue("result").ToObject());
  1151. var engine2 = new Engine(o => o.AddObjectConverter(new NegateBoolConverter()));
  1152. engine2.SetValue("p", new { Test = true });
  1153. engine2.Execute("var result = p.Test;");
  1154. Assert.False((bool) engine2.GetValue("result").ToObject());
  1155. }
  1156. [Fact]
  1157. public void CanConvertEnumsToString()
  1158. {
  1159. var engine1 = new Engine(o => o.AddObjectConverter(new EnumsToStringConverter()))
  1160. .SetValue("assert", new Action<bool>(Assert.True));
  1161. engine1.SetValue("p", new { Comparison = StringComparison.CurrentCulture });
  1162. engine1.Execute("assert(p.Comparison === 'CurrentCulture');");
  1163. engine1.Execute("var result = p.Comparison;");
  1164. Assert.Equal("CurrentCulture", (string) engine1.GetValue("result").ToObject());
  1165. }
  1166. [Fact]
  1167. public void CanUserIncrementOperator()
  1168. {
  1169. var p = new Person
  1170. {
  1171. Age = 1
  1172. };
  1173. _engine.SetValue("p", p);
  1174. RunTest(@"
  1175. assert(++p.Age === 2);
  1176. ");
  1177. Assert.Equal(2, p.Age);
  1178. }
  1179. [Fact]
  1180. public void CanOverwriteValues()
  1181. {
  1182. _engine.SetValue("x", 3);
  1183. _engine.SetValue("x", 4);
  1184. RunTest(@"
  1185. assert(x === 4);
  1186. ");
  1187. }
  1188. [Fact]
  1189. public void ShouldCreateGenericType()
  1190. {
  1191. RunTest(@"
  1192. var ListOfString = System.Collections.Generic.List(System.String);
  1193. var list = new ListOfString();
  1194. list.Add('foo');
  1195. list.Add(1);
  1196. assert(2 === list.Count);
  1197. ");
  1198. }
  1199. [Fact]
  1200. public void EnumComparesByName()
  1201. {
  1202. var o = new
  1203. {
  1204. r = Colors.Red,
  1205. b = Colors.Blue,
  1206. g = Colors.Green,
  1207. b2 = Colors.Red
  1208. };
  1209. _engine.SetValue("o", o);
  1210. _engine.SetValue("assertFalse", new Action<bool>(Assert.False));
  1211. RunTest(@"
  1212. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1213. var colors = domain.Colors;
  1214. assert(o.r === colors.Red);
  1215. assert(o.g === colors.Green);
  1216. assert(o.b === colors.Blue);
  1217. assertFalse(o.b2 === colors.Blue);
  1218. ");
  1219. }
  1220. [Fact]
  1221. public void ShouldSetEnumProperty()
  1222. {
  1223. var s = new Circle
  1224. {
  1225. Color = Colors.Red
  1226. };
  1227. _engine.SetValue("s", s);
  1228. RunTest(@"
  1229. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1230. var colors = domain.Colors;
  1231. s.Color = colors.Blue;
  1232. assert(s.Color === colors.Blue);
  1233. ");
  1234. _engine.SetValue("s", s);
  1235. RunTest(@"
  1236. s.Color = colors.Blue | colors.Green;
  1237. assert(s.Color === colors.Blue | colors.Green);
  1238. ");
  1239. Assert.Equal(Colors.Blue | Colors.Green, s.Color);
  1240. }
  1241. private enum TestEnumInt32 : int
  1242. {
  1243. None,
  1244. One = 1,
  1245. Min = int.MaxValue,
  1246. Max = int.MaxValue
  1247. }
  1248. private enum TestEnumUInt32 : uint
  1249. {
  1250. None,
  1251. One = 1,
  1252. Min = uint.MaxValue,
  1253. Max = uint.MaxValue
  1254. }
  1255. private enum TestEnumInt64 : long
  1256. {
  1257. None,
  1258. One = 1,
  1259. Min = long.MaxValue,
  1260. Max = long.MaxValue
  1261. }
  1262. private enum TestEnumUInt64 : ulong
  1263. {
  1264. None,
  1265. One = 1,
  1266. Min = ulong.MaxValue,
  1267. Max = ulong.MaxValue
  1268. }
  1269. private void TestEnum<T>(T enumValue)
  1270. {
  1271. var i = Convert.ChangeType(enumValue, Enum.GetUnderlyingType(typeof(T)));
  1272. var s = Convert.ToString(i, CultureInfo.InvariantCulture);
  1273. var o = new Tuple<T>(enumValue);
  1274. _engine.SetValue("o", o);
  1275. RunTest("assert(o.Item1 === " + s + ");");
  1276. }
  1277. [Fact]
  1278. public void ShouldWorkWithEnumInt32()
  1279. {
  1280. TestEnum(TestEnumInt32.None);
  1281. TestEnum(TestEnumInt32.One);
  1282. TestEnum(TestEnumInt32.Min);
  1283. TestEnum(TestEnumInt32.Max);
  1284. }
  1285. [Fact]
  1286. public void ShouldWorkWithEnumUInt32()
  1287. {
  1288. TestEnum(TestEnumUInt32.None);
  1289. TestEnum(TestEnumUInt32.One);
  1290. TestEnum(TestEnumUInt32.Min);
  1291. TestEnum(TestEnumUInt32.Max);
  1292. }
  1293. [Fact]
  1294. public void ShouldWorkWithEnumInt64()
  1295. {
  1296. TestEnum(TestEnumInt64.None);
  1297. TestEnum(TestEnumInt64.One);
  1298. TestEnum(TestEnumInt64.Min);
  1299. TestEnum(TestEnumInt64.Max);
  1300. }
  1301. [Fact]
  1302. public void ShouldWorkWithEnumUInt64()
  1303. {
  1304. TestEnum(TestEnumUInt64.None);
  1305. TestEnum(TestEnumUInt64.One);
  1306. TestEnum(TestEnumUInt64.Min);
  1307. TestEnum(TestEnumUInt64.Max);
  1308. }
  1309. [Fact]
  1310. public void EnumIsConvertedToNumber()
  1311. {
  1312. var o = new
  1313. {
  1314. r = Colors.Red,
  1315. b = Colors.Blue,
  1316. g = Colors.Green
  1317. };
  1318. _engine.SetValue("o", o);
  1319. RunTest(@"
  1320. assert(o.r === 0);
  1321. assert(o.g === 1);
  1322. assert(o.b === 10);
  1323. ");
  1324. }
  1325. [Fact]
  1326. public void ShouldConvertToEnum()
  1327. {
  1328. var s = new Circle
  1329. {
  1330. Color = Colors.Red
  1331. };
  1332. _engine.SetValue("s", s);
  1333. RunTest(@"
  1334. assert(s.Color === 0);
  1335. s.Color = 10;
  1336. assert(s.Color === 10);
  1337. ");
  1338. _engine.SetValue("s", s);
  1339. RunTest(@"
  1340. s.Color = 11;
  1341. assert(s.Color === 11);
  1342. ");
  1343. Assert.Equal(Colors.Blue | Colors.Green, s.Color);
  1344. }
  1345. [Fact]
  1346. public void ShouldUseExplicitPropertyGetter()
  1347. {
  1348. _engine.SetValue("c", new Company("ACME"));
  1349. RunTest(@"
  1350. assert(c.Name === 'ACME');
  1351. ");
  1352. }
  1353. [Fact]
  1354. public void ShouldUseExplicitIndexerPropertyGetter()
  1355. {
  1356. var company = new Company("ACME");
  1357. ((ICompany) company)["Foo"] = "Bar";
  1358. _engine.SetValue("c", company);
  1359. RunTest(@"
  1360. assert(c.Foo === 'Bar');
  1361. ");
  1362. }
  1363. [Fact]
  1364. public void ShouldUseExplicitPropertySetter()
  1365. {
  1366. _engine.SetValue("c", new Company("ACME"));
  1367. RunTest(@"
  1368. c.Name = 'Foo';
  1369. assert(c.Name === 'Foo');
  1370. ");
  1371. }
  1372. [Fact]
  1373. public void ShouldUseExplicitIndexerPropertySetter()
  1374. {
  1375. var company = new Company("ACME");
  1376. ((ICompany) company)["Foo"] = "Bar";
  1377. _engine.SetValue("c", company);
  1378. RunTest(@"
  1379. c.Foo = 'Baz';
  1380. assert(c.Foo === 'Baz');
  1381. ");
  1382. }
  1383. [Fact]
  1384. public void ShouldUseExplicitMethod()
  1385. {
  1386. _engine.SetValue("c", new Company("ACME"));
  1387. RunTest(@"
  1388. assert(0 === c.CompareTo(c));
  1389. ");
  1390. }
  1391. [Fact]
  1392. public void ShouldCallInstanceMethodWithParams()
  1393. {
  1394. _engine.SetValue("a", new A());
  1395. RunTest(@"
  1396. assert(a.Call13('1','2','3') === '1,2,3');
  1397. assert(a.Call13('1') === '1');
  1398. assert(a.Call13(1) === '1');
  1399. assert(a.Call13() === '');
  1400. assert(a.Call14('a','1','2','3') === 'a:1,2,3');
  1401. assert(a.Call14('a','1') === 'a:1');
  1402. assert(a.Call14('a') === 'a:');
  1403. function call13wrapper(){ return a.Call13.apply(a, Array.prototype.slice.call(arguments)); }
  1404. assert(call13wrapper('1','2','3') === '1,2,3');
  1405. assert(a.Call13('1','2','3') === a.Call13(['1','2','3']));
  1406. ");
  1407. }
  1408. [Fact]
  1409. public void ShouldCallInstanceMethodWithJsValueParams()
  1410. {
  1411. _engine.SetValue("a", new A());
  1412. RunTest(@"
  1413. assert(a.Call16('1','2','3') === '1,2,3');
  1414. assert(a.Call16('1') === '1');
  1415. assert(a.Call16(1) === '1');
  1416. assert(a.Call16() === '');
  1417. assert(a.Call16('1','2','3') === a.Call16(['1','2','3']));
  1418. ");
  1419. }
  1420. [Fact]
  1421. public void NullValueAsArgumentShouldWork()
  1422. {
  1423. _engine.SetValue("a", new A());
  1424. RunTest(@"
  1425. var x = a.Call2(null);
  1426. assert(x === null);
  1427. ");
  1428. }
  1429. [Fact]
  1430. public void ShouldSetPropertyToNull()
  1431. {
  1432. var p = new Person { Name = "Mickey" };
  1433. _engine.SetValue("p", p);
  1434. RunTest(@"
  1435. assert(p.Name != null);
  1436. p.Name = null;
  1437. assert(p.Name == null);
  1438. ");
  1439. Assert.True(p.Name == null);
  1440. }
  1441. [Fact]
  1442. public void ShouldCallMethodWithNull()
  1443. {
  1444. _engine.SetValue("a", new A());
  1445. RunTest(@"
  1446. a.Call15(null);
  1447. var result = a.Call2(null);
  1448. assert(result == null);
  1449. ");
  1450. }
  1451. [Fact]
  1452. public void ShouldReturnUndefinedProperty()
  1453. {
  1454. _engine.SetValue("uo", new { foo = "bar" });
  1455. _engine.SetValue("ud", new Dictionary<string, object> { { "foo", "bar" } });
  1456. _engine.SetValue("ul", new List<string> { "foo", "bar" });
  1457. RunTest(@"
  1458. assert(!uo.undefinedProperty);
  1459. assert(!ul[5]);
  1460. assert(!ud.undefinedProperty);
  1461. ");
  1462. }
  1463. private class FailingObject2
  1464. {
  1465. public int this[int index] => throw new ArgumentException("index is bad", nameof(index));
  1466. }
  1467. [Fact]
  1468. public void ShouldPropagateIndexerExceptions()
  1469. {
  1470. var engine = new Engine();
  1471. engine.Execute(@"function f2(obj) { return obj[1]; }");
  1472. var failingObject = new FailingObject2();
  1473. Assert.Throws<ArgumentException>(() => engine.Invoke("f2", failingObject));
  1474. }
  1475. [Fact]
  1476. public void ShouldAutomaticallyConvertArraysToFindBestInteropResolution()
  1477. {
  1478. _engine.SetValue("a", new ArrayConverterTestClass());
  1479. _engine.SetValue("item1", new ArrayConverterItem(1));
  1480. _engine.SetValue("item2", new ArrayConverterItem(2));
  1481. RunTest(@"
  1482. assert(a.MethodAcceptsArrayOfInt([false, '1', 2]) === a.MethodAcceptsArrayOfInt([0, 1, 2]));
  1483. assert(a.MethodAcceptsArrayOfStrings(['1', 2]) === a.MethodAcceptsArrayOfStrings([1, 2]));
  1484. assert(a.MethodAcceptsArrayOfBool(['1', 0]) === a.MethodAcceptsArrayOfBool([true, false]));
  1485. assert(a.MethodAcceptsArrayOfStrings([item1, item2]) === a.MethodAcceptsArrayOfStrings(['1', '2']));
  1486. assert(a.MethodAcceptsArrayOfInt([item1, item2]) === a.MethodAcceptsArrayOfInt([1, 2]));
  1487. ");
  1488. }
  1489. [Fact]
  1490. public void ShouldImportNamespaceNestedType()
  1491. {
  1492. RunTest(@"
  1493. var shapes = importNamespace('Shapes.Circle');
  1494. var kinds = shapes.Kind;
  1495. assert(kinds.Unit === 0);
  1496. assert(kinds.Ellipse === 1);
  1497. assert(kinds.Round === 5);
  1498. ");
  1499. }
  1500. [Fact]
  1501. public void ShouldImportNamespaceNestedNestedType()
  1502. {
  1503. RunTest(@"
  1504. var meta = importNamespace('Shapes.Circle.Meta');
  1505. var usages = meta.Usage;
  1506. assert(usages.Public === 0);
  1507. assert(usages.Private === 1);
  1508. assert(usages.Internal === 11);
  1509. ");
  1510. }
  1511. [Fact]
  1512. public void ShouldGetNestedNestedProp()
  1513. {
  1514. RunTest(@"
  1515. var meta = importNamespace('Shapes.Circle');
  1516. var m = new meta.Meta();
  1517. assert(m.Description === 'descp');
  1518. ");
  1519. }
  1520. [Fact]
  1521. public void ShouldSetNestedNestedProp()
  1522. {
  1523. RunTest(@"
  1524. var meta = importNamespace('Shapes.Circle');
  1525. var m = new meta.Meta();
  1526. m.Description = 'hello';
  1527. assert(m.Description === 'hello');
  1528. ");
  1529. }
  1530. [Fact]
  1531. public void CanGetStaticNestedField()
  1532. {
  1533. RunTest(@"
  1534. var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
  1535. var statics = domain.ClassWithStaticFields;
  1536. assert(statics.Get == 'Get');
  1537. ");
  1538. }
  1539. [Fact]
  1540. public void CanSetStaticNestedField()
  1541. {
  1542. RunTest(@"
  1543. var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
  1544. var statics = domain.ClassWithStaticFields;
  1545. statics.Set = 'hello';
  1546. assert(statics.Set == 'hello');
  1547. ");
  1548. Assert.Equal(Nested.ClassWithStaticFields.Set, "hello");
  1549. }
  1550. [Fact]
  1551. public void CanGetStaticNestedAccessor()
  1552. {
  1553. RunTest(@"
  1554. var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
  1555. var statics = domain.ClassWithStaticFields;
  1556. assert(statics.Getter == 'Getter');
  1557. ");
  1558. }
  1559. [Fact]
  1560. public void CanSetStaticNestedAccessor()
  1561. {
  1562. RunTest(@"
  1563. var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
  1564. var statics = domain.ClassWithStaticFields;
  1565. statics.Setter = 'hello';
  1566. assert(statics.Setter == 'hello');
  1567. ");
  1568. Assert.Equal(Nested.ClassWithStaticFields.Setter, "hello");
  1569. }
  1570. [Fact]
  1571. public void CantSetStaticNestedReadonly()
  1572. {
  1573. RunTest(@"
  1574. var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
  1575. var statics = domain.ClassWithStaticFields;
  1576. statics.Readonly = 'hello';
  1577. assert(statics.Readonly == 'Readonly');
  1578. ");
  1579. Assert.Equal(Nested.ClassWithStaticFields.Readonly, "Readonly");
  1580. }
  1581. [Fact]
  1582. public void ShouldExecuteFunctionWithValueTypeParameterCorrectly()
  1583. {
  1584. _engine.SetValue("a", new A());
  1585. // Func<int, int>
  1586. RunTest(@"
  1587. assert(a.Call17(function(value){ return value; }) === 17);
  1588. ");
  1589. }
  1590. [Fact]
  1591. public void ShouldExecuteActionWithValueTypeParameterCorrectly()
  1592. {
  1593. _engine.SetValue("a", new A());
  1594. // Action<int>
  1595. RunTest(@"
  1596. a.Call18(function(value){ assert(value === 18); });
  1597. ");
  1598. }
  1599. [Fact]
  1600. public void ShouldConvertToJsValue()
  1601. {
  1602. RunTest(@"
  1603. var now = System.DateTime.Now;
  1604. assert(new String(now) == now.toString());
  1605. var zero = System.Int32.MaxValue;
  1606. assert(new String(zero) == zero.toString());
  1607. ");
  1608. }
  1609. [Fact]
  1610. public void ShouldNotCatchClrExceptions()
  1611. {
  1612. var engine = new Engine()
  1613. .SetValue("throwMyException", new Action(() => { throw new NotSupportedException(); }))
  1614. .SetValue("Thrower", typeof(Thrower))
  1615. .Execute(@"
  1616. function throwException1(){
  1617. try {
  1618. throwMyException();
  1619. return;
  1620. }
  1621. catch(e) {
  1622. return;
  1623. }
  1624. }
  1625. function throwException2(){
  1626. try {
  1627. new Thrower().ThrowNotSupportedException();
  1628. return;
  1629. }
  1630. catch(e) {
  1631. return;
  1632. }
  1633. }
  1634. ");
  1635. Assert.ThrowsAny<NotSupportedException>(() => engine.Invoke("throwException1"));
  1636. Assert.ThrowsAny<NotSupportedException>(() => engine.Invoke("throwException2"));
  1637. }
  1638. [Fact]
  1639. public void ShouldCatchAllClrExceptions()
  1640. {
  1641. var exceptionMessage = "myExceptionMessage";
  1642. var engine = new Engine(o => o.CatchClrExceptions())
  1643. .SetValue("throwMyException", new Action(() => { throw new Exception(exceptionMessage); }))
  1644. .SetValue("Thrower", typeof(Thrower))
  1645. .Execute(@"
  1646. function throwException1(){
  1647. try {
  1648. throwMyException();
  1649. return '';
  1650. }
  1651. catch(e) {
  1652. return e.message;
  1653. }
  1654. }
  1655. function throwException2(){
  1656. try {
  1657. new Thrower().ThrowExceptionWithMessage('myExceptionMessage');
  1658. return;
  1659. }
  1660. catch(e) {
  1661. return e.message;
  1662. }
  1663. }
  1664. ");
  1665. Assert.Equal(engine.Invoke("throwException1").AsString(), exceptionMessage);
  1666. Assert.Equal(engine.Invoke("throwException2").AsString(), exceptionMessage);
  1667. }
  1668. private class MemberExceptionTest
  1669. {
  1670. public MemberExceptionTest(bool throwOnCreate)
  1671. {
  1672. if (throwOnCreate)
  1673. {
  1674. throw new InvalidOperationException("thrown as requested");
  1675. }
  1676. }
  1677. public JsValue ThrowingProperty1
  1678. {
  1679. get => throw new InvalidOperationException();
  1680. set => throw new InvalidOperationException();
  1681. }
  1682. public object ThrowingProperty2
  1683. {
  1684. get => throw new InvalidOperationException();
  1685. set => throw new InvalidOperationException();
  1686. }
  1687. public void ThrowingFunction()
  1688. {
  1689. throw new InvalidOperationException();
  1690. }
  1691. }
  1692. [Fact]
  1693. public void ShouldCatchClrMemberExceptions()
  1694. {
  1695. var engine = new Engine(cfg =>
  1696. {
  1697. cfg.AllowClr();
  1698. cfg.CatchClrExceptions();
  1699. });
  1700. engine.SetValue("assert", new Action<bool>(Assert.True));
  1701. engine.SetValue("log", new Action<object>(Console.WriteLine));
  1702. engine.SetValue("create", typeof(MemberExceptionTest));
  1703. engine.SetValue("instance", new MemberExceptionTest(false));
  1704. // Test calling a constructor that throws an exception
  1705. engine.Execute(@"
  1706. try
  1707. {
  1708. create(true);
  1709. assert(false);
  1710. }
  1711. catch (e)
  1712. {
  1713. assert(true);
  1714. }
  1715. ");
  1716. // Test calling a member function that throws an exception
  1717. engine.Execute(@"
  1718. try
  1719. {
  1720. instance.ThrowingFunction();
  1721. assert(false);
  1722. }
  1723. catch (e)
  1724. {
  1725. assert(true);
  1726. }
  1727. ");
  1728. // Test using a property getter that throws an exception
  1729. engine.Execute(@"
  1730. try
  1731. {
  1732. log(o.ThrowingProperty);
  1733. assert(false);
  1734. }
  1735. catch (e)
  1736. {
  1737. assert(true);
  1738. }
  1739. ");
  1740. // Test using a property setter that throws an exception
  1741. engine.Execute(@"
  1742. try
  1743. {
  1744. instance.ThrowingProperty1 = 123;
  1745. assert(false);
  1746. }
  1747. catch (e)
  1748. {
  1749. assert(true);
  1750. }
  1751. try
  1752. {
  1753. instance.ThrowingProperty2 = 456;
  1754. assert(false);
  1755. }
  1756. catch (e)
  1757. {
  1758. assert(true);
  1759. }
  1760. ");
  1761. }
  1762. [Fact]
  1763. public void ShouldCatchSomeExceptions()
  1764. {
  1765. var exceptionMessage = "myExceptionMessage";
  1766. var engine = new Engine(o => o.CatchClrExceptions(e => e is NotSupportedException))
  1767. .SetValue("throwMyException1", new Action(() => { throw new NotSupportedException(exceptionMessage); }))
  1768. .SetValue("throwMyException2", new Action(() => { throw new ArgumentNullException(); }))
  1769. .SetValue("Thrower", typeof(Thrower))
  1770. .Execute(@"
  1771. function throwException1(){
  1772. try {
  1773. throwMyException1();
  1774. return '';
  1775. }
  1776. catch(e) {
  1777. return e.message;
  1778. }
  1779. }
  1780. function throwException2(){
  1781. try {
  1782. throwMyException2();
  1783. return '';
  1784. }
  1785. catch(e) {
  1786. return e.message;
  1787. }
  1788. }
  1789. function throwException3(){
  1790. try {
  1791. new Thrower().ThrowNotSupportedExceptionWithMessage('myExceptionMessage');
  1792. return '';
  1793. }
  1794. catch(e) {
  1795. return e.message;
  1796. }
  1797. }
  1798. function throwException4(){
  1799. try {
  1800. new Thrower().ThrowArgumentNullException();
  1801. return '';
  1802. }
  1803. catch(e) {
  1804. return e.message;
  1805. }
  1806. }
  1807. ");
  1808. Assert.Equal(engine.Invoke("throwException1").AsString(), exceptionMessage);
  1809. Assert.Throws<ArgumentNullException>(() => engine.Invoke("throwException2"));
  1810. Assert.Equal(engine.Invoke("throwException3").AsString(), exceptionMessage);
  1811. Assert.Throws<ArgumentNullException>(() => engine.Invoke("throwException4"));
  1812. }
  1813. [Fact]
  1814. public void ArrayFromShouldConvertListToArrayLike()
  1815. {
  1816. var list = new List<Person>
  1817. {
  1818. new Person { Name = "Mike" },
  1819. new Person { Name = "Mika" }
  1820. };
  1821. _engine.SetValue("a", list);
  1822. RunTest(@"
  1823. var arr = new Array(a);
  1824. assert(arr.length === 2);
  1825. assert(arr[0].Name === 'Mike');
  1826. assert(arr[1].Name === 'Mika');
  1827. ");
  1828. RunTest(@"
  1829. var arr = Array.from(a);
  1830. assert(arr.length === 2);
  1831. assert(arr[0].Name === 'Mike');
  1832. assert(arr[1].Name === 'Mika');
  1833. ");
  1834. }
  1835. [Fact]
  1836. public void ArrayFromShouldConvertArrayToArrayLike()
  1837. {
  1838. var list = new[]
  1839. {
  1840. new Person { Name = "Mike" },
  1841. new Person { Name = "Mika" }
  1842. };
  1843. _engine.SetValue("a", list);
  1844. RunTest(@"
  1845. var arr = new Array(a);
  1846. assert(arr.length === 2);
  1847. assert(arr[0].Name === 'Mike');
  1848. assert(arr[1].Name === 'Mika');
  1849. ");
  1850. RunTest(@"
  1851. var arr = Array.from(a);
  1852. assert(arr.length === 2);
  1853. assert(arr[0].Name === 'Mike');
  1854. assert(arr[1].Name === 'Mika');
  1855. ");
  1856. }
  1857. [Fact]
  1858. public void ArrayFromShouldConvertIEnumerable()
  1859. {
  1860. var enumerable = new[]
  1861. {
  1862. new Person { Name = "Mike" },
  1863. new Person { Name = "Mika" }
  1864. }.Select(x => x);
  1865. _engine.SetValue("a", enumerable);
  1866. RunTest(@"
  1867. var arr = new Array(a);
  1868. assert(arr.length === 2);
  1869. assert(arr[0].Name === 'Mike');
  1870. assert(arr[1].Name === 'Mika');
  1871. ");
  1872. RunTest(@"
  1873. var arr = Array.from(a);
  1874. assert(arr.length === 2);
  1875. assert(arr[0].Name === 'Mike');
  1876. assert(arr[1].Name === 'Mika');
  1877. ");
  1878. }
  1879. [Fact]
  1880. public void ShouldBeAbleToPlusAssignStringProperty()
  1881. {
  1882. var p = new Person();
  1883. var engine = new Engine();
  1884. engine.SetValue("P", p);
  1885. engine.Evaluate("P.Name = 'b';");
  1886. engine.Evaluate("P.Name += 'c';");
  1887. Assert.Equal("bc", p.Name);
  1888. }
  1889. [Fact]
  1890. public void ShouldNotResolveToPrimitiveSymbol()
  1891. {
  1892. var engine = new Engine(options =>
  1893. options.AllowClr(typeof(FloatIndexer).GetTypeInfo().Assembly));
  1894. var c = engine.Evaluate(@"
  1895. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1896. return new domain.FloatIndexer();
  1897. ");
  1898. Assert.NotNull(c.ToString());
  1899. Assert.Equal((uint) 0, c.As<ObjectInstance>().Length);
  1900. }
  1901. private class DictionaryWrapper
  1902. {
  1903. public IDictionary<string, object> Values { get; set; }
  1904. }
  1905. private class DictionaryTest
  1906. {
  1907. public void Test1(IDictionary<string, object> values)
  1908. {
  1909. Assert.Equal(1, Convert.ToInt32(values["a"]));
  1910. }
  1911. public void Test2(DictionaryWrapper dictionaryObject)
  1912. {
  1913. Assert.Equal(1, Convert.ToInt32(dictionaryObject.Values["a"]));
  1914. }
  1915. }
  1916. [Fact]
  1917. public void ShouldBeAbleToPassDictionaryToMethod()
  1918. {
  1919. var engine = new Engine();
  1920. engine.SetValue("dictionaryTest", new DictionaryTest());
  1921. engine.Evaluate("dictionaryTest.test1({ a: 1 });");
  1922. }
  1923. [Fact]
  1924. public void ShouldBeAbleToPassDictionaryInObjectToMethod()
  1925. {
  1926. var engine = new Engine();
  1927. engine.SetValue("dictionaryTest", new DictionaryTest());
  1928. engine.Evaluate("dictionaryTest.test2({ values: { a: 1 } });");
  1929. }
  1930. [Fact]
  1931. public void ShouldSupportSpreadForDictionary()
  1932. {
  1933. var engine = new Engine();
  1934. var state = new Dictionary<string, object>
  1935. {
  1936. { "invoice", new Dictionary<string, object> { ["number"] = "42" } }
  1937. };
  1938. engine.SetValue("state", state);
  1939. var result = (IDictionary<string, object>) engine
  1940. .Evaluate("({ supplier: 'S1', ...state.invoice })")
  1941. .ToObject();
  1942. Assert.Equal("S1", result["supplier"]);
  1943. Assert.Equal("42", result["number"]);
  1944. }
  1945. [Fact]
  1946. public void ShouldSupportSpreadForDictionary2()
  1947. {
  1948. var engine = new Engine();
  1949. var state = new Dictionary<string, object>
  1950. {
  1951. { "invoice", new Dictionary<string, object> { ["number"] = "42" } }
  1952. };
  1953. engine.SetValue("state", state);
  1954. var result = (IDictionary<string, object>) engine
  1955. .Execute("function getValue() { return {supplier: 'S1', ...state.invoice}; }")
  1956. .Invoke("getValue")
  1957. .ToObject();
  1958. Assert.Equal("S1", result["supplier"]);
  1959. Assert.Equal("42", result["number"]);
  1960. }
  1961. [Fact]
  1962. public void ShouldSupportSpreadForObject()
  1963. {
  1964. var engine = new Engine();
  1965. var person = new Person
  1966. {
  1967. Name = "Mike",
  1968. Age = 20
  1969. };
  1970. engine.SetValue("p", person);
  1971. var result = (IDictionary<string, object>) engine
  1972. .Evaluate("({ supplier: 'S1', ...p })")
  1973. .ToObject();
  1974. Assert.Equal("S1", result["supplier"]);
  1975. Assert.Equal("Mike", result["Name"]);
  1976. Assert.Equal(20d, result["Age"]);
  1977. }
  1978. [Fact]
  1979. public void ShouldBeAbleToJsonStringifyClrObjects()
  1980. {
  1981. var engine = new Engine();
  1982. engine.Evaluate("var jsObj = { 'key1' :'value1', 'key2' : 'value2' }");
  1983. engine.SetValue("netObj", new Dictionary<string, object>
  1984. {
  1985. { "key1", "value1" },
  1986. { "key2", "value2" }
  1987. });
  1988. var jsValue = engine.Evaluate("jsObj['key1']").AsString();
  1989. var clrValue = engine.Evaluate("netObj['key1']").AsString();
  1990. Assert.Equal(jsValue, clrValue);
  1991. jsValue = engine.Evaluate("JSON.stringify(jsObj)").AsString();
  1992. clrValue = engine.Evaluate("JSON.stringify(netObj)").AsString();
  1993. Assert.Equal(jsValue, clrValue);
  1994. // Write properties on screen using showProps function defined on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
  1995. engine.Execute(@"function showProps(obj, objName) {
  1996. var result = """";
  1997. for (var i in obj) {
  1998. if (obj.hasOwnProperty(i)) {
  1999. result += objName + ""."" + i + "" = "" + obj[i] + ""\n"";
  2000. }
  2001. }
  2002. return result;
  2003. }");
  2004. jsValue = engine.Evaluate("showProps(jsObj, 'theObject')").AsString();
  2005. clrValue = engine.Evaluate("showProps(jsObj, 'theObject')").AsString();
  2006. Assert.Equal(jsValue, clrValue);
  2007. }
  2008. [Fact]
  2009. public void SettingValueViaIntegerIndexer()
  2010. {
  2011. var engine = new Engine(cfg => cfg.AllowClr(typeof(FloatIndexer).GetTypeInfo().Assembly));
  2012. engine.SetValue("log", new Action<object>(Console.WriteLine));
  2013. engine.Execute(@"
  2014. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  2015. var fia = new domain.IntegerIndexer();
  2016. log(fia[0]);
  2017. ");
  2018. Assert.Equal(123, engine.Evaluate("fia[0]").AsNumber());
  2019. engine.Evaluate("fia[0] = 678;");
  2020. Assert.Equal(678, engine.Evaluate("fia[0]").AsNumber());
  2021. }
  2022. [Fact]
  2023. public void IndexingBsonProperties()
  2024. {
  2025. const string jsonAnimals = @" { ""Animals"": [ { ""Id"": 1, ""Type"": ""Cat"" } ] }";
  2026. var bsonAnimals = BsonDocument.Parse(jsonAnimals);
  2027. _engine.SetValue("animals", bsonAnimals["Animals"]);
  2028. // weak equality does conversions from native types
  2029. Assert.True(_engine.Evaluate("animals[0].Type == 'Cat'").AsBoolean());
  2030. Assert.True(_engine.Evaluate("animals[0].Id == 1").AsBoolean());
  2031. }
  2032. [Fact]
  2033. public void IntegerEnumResolutionShouldWork()
  2034. {
  2035. var engine = new Engine(options => options.AllowClr(GetType().Assembly));
  2036. engine.SetValue("a", new OverLoading());
  2037. engine.SetValue("E", TypeReference.CreateTypeReference(engine, typeof(IntegerEnum)));
  2038. Assert.Equal("integer-enum", engine.Evaluate("a.testFunc(E.a);").AsString());
  2039. }
  2040. [Fact]
  2041. public void UnsignedIntegerEnumResolutionShouldWork()
  2042. {
  2043. var engine = new Engine(options => options.AllowClr(GetType().Assembly));
  2044. engine.SetValue("E", TypeReference.CreateTypeReference(engine, typeof(UintEnum)));
  2045. Assert.Equal(1, engine.Evaluate("E.b;").AsNumber());
  2046. }
  2047. public class TestItem
  2048. {
  2049. public double Cost { get; set; }
  2050. public double Age { get; set; }
  2051. public string Name { get; set; }
  2052. }
  2053. public class TestItemList : List<TestItem>
  2054. {
  2055. public double Sum(Func<TestItem, double> calc)
  2056. {
  2057. double rc = 0;
  2058. foreach (var item in this)
  2059. {
  2060. rc += calc(item);
  2061. }
  2062. return rc;
  2063. }
  2064. public TestItemList Where(Func<TestItem, bool> cond)
  2065. {
  2066. var rc = new TestItemList();
  2067. foreach (var item in this)
  2068. {
  2069. if (cond(item))
  2070. {
  2071. rc.Add(item);
  2072. }
  2073. }
  2074. return rc;
  2075. }
  2076. }
  2077. [Fact]
  2078. public void DelegateCanReturnValue()
  2079. {
  2080. var engine = new Engine(options => options.AllowClr(GetType().Assembly));
  2081. var lst = new TestItemList();
  2082. lst.Add(new TestItem() { Name = "a", Cost = 1, Age = 10 });
  2083. lst.Add(new TestItem() { Name = "a", Cost = 1, Age = 10 });
  2084. lst.Add(new TestItem() { Name = "b", Cost = 1, Age = 10 });
  2085. lst.Add(new TestItem() { Name = "b", Cost = 1, Age = 10 });
  2086. lst.Add(new TestItem() { Name = "b", Cost = 1, Age = 10 });
  2087. engine.SetValue("lst", lst);
  2088. Assert.Equal(5, engine.Evaluate("lst.Sum(x => x.Cost);").AsNumber());
  2089. Assert.Equal(50, engine.Evaluate("lst.Sum(x => x.Age);").AsNumber());
  2090. Assert.Equal(3, engine.Evaluate("lst.Where(x => x.Name == 'b').Count;").AsNumber());
  2091. Assert.Equal(30, engine.Evaluate("lst.Where(x => x.Name == 'b').Sum(x => x.Age);").AsNumber());
  2092. }
  2093. [Fact]
  2094. public void ExceptionFromConstructorShouldPropagate()
  2095. {
  2096. _engine.SetValue("Class", TypeReference.CreateTypeReference(_engine, typeof(MemberExceptionTest)));
  2097. var ex = Assert.Throws<InvalidOperationException>(() => _engine.Evaluate("new Class(true);"));
  2098. Assert.Equal("thrown as requested", ex.Message);
  2099. }
  2100. [Fact]
  2101. public void ObjectWrapperOverridingEquality()
  2102. {
  2103. // equality same via name
  2104. _engine.SetValue("a", new Person { Name = "Name" });
  2105. _engine.SetValue("b", new Person { Name = "Name" });
  2106. _engine.Evaluate("const arr = [ null, a, undefined ];");
  2107. Assert.Equal(1, _engine.Evaluate("arr.filter(x => x == b).length").AsNumber());
  2108. Assert.Equal(1, _engine.Evaluate("arr.filter(x => x === b).length").AsNumber());
  2109. Assert.True(_engine.Evaluate("arr.find(x => x == b) === a").AsBoolean());
  2110. Assert.True(_engine.Evaluate("arr.find(x => x === b) == a").AsBoolean());
  2111. Assert.Equal(1, _engine.Evaluate("arr.findIndex(x => x == b)").AsNumber());
  2112. Assert.Equal(1, _engine.Evaluate("arr.findIndex(x => x === b)").AsNumber());
  2113. Assert.Equal(1, _engine.Evaluate("arr.indexOf(b)").AsNumber());
  2114. Assert.True(_engine.Evaluate("arr.includes(b)").AsBoolean());
  2115. }
  2116. [Fact]
  2117. public void ObjectWrapperWrappingDictionaryShouldNotBeArrayLike()
  2118. {
  2119. var wrapper = new ObjectWrapper(_engine, new Dictionary<string, object>());
  2120. Assert.False(wrapper.IsArrayLike);
  2121. }
  2122. [Fact]
  2123. public void ShouldHandleCyclicReferences()
  2124. {
  2125. var engine = new Engine();
  2126. static void Test(string message, object value)
  2127. {
  2128. Console.WriteLine(message);
  2129. }
  2130. engine.Realm.GlobalObject.FastAddProperty("global", engine.Realm.GlobalObject, true, true, true);
  2131. engine.Realm.GlobalObject.FastAddProperty("test", new DelegateWrapper(engine, (Action<string, object>) Test), true, true, true);
  2132. var ex = Assert.Throws<JavaScriptException>(() => engine.Realm.GlobalObject.ToObject());
  2133. Assert.Equal("Cyclic reference detected.", ex.Message);
  2134. ex = Assert.Throws<JavaScriptException>(() =>
  2135. engine.Execute(@"
  2136. var demo={};
  2137. demo.value=1;
  2138. test('Test 1', demo.value===1);
  2139. test('Test 2', demo.value);
  2140. demo.demo=demo;
  2141. test('Test 3', demo);
  2142. test('Test 4', global);"
  2143. )
  2144. );
  2145. Assert.Equal("Cyclic reference detected.", ex.Message);
  2146. }
  2147. [Fact]
  2148. public void CanConfigurePropertyNameMatcher()
  2149. {
  2150. // defaults
  2151. var e = new Engine();
  2152. e.SetValue("a", new A());
  2153. Assert.True(e.Evaluate("a.call1").IsObject());
  2154. Assert.True(e.Evaluate("a.Call1").IsObject());
  2155. Assert.True(e.Evaluate("a.CALL1").IsUndefined());
  2156. e = new Engine(options =>
  2157. {
  2158. options.SetTypeResolver(new TypeResolver
  2159. {
  2160. MemberNameComparer = StringComparer.Ordinal
  2161. });
  2162. });
  2163. e.SetValue("a", new A());
  2164. Assert.True(e.Evaluate("a.call1").IsUndefined());
  2165. Assert.True(e.Evaluate("a.Call1").IsObject());
  2166. Assert.True(e.Evaluate("a.CALL1").IsUndefined());
  2167. e = new Engine(options =>
  2168. {
  2169. options.SetTypeResolver(new TypeResolver
  2170. {
  2171. MemberNameComparer = StringComparer.OrdinalIgnoreCase
  2172. });
  2173. });
  2174. e.SetValue("a", new A());
  2175. Assert.True(e.Evaluate("a.call1").IsObject());
  2176. Assert.True(e.Evaluate("a.Call1").IsObject());
  2177. Assert.True(e.Evaluate("a.CALL1").IsObject());
  2178. }
  2179. [Fact]
  2180. public void ShouldNotEnumerateClassMethods()
  2181. {
  2182. var engine = new Engine();
  2183. var dictionary = new Dictionary<string, object>
  2184. {
  2185. { "foo", 5 },
  2186. { "bar", "A string" }
  2187. };
  2188. engine.SetValue("dictionary", dictionary);
  2189. var result = engine.Evaluate($"Object.keys(dictionary).join(',')").AsString();
  2190. Assert.Equal("foo,bar", result);
  2191. engine.Execute("dictionary.ContainsKey('foo')");
  2192. result = engine.Evaluate($"Object.keys(dictionary).join(',')").AsString();
  2193. Assert.Equal("foo,bar", result);
  2194. }
  2195. [Fact]
  2196. public void ShouldNotEnumerateExtensionMethods()
  2197. {
  2198. var engine = new Engine(cfg => cfg.AddExtensionMethods(typeof(Enumerable)));
  2199. var result = engine.Evaluate("Object.keys({ ...[1,2,3] }).join(',')").AsString();
  2200. Assert.Equal("0,1,2", result);
  2201. var script = @"
  2202. var arr = [1,2,3];
  2203. var keys = [];
  2204. for(var index in arr) keys.push(index);
  2205. keys.join(',');
  2206. ";
  2207. result = engine.Evaluate(script).ToString();
  2208. Assert.Equal("0,1,2", result);
  2209. }
  2210. [Fact]
  2211. public void CanCheckIfCallable()
  2212. {
  2213. var engine = new Engine();
  2214. engine.Evaluate("var f = () => true;");
  2215. var result = engine.GetValue("f");
  2216. Assert.True(result.IsCallable());
  2217. var callable = result.AsCallable();
  2218. Assert.True(callable.Call(JsValue.Undefined, Array.Empty<JsValue>()).AsBoolean());
  2219. Assert.True(callable.Call().AsBoolean());
  2220. }
  2221. [Fact]
  2222. public void CanGiveCustomNameToInteropMembers()
  2223. {
  2224. static IEnumerable<string> MemberNameCreator(MemberInfo prop)
  2225. {
  2226. var attributes = prop.GetCustomAttributes(typeof(CustomNameAttribute), true);
  2227. if (attributes.Length > 0)
  2228. {
  2229. foreach (CustomNameAttribute attribute in attributes)
  2230. {
  2231. yield return attribute.Name;
  2232. }
  2233. }
  2234. else
  2235. {
  2236. yield return prop.Name;
  2237. }
  2238. }
  2239. var customTypeResolver = new TypeResolver
  2240. {
  2241. MemberNameCreator = MemberNameCreator
  2242. };
  2243. var engine = new Engine(options =>
  2244. {
  2245. options.SetTypeResolver(customTypeResolver);
  2246. options.AddExtensionMethods(typeof(CustomNamedExtensions));
  2247. });
  2248. engine.SetValue("o", new CustomNamed());
  2249. Assert.Equal("StringField", engine.Evaluate("o.jsStringField").AsString());
  2250. Assert.Equal("StringField", engine.Evaluate("o.jsStringField2").AsString());
  2251. Assert.Equal("StaticStringField", engine.Evaluate("o.jsStaticStringField").AsString());
  2252. Assert.Equal("StringProperty", engine.Evaluate("o.jsStringProperty").AsString());
  2253. Assert.Equal("Method", engine.Evaluate("o.jsMethod()").AsString());
  2254. Assert.Equal("StaticMethod", engine.Evaluate("o.jsStaticMethod()").AsString());
  2255. Assert.Equal("InterfaceStringProperty", engine.Evaluate("o.jsInterfaceStringProperty").AsString());
  2256. Assert.Equal("InterfaceMethod", engine.Evaluate("o.jsInterfaceMethod()").AsString());
  2257. Assert.Equal("ExtensionMethod", engine.Evaluate("o.jsExtensionMethod()").AsString());
  2258. engine.SetValue("XmlHttpRequest", typeof(CustomNamedEnum));
  2259. engine.Evaluate("o.jsEnumProperty = XmlHttpRequest.HEADERS_RECEIVED;");
  2260. Assert.Equal((int) CustomNamedEnum.HeadersReceived, engine.Evaluate("o.jsEnumProperty").AsNumber());
  2261. }
  2262. [Fact]
  2263. public void ShouldBeAbleToHandleInvalidClrConversionViaCatchClrExceptions()
  2264. {
  2265. var engine = new Engine(cfg => cfg.CatchClrExceptions());
  2266. engine.SetValue("a", new Person());
  2267. var ex = Assert.Throws<JavaScriptException>(() => engine.Execute("a.age = \"It won't work, but it's normal\""));
  2268. Assert.Equal("Input string was not in a correct format.", ex.Message);
  2269. }
  2270. [Fact]
  2271. public void ShouldLetNotSupportedExceptionBubble()
  2272. {
  2273. _engine.SetValue("profile", new Profile());
  2274. var ex = Assert.Throws<NotSupportedException>(() => _engine.Evaluate("profile.AnyProperty"));
  2275. Assert.Equal("NOT SUPPORTED", ex.Message);
  2276. }
  2277. private class Profile
  2278. {
  2279. public int AnyProperty => throw new NotSupportedException("NOT SUPPORTED");
  2280. }
  2281. }
  2282. }