InteropTests.cs 83 KB

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