InteropTests.cs 107 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548
  1. using System.Collections;
  2. using System.Globalization;
  3. using System.Reflection;
  4. using System.Runtime.CompilerServices;
  5. using Jint.Native;
  6. using Jint.Runtime;
  7. using Jint.Runtime.Interop;
  8. using Jint.Tests.Runtime.Converters;
  9. using Jint.Tests.Runtime.Domain;
  10. using Jint.Tests.Runtime.TestClasses;
  11. using MongoDB.Bson;
  12. using Shapes;
  13. namespace Jint.Tests.Runtime;
  14. public partial class InteropTests : IDisposable
  15. {
  16. private readonly Engine _engine;
  17. public InteropTests()
  18. {
  19. _engine = new Engine(cfg => cfg.AllowClr(
  20. typeof(Shape).GetTypeInfo().Assembly,
  21. typeof(Console).GetTypeInfo().Assembly,
  22. typeof(File).GetTypeInfo().Assembly))
  23. .SetValue("log", new Action<object>(Console.WriteLine))
  24. .SetValue("assert", new Action<bool>(Assert.True))
  25. .SetValue("equal", new Action<object, object>(Assert.Equal))
  26. ;
  27. }
  28. void IDisposable.Dispose()
  29. {
  30. }
  31. private void RunTest(string source)
  32. {
  33. _engine.Execute(source);
  34. }
  35. public class Foo
  36. {
  37. public static Bar GetBar()
  38. {
  39. return new Bar();
  40. }
  41. }
  42. public class Bar
  43. {
  44. public string Test { get; set; } = "123";
  45. }
  46. [Fact]
  47. public void ShouldStringifyNetObjects()
  48. {
  49. _engine.SetValue("foo", new Foo());
  50. var json = _engine.Evaluate("JSON.stringify(foo.GetBar())").AsString();
  51. Assert.Equal("{\"Test\":\"123\"}", json);
  52. }
  53. [Fact]
  54. public void EngineShouldStringifyADictionary()
  55. {
  56. var engine = new Engine();
  57. var d = new Hashtable();
  58. d["Values"] = 1;
  59. engine.SetValue("d", d);
  60. Assert.Equal("{\"Values\":1}", engine.Evaluate($"JSON.stringify(d)").AsString());
  61. }
  62. [Fact]
  63. public void EngineShouldStringifyADictionaryOfStringAndObjectCorrectly()
  64. {
  65. var engine = new Engine();
  66. var dictionary = new Dictionary<string, object>
  67. {
  68. { "foo", 5 },
  69. { "bar", "A string" }
  70. };
  71. engine.SetValue(nameof(dictionary), dictionary);
  72. var result = engine.Evaluate($"JSON.stringify({nameof(dictionary)})").AsString();
  73. Assert.Equal("{\"foo\":5,\"bar\":\"A string\"}", result);
  74. }
  75. [Fact]
  76. public void EngineShouldRoundtripParsedJSONBackToStringCorrectly()
  77. {
  78. var engine = new Engine();
  79. const string json = "{\"foo\":5,\"bar\":\"A string\"}";
  80. var parsed = engine.Evaluate($"JSON.parse('{json}')").ToObject();
  81. engine.SetValue(nameof(parsed), parsed);
  82. var result = engine.Evaluate($"JSON.stringify({nameof(parsed)})").AsString();
  83. Assert.Equal(json, result);
  84. }
  85. [Fact]
  86. public void PrimitiveTypesCanBeSet()
  87. {
  88. _engine.SetValue("x", 10);
  89. _engine.SetValue("y", true);
  90. _engine.SetValue("z", "foo");
  91. RunTest(@"
  92. assert(x === 10);
  93. assert(y === true);
  94. assert(z === 'foo');
  95. ");
  96. }
  97. [Fact]
  98. public void TypePropertyAccess()
  99. {
  100. var userClass = new Person();
  101. var result = new Engine()
  102. .SetValue("userclass", userClass)
  103. .Evaluate("userclass.TypeProperty.Name;")
  104. .AsString();
  105. Assert.Equal("Person", result);
  106. }
  107. [Fact]
  108. public void CanAccessMemberNamedItem()
  109. {
  110. _engine.Execute(@"
  111. function item2(arg) {
  112. return arg.item2
  113. }
  114. function item1(arg) {
  115. return arg.item
  116. }
  117. function item3(arg) {
  118. return arg.Item
  119. }
  120. ");
  121. var argument = new Dictionary<string, object>
  122. {
  123. { "item2", "item2 value" },
  124. { "item", "item value" },
  125. { "Item", "Item value" }
  126. };
  127. Assert.Equal("item2 value", _engine.Invoke("item2", argument));
  128. Assert.Equal("item value", _engine.Invoke("item1", argument));
  129. Assert.Equal("Item value", _engine.Invoke("item3", argument));
  130. var company = new Company("Acme Ltd");
  131. _engine.SetValue("c", company);
  132. Assert.Equal("item thingie", _engine.Evaluate("c.Item"));
  133. Assert.Equal("item thingie", _engine.Evaluate("c.item"));
  134. Assert.Equal("value", _engine.Evaluate("c['key']"));
  135. }
  136. [Fact]
  137. public void DelegatesCanBeSet()
  138. {
  139. _engine.SetValue("square", new Func<double, double>(x => x * x));
  140. RunTest(@"
  141. assert(square(10) === 100);
  142. ");
  143. }
  144. [Fact]
  145. public void DelegateWithNullableParameterCanBePassedANull()
  146. {
  147. _engine.SetValue("isnull", new Func<double?, bool>(x => x == null));
  148. RunTest(@"
  149. assert(isnull(null) === true);
  150. ");
  151. }
  152. [Fact]
  153. public void DelegateWithObjectParameterCanBePassedANull()
  154. {
  155. _engine.SetValue("isnull", new Func<object, bool>(x => x == null));
  156. RunTest(@"
  157. assert(isnull(null) === true);
  158. ");
  159. }
  160. [Fact]
  161. public void DelegateWithNullableParameterCanBePassedAnUndefined()
  162. {
  163. _engine.SetValue("isnull", new Func<double?, bool>(x => x == null));
  164. RunTest(@"
  165. assert(isnull(undefined) === true);
  166. ");
  167. }
  168. [Fact]
  169. public void DelegateWithObjectParameterCanBePassedAnUndefined()
  170. {
  171. _engine.SetValue("isnull", new Func<object, bool>(x => x == null));
  172. RunTest(@"
  173. assert(isnull(undefined) === true);
  174. ");
  175. }
  176. [Fact]
  177. public void DelegateWithNullableParameterCanBeExcluded()
  178. {
  179. _engine.SetValue("isnull", new Func<double?, bool>(x => x == null));
  180. RunTest(@"
  181. assert(isnull() === true);
  182. ");
  183. }
  184. [Fact]
  185. public void DelegateWithObjectParameterCanBeExcluded()
  186. {
  187. _engine.SetValue("isnull", new Func<object, bool>(x => x == null));
  188. RunTest(@"
  189. assert(isnull() === true);
  190. ");
  191. }
  192. [Fact]
  193. public void DynamicDelegateCanBeSet()
  194. {
  195. #if NETFRAMEWORK
  196. var parameters = new[]
  197. {
  198. System.Linq.Expressions.Expression.Parameter(typeof(int)),
  199. System.Linq.Expressions.Expression.Parameter(typeof(int))
  200. };
  201. var exp = System.Linq.Expressions.Expression.Add(parameters[0], parameters[1]);
  202. var del = System.Linq.Expressions.Expression.Lambda(exp, parameters).Compile();
  203. _engine.SetValue("add", del);
  204. RunTest(@"
  205. assert(add(1,1) === 2);
  206. ");
  207. #endif
  208. }
  209. [Fact]
  210. public void ExtraParametersAreIgnored()
  211. {
  212. _engine.SetValue("passNumber", new Func<int, int>(x => x));
  213. RunTest(@"
  214. assert(passNumber(123,'test',{},[],null) === 123);
  215. ");
  216. }
  217. private delegate string callParams(params object[] values);
  218. private delegate string callArgumentAndParams(string firstParam, params object[] values);
  219. [Fact]
  220. public void DelegatesWithParamsParameterCanBeInvoked()
  221. {
  222. var a = new A();
  223. _engine.SetValue("callParams", new callParams(a.Call13));
  224. _engine.SetValue("callArgumentAndParams", new callArgumentAndParams(a.Call14));
  225. RunTest(@"
  226. assert(callParams('1','2','3') === '1,2,3');
  227. assert(callParams('1') === '1');
  228. assert(callParams() === '');
  229. assert(callArgumentAndParams('a','1','2','3') === 'a:1,2,3');
  230. assert(callArgumentAndParams('a','1') === 'a:1');
  231. assert(callArgumentAndParams('a') === 'a:');
  232. assert(callArgumentAndParams() === ':');
  233. ");
  234. }
  235. [Fact]
  236. public void CanGetObjectProperties()
  237. {
  238. var p = new Person
  239. {
  240. Name = "Mickey Mouse"
  241. };
  242. _engine.SetValue("p", p);
  243. RunTest(@"
  244. assert(p.Name === 'Mickey Mouse');
  245. ");
  246. }
  247. [Fact]
  248. public void CanInvokeObjectMethods()
  249. {
  250. var p = new Person
  251. {
  252. Name = "Mickey Mouse"
  253. };
  254. _engine.SetValue("p", p);
  255. RunTest(@"
  256. assert(p.ToString() === 'Mickey Mouse');
  257. ");
  258. }
  259. [Fact]
  260. public void CanInvokeObjectMethodsWithPascalCase()
  261. {
  262. var p = new Person
  263. {
  264. Name = "Mickey Mouse"
  265. };
  266. _engine.SetValue("p", p);
  267. RunTest(@"
  268. assert(p.toString() === 'Mickey Mouse');
  269. ");
  270. }
  271. [Fact]
  272. public void CanSetObjectProperties()
  273. {
  274. var p = new Person
  275. {
  276. Name = "Mickey Mouse"
  277. };
  278. _engine.SetValue("p", p);
  279. RunTest(@"
  280. p.Name = 'Donald Duck';
  281. assert(p.Name === 'Donald Duck');
  282. ");
  283. Assert.Equal("Donald Duck", p.Name);
  284. }
  285. [Fact]
  286. public void CanGetIndexUsingStringKey()
  287. {
  288. var dictionary = new Dictionary<string, Person>();
  289. dictionary.Add("person1", new Person { Name = "Mickey Mouse" });
  290. dictionary.Add("person2", new Person { Name = "Goofy" });
  291. _engine.SetValue("dictionary", dictionary);
  292. RunTest(@"
  293. assert(dictionary['person1'].Name === 'Mickey Mouse');
  294. assert(dictionary['person2'].Name === 'Goofy');
  295. ");
  296. }
  297. [Fact]
  298. public void CanSetIndexUsingStringKey()
  299. {
  300. var dictionary = new Dictionary<string, Person>();
  301. dictionary.Add("person1", new Person { Name = "Mickey Mouse" });
  302. dictionary.Add("person2", new Person { Name = "Goofy" });
  303. _engine.SetValue("dictionary", dictionary);
  304. RunTest(@"
  305. dictionary['person2'].Name = 'Donald Duck';
  306. assert(dictionary['person2'].Name === 'Donald Duck');
  307. ");
  308. Assert.Equal("Donald Duck", dictionary["person2"].Name);
  309. }
  310. [Fact]
  311. public void CanGetIndexUsingIntegerKey()
  312. {
  313. var dictionary = new Dictionary<int, string>();
  314. dictionary.Add(1, "Mickey Mouse");
  315. dictionary.Add(2, "Goofy");
  316. _engine.SetValue("dictionary", dictionary);
  317. RunTest(@"
  318. assert(dictionary[1] === 'Mickey Mouse');
  319. assert(dictionary[2] === 'Goofy');
  320. ");
  321. }
  322. [Fact]
  323. public void CanSetIndexUsingIntegerKey()
  324. {
  325. var dictionary = new Dictionary<int, string>();
  326. dictionary.Add(1, "Mickey Mouse");
  327. dictionary.Add(2, "Goofy");
  328. _engine.SetValue("dictionary", dictionary);
  329. RunTest(@"
  330. dictionary[2] = 'Donald Duck';
  331. assert(dictionary[2] === 'Donald Duck');
  332. ");
  333. Assert.Equal("Mickey Mouse", dictionary[1]);
  334. Assert.Equal("Donald Duck", dictionary[2]);
  335. }
  336. private class DoubleIndexedClass
  337. {
  338. public int this[int index] => index;
  339. public string this[string index] => index;
  340. }
  341. [Fact]
  342. public void CanGetIndexUsingBothIntAndStringIndex()
  343. {
  344. var dictionary = new DoubleIndexedClass();
  345. _engine.SetValue("dictionary", dictionary);
  346. RunTest(@"
  347. assert(dictionary[1] === 1);
  348. assert(dictionary['test'] === 'test');
  349. ");
  350. }
  351. [Fact]
  352. public void CanUseGenericMethods()
  353. {
  354. var dictionary = new Dictionary<int, string>();
  355. dictionary.Add(1, "Mickey Mouse");
  356. _engine.SetValue("dictionary", dictionary);
  357. RunTest(@"
  358. dictionary.Add(2, 'Goofy');
  359. assert(dictionary[2] === 'Goofy');
  360. ");
  361. Assert.Equal("Mickey Mouse", dictionary[1]);
  362. Assert.Equal("Goofy", dictionary[2]);
  363. }
  364. [Fact]
  365. public void CanUseMultiGenericTypes()
  366. {
  367. RunTest(@"
  368. var type = System.Collections.Generic.Dictionary(System.Int32, System.String);
  369. var dictionary = new type();
  370. dictionary.Add(1, 'Mickey Mouse');
  371. dictionary.Add(2, 'Goofy');
  372. assert(dictionary[2] === 'Goofy');
  373. ");
  374. }
  375. [Fact]
  376. public void CanUseIndexOnCollection()
  377. {
  378. var collection = new System.Collections.ObjectModel.Collection<string>();
  379. collection.Add("Mickey Mouse");
  380. collection.Add("Goofy");
  381. _engine.SetValue("dictionary", collection);
  382. RunTest(@"
  383. dictionary[1] = 'Donald Duck';
  384. assert(dictionary[1] === 'Donald Duck');
  385. ");
  386. Assert.Equal("Mickey Mouse", collection[0]);
  387. Assert.Equal("Donald Duck", collection[1]);
  388. }
  389. [Fact]
  390. public void CanUseIndexOnList()
  391. {
  392. var list = new List<object>(2);
  393. list.Add("Mickey Mouse");
  394. list.Add("Goofy");
  395. _engine.SetValue("list", list);
  396. _engine.Evaluate("list[1] = 'Donald Duck';");
  397. Assert.Equal("Donald Duck", _engine.Evaluate("list[1]").AsString());
  398. Assert.Equal("Mickey Mouse", list[0]);
  399. Assert.Equal("Donald Duck", list[1]);
  400. }
  401. [Fact]
  402. public void ShouldForOfOnLists()
  403. {
  404. _engine.SetValue("list", new List<string> { "a", "b" });
  405. var result = _engine.Evaluate("var l = ''; for (var x of list) l += x; return l;").AsString();
  406. Assert.Equal("ab", result);
  407. }
  408. [Fact]
  409. public void ShouldForOfOnArrays()
  410. {
  411. _engine.SetValue("arr", new[] { "a", "b" });
  412. var result = _engine.Evaluate("var l = ''; for (var x of arr) l += x; return l;").AsString();
  413. Assert.Equal("ab", result);
  414. }
  415. [Fact]
  416. public void ShouldForOfOnDictionaries()
  417. {
  418. _engine.SetValue("dict", new Dictionary<string, string> { { "a", "1" }, { "b", "2" } });
  419. var result = _engine.Evaluate("var l = ''; for (var x of dict) l += x; return l;").AsString();
  420. Assert.Equal("a,1b,2", result);
  421. }
  422. [Fact]
  423. public void ShouldForOfOnEnumerable()
  424. {
  425. _engine.SetValue("c", new Company("name"));
  426. var result = _engine.Evaluate("var l = ''; for (var x of c.getNameChars()) l += x + ','; return l;").AsString();
  427. Assert.Equal("n,a,m,e,", result);
  428. }
  429. [Fact]
  430. public void ShouldThrowWhenForOfOnObject()
  431. {
  432. // normal objects are not iterable in javascript
  433. var o = new { A = 1, B = 2 };
  434. _engine.SetValue("anonymous", o);
  435. var ex = Assert.Throws<JavaScriptException>(() => _engine.Evaluate("for (var x of anonymous) {}"));
  436. Assert.Equal("The value is not iterable", ex.Message);
  437. }
  438. [Fact]
  439. public void CanAccessAnonymousObject()
  440. {
  441. var p = new
  442. {
  443. Name = "Mickey Mouse"
  444. };
  445. _engine.SetValue("p", p);
  446. RunTest(@"
  447. assert(p.Name === 'Mickey Mouse');
  448. ");
  449. }
  450. [Fact]
  451. public void CanAccessAnonymousObjectProperties()
  452. {
  453. var p = new
  454. {
  455. Address = new
  456. {
  457. City = "Mouseton"
  458. }
  459. };
  460. _engine.SetValue("p", p);
  461. RunTest(@"
  462. assert(p.Address.City === 'Mouseton');
  463. ");
  464. }
  465. [Fact]
  466. public void PocosCanReturnJsValueDirectly()
  467. {
  468. var o = new
  469. {
  470. x = new JsNumber(1),
  471. y = new JsString("string")
  472. };
  473. _engine.SetValue("o", o);
  474. RunTest(@"
  475. assert(o.x === 1);
  476. assert(o.y === 'string');
  477. ");
  478. }
  479. [Fact]
  480. public void PocosCanReturnObjectInstanceDirectly()
  481. {
  482. var x = new JsObject(_engine);
  483. x.Set("foo", new JsString("bar"));
  484. var o = new
  485. {
  486. x
  487. };
  488. _engine.SetValue("o", o);
  489. RunTest(@"
  490. assert(o.x.foo === 'bar');
  491. ");
  492. }
  493. [Fact]
  494. public void DateTimeIsConvertedToDate()
  495. {
  496. var o = new
  497. {
  498. z = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
  499. };
  500. _engine.SetValue("o", o);
  501. RunTest(@"
  502. assert(o.z.valueOf() === 0);
  503. ");
  504. }
  505. [Fact]
  506. public void DateTimeOffsetIsConvertedToDate()
  507. {
  508. var o = new
  509. {
  510. z = new DateTimeOffset(1970, 1, 1, 0, 0, 0, new TimeSpan())
  511. };
  512. _engine.SetValue("o", o);
  513. RunTest(@"
  514. assert(o.z.valueOf() === 0);
  515. ");
  516. }
  517. [Fact]
  518. public void EcmaValuesAreAutomaticallyConvertedWhenSetInPoco()
  519. {
  520. var p = new Person
  521. {
  522. Name = "foo"
  523. };
  524. _engine.SetValue("p", p);
  525. RunTest(@"
  526. assert(p.Name === 'foo');
  527. assert(p.Age === 0);
  528. p.Name = 'bar';
  529. p.Age = 10;
  530. ");
  531. Assert.Equal("bar", p.Name);
  532. Assert.Equal(10, p.Age);
  533. }
  534. [Fact]
  535. public void EcmaValuesAreAutomaticallyConvertedToBestMatchWhenSetInPoco()
  536. {
  537. var p = new Person
  538. {
  539. Name = "foo"
  540. };
  541. _engine.SetValue("p", p);
  542. RunTest(@"
  543. p.Name = 10;
  544. p.Age = '20';
  545. ");
  546. Assert.Equal("10", p.Name);
  547. Assert.Equal(20, p.Age);
  548. }
  549. [Fact]
  550. public void ShouldCallInstanceMethodWithoutArgument()
  551. {
  552. _engine.SetValue("a", new A());
  553. RunTest(@"
  554. assert(a.Call1() === 0);
  555. ");
  556. }
  557. [Fact]
  558. public void ShouldCallInstanceMethodOverloadArgument()
  559. {
  560. _engine.SetValue("a", new A());
  561. RunTest(@"
  562. assert(a.Call1(1) === 1);
  563. ");
  564. }
  565. [Fact]
  566. public void ShouldCallInstanceMethodWithString()
  567. {
  568. var p = new Person();
  569. _engine.SetValue("a", new A());
  570. _engine.SetValue("p", p);
  571. RunTest(@"
  572. p.Name = a.Call2('foo');
  573. assert(p.Name === 'foo');
  574. ");
  575. Assert.Equal("foo", p.Name);
  576. }
  577. [Fact]
  578. public void CanUseTrim()
  579. {
  580. var p = new Person { Name = "Mickey Mouse " };
  581. _engine.SetValue("p", p);
  582. RunTest(@"
  583. assert(p.Name === 'Mickey Mouse ');
  584. p.Name = p.Name.trim();
  585. assert(p.Name === 'Mickey Mouse');
  586. ");
  587. Assert.Equal("Mickey Mouse", p.Name);
  588. }
  589. [Fact]
  590. public void CanUseMathFloor()
  591. {
  592. var p = new Person();
  593. _engine.SetValue("p", p);
  594. RunTest(@"
  595. p.Age = Math.floor(1.6);p
  596. assert(p.Age === 1);
  597. ");
  598. Assert.Equal(1, p.Age);
  599. }
  600. [Fact]
  601. public void CanUseDelegateAsFunction()
  602. {
  603. var even = new Func<int, bool>(x => x % 2 == 0);
  604. _engine.SetValue("even", even);
  605. RunTest(@"
  606. assert(even(2) === true);
  607. ");
  608. }
  609. private struct TestStruct
  610. {
  611. public int Value;
  612. public TestStruct(int value)
  613. {
  614. Value = value;
  615. }
  616. }
  617. private class TestClass
  618. {
  619. public string String { get; set; }
  620. public int Int { get; set; }
  621. public int? NullableInt { get; set; }
  622. public DateTime? NullableDate { get; set; }
  623. public bool? NullableBool { get; set; }
  624. public bool Bool { get; set; }
  625. public TestEnumInt32? NullableEnum { get; set; }
  626. public TestStruct? NullableStruct { get; set; }
  627. public void SetBool(bool value)
  628. {
  629. Bool = value;
  630. }
  631. public void SetInt(int value)
  632. {
  633. Int = value;
  634. }
  635. public void SetString(string value)
  636. {
  637. String = value;
  638. }
  639. }
  640. [Fact]
  641. public void CanSetNullablePropertiesOnPocos()
  642. {
  643. var instance = new TestClass();
  644. _engine.SetValue("instance", instance);
  645. _engine.SetValue("TestStruct", typeof(TestStruct));
  646. RunTest(@"
  647. instance.NullableInt = 2;
  648. instance.NullableDate = new Date();
  649. instance.NullableBool = true;
  650. instance.NullableEnum = 1;
  651. instance.NullableStruct = new TestStruct(5);
  652. assert(instance.NullableInt===2);
  653. assert(instance.NullableDate!=null);
  654. assert(instance.NullableBool===true);
  655. assert(instance.NullableEnum===1);
  656. assert(instance.NullableStruct.Value===5);
  657. ");
  658. }
  659. private class ReadOnlyList : IReadOnlyList<Person>
  660. {
  661. private readonly Person[] _data;
  662. public ReadOnlyList(params Person[] data)
  663. {
  664. _data = data;
  665. }
  666. public IEnumerator<Person> GetEnumerator()
  667. {
  668. return ((IEnumerable<Person>) _data).GetEnumerator();
  669. }
  670. IEnumerator IEnumerable.GetEnumerator()
  671. {
  672. return _data.GetEnumerator();
  673. }
  674. public int Count => _data.Length;
  675. public Person this[int index] => _data[index];
  676. }
  677. [Fact]
  678. public void CanAddArrayPrototypeForArrayLikeClrObjects()
  679. {
  680. var e = new Engine(cfg => cfg
  681. .AllowClr(typeof(Person).Assembly)
  682. );
  683. var person = new Person
  684. {
  685. Age = 12,
  686. Name = "John"
  687. };
  688. dynamic obj = new
  689. {
  690. values = new ReadOnlyList(person)
  691. };
  692. e.SetValue("o", obj);
  693. var name = e.Evaluate("o.values.filter(x => x.age == 12)[0].name").ToString();
  694. Assert.Equal("John", name);
  695. }
  696. [Fact]
  697. public void CanSetIsConcatSpreadableForArrays()
  698. {
  699. var engine = new Engine();
  700. engine
  701. .SetValue("list1", new List<string> { "A", "B", "C" })
  702. .SetValue("list2", new List<string> { "D", "E", "F" })
  703. .Execute("var array1 = ['A', 'B', 'C'];")
  704. .Execute("var array2 = ['D', 'E', 'F'];");
  705. Assert.True(engine.Evaluate("list1[Symbol.isConcatSpreadable] = true; list1[Symbol.isConcatSpreadable];").AsBoolean());
  706. Assert.True(engine.Evaluate("list2[Symbol.isConcatSpreadable] = true; list2[Symbol.isConcatSpreadable];").AsBoolean());
  707. Assert.Equal("[\"A\",\"B\",\"C\"]", engine.Evaluate("JSON.stringify(array1);"));
  708. Assert.Equal("[\"D\",\"E\",\"F\"]", engine.Evaluate("JSON.stringify(array2);"));
  709. Assert.Equal("[\"A\",\"B\",\"C\"]", engine.Evaluate("JSON.stringify(list1);"));
  710. Assert.Equal("[\"D\",\"E\",\"F\"]", engine.Evaluate("JSON.stringify(list2);"));
  711. const string Concatenated = "[\"A\",\"B\",\"C\",\"D\",\"E\",\"F\"]";
  712. Assert.Equal(Concatenated, engine.Evaluate("JSON.stringify(array1.concat(array2));"));
  713. Assert.Equal(Concatenated, engine.Evaluate("JSON.stringify(array1.concat(list2));"));
  714. Assert.Equal(Concatenated, engine.Evaluate("JSON.stringify(list1.concat(array2));"));
  715. Assert.Equal(Concatenated, engine.Evaluate("JSON.stringify(list1.concat(list2));"));
  716. Assert.False(engine.Evaluate("list1[Symbol.isConcatSpreadable] = false; list1[Symbol.isConcatSpreadable];").AsBoolean());
  717. Assert.False(engine.Evaluate("list2[Symbol.isConcatSpreadable] = false; list2[Symbol.isConcatSpreadable];").AsBoolean());
  718. Assert.Equal("[[\"A\",\"B\",\"C\"]]", engine.Evaluate("JSON.stringify([].concat(list1));"));
  719. Assert.Equal("[[\"A\",\"B\",\"C\"],[\"D\",\"E\",\"F\"]]", engine.Evaluate("JSON.stringify(list1.concat(list2));"));
  720. }
  721. [Fact]
  722. public void ShouldConvertArrayToArrayInstance()
  723. {
  724. var result = _engine
  725. .SetValue("values", new[] { 1, 2, 3, 4, 5, 6 })
  726. .Evaluate("values.filter(function(x){ return x % 2 == 0; })");
  727. var parts = result.ToObject();
  728. Assert.True(parts.GetType().IsArray);
  729. Assert.Equal(3, ((object[]) parts).Length);
  730. Assert.Equal(2d, ((object[]) parts)[0]);
  731. Assert.Equal(4d, ((object[]) parts)[1]);
  732. Assert.Equal(6d, ((object[]) parts)[2]);
  733. }
  734. [Fact]
  735. public void ShouldConvertListsToArrayInstance()
  736. {
  737. var result = _engine
  738. .SetValue("values", new List<object> { 1, 2, 3, 4, 5, 6 })
  739. .Evaluate("new Array(values).filter(function(x){ return x % 2 == 0; })");
  740. var parts = result.ToObject();
  741. Assert.True(parts.GetType().IsArray);
  742. Assert.Equal(3, ((object[]) parts).Length);
  743. Assert.Equal(2d, ((object[]) parts)[0]);
  744. Assert.Equal(4d, ((object[]) parts)[1]);
  745. Assert.Equal(6d, ((object[]) parts)[2]);
  746. }
  747. [Fact]
  748. public void ShouldConvertArrayInstanceToArray()
  749. {
  750. var parts = _engine.Evaluate("'[email protected]'.split('@');").ToObject();
  751. Assert.True(parts.GetType().IsArray);
  752. Assert.Equal(2, ((object[]) parts).Length);
  753. Assert.Equal("foo", ((object[]) parts)[0]);
  754. Assert.Equal("bar.com", ((object[]) parts)[1]);
  755. }
  756. [Fact]
  757. public void ShouldLoopWithNativeEnumerator()
  758. {
  759. JsValue adder(JsValue argValue)
  760. {
  761. var args = argValue.AsArray();
  762. double sum = 0;
  763. foreach (var item in args)
  764. {
  765. if (item.IsNumber())
  766. {
  767. sum += item.AsNumber();
  768. }
  769. }
  770. return sum;
  771. }
  772. var result = _engine.SetValue("getSum", new Func<JsValue, JsValue>(adder))
  773. .Evaluate("getSum([1,2,3]);");
  774. Assert.True(result == 6);
  775. }
  776. [Fact]
  777. public void ShouldConvertBooleanInstanceToBool()
  778. {
  779. var value = _engine.Evaluate("new Boolean(true)").ToObject();
  780. Assert.Equal(typeof(bool), value.GetType());
  781. Assert.Equal(true, value);
  782. }
  783. [Fact]
  784. public void ShouldAllowBooleanCoercion()
  785. {
  786. var engine = new Engine(options => { options.Interop.ValueCoercion = ValueCoercionType.Boolean; });
  787. engine.SetValue("o", new TestClass());
  788. Assert.True(engine.Evaluate("o.Bool = 1; return o.Bool;").AsBoolean());
  789. Assert.True(engine.Evaluate("o.Bool = 'dog'; return o.Bool;").AsBoolean());
  790. Assert.True(engine.Evaluate("o.Bool = {}; return o.Bool;").AsBoolean());
  791. Assert.False(engine.Evaluate("o.Bool = 0; return o.Bool;").AsBoolean());
  792. Assert.False(engine.Evaluate("o.Bool = ''; return o.Bool;").AsBoolean());
  793. Assert.False(engine.Evaluate("o.Bool = null; return o.Bool;").AsBoolean());
  794. Assert.False(engine.Evaluate("o.Bool = undefined; return o.Bool;").AsBoolean());
  795. engine.Evaluate("class MyClass { valueOf() { return 42; } }");
  796. Assert.Equal(true, engine.Evaluate("let obj = new MyClass(); o.Bool = obj; return o.Bool;").AsBoolean());
  797. engine.SetValue("func3", new Action<bool, bool, bool>((param1, param2, param3) =>
  798. {
  799. Assert.True(param1);
  800. Assert.True(param2);
  801. Assert.True(param3);
  802. }));
  803. engine.Evaluate("func3(true, obj, [ 1, 2, 3])");
  804. Assert.Equal(true, engine.Evaluate("o.SetBool(42); return o.Bool;").AsBoolean());
  805. Assert.Equal(true, engine.Evaluate("o.SetBool(obj); return o.Bool;").AsBoolean());
  806. Assert.Equal(true, engine.Evaluate("o.SetBool([ 1, 2, 3].length); return o.Bool;").AsBoolean());
  807. }
  808. [Fact]
  809. public void ShouldAllowNumberCoercion()
  810. {
  811. var engine = new Engine(options => { options.Interop.ValueCoercion = ValueCoercionType.Number; });
  812. engine.SetValue("o", new TestClass());
  813. Assert.Equal(1, engine.Evaluate("o.Int = true; return o.Int;").AsNumber());
  814. Assert.Equal(0, engine.Evaluate("o.Int = false; return o.Int;").AsNumber());
  815. engine.Evaluate("class MyClass { valueOf() { return 42; } }");
  816. Assert.Equal(42, engine.Evaluate("let obj = new MyClass(); o.Int = obj; return o.Int;").AsNumber());
  817. // but null and undefined should be injected as nulls to nullable objects
  818. Assert.True(engine.Evaluate("o.NullableInt = null; return o.NullableInt;").IsNull());
  819. Assert.True(engine.Evaluate("o.NullableInt = undefined; return o.NullableInt;").IsNull());
  820. engine.SetValue("func3", new Action<int, double, long>((param1, param2, param3) =>
  821. {
  822. Assert.Equal(1, param1);
  823. Assert.Equal(42, param2);
  824. Assert.Equal(3, param3);
  825. }));
  826. engine.Evaluate("func3(true, obj, [ 1, 2, 3].length)");
  827. Assert.Equal(1, engine.Evaluate("o.SetInt(true); return o.Int;").AsNumber());
  828. Assert.Equal(42, engine.Evaluate("o.SetInt(obj); return o.Int;").AsNumber());
  829. Assert.Equal(3, engine.Evaluate("o.SetInt([ 1, 2, 3].length); return o.Int;").AsNumber());
  830. }
  831. [Fact]
  832. public void ShouldAllowStringCoercion()
  833. {
  834. var engine = new Engine(options => { options.Interop.ValueCoercion = ValueCoercionType.String; });
  835. // basic premise, booleans in JS are lower-case, so should the the toString under interop
  836. Assert.Equal("true", engine.Evaluate("'' + true").AsString());
  837. engine.SetValue("o", new TestClass());
  838. Assert.Equal("false", engine.Evaluate("'' + o.Bool").AsString());
  839. Assert.Equal("true", engine.Evaluate("o.Bool = true; o.String = o.Bool; return o.String;").AsString());
  840. Assert.Equal("true", engine.Evaluate("o.String = true; return o.String;").AsString());
  841. engine.SetValue("func1", new Func<bool>(() => true));
  842. Assert.Equal("true", engine.Evaluate("'' + func1()").AsString());
  843. engine.SetValue("func2", new Func<JsValue>(() => JsBoolean.True));
  844. Assert.Equal("true", engine.Evaluate("'' + func2()").AsString());
  845. // but null and undefined should be injected as nulls to c# objects
  846. Assert.True(engine.Evaluate("o.String = null; return o.String;").IsNull());
  847. Assert.True(engine.Evaluate("o.String = undefined; return o.String;").IsNull());
  848. Assert.Equal("1,2,3", engine.Evaluate("o.String = [ 1, 2, 3 ]; return o.String;").AsString());
  849. engine.Evaluate("class MyClass { toString() { return 'hello world'; } }");
  850. Assert.Equal("hello world", engine.Evaluate("let obj = new MyClass(); o.String = obj; return o.String;").AsString());
  851. engine.SetValue("func3", new Action<string, string, string>((param1, param2, param3) =>
  852. {
  853. Assert.Equal("true", param1);
  854. Assert.Equal("hello world", param2);
  855. Assert.Equal("1,2,3", param3);
  856. }));
  857. engine.Evaluate("func3(true, obj, [ 1, 2, 3])");
  858. Assert.Equal("true", engine.Evaluate("o.SetString(true); return o.String;").AsString());
  859. Assert.Equal("hello world", engine.Evaluate("o.SetString(obj); return o.String;").AsString());
  860. Assert.Equal("1,2,3", engine.Evaluate("o.SetString([ 1, 2, 3]); return o.String;").AsString());
  861. }
  862. [Fact]
  863. public void ShouldConvertDateInstanceToDateTime()
  864. {
  865. var result = _engine.Evaluate("new Date(0)");
  866. var value = result.ToObject() is DateTime ? (DateTime) result.ToObject() : default;
  867. Assert.Equal(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), value);
  868. Assert.Equal(DateTimeKind.Utc, value.Kind);
  869. }
  870. [Fact]
  871. public void ShouldConvertDateInstanceToLocalDateTime()
  872. {
  873. TimeZoneInfo timeZone;
  874. try
  875. {
  876. timeZone = TimeZoneInfo.FindSystemTimeZoneById("Europe/Helsinki");
  877. }
  878. catch (TimeZoneNotFoundException)
  879. {
  880. timeZone = TimeZoneInfo.FindSystemTimeZoneById("FLE Standard Time");
  881. }
  882. var engine = new Engine(options =>
  883. {
  884. options.TimeZone = timeZone;
  885. options.Interop.DateTimeKind = DateTimeKind.Local;
  886. });
  887. var result = engine.Evaluate("new Date(0)");
  888. var value = result.ToObject() is DateTime ? (DateTime) result.ToObject() : default;
  889. Assert.Equal(new DateTime(1970, 1, 1, 2, 0, 0, DateTimeKind.Local), value);
  890. Assert.Equal(DateTimeKind.Local, value.Kind);
  891. }
  892. [Fact]
  893. public void ShouldConvertNumberInstanceToDouble()
  894. {
  895. var result = _engine.Evaluate("new Number(10)");
  896. var value = result.ToObject();
  897. Assert.Equal(typeof(double), value.GetType());
  898. Assert.Equal(10d, value);
  899. }
  900. [Fact]
  901. public void ShouldConvertStringInstanceToString()
  902. {
  903. var value = _engine.Evaluate("new String('foo')").ToObject();
  904. Assert.Equal(typeof(string), value.GetType());
  905. Assert.Equal("foo", value);
  906. }
  907. [Fact]
  908. public void ShouldNotTryToConvertCompatibleTypes()
  909. {
  910. _engine.SetValue("a", new A());
  911. RunTest(@"
  912. assert(a.Call3('foo') === 'foo');
  913. assert(a.Call3(1) === '1');
  914. ");
  915. }
  916. [Fact]
  917. public void ShouldNotTryToConvertDerivedTypes()
  918. {
  919. _engine.SetValue("a", new A());
  920. _engine.SetValue("p", new Person { Name = "Mickey" });
  921. RunTest(@"
  922. assert(a.Call4(p) === 'Mickey');
  923. ");
  924. }
  925. [Fact]
  926. public void ShouldExecuteFunctionCallBackAsDelegate()
  927. {
  928. _engine.SetValue("a", new A());
  929. RunTest(@"
  930. assert(a.Call5(function(a,b){ return a+b }) === '1foo');
  931. ");
  932. }
  933. [Fact]
  934. public void ShouldExecuteFunctionCallBackAsFuncAndThisCanBeAssigned()
  935. {
  936. _engine.SetValue("a", new A());
  937. RunTest(@"
  938. assert(a.Call6(function(a,b){ return this+a+b }) === 'bar1foo');
  939. ");
  940. }
  941. [Fact]
  942. public void ShouldExecuteFunctionCallBackAsPredicate()
  943. {
  944. _engine.SetValue("a", new A());
  945. // Func<>
  946. RunTest(@"
  947. assert(a.Call8(function(){ return 'foo'; }) === 'foo');
  948. ");
  949. }
  950. [Fact]
  951. public void ShouldExecuteFunctionWithParameterCallBackAsPredicate()
  952. {
  953. _engine.SetValue("a", new A());
  954. // Func<,>
  955. RunTest(@"
  956. assert(a.Call7('foo', function(a){ return a === 'foo'; }) === true);
  957. ");
  958. }
  959. [Fact]
  960. public void ShouldExecuteActionCallBackAsPredicate()
  961. {
  962. _engine.SetValue("a", new A());
  963. // Action
  964. RunTest(@"
  965. var value;
  966. a.Call9(function(){ value = 'foo'; });
  967. assert(value === 'foo');
  968. ");
  969. }
  970. [Fact]
  971. public void ShouldExecuteActionWithParameterCallBackAsPredicate()
  972. {
  973. _engine.SetValue("a", new A());
  974. // Action<>
  975. RunTest(@"
  976. var value;
  977. a.Call10('foo', function(b){ value = b; });
  978. assert(value === 'foo');
  979. ");
  980. }
  981. [Fact]
  982. public void ShouldExecuteActionWithMultipleParametersCallBackAsPredicate()
  983. {
  984. _engine.SetValue("a", new A());
  985. // Action<,>
  986. RunTest(@"
  987. var value;
  988. a.Call11('foo', 'bar', function(a,b){ value = a + b; });
  989. assert(value === 'foobar');
  990. ");
  991. }
  992. [Fact]
  993. public void ShouldExecuteFunc()
  994. {
  995. _engine.SetValue("a", new A());
  996. // Func<int, int>
  997. RunTest(@"
  998. var result = a.Call12(42, function(a){ return a + a; });
  999. assert(result === 84);
  1000. ");
  1001. }
  1002. [Fact]
  1003. public void ShouldExecuteActionCallbackOnEventChanged()
  1004. {
  1005. var collection = new System.Collections.ObjectModel.ObservableCollection<string>();
  1006. Assert.True(collection.Count == 0);
  1007. _engine.SetValue("collection", collection);
  1008. RunTest(@"
  1009. var callCount = 0;
  1010. var handler = function(sender, eventArgs) { callCount++; } ;
  1011. collection.add_CollectionChanged(handler);
  1012. collection.Add('test');
  1013. collection.remove_CollectionChanged(handler);
  1014. collection.Add('test');
  1015. var json = JSON.stringify(Object.keys(handler));
  1016. ");
  1017. var callCount = (int) _engine.GetValue("callCount").AsNumber();
  1018. Assert.Equal(1, callCount);
  1019. Assert.Equal(2, collection.Count);
  1020. // make sure our delegate holder is hidden
  1021. Assert.Equal("[]", _engine.Evaluate("json"));
  1022. }
  1023. [Fact]
  1024. public void ShouldUseSystemIO()
  1025. {
  1026. RunTest(@"
  1027. var filename = System.IO.Path.GetTempFileName();
  1028. var sw = System.IO.File.CreateText(filename);
  1029. sw.Write('Hello World');
  1030. sw.Dispose();
  1031. var content = System.IO.File.ReadAllText(filename);
  1032. System.Console.WriteLine(content);
  1033. assert(content === 'Hello World');
  1034. ");
  1035. }
  1036. [Fact]
  1037. public void ShouldImportNamespace()
  1038. {
  1039. RunTest(@"
  1040. var Shapes = importNamespace('Shapes');
  1041. var circle = new Shapes.Circle();
  1042. assert(circle.Radius === 0);
  1043. assert(circle.Perimeter() === 0);
  1044. ");
  1045. }
  1046. [Fact]
  1047. public void ShouldImportEmptyNamespace()
  1048. {
  1049. RunTest("""
  1050. var nullSpace = importNamespace(null);
  1051. var c1 = new nullSpace.ShapeWithoutNameSpace();
  1052. assert(c1.Perimeter() === 42);
  1053. var undefinedSpace = importNamespace(undefined);
  1054. var c2 = new undefinedSpace.ShapeWithoutNameSpace();
  1055. assert(c2.Perimeter() === 42);
  1056. var defaultSpace = importNamespace();
  1057. var c3 = new defaultSpace.ShapeWithoutNameSpace();
  1058. assert(c3.Perimeter() === 42);
  1059. """);
  1060. }
  1061. [Fact]
  1062. public void ShouldConstructReferenceTypeWithParameters()
  1063. {
  1064. RunTest(@"
  1065. var Shapes = importNamespace('Shapes');
  1066. var circle = new Shapes.Circle(1);
  1067. assert(circle.Radius === 1);
  1068. assert(circle.Perimeter() === Math.PI);
  1069. ");
  1070. }
  1071. [Fact]
  1072. public void ShouldConstructValueTypeWithoutParameters()
  1073. {
  1074. RunTest(@"
  1075. var guid = new System.Guid();
  1076. assert('00000000-0000-0000-0000-000000000000' === guid.ToString());
  1077. ");
  1078. }
  1079. [Fact]
  1080. public void ShouldInvokeAFunctionByName()
  1081. {
  1082. RunTest(@"
  1083. function add(x, y) { return x + y; }
  1084. ");
  1085. Assert.Equal(3, _engine.Invoke("add", 1, 2));
  1086. }
  1087. [Fact]
  1088. public void ShouldNotInvokeNonFunctionValue()
  1089. {
  1090. RunTest(@"
  1091. var x= 10;
  1092. ");
  1093. Assert.Throws<JavaScriptException>(() => _engine.Invoke("x", 1, 2));
  1094. }
  1095. [Fact]
  1096. public void CanGetField()
  1097. {
  1098. var o = new ClassWithField
  1099. {
  1100. Field = "Mickey Mouse"
  1101. };
  1102. _engine.SetValue("o", o);
  1103. RunTest(@"
  1104. assert(o.Field === 'Mickey Mouse');
  1105. ");
  1106. }
  1107. [Fact]
  1108. public void CanSetField()
  1109. {
  1110. var o = new ClassWithField();
  1111. _engine.SetValue("o", o);
  1112. RunTest(@"
  1113. o.Field = 'Mickey Mouse';
  1114. assert(o.Field === 'Mickey Mouse');
  1115. ");
  1116. Assert.Equal("Mickey Mouse", o.Field);
  1117. }
  1118. [Fact]
  1119. public void CanGetStaticField()
  1120. {
  1121. RunTest(@"
  1122. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1123. var statics = domain.ClassWithStaticFields;
  1124. assert(statics.Get == 'Get');
  1125. ");
  1126. }
  1127. [Fact]
  1128. public void CanSetStaticField()
  1129. {
  1130. RunTest(@"
  1131. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1132. var statics = domain.ClassWithStaticFields;
  1133. statics.Set = 'hello';
  1134. assert(statics.Set == 'hello');
  1135. ");
  1136. Assert.Equal(ClassWithStaticFields.Set, "hello");
  1137. }
  1138. [Fact]
  1139. public void CanGetStaticAccessor()
  1140. {
  1141. RunTest(@"
  1142. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1143. var statics = domain.ClassWithStaticFields;
  1144. assert(statics.Getter == 'Getter');
  1145. ");
  1146. }
  1147. [Fact]
  1148. public void CanSetStaticAccessor()
  1149. {
  1150. RunTest(@"
  1151. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1152. var statics = domain.ClassWithStaticFields;
  1153. statics.Setter = 'hello';
  1154. assert(statics.Setter == 'hello');
  1155. ");
  1156. Assert.Equal(ClassWithStaticFields.Setter, "hello");
  1157. }
  1158. [Fact]
  1159. public void CantSetStaticReadonly()
  1160. {
  1161. RunTest(@"
  1162. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1163. var statics = domain.ClassWithStaticFields;
  1164. statics.Readonly = 'hello';
  1165. assert(statics.Readonly == 'Readonly');
  1166. ");
  1167. Assert.Equal(ClassWithStaticFields.Readonly, "Readonly");
  1168. }
  1169. [Fact]
  1170. public void CanSetCustomConverters()
  1171. {
  1172. var engine1 = new Engine();
  1173. engine1.SetValue("p", new { Test = true });
  1174. engine1.Execute("var result = p.Test;");
  1175. Assert.True((bool) engine1.GetValue("result").ToObject());
  1176. var engine2 = new Engine(o => o.AddObjectConverter(new NegateBoolConverter()));
  1177. engine2.SetValue("p", new { Test = true });
  1178. engine2.Execute("var result = p.Test;");
  1179. Assert.False((bool) engine2.GetValue("result").ToObject());
  1180. }
  1181. [Fact]
  1182. public void CanConvertEnumsToString()
  1183. {
  1184. var engine1 = new Engine(o => o.AddObjectConverter(new EnumsToStringConverter()))
  1185. .SetValue("assert", new Action<bool>(Assert.True));
  1186. engine1.SetValue("p", new { Comparison = StringComparison.CurrentCulture });
  1187. engine1.Execute("assert(p.Comparison === 'CurrentCulture');");
  1188. engine1.Execute("var result = p.Comparison;");
  1189. Assert.Equal("CurrentCulture", (string) engine1.GetValue("result").ToObject());
  1190. }
  1191. [Fact]
  1192. public void CanUserIncrementOperator()
  1193. {
  1194. var p = new Person
  1195. {
  1196. Age = 1
  1197. };
  1198. _engine.SetValue("p", p);
  1199. RunTest(@"
  1200. assert(++p.Age === 2);
  1201. ");
  1202. Assert.Equal(2, p.Age);
  1203. }
  1204. [Fact]
  1205. public void CanOverwriteValues()
  1206. {
  1207. _engine.SetValue("x", 3);
  1208. _engine.SetValue("x", 4);
  1209. RunTest(@"
  1210. assert(x === 4);
  1211. ");
  1212. }
  1213. [Fact]
  1214. public void ShouldCreateGenericType()
  1215. {
  1216. RunTest(@"
  1217. var ListOfString = System.Collections.Generic.List(System.String);
  1218. var list = new ListOfString();
  1219. list.Add('foo');
  1220. list.Add(1);
  1221. assert(2 === list.Count);
  1222. ");
  1223. }
  1224. [Fact]
  1225. public void EnumComparesByName()
  1226. {
  1227. var o = new
  1228. {
  1229. r = Colors.Red,
  1230. b = Colors.Blue,
  1231. g = Colors.Green,
  1232. b2 = Colors.Red
  1233. };
  1234. _engine.SetValue("o", o);
  1235. _engine.SetValue("assertFalse", new Action<bool>(Assert.False));
  1236. RunTest(@"
  1237. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1238. var colors = domain.Colors;
  1239. assert(o.r === colors.Red);
  1240. assert(o.g === colors.Green);
  1241. assert(o.b === colors.Blue);
  1242. assertFalse(o.b2 === colors.Blue);
  1243. ");
  1244. }
  1245. [Fact]
  1246. public void ShouldSetEnumProperty()
  1247. {
  1248. var s = new Circle
  1249. {
  1250. Color = Colors.Red
  1251. };
  1252. _engine.SetValue("s", s);
  1253. RunTest(@"
  1254. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1255. var colors = domain.Colors;
  1256. s.Color = colors.Blue;
  1257. assert(s.Color === colors.Blue);
  1258. ");
  1259. _engine.SetValue("s", s);
  1260. RunTest(@"
  1261. s.Color = colors.Blue | colors.Green;
  1262. assert(s.Color === colors.Blue | colors.Green);
  1263. ");
  1264. Assert.Equal(Colors.Blue | Colors.Green, s.Color);
  1265. }
  1266. private enum TestEnumInt32 : int
  1267. {
  1268. None,
  1269. One = 1,
  1270. Min = int.MaxValue,
  1271. Max = int.MaxValue
  1272. }
  1273. private enum TestEnumUInt32 : uint
  1274. {
  1275. None,
  1276. One = 1,
  1277. Min = uint.MaxValue,
  1278. Max = uint.MaxValue
  1279. }
  1280. private enum TestEnumInt64 : long
  1281. {
  1282. None,
  1283. One = 1,
  1284. Min = long.MaxValue,
  1285. Max = long.MaxValue
  1286. }
  1287. private enum TestEnumUInt64 : ulong
  1288. {
  1289. None,
  1290. One = 1,
  1291. Min = ulong.MaxValue,
  1292. Max = ulong.MaxValue
  1293. }
  1294. private void TestEnum<T>(T enumValue)
  1295. {
  1296. var i = Convert.ChangeType(enumValue, Enum.GetUnderlyingType(typeof(T)));
  1297. var s = Convert.ToString(i, CultureInfo.InvariantCulture);
  1298. var o = new Tuple<T>(enumValue);
  1299. _engine.SetValue("o", o);
  1300. RunTest("assert(o.Item1 === " + s + ");");
  1301. }
  1302. [Fact]
  1303. public void ShouldWorkWithEnumInt32()
  1304. {
  1305. TestEnum(TestEnumInt32.None);
  1306. TestEnum(TestEnumInt32.One);
  1307. TestEnum(TestEnumInt32.Min);
  1308. TestEnum(TestEnumInt32.Max);
  1309. }
  1310. [Fact]
  1311. public void ShouldWorkWithEnumUInt32()
  1312. {
  1313. TestEnum(TestEnumUInt32.None);
  1314. TestEnum(TestEnumUInt32.One);
  1315. TestEnum(TestEnumUInt32.Min);
  1316. TestEnum(TestEnumUInt32.Max);
  1317. }
  1318. [Fact]
  1319. public void ShouldWorkWithEnumInt64()
  1320. {
  1321. TestEnum(TestEnumInt64.None);
  1322. TestEnum(TestEnumInt64.One);
  1323. TestEnum(TestEnumInt64.Min);
  1324. TestEnum(TestEnumInt64.Max);
  1325. }
  1326. [Fact]
  1327. public void ShouldWorkWithEnumUInt64()
  1328. {
  1329. TestEnum(TestEnumUInt64.None);
  1330. TestEnum(TestEnumUInt64.One);
  1331. TestEnum(TestEnumUInt64.Min);
  1332. TestEnum(TestEnumUInt64.Max);
  1333. }
  1334. [Fact]
  1335. public void EnumIsConvertedToNumber()
  1336. {
  1337. var o = new
  1338. {
  1339. r = Colors.Red,
  1340. b = Colors.Blue,
  1341. g = Colors.Green
  1342. };
  1343. _engine.SetValue("o", o);
  1344. RunTest(@"
  1345. assert(o.r === 0);
  1346. assert(o.g === 1);
  1347. assert(o.b === 10);
  1348. ");
  1349. }
  1350. [Fact]
  1351. public void ShouldConvertToEnum()
  1352. {
  1353. var s = new Circle
  1354. {
  1355. Color = Colors.Red
  1356. };
  1357. _engine.SetValue("s", s);
  1358. RunTest(@"
  1359. assert(s.Color === 0);
  1360. s.Color = 10;
  1361. assert(s.Color === 10);
  1362. ");
  1363. _engine.SetValue("s", s);
  1364. RunTest(@"
  1365. s.Color = 11;
  1366. assert(s.Color === 11);
  1367. ");
  1368. Assert.Equal(Colors.Blue | Colors.Green, s.Color);
  1369. }
  1370. [Fact]
  1371. public void ShouldUseExplicitPropertyGetter()
  1372. {
  1373. _engine.SetValue("c", new Company("ACME"));
  1374. Assert.Equal("ACME", _engine.Evaluate("c.Name"));
  1375. }
  1376. [Fact]
  1377. public void ShouldUseExplicitIndexerPropertyGetter()
  1378. {
  1379. var company = new Company("ACME");
  1380. ((ICompany) company)["Foo"] = "Bar";
  1381. _engine.SetValue("c", company);
  1382. Assert.Equal("Bar", _engine.Evaluate("c.Foo"));
  1383. }
  1384. [Fact]
  1385. public void ShouldUseExplicitPropertySetter()
  1386. {
  1387. _engine.SetValue("c", new Company("ACME"));
  1388. Assert.Equal("Foo", _engine.Evaluate("c.Name = 'Foo'; c.Name;"));
  1389. }
  1390. [Fact]
  1391. public void ShouldUseExplicitIndexerPropertySetter()
  1392. {
  1393. var company = new Company("ACME");
  1394. ((ICompany) company)["Foo"] = "Bar";
  1395. _engine.SetValue("c", company);
  1396. RunTest(@"
  1397. c.Foo = 'Baz';
  1398. assert(c.Foo === 'Baz');
  1399. ");
  1400. }
  1401. [Fact]
  1402. public void ShouldUseExplicitMethod()
  1403. {
  1404. _engine.SetValue("c", new Company("ACME"));
  1405. RunTest(@"
  1406. assert(0 === c.CompareTo(c));
  1407. ");
  1408. }
  1409. [Fact]
  1410. public void ShouldCallInstanceMethodWithParams()
  1411. {
  1412. _engine.SetValue("a", new A());
  1413. RunTest(@"
  1414. assert(a.Call13('1','2','3') === '1,2,3');
  1415. assert(a.Call13('1') === '1');
  1416. assert(a.Call13(1) === '1');
  1417. assert(a.Call13() === '');
  1418. assert(a.Call14('a','1','2','3') === 'a:1,2,3');
  1419. assert(a.Call14('a','1') === 'a:1');
  1420. assert(a.Call14('a') === 'a:');
  1421. function call13wrapper(){ return a.Call13.apply(a, Array.prototype.slice.call(arguments)); }
  1422. assert(call13wrapper('1','2','3') === '1,2,3');
  1423. assert(a.Call13('1','2','3') === a.Call13(['1','2','3']));
  1424. ");
  1425. }
  1426. [Fact]
  1427. public void ShouldCallInstanceMethodWithJsValueParams()
  1428. {
  1429. _engine.SetValue("a", new A());
  1430. RunTest(@"
  1431. assert(a.Call16('1','2','3') === '1,2,3');
  1432. assert(a.Call16('1') === '1');
  1433. assert(a.Call16(1) === '1');
  1434. assert(a.Call16() === '');
  1435. assert(a.Call16('1','2','3') === a.Call16(['1','2','3']));
  1436. ");
  1437. }
  1438. [Fact]
  1439. public void NullValueAsArgumentShouldWork()
  1440. {
  1441. _engine.SetValue("a", new A());
  1442. RunTest(@"
  1443. var x = a.Call2(null);
  1444. assert(x === null);
  1445. ");
  1446. }
  1447. [Fact]
  1448. public void ShouldSetPropertyToNull()
  1449. {
  1450. var p = new Person { Name = "Mickey" };
  1451. _engine.SetValue("p", p);
  1452. RunTest(@"
  1453. assert(p.Name != null);
  1454. p.Name = null;
  1455. assert(p.Name == null);
  1456. ");
  1457. Assert.True(p.Name == null);
  1458. }
  1459. [Fact]
  1460. public void ShouldCallMethodWithNull()
  1461. {
  1462. _engine.SetValue("a", new A());
  1463. RunTest(@"
  1464. a.Call15(null);
  1465. var result = a.Call2(null);
  1466. assert(result == null);
  1467. ");
  1468. }
  1469. [Fact]
  1470. public void ShouldReturnUndefinedProperty()
  1471. {
  1472. _engine.SetValue("uo", new { foo = "bar" });
  1473. _engine.SetValue("ud", new Dictionary<string, object> { { "foo", "bar" } });
  1474. _engine.SetValue("ul", new List<string> { "foo", "bar" });
  1475. RunTest(@"
  1476. assert(!uo.undefinedProperty);
  1477. assert(!ul[5]);
  1478. assert(!ud.undefinedProperty);
  1479. ");
  1480. }
  1481. private class FailingObject2
  1482. {
  1483. public int this[int index] => throw new ArgumentException("index is bad", nameof(index));
  1484. }
  1485. [Fact]
  1486. public void ShouldPropagateIndexerExceptions()
  1487. {
  1488. var engine = new Engine();
  1489. engine.Execute(@"function f2(obj) { return obj[1]; }");
  1490. var failingObject = new FailingObject2();
  1491. Assert.Throws<ArgumentException>(() => engine.Invoke("f2", failingObject));
  1492. }
  1493. [Fact]
  1494. public void ShouldAutomaticallyConvertArraysToFindBestInteropResolution()
  1495. {
  1496. _engine.SetValue("a", new ArrayConverterTestClass());
  1497. _engine.SetValue("item1", new ArrayConverterItem(1));
  1498. _engine.SetValue("item2", new ArrayConverterItem(2));
  1499. RunTest(@"
  1500. assert(a.MethodAcceptsArrayOfInt([false, '1', 2]) === a.MethodAcceptsArrayOfInt([0, 1, 2]));
  1501. assert(a.MethodAcceptsArrayOfStrings(['1', 2]) === a.MethodAcceptsArrayOfStrings([1, 2]));
  1502. assert(a.MethodAcceptsArrayOfBool(['1', 0]) === a.MethodAcceptsArrayOfBool([true, false]));
  1503. assert(a.MethodAcceptsArrayOfStrings([item1, item2]) === a.MethodAcceptsArrayOfStrings(['1', '2']));
  1504. assert(a.MethodAcceptsArrayOfInt([item1, item2]) === a.MethodAcceptsArrayOfInt([1, 2]));
  1505. ");
  1506. }
  1507. [Fact]
  1508. public void ShouldImportNamespaceNestedType()
  1509. {
  1510. RunTest(@"
  1511. var shapes = importNamespace('Shapes.Circle');
  1512. var kinds = shapes.Kind;
  1513. assert(kinds.Unit === 0);
  1514. assert(kinds.Ellipse === 1);
  1515. assert(kinds.Round === 5);
  1516. ");
  1517. }
  1518. [Fact]
  1519. public void ShouldImportNamespaceNestedNestedType()
  1520. {
  1521. RunTest(@"
  1522. var meta = importNamespace('Shapes.Circle.Meta');
  1523. var usages = meta.Usage;
  1524. assert(usages.Public === 0);
  1525. assert(usages.Private === 1);
  1526. assert(usages.Internal === 11);
  1527. ");
  1528. }
  1529. [Fact]
  1530. public void ShouldGetNestedTypeFromParentType()
  1531. {
  1532. RunTest(@"
  1533. var Shapes = importNamespace('Shapes');
  1534. var usages = Shapes.Circle.Meta.Usage;
  1535. assert(usages.Public === 0);
  1536. assert(usages.Private === 1);
  1537. assert(usages.Internal === 11);
  1538. ");
  1539. }
  1540. [Fact]
  1541. public void ShouldGetNestedNestedProp()
  1542. {
  1543. RunTest(@"
  1544. var meta = importNamespace('Shapes.Circle');
  1545. var m = new meta.Meta();
  1546. assert(m.Description === 'descp');
  1547. ");
  1548. }
  1549. [Fact]
  1550. public void ShouldSetNestedNestedProp()
  1551. {
  1552. RunTest(@"
  1553. var meta = importNamespace('Shapes.Circle');
  1554. var m = new meta.Meta();
  1555. m.Description = 'hello';
  1556. assert(m.Description === 'hello');
  1557. ");
  1558. }
  1559. [Fact]
  1560. public void CanGetStaticNestedField()
  1561. {
  1562. RunTest(@"
  1563. var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
  1564. var statics = domain.ClassWithStaticFields;
  1565. assert(statics.Get == 'Get');
  1566. ");
  1567. }
  1568. [Fact]
  1569. public void CanSetStaticNestedField()
  1570. {
  1571. RunTest(@"
  1572. var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
  1573. var statics = domain.ClassWithStaticFields;
  1574. statics.Set = 'hello';
  1575. assert(statics.Set == 'hello');
  1576. ");
  1577. Assert.Equal(Nested.ClassWithStaticFields.Set, "hello");
  1578. }
  1579. [Fact]
  1580. public void CanGetStaticNestedAccessor()
  1581. {
  1582. RunTest(@"
  1583. var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
  1584. var statics = domain.ClassWithStaticFields;
  1585. assert(statics.Getter == 'Getter');
  1586. ");
  1587. }
  1588. [Fact]
  1589. public void CanSetStaticNestedAccessor()
  1590. {
  1591. RunTest(@"
  1592. var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
  1593. var statics = domain.ClassWithStaticFields;
  1594. statics.Setter = 'hello';
  1595. assert(statics.Setter == 'hello');
  1596. ");
  1597. Assert.Equal(Nested.ClassWithStaticFields.Setter, "hello");
  1598. }
  1599. [Fact]
  1600. public void CantSetStaticNestedReadonly()
  1601. {
  1602. RunTest(@"
  1603. var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
  1604. var statics = domain.ClassWithStaticFields;
  1605. statics.Readonly = 'hello';
  1606. assert(statics.Readonly == 'Readonly');
  1607. ");
  1608. Assert.Equal(Nested.ClassWithStaticFields.Readonly, "Readonly");
  1609. }
  1610. [Fact]
  1611. public void ShouldExecuteFunctionWithValueTypeParameterCorrectly()
  1612. {
  1613. _engine.SetValue("a", new A());
  1614. // Func<int, int>
  1615. RunTest(@"
  1616. assert(a.Call17(function(value){ return value; }) === 17);
  1617. ");
  1618. }
  1619. [Fact]
  1620. public void ShouldExecuteActionWithValueTypeParameterCorrectly()
  1621. {
  1622. _engine.SetValue("a", new A());
  1623. // Action<int>
  1624. RunTest(@"
  1625. a.Call18(function(value){ assert(value === 18); });
  1626. ");
  1627. }
  1628. [Fact]
  1629. public void ShouldConvertToJsValue()
  1630. {
  1631. RunTest(@"
  1632. var now = System.DateTime.Now;
  1633. assert(new String(now) == now.toString());
  1634. var zero = System.Int32.MaxValue;
  1635. assert(new String(zero) == zero.toString());
  1636. ");
  1637. }
  1638. [Fact]
  1639. public void ShouldNotCatchClrExceptions()
  1640. {
  1641. var engine = new Engine()
  1642. .SetValue("throwMyException", new Action(() => { throw new NotSupportedException(); }))
  1643. .SetValue("Thrower", typeof(Thrower))
  1644. .Execute(@"
  1645. function throwException1(){
  1646. try {
  1647. throwMyException();
  1648. return;
  1649. }
  1650. catch(e) {
  1651. return;
  1652. }
  1653. }
  1654. function throwException2(){
  1655. try {
  1656. new Thrower().ThrowNotSupportedException();
  1657. return;
  1658. }
  1659. catch(e) {
  1660. return;
  1661. }
  1662. }
  1663. ");
  1664. Assert.ThrowsAny<NotSupportedException>(() => engine.Invoke("throwException1"));
  1665. Assert.ThrowsAny<NotSupportedException>(() => engine.Invoke("throwException2"));
  1666. }
  1667. [Fact]
  1668. public void ShouldCatchAllClrExceptions()
  1669. {
  1670. var exceptionMessage = "myExceptionMessage";
  1671. var engine = new Engine(o => o.CatchClrExceptions())
  1672. .SetValue("throwMyException", new Action(() => { throw new Exception(exceptionMessage); }))
  1673. .SetValue("Thrower", typeof(Thrower))
  1674. .Execute(@"
  1675. function throwException1(){
  1676. try {
  1677. throwMyException();
  1678. return '';
  1679. }
  1680. catch(e) {
  1681. return e.message;
  1682. }
  1683. }
  1684. function throwException2(){
  1685. try {
  1686. new Thrower().ThrowExceptionWithMessage('myExceptionMessage');
  1687. return;
  1688. }
  1689. catch(e) {
  1690. return e.message;
  1691. }
  1692. }
  1693. ");
  1694. Assert.Equal(engine.Invoke("throwException1").AsString(), exceptionMessage);
  1695. Assert.Equal(engine.Invoke("throwException2").AsString(), exceptionMessage);
  1696. }
  1697. [Fact]
  1698. public void ShouldNotCatchClrFromApply()
  1699. {
  1700. var engine = new Engine(options =>
  1701. {
  1702. options.CatchClrExceptions(e =>
  1703. {
  1704. Assert.Fail("was called");
  1705. return true;
  1706. });
  1707. });
  1708. engine.Execute(@"
  1709. function throwError() {
  1710. throw new Error();
  1711. }
  1712. // doesn't cause ExceptionDelegateHandler call
  1713. try { throwError(); } catch {}
  1714. // does cause ExceptionDelegateHandler call
  1715. try { throwError.apply(); } catch {}
  1716. ");
  1717. }
  1718. private class MemberExceptionTest
  1719. {
  1720. public MemberExceptionTest(bool throwOnCreate)
  1721. {
  1722. if (throwOnCreate)
  1723. {
  1724. throw new InvalidOperationException("thrown as requested");
  1725. }
  1726. }
  1727. public JsValue ThrowingProperty1
  1728. {
  1729. get => throw new InvalidOperationException();
  1730. set => throw new InvalidOperationException();
  1731. }
  1732. public object ThrowingProperty2
  1733. {
  1734. get => throw new InvalidOperationException();
  1735. set => throw new InvalidOperationException();
  1736. }
  1737. public void ThrowingFunction()
  1738. {
  1739. throw new InvalidOperationException();
  1740. }
  1741. }
  1742. [Fact]
  1743. public void ShouldCatchClrMemberExceptions()
  1744. {
  1745. var engine = new Engine(cfg =>
  1746. {
  1747. cfg.AllowClr();
  1748. cfg.CatchClrExceptions();
  1749. });
  1750. engine.SetValue("assert", new Action<bool>(Assert.True));
  1751. engine.SetValue("log", new Action<object>(Console.WriteLine));
  1752. engine.SetValue("create", typeof(MemberExceptionTest));
  1753. engine.SetValue("instance", new MemberExceptionTest(false));
  1754. // Test calling a constructor that throws an exception
  1755. engine.Execute(@"
  1756. try
  1757. {
  1758. create(true);
  1759. assert(false);
  1760. }
  1761. catch (e)
  1762. {
  1763. assert(true);
  1764. }
  1765. ");
  1766. // Test calling a member function that throws an exception
  1767. engine.Execute(@"
  1768. try
  1769. {
  1770. instance.ThrowingFunction();
  1771. assert(false);
  1772. }
  1773. catch (e)
  1774. {
  1775. assert(true);
  1776. }
  1777. ");
  1778. // Test using a property getter that throws an exception
  1779. engine.Execute(@"
  1780. try
  1781. {
  1782. log(o.ThrowingProperty);
  1783. assert(false);
  1784. }
  1785. catch (e)
  1786. {
  1787. assert(true);
  1788. }
  1789. ");
  1790. // Test using a property setter that throws an exception
  1791. engine.Execute(@"
  1792. try
  1793. {
  1794. instance.ThrowingProperty1 = 123;
  1795. assert(false);
  1796. }
  1797. catch (e)
  1798. {
  1799. assert(true);
  1800. }
  1801. try
  1802. {
  1803. instance.ThrowingProperty2 = 456;
  1804. assert(false);
  1805. }
  1806. catch (e)
  1807. {
  1808. assert(true);
  1809. }
  1810. ");
  1811. }
  1812. [Fact]
  1813. public void ShouldCatchSomeExceptions()
  1814. {
  1815. var exceptionMessage = "myExceptionMessage";
  1816. var engine = new Engine(o => o.CatchClrExceptions(e => e is NotSupportedException))
  1817. .SetValue("throwMyException1", new Action(() => { throw new NotSupportedException(exceptionMessage); }))
  1818. .SetValue("throwMyException2", new Action(() => { throw new ArgumentNullException(); }))
  1819. .SetValue("Thrower", typeof(Thrower))
  1820. .Execute(@"
  1821. function throwException1(){
  1822. try {
  1823. throwMyException1();
  1824. return '';
  1825. }
  1826. catch(e) {
  1827. return e.message;
  1828. }
  1829. }
  1830. function throwException2(){
  1831. try {
  1832. throwMyException2();
  1833. return '';
  1834. }
  1835. catch(e) {
  1836. return e.message;
  1837. }
  1838. }
  1839. function throwException3(){
  1840. try {
  1841. new Thrower().ThrowNotSupportedExceptionWithMessage('myExceptionMessage');
  1842. return '';
  1843. }
  1844. catch(e) {
  1845. return e.message;
  1846. }
  1847. }
  1848. function throwException4(){
  1849. try {
  1850. new Thrower().ThrowArgumentNullException();
  1851. return '';
  1852. }
  1853. catch(e) {
  1854. return e.message;
  1855. }
  1856. }
  1857. ");
  1858. Assert.Equal(engine.Invoke("throwException1").AsString(), exceptionMessage);
  1859. Assert.Throws<ArgumentNullException>(() => engine.Invoke("throwException2"));
  1860. Assert.Equal(engine.Invoke("throwException3").AsString(), exceptionMessage);
  1861. Assert.Throws<ArgumentNullException>(() => engine.Invoke("throwException4"));
  1862. }
  1863. [Fact]
  1864. public void ArrayFromShouldConvertListToArrayLike()
  1865. {
  1866. var list = new List<Person>
  1867. {
  1868. new Person { Name = "Mike" },
  1869. new Person { Name = "Mika" }
  1870. };
  1871. _engine.SetValue("a", list);
  1872. RunTest(@"
  1873. var arr = new Array(a);
  1874. assert(arr.length === 2);
  1875. assert(arr[0].Name === 'Mike');
  1876. assert(arr[1].Name === 'Mika');
  1877. ");
  1878. RunTest(@"
  1879. var arr = Array.from(a);
  1880. assert(arr.length === 2);
  1881. assert(arr[0].Name === 'Mike');
  1882. assert(arr[1].Name === 'Mika');
  1883. ");
  1884. }
  1885. [Fact]
  1886. public void ArrayFromShouldConvertArrayToArrayLike()
  1887. {
  1888. var list = new[]
  1889. {
  1890. new Person { Name = "Mike" },
  1891. new Person { Name = "Mika" }
  1892. };
  1893. _engine.SetValue("a", list);
  1894. RunTest(@"
  1895. var arr = new Array(a);
  1896. assert(arr.length === 2);
  1897. assert(arr[0].Name === 'Mike');
  1898. assert(arr[1].Name === 'Mika');
  1899. ");
  1900. RunTest(@"
  1901. var arr = Array.from(a);
  1902. assert(arr.length === 2);
  1903. assert(arr[0].Name === 'Mike');
  1904. assert(arr[1].Name === 'Mika');
  1905. ");
  1906. }
  1907. [Fact]
  1908. public void ArrayFromShouldConvertIEnumerable()
  1909. {
  1910. var enumerable = new[]
  1911. {
  1912. new Person { Name = "Mike" },
  1913. new Person { Name = "Mika" }
  1914. }.Select(x => x);
  1915. _engine.SetValue("a", enumerable);
  1916. RunTest(@"
  1917. var arr = new Array(a);
  1918. assert(arr.length === 2);
  1919. assert(arr[0].Name === 'Mike');
  1920. assert(arr[1].Name === 'Mika');
  1921. ");
  1922. RunTest(@"
  1923. var arr = Array.from(a);
  1924. assert(arr.length === 2);
  1925. assert(arr[0].Name === 'Mike');
  1926. assert(arr[1].Name === 'Mika');
  1927. ");
  1928. }
  1929. [Fact]
  1930. public void ShouldBeAbleToPlusAssignStringProperty()
  1931. {
  1932. var p = new Person();
  1933. var engine = new Engine();
  1934. engine.SetValue("P", p);
  1935. engine.Evaluate("P.Name = 'b';");
  1936. engine.Evaluate("P.Name += 'c';");
  1937. Assert.Equal("bc", p.Name);
  1938. }
  1939. [Fact]
  1940. public void ShouldNotResolveToPrimitiveSymbol()
  1941. {
  1942. var engine = new Engine(options =>
  1943. options.AllowClr(typeof(FloatIndexer).GetTypeInfo().Assembly));
  1944. var c = engine.Evaluate(@"
  1945. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1946. return new domain.FloatIndexer();
  1947. ");
  1948. Assert.NotNull(c.ToString());
  1949. Assert.Equal((uint) 0, c.AsObject().GetLength());
  1950. }
  1951. private class DictionaryWrapper
  1952. {
  1953. public IDictionary<string, object> Values { get; set; }
  1954. }
  1955. private class DictionaryTest
  1956. {
  1957. public void Test1(IDictionary<string, object> values)
  1958. {
  1959. Assert.Equal(1, Convert.ToInt32(values["a"]));
  1960. }
  1961. public void Test2(DictionaryWrapper dictionaryObject)
  1962. {
  1963. Assert.Equal(1, Convert.ToInt32(dictionaryObject.Values["a"]));
  1964. }
  1965. }
  1966. [Fact]
  1967. public void ShouldBeAbleToPassDictionaryToMethod()
  1968. {
  1969. var engine = new Engine();
  1970. engine.SetValue("dictionaryTest", new DictionaryTest());
  1971. engine.Evaluate("dictionaryTest.test1({ a: 1 });");
  1972. }
  1973. [Fact]
  1974. public void ShouldBeAbleToPassDictionaryInObjectToMethod()
  1975. {
  1976. var engine = new Engine();
  1977. engine.SetValue("dictionaryTest", new DictionaryTest());
  1978. engine.Evaluate("dictionaryTest.test2({ values: { a: 1 } });");
  1979. }
  1980. [Fact]
  1981. public void ShouldSupportSpreadForDictionary()
  1982. {
  1983. var engine = new Engine();
  1984. var state = new Dictionary<string, object>
  1985. {
  1986. { "invoice", new Dictionary<string, object> { ["number"] = "42" } }
  1987. };
  1988. engine.SetValue("state", state);
  1989. var result = (IDictionary<string, object>) engine
  1990. .Evaluate("({ supplier: 'S1', ...state.invoice })")
  1991. .ToObject();
  1992. Assert.Equal("S1", result["supplier"]);
  1993. Assert.Equal("42", result["number"]);
  1994. }
  1995. [Fact]
  1996. public void ShouldSupportSpreadForDictionary2()
  1997. {
  1998. var engine = new Engine();
  1999. var state = new Dictionary<string, object>
  2000. {
  2001. { "invoice", new Dictionary<string, object> { ["number"] = "42" } }
  2002. };
  2003. engine.SetValue("state", state);
  2004. var result = (IDictionary<string, object>) engine
  2005. .Execute("function getValue() { return {supplier: 'S1', ...state.invoice}; }")
  2006. .Invoke("getValue")
  2007. .ToObject();
  2008. Assert.Equal("S1", result["supplier"]);
  2009. Assert.Equal("42", result["number"]);
  2010. }
  2011. [Fact]
  2012. public void ShouldSupportSpreadForObject()
  2013. {
  2014. var engine = new Engine();
  2015. var person = new Person
  2016. {
  2017. Name = "Mike",
  2018. Age = 20
  2019. };
  2020. engine.SetValue("p", person);
  2021. var result = (IDictionary<string, object>) engine
  2022. .Evaluate("({ supplier: 'S1', ...p })")
  2023. .ToObject();
  2024. Assert.Equal("S1", result["supplier"]);
  2025. Assert.Equal("Mike", result["Name"]);
  2026. Assert.Equal(20d, result["Age"]);
  2027. }
  2028. [Fact]
  2029. public void ShouldBeAbleToJsonStringifyClrObjects()
  2030. {
  2031. var engine = new Engine();
  2032. engine.Evaluate("var jsObj = { 'key1' :'value1', 'key2' : 'value2' }");
  2033. engine.SetValue("netObj", new Dictionary<string, object>
  2034. {
  2035. { "key1", "value1" },
  2036. { "key2", "value2" }
  2037. });
  2038. var jsValue = engine.Evaluate("jsObj['key1']").AsString();
  2039. var clrValue = engine.Evaluate("netObj['key1']").AsString();
  2040. Assert.Equal(jsValue, clrValue);
  2041. jsValue = engine.Evaluate("JSON.stringify(jsObj)").AsString();
  2042. clrValue = engine.Evaluate("JSON.stringify(netObj)").AsString();
  2043. Assert.Equal(jsValue, clrValue);
  2044. // Write properties on screen using showProps function defined on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
  2045. engine.Execute(@"function showProps(obj, objName) {
  2046. var result = """";
  2047. for (var i in obj) {
  2048. if (obj.hasOwnProperty(i)) {
  2049. result += objName + ""."" + i + "" = "" + obj[i] + ""\n"";
  2050. }
  2051. }
  2052. return result;
  2053. }");
  2054. jsValue = engine.Evaluate("showProps(jsObj, 'theObject')").AsString();
  2055. clrValue = engine.Evaluate("showProps(jsObj, 'theObject')").AsString();
  2056. Assert.Equal(jsValue, clrValue);
  2057. }
  2058. [Fact]
  2059. public void SettingValueViaIntegerIndexer()
  2060. {
  2061. var engine = new Engine(cfg => cfg.AllowClr(typeof(FloatIndexer).GetTypeInfo().Assembly));
  2062. engine.SetValue("log", new Action<object>(Console.WriteLine));
  2063. engine.Execute(@"
  2064. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  2065. var fia = new domain.IntegerIndexer();
  2066. log(fia[0]);
  2067. ");
  2068. Assert.Equal(123, engine.Evaluate("fia[0]").AsNumber());
  2069. engine.Evaluate("fia[0] = 678;");
  2070. Assert.Equal(678, engine.Evaluate("fia[0]").AsNumber());
  2071. }
  2072. [Fact]
  2073. public void IndexingBsonProperties()
  2074. {
  2075. const string jsonAnimals = @" { ""Animals"": [ { ""Id"": 1, ""Type"": ""Cat"" } ] }";
  2076. var bsonAnimals = BsonDocument.Parse(jsonAnimals);
  2077. _engine.SetValue("animals", bsonAnimals["Animals"]);
  2078. // weak equality does conversions from native types
  2079. Assert.True(_engine.Evaluate("animals[0].Type == 'Cat'").AsBoolean());
  2080. Assert.True(_engine.Evaluate("animals[0].Id == 1").AsBoolean());
  2081. }
  2082. [Fact]
  2083. public void IntegerAndFloatInFunctionOverloads()
  2084. {
  2085. var engine = new Engine(options => options.AllowClr(GetType().Assembly));
  2086. engine.SetValue("a", new OverLoading());
  2087. Assert.Equal("int-val", engine.Evaluate("a.testFunc(123);").AsString());
  2088. Assert.Equal("float-val", engine.Evaluate("a.testFunc(12.3);").AsString());
  2089. }
  2090. [Fact]
  2091. public void TypeConversionWithTemporaryInvalidValuesShouldNotCache()
  2092. {
  2093. var engine = new Engine(options => options.AllowClr());
  2094. engine.SetValue("IntValueInput", TypeReference.CreateTypeReference(engine, typeof(IntValueInput)));
  2095. var ex = Assert.Throws<JavaScriptException>(() => engine.Evaluate("new IntValueInput().testFunc(NaN);").AsString());
  2096. Assert.Equal("No public methods with the specified arguments were found.", ex.Message);
  2097. Assert.Equal(123, engine.Evaluate("new IntValueInput().testFunc(123);").AsNumber());
  2098. }
  2099. [Fact]
  2100. public void CanConvertFloatingPointToIntegerWithoutError()
  2101. {
  2102. var engine = new Engine(options => options.AllowClr());
  2103. engine.SetValue("IntValueInput", TypeReference.CreateTypeReference(engine, typeof(IntValueInput)));
  2104. Assert.Equal(12, engine.Evaluate("new IntValueInput().testFunc(12.3);").AsNumber());
  2105. }
  2106. public class IntValueInput
  2107. {
  2108. public int TestFunc(int value) => value;
  2109. }
  2110. public class TestItem
  2111. {
  2112. public double Cost { get; set; }
  2113. public double Age { get; set; }
  2114. public string Name { get; set; }
  2115. }
  2116. public class TestItemList : List<TestItem>
  2117. {
  2118. public double Sum(Func<TestItem, double> calc)
  2119. {
  2120. double rc = 0;
  2121. foreach (var item in this)
  2122. {
  2123. rc += calc(item);
  2124. }
  2125. return rc;
  2126. }
  2127. public TestItemList Where(Func<TestItem, bool> cond)
  2128. {
  2129. var rc = new TestItemList();
  2130. foreach (var item in this)
  2131. {
  2132. if (cond(item))
  2133. {
  2134. rc.Add(item);
  2135. }
  2136. }
  2137. return rc;
  2138. }
  2139. }
  2140. [Fact]
  2141. public void DelegateCanReturnValue()
  2142. {
  2143. var engine = new Engine(options => options.AllowClr(GetType().Assembly));
  2144. var lst = new TestItemList();
  2145. lst.Add(new TestItem() { Name = "a", Cost = 1, Age = 10 });
  2146. lst.Add(new TestItem() { Name = "a", Cost = 1, Age = 10 });
  2147. lst.Add(new TestItem() { Name = "b", Cost = 1, Age = 10 });
  2148. lst.Add(new TestItem() { Name = "b", Cost = 1, Age = 10 });
  2149. lst.Add(new TestItem() { Name = "b", Cost = 1, Age = 10 });
  2150. engine.SetValue("lst", lst);
  2151. Assert.Equal(5, engine.Evaluate("lst.Sum(x => x.Cost);").AsNumber());
  2152. Assert.Equal(50, engine.Evaluate("lst.Sum(x => x.Age);").AsNumber());
  2153. Assert.Equal(3, engine.Evaluate("lst.Where(x => x.Name == 'b').Count;").AsNumber());
  2154. Assert.Equal(30, engine.Evaluate("lst.Where(x => x.Name == 'b').Sum(x => x.Age);").AsNumber());
  2155. }
  2156. [Fact]
  2157. public void ObjectWrapperOverridingEquality()
  2158. {
  2159. // equality same via name
  2160. _engine.SetValue("a", new Person { Name = "Name" });
  2161. _engine.SetValue("b", new Person { Name = "Name" });
  2162. _engine.Evaluate("const arr = [ null, a, undefined ];");
  2163. Assert.Equal(1, _engine.Evaluate("arr.filter(x => x == b).length").AsNumber());
  2164. Assert.Equal(1, _engine.Evaluate("arr.filter(x => x === b).length").AsNumber());
  2165. Assert.True(_engine.Evaluate("arr.find(x => x == b) === a").AsBoolean());
  2166. Assert.True(_engine.Evaluate("arr.find(x => x === b) == a").AsBoolean());
  2167. Assert.Equal(1, _engine.Evaluate("arr.findIndex(x => x == b)").AsNumber());
  2168. Assert.Equal(1, _engine.Evaluate("arr.findIndex(x => x === b)").AsNumber());
  2169. Assert.Equal(1, _engine.Evaluate("arr.indexOf(b)").AsNumber());
  2170. Assert.True(_engine.Evaluate("arr.includes(b)").AsBoolean());
  2171. }
  2172. [Fact]
  2173. public void ObjectWrapperWrappingDictionaryShouldNotBeArrayLike()
  2174. {
  2175. var wrapper = ObjectWrapper.Create(_engine, new Dictionary<string, object>());
  2176. Assert.False(wrapper.IsArrayLike);
  2177. }
  2178. [Fact]
  2179. public void ShouldHandleCyclicReferences()
  2180. {
  2181. var engine = new Engine();
  2182. static void Test(string message, object value)
  2183. {
  2184. Console.WriteLine(message);
  2185. }
  2186. engine.Realm.GlobalObject.FastSetDataProperty("global", engine.Realm.GlobalObject);
  2187. engine.Realm.GlobalObject.FastSetDataProperty("test", new DelegateWrapper(engine, (Action<string, object>) Test));
  2188. {
  2189. var ex = Assert.Throws<JavaScriptException>(() => engine.Realm.GlobalObject.ToObject());
  2190. Assert.Equal("Cyclic reference detected.", ex.Message);
  2191. }
  2192. {
  2193. var ex = Assert.Throws<JavaScriptException>(() =>
  2194. engine.Execute(@"
  2195. var demo={};
  2196. demo.value=1;
  2197. test('Test 1', demo.value===1);
  2198. test('Test 2', demo.value);
  2199. demo.demo=demo;
  2200. test('Test 3', demo);
  2201. test('Test 4', global);"
  2202. )
  2203. );
  2204. Assert.Equal("Cyclic reference detected.", ex.Message);
  2205. }
  2206. }
  2207. [Fact]
  2208. public void CanConfigurePropertyNameMatcher()
  2209. {
  2210. // defaults
  2211. var e = new Engine();
  2212. e.SetValue("a", new A());
  2213. Assert.True(e.Evaluate("a.call1").IsObject());
  2214. Assert.True(e.Evaluate("a.Call1").IsObject());
  2215. Assert.True(e.Evaluate("a.CALL1").IsUndefined());
  2216. e = new Engine(options =>
  2217. {
  2218. options.SetTypeResolver(new TypeResolver
  2219. {
  2220. MemberNameComparer = StringComparer.Ordinal
  2221. });
  2222. });
  2223. e.SetValue("a", new A());
  2224. Assert.True(e.Evaluate("a.call1").IsUndefined());
  2225. Assert.True(e.Evaluate("a.Call1").IsObject());
  2226. Assert.True(e.Evaluate("a.CALL1").IsUndefined());
  2227. e = new Engine(options =>
  2228. {
  2229. options.SetTypeResolver(new TypeResolver
  2230. {
  2231. MemberNameComparer = StringComparer.OrdinalIgnoreCase
  2232. });
  2233. });
  2234. e.SetValue("a", new A());
  2235. Assert.True(e.Evaluate("a.call1").IsObject());
  2236. Assert.True(e.Evaluate("a.Call1").IsObject());
  2237. Assert.True(e.Evaluate("a.CALL1").IsObject());
  2238. }
  2239. [Fact]
  2240. public void ShouldNotEnumerateClassMethods()
  2241. {
  2242. var engine = new Engine();
  2243. var dictionary = new Dictionary<string, object>
  2244. {
  2245. { "foo", 5 },
  2246. { "bar", "A string" }
  2247. };
  2248. engine.SetValue("dictionary", dictionary);
  2249. var result = engine.Evaluate($"Object.keys(dictionary).join(',')").AsString();
  2250. Assert.Equal("foo,bar", result);
  2251. engine.Execute("dictionary.ContainsKey('foo')");
  2252. result = engine.Evaluate($"Object.keys(dictionary).join(',')").AsString();
  2253. Assert.Equal("foo,bar", result);
  2254. }
  2255. [Fact]
  2256. public void ShouldNotEnumerateExtensionMethods()
  2257. {
  2258. var engine = new Engine(cfg => cfg.AddExtensionMethods(typeof(Enumerable)));
  2259. var result = engine.Evaluate("Object.keys({ ...[1,2,3] }).join(',')").AsString();
  2260. Assert.Equal("0,1,2", result);
  2261. var script = @"
  2262. var arr = [1,2,3];
  2263. var keys = [];
  2264. for(var index in arr) keys.push(index);
  2265. keys.join(',');
  2266. ";
  2267. result = engine.Evaluate(script).ToString();
  2268. Assert.Equal("0,1,2", result);
  2269. }
  2270. [Fact]
  2271. public void CanCheckIfCallable()
  2272. {
  2273. var engine = new Engine();
  2274. engine.Evaluate("var f = () => true;");
  2275. var result = engine.GetValue("f");
  2276. Assert.True(result.IsCallable);
  2277. Assert.True(result.Call(Array.Empty<JsValue>()).AsBoolean());
  2278. Assert.True(result.Call().AsBoolean());
  2279. }
  2280. [Fact]
  2281. public void CanGiveCustomNameToInteropMembers()
  2282. {
  2283. static IEnumerable<string> MemberNameCreator(MemberInfo prop)
  2284. {
  2285. var attributes = prop.GetCustomAttributes(typeof(CustomNameAttribute), true);
  2286. if (attributes.Length > 0)
  2287. {
  2288. foreach (CustomNameAttribute attribute in attributes)
  2289. {
  2290. yield return attribute.Name;
  2291. }
  2292. }
  2293. else
  2294. {
  2295. yield return prop.Name;
  2296. }
  2297. }
  2298. var customTypeResolver = new TypeResolver
  2299. {
  2300. MemberNameCreator = MemberNameCreator
  2301. };
  2302. var engine = new Engine(options =>
  2303. {
  2304. options.SetTypeResolver(customTypeResolver);
  2305. options.AddExtensionMethods(typeof(CustomNamedExtensions));
  2306. });
  2307. engine.SetValue("o", new CustomNamed());
  2308. Assert.Equal("StringField", engine.Evaluate("o.jsStringField").AsString());
  2309. Assert.Equal("StringField", engine.Evaluate("o.jsStringField2").AsString());
  2310. Assert.Equal("StaticStringField", engine.Evaluate("o.jsStaticStringField").AsString());
  2311. Assert.Equal("StringProperty", engine.Evaluate("o.jsStringProperty").AsString());
  2312. Assert.Equal("Method", engine.Evaluate("o.jsMethod()").AsString());
  2313. Assert.Equal("StaticMethod", engine.Evaluate("o.jsStaticMethod()").AsString());
  2314. Assert.Equal("InterfaceStringProperty", engine.Evaluate("o.jsInterfaceStringProperty").AsString());
  2315. Assert.Equal("InterfaceMethod", engine.Evaluate("o.jsInterfaceMethod()").AsString());
  2316. Assert.Equal("ExtensionMethod", engine.Evaluate("o.jsExtensionMethod()").AsString());
  2317. engine.SetValue("XmlHttpRequest", typeof(CustomNamedEnum));
  2318. engine.Evaluate("o.jsEnumProperty = XmlHttpRequest.HEADERS_RECEIVED;");
  2319. Assert.Equal((int) CustomNamedEnum.HeadersReceived, engine.Evaluate("o.jsEnumProperty").AsNumber());
  2320. }
  2321. [Fact]
  2322. public void ShouldBeAbleToHandleInvalidClrConversionViaCatchClrExceptions()
  2323. {
  2324. var engine = new Engine(cfg => cfg.CatchClrExceptions());
  2325. engine.SetValue("a", new Person());
  2326. var ex = Assert.Throws<JavaScriptException>(() => engine.Execute("a.age = 'It will not work, but it is normal'"));
  2327. Assert.Contains("input string ", ex.Message, StringComparison.OrdinalIgnoreCase);
  2328. Assert.Contains(" was not in a correct format", ex.Message, StringComparison.OrdinalIgnoreCase);
  2329. }
  2330. [Fact]
  2331. public void ShouldLetNotSupportedExceptionBubble()
  2332. {
  2333. _engine.SetValue("profile", new Profile());
  2334. var ex = Assert.Throws<NotSupportedException>(() => _engine.Evaluate("profile.AnyProperty"));
  2335. Assert.Equal("NOT SUPPORTED", ex.Message);
  2336. }
  2337. [Fact]
  2338. public void ShouldBeAbleToUseConvertibleStructAsMethodParameter()
  2339. {
  2340. _engine.SetValue("test", new DiscordTestClass());
  2341. _engine.SetValue("id", new DiscordId("12345"));
  2342. Assert.Equal("12345", _engine.Evaluate("String(id)").AsString());
  2343. Assert.Equal("12345", _engine.Evaluate("test.echo('12345')").AsString());
  2344. Assert.Equal("12345", _engine.Evaluate("test.create(12345)").AsString());
  2345. }
  2346. [Fact]
  2347. public void ShouldGetIteratorForListAndDictionary()
  2348. {
  2349. const string Script = @"
  2350. var it = collection[Symbol.iterator]();
  2351. var result = it.next();
  2352. var str = """";
  2353. while (!result.done) {
  2354. str += result.value;
  2355. result = it.next();
  2356. }
  2357. return str;";
  2358. _engine.SetValue("collection", new List<string> { "a", "b", "c" });
  2359. Assert.Equal("abc", _engine.Evaluate(Script));
  2360. _engine.SetValue("collection", new Dictionary<string, object> { { "a", 1 }, { "b", 2 }, { "c", 3 } });
  2361. Assert.Equal("a,1b,2c,3", _engine.Evaluate(Script));
  2362. }
  2363. [Fact]
  2364. public void ShouldNotIntroduceNewPropertiesWhenTraversing()
  2365. {
  2366. _engine.SetValue("x", new Dictionary<string, int> { { "First", 1 }, { "Second", 2 } });
  2367. Assert.Equal("[\"First\",\"Second\"]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));
  2368. Assert.Equal("x['First']: 1", _engine.Evaluate("\"x['First']: \" + x['First']"));
  2369. Assert.Equal("[\"First\",\"Second\"]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));
  2370. Assert.Equal("x['Third']: undefined", _engine.Evaluate("\"x['Third']: \" + x['Third']"));
  2371. Assert.Equal("[\"First\",\"Second\"]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));
  2372. Assert.Equal(JsValue.Undefined, _engine.Evaluate("x.length"));
  2373. Assert.Equal("[\"First\",\"Second\"]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));
  2374. Assert.Equal(2, _engine.Evaluate("x.Count").AsNumber());
  2375. Assert.Equal("[\"First\",\"Second\"]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));
  2376. _engine.Evaluate("x.Clear();");
  2377. Assert.Equal("[]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));
  2378. _engine.Evaluate("x['Fourth'] = 4;");
  2379. Assert.Equal("[\"Fourth\"]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));
  2380. Assert.False(_engine.Evaluate("Object.prototype.hasOwnProperty.call(x, 'Third')").AsBoolean());
  2381. }
  2382. [Fact]
  2383. public void CanConfigureCustomObjectTypeForJsToClrConversion()
  2384. {
  2385. var engine = new Engine(options =>
  2386. {
  2387. options.Interop.CreateClrObject = oi => new Dictionary<string, object>();
  2388. });
  2389. object capture = null;
  2390. var callback = (object value) => capture = value;
  2391. engine.SetValue("callback", callback);
  2392. engine.Evaluate("callback(({'a': 'b'}));");
  2393. Assert.IsType<Dictionary<string, object>>(capture);
  2394. var dictionary = (Dictionary<string, object>) capture;
  2395. Assert.Equal("b", dictionary["a"]);
  2396. }
  2397. [Fact]
  2398. public void ArrayPrototypeIndexOfWithInteropList()
  2399. {
  2400. var engine = new Jint.Engine();
  2401. engine.SetValue("list", new List<string> { "A", "B", "C" });
  2402. Assert.Equal(1, engine.Evaluate("list.indexOf('B')"));
  2403. Assert.Equal(1, engine.Evaluate("list.lastIndexOf('B')"));
  2404. Assert.Equal(1, engine.Evaluate("Array.prototype.indexOf.call(list, 'B')"));
  2405. Assert.Equal(1, engine.Evaluate("Array.prototype.lastIndexOf.call(list, 'B')"));
  2406. }
  2407. [Fact]
  2408. public void ArrayPrototypeFindWithInteropList()
  2409. {
  2410. var engine = new Jint.Engine();
  2411. var list = new List<string> { "A", "B", "C" };
  2412. engine.SetValue("list", list);
  2413. Assert.Equal(1, engine.Evaluate("list.findIndex((x) => x === 'B')"));
  2414. Assert.Equal('B', engine.Evaluate("list.find((x) => x === 'B')"));
  2415. }
  2416. [Fact]
  2417. public void ArrayPrototypePushWithInteropList()
  2418. {
  2419. var engine = new Jint.Engine();
  2420. var list = new List<string> { "A", "B", "C" };
  2421. engine.SetValue("list", list);
  2422. engine.Evaluate("list.push('D')");
  2423. Assert.Equal(4, list.Count);
  2424. Assert.Equal("D", list[3]);
  2425. Assert.Equal(3, engine.Evaluate("list.lastIndexOf('D')"));
  2426. }
  2427. [Fact]
  2428. public void ArrayPrototypePopWithInteropList()
  2429. {
  2430. var engine = new Jint.Engine();
  2431. var list = new List<string> { "A", "B", "C" };
  2432. engine.SetValue("list", list);
  2433. Assert.Equal(2, engine.Evaluate("list.lastIndexOf('C')"));
  2434. Assert.Equal(3, list.Count);
  2435. Assert.Equal("C", engine.Evaluate("list.pop()"));
  2436. Assert.Equal(2, list.Count);
  2437. Assert.Equal(-1, engine.Evaluate("list.lastIndexOf('C')"));
  2438. }
  2439. [Fact]
  2440. public void ShouldBeJavaScriptException()
  2441. {
  2442. var engine = new Engine(cfg => cfg.AllowClr().AllowOperatorOverloading().CatchClrExceptions());
  2443. engine.SetValue("Dimensional", typeof(Dimensional));
  2444. engine.Execute(@"
  2445. function Eval(param0, param1)
  2446. {
  2447. var result = param0 + param1;
  2448. return result;
  2449. }");
  2450. // checking working custom type
  2451. Assert.Equal(new Dimensional("kg", 90), (new Dimensional("kg", 30) + new Dimensional("kg", 60)));
  2452. Assert.Equal(new Dimensional("kg", 90), engine.Invoke("Eval", new object[] { new Dimensional("kg", 30), new Dimensional("kg", 60) }).ToObject());
  2453. Assert.Throws<InvalidOperationException>(() => new Dimensional("kg", 30) + new Dimensional("piece", 70));
  2454. // checking throwing exception in override operator
  2455. string errorMsg = string.Empty;
  2456. errorMsg = Assert.Throws<JavaScriptException>(() => engine.Invoke("Eval", new object[] { new Dimensional("kg", 30), new Dimensional("piece", 70) })).Message;
  2457. Assert.Equal("Dimensionals with different measure types are non-summable", errorMsg);
  2458. }
  2459. private class Profile
  2460. {
  2461. public int AnyProperty => throw new NotSupportedException("NOT SUPPORTED");
  2462. }
  2463. [Fact]
  2464. public void GenericParameterResolutionShouldWorkWithNulls()
  2465. {
  2466. var result = new Engine()
  2467. .SetValue("JintCommon", new JintCommon())
  2468. .Evaluate("JintCommon.sum(1, null)")
  2469. .AsNumber();
  2470. Assert.Equal(2, result);
  2471. }
  2472. public class JintCommon
  2473. {
  2474. public int Sum(int a, int? b) => a + b.GetValueOrDefault(1);
  2475. }
  2476. private delegate void ParamsTestDelegate(params Action[] callbacks);
  2477. [Fact]
  2478. public void CanUseParamsActions()
  2479. {
  2480. var engine = new Engine();
  2481. engine.SetValue("print", new Action<string>(_ => { }));
  2482. engine.SetValue("callAll", new DelegateWrapper(engine, new ParamsTestDelegate(ParamsTest)));
  2483. engine.Execute(@"
  2484. callAll(
  2485. function() { print('a'); },
  2486. function() { print('b'); },
  2487. function() { print('c'); }
  2488. );
  2489. ");
  2490. }
  2491. private static void ParamsTest(params Action[] callbacks)
  2492. {
  2493. foreach (var callback in callbacks)
  2494. {
  2495. callback.Invoke();
  2496. }
  2497. }
  2498. [Fact]
  2499. public void ObjectWrapperIdentityIsMaintained()
  2500. {
  2501. // run in separate method so stack won't keep reference
  2502. var reference = RunWeakReferenceTest();
  2503. GC.Collect();
  2504. // make sure no dangling reference is left
  2505. Assert.False(reference.IsAlive);
  2506. }
  2507. [MethodImpl(MethodImplOptions.NoInlining)]
  2508. private static WeakReference RunWeakReferenceTest()
  2509. {
  2510. var o = new object();
  2511. var engine = new Engine()
  2512. .SetValue("o", o);
  2513. var wrapper1 = (ObjectWrapper) engine.GetValue("o");
  2514. var reference = new WeakReference(wrapper1);
  2515. Assert.Same(wrapper1, engine.GetValue("o"));
  2516. Assert.Same(o, wrapper1.Target);
  2517. // reset
  2518. engine.Realm.GlobalObject.RemoveOwnProperty("o");
  2519. return reference;
  2520. }
  2521. [Fact]
  2522. public void CanUseClrFunction()
  2523. {
  2524. var engine = new Engine();
  2525. engine.SetValue("fn", new ClrFunction(engine, "fn", (_, args) => (JsValue) (args[0].AsInteger() + 1)));
  2526. var result = engine.Evaluate("fn(1)");
  2527. Assert.Equal(2, result);
  2528. }
  2529. [Fact]
  2530. public void ShouldAllowClrExceptionsThrough()
  2531. {
  2532. var engine = new Engine(opts => opts.CatchClrExceptions(exc => false));
  2533. engine.SetValue("fn", new ClrFunction(engine, "fn", (_, _) => throw new InvalidOperationException("This is a C# error")));
  2534. const string Source = @"
  2535. function wrap() {
  2536. fn();
  2537. }
  2538. wrap();
  2539. ";
  2540. Assert.Throws<InvalidOperationException>(() => engine.Execute(Source));
  2541. }
  2542. [Fact]
  2543. public void ShouldConvertClrExceptionsToErrors()
  2544. {
  2545. var engine = new Engine(opts => opts.CatchClrExceptions(exc => exc is InvalidOperationException));
  2546. engine.SetValue("fn", new ClrFunction(engine, "fn", (_, _) => throw new InvalidOperationException("This is a C# error")));
  2547. const string Source = @"
  2548. function wrap() {
  2549. fn();
  2550. }
  2551. wrap();
  2552. ";
  2553. var exc = Assert.Throws<JavaScriptException>(() => engine.Execute(Source));
  2554. Assert.Equal(exc.Message, "This is a C# error");
  2555. }
  2556. [Fact]
  2557. public void ShouldAllowCatchingConvertedClrExceptions()
  2558. {
  2559. var engine = new Engine(opts => opts.CatchClrExceptions(exc => exc is InvalidOperationException));
  2560. engine.SetValue("fn", new ClrFunction(engine, "fn", (_, _) => throw new InvalidOperationException("This is a C# error")));
  2561. const string Source = @"
  2562. try {
  2563. fn();
  2564. } catch (e) {
  2565. throw new Error('Caught: ' + e.message);
  2566. }
  2567. ";
  2568. var exc = Assert.Throws<JavaScriptException>(() => engine.Execute(Source));
  2569. Assert.Equal(exc.Message, "Caught: This is a C# error");
  2570. }
  2571. class Baz
  2572. {
  2573. public int DisposeCalls { get; private set; }
  2574. public IEnumerable<int> Enumerator
  2575. {
  2576. get
  2577. {
  2578. try
  2579. {
  2580. for (int i = 0; i < 10; i++) yield return i;
  2581. }
  2582. finally // finally clause is translated into IDisposable.Dispose in underlying IEnumerator
  2583. {
  2584. ++DisposeCalls;
  2585. }
  2586. }
  2587. }
  2588. }
  2589. [Fact]
  2590. public void ShouldCallEnumeratorDisposeOnNormalTermination()
  2591. {
  2592. var engine = new Engine();
  2593. var baz = new Baz();
  2594. engine.SetValue("baz", baz);
  2595. const string Source = @"
  2596. for (let i of baz.Enumerator) {
  2597. }";
  2598. engine.Execute(Source);
  2599. Assert.Equal(1, baz.DisposeCalls);
  2600. }
  2601. [Fact]
  2602. public void ShouldCallEnumeratorDisposeOnBreak()
  2603. {
  2604. var engine = new Engine();
  2605. var baz = new Baz();
  2606. engine.SetValue("baz", baz);
  2607. const string Source = @"
  2608. for (let i of baz.Enumerator) {
  2609. if (i == 2) break;
  2610. }";
  2611. engine.Execute(Source);
  2612. Assert.Equal(1, baz.DisposeCalls);
  2613. }
  2614. [Fact]
  2615. public void ShouldCallEnumeratorDisposeOnException()
  2616. {
  2617. var engine = new Engine();
  2618. var baz = new Baz();
  2619. engine.SetValue("baz", baz);
  2620. const string Source = @"
  2621. try {
  2622. for (let i of baz.Enumerator) {
  2623. if (i == 2) throw 'exception';
  2624. }
  2625. } catch (e) {
  2626. }";
  2627. engine.Execute(Source);
  2628. Assert.Equal(1, baz.DisposeCalls);
  2629. }
  2630. public class PropertyTestClass
  2631. {
  2632. public object Value;
  2633. }
  2634. [Fact]
  2635. public void PropertiesOfJsObjectPassedToClrShouldBeReadable()
  2636. {
  2637. _engine.SetValue("MyClass", typeof(PropertyTestClass));
  2638. RunTest(@"
  2639. var obj = new MyClass();
  2640. obj.Value = { foo: 'bar' };
  2641. equal('bar', obj.Value.foo);
  2642. ");
  2643. }
  2644. [Fact]
  2645. public void ShouldBeAbleToDeleteDictionaryEntries()
  2646. {
  2647. var engine = new Engine(options => options.Strict());
  2648. var dictionary = new Dictionary<string, int>
  2649. {
  2650. { "a", 1 },
  2651. { "b", 2 }
  2652. };
  2653. engine.SetValue("data", dictionary);
  2654. Assert.True(engine.Evaluate("Object.hasOwn(data, 'a')").AsBoolean());
  2655. Assert.True(engine.Evaluate("data['a'] === 1").AsBoolean());
  2656. engine.Evaluate("data['a'] = 42");
  2657. Assert.True(engine.Evaluate("data['a'] === 42").AsBoolean());
  2658. Assert.Equal(42, dictionary["a"]);
  2659. engine.Execute("delete data['a'];");
  2660. Assert.False(engine.Evaluate("Object.hasOwn(data, 'a')").AsBoolean());
  2661. Assert.False(engine.Evaluate("data['a'] === 42").AsBoolean());
  2662. Assert.False(dictionary.ContainsKey("a"));
  2663. var engineNoWrite = new Engine(options => options.Strict().AllowClrWrite(false));
  2664. dictionary = new Dictionary<string, int>
  2665. {
  2666. { "a", 1 },
  2667. { "b", 2 }
  2668. };
  2669. engineNoWrite.SetValue("data", dictionary);
  2670. var ex1 = Assert.Throws<JavaScriptException>(() => engineNoWrite.Evaluate("data['a'] = 42"));
  2671. Assert.Equal("Cannot assign to read only property 'a' of System.Collections.Generic.Dictionary`2[System.String,System.Int32]", ex1.Message);
  2672. // no changes
  2673. Assert.True(engineNoWrite.Evaluate("data['a'] === 1").AsBoolean());
  2674. var ex2 = Assert.Throws<JavaScriptException>(() => engineNoWrite.Execute("delete data['a'];"));
  2675. Assert.Equal("Cannot delete property 'a' of System.Collections.Generic.Dictionary`2[System.String,System.Int32]", ex2.Message);
  2676. }
  2677. public record RecordTestClass(object Value = null);
  2678. public class RecordTestClassContext
  2679. {
  2680. public object Method(RecordTestClass recordTest)
  2681. {
  2682. return recordTest.Value;
  2683. }
  2684. }
  2685. private class ClassWithIndexerAndProperty
  2686. {
  2687. public string MyProp { get; } = "from property";
  2688. public string this[string name] => name != nameof(MyProp) ? "from indexer" : null;
  2689. }
  2690. [Fact]
  2691. public void CanToStringObjectWithoutToPrimitiveSymbol()
  2692. {
  2693. var engine = new Engine();
  2694. engine.SetValue("obj", new ClassWithIndexerAndProperty());
  2695. Assert.Equal("Jint.Tests.Runtime.InteropTests+ClassWithIndexerAndProperty", engine.Evaluate("obj + ''").AsString());
  2696. engine.SetValue("obj", new Company("name"));
  2697. Assert.Equal("Jint.Tests.Runtime.Domain.Company", engine.Evaluate("obj + ''").AsString());
  2698. }
  2699. [Fact]
  2700. public void CanConstructOptionalRecordClass()
  2701. {
  2702. _engine.SetValue("Context", new RecordTestClassContext());
  2703. Assert.Equal(null, _engine.Evaluate("Context.method({});").ToObject());
  2704. Assert.Equal(5, _engine.Evaluate("Context.method({ value: 5 });").AsInteger());
  2705. }
  2706. [Fact]
  2707. public void CanPassDateTimeMinAndMaxViaInterop()
  2708. {
  2709. var engine = new Engine(cfg => cfg.AllowClrWrite());
  2710. var dt = DateTime.UtcNow;
  2711. engine.SetValue("capture", new Action<object>(o => dt = (DateTime) o));
  2712. engine.SetValue("minDate", DateTime.MinValue);
  2713. engine.Execute("capture(minDate);");
  2714. Assert.Equal(DateTime.MinValue, dt);
  2715. engine.SetValue("maxDate", DateTime.MaxValue);
  2716. engine.Execute("capture(maxDate);");
  2717. Assert.Equal(DateTime.MaxValue, dt);
  2718. }
  2719. private class Container
  2720. {
  2721. private readonly Child _child = new();
  2722. public Child Child => _child;
  2723. public BaseClass Get() => _child;
  2724. }
  2725. private class BaseClass { }
  2726. private class Child : BaseClass { }
  2727. [Fact]
  2728. public void AccessingBaseTypeShouldBeEqualToAccessingDerivedType()
  2729. {
  2730. var engine = new Engine().SetValue("container", new Container());
  2731. var res = engine.Evaluate("container.Child === container.Get()"); // These two should be the same object. But this PR makes `container.Get()` return a different object
  2732. Assert.True(res.AsBoolean());
  2733. }
  2734. public interface IIndexer<out T>
  2735. {
  2736. T this[int index] { get; }
  2737. }
  2738. public interface ICountable<out T>
  2739. {
  2740. int Count { get; }
  2741. }
  2742. public interface IStringCollection : IIndexer<string>, ICountable<string>
  2743. {
  2744. string this[string name] { get; }
  2745. }
  2746. public class Strings : IStringCollection
  2747. {
  2748. private readonly string[] _strings;
  2749. public Strings(string[] strings)
  2750. {
  2751. _strings = strings;
  2752. }
  2753. public string this[string name] => null;
  2754. public string this[int index] => _strings[index];
  2755. public int Count => _strings.Length;
  2756. }
  2757. public class Utils
  2758. {
  2759. public IStringCollection GetStrings() => new Strings(new [] { "a", "b", "c" });
  2760. }
  2761. [Fact]
  2762. public void AccessingInterfaceShouldContainExtendedInterfaces()
  2763. {
  2764. var engine = new Engine();
  2765. engine.SetValue("Utils", new Utils());
  2766. var result = engine.Evaluate("const strings = Utils.GetStrings(); strings.Count;").AsNumber();
  2767. Assert.Equal(3, result);
  2768. }
  2769. [Fact]
  2770. public void IntegerIndexerIfPreferredOverStringIndexerWhenFound()
  2771. {
  2772. var engine = new Engine();
  2773. engine.SetValue("Utils", new Utils());
  2774. var result = engine.Evaluate("const strings = Utils.GetStrings(); strings[2];");
  2775. Assert.Equal("c", result);
  2776. }
  2777. [Fact]
  2778. public void CanDestructureInteropTargetMethod()
  2779. {
  2780. var engine = new Engine();
  2781. engine.SetValue("test", new Utils());
  2782. var result = engine.Evaluate("const { getStrings } = test; getStrings().Count;");
  2783. Assert.Equal(3, result);
  2784. }
  2785. private class MetadataWrapper : IDictionary<string, object>
  2786. {
  2787. public IEnumerator<KeyValuePair<string, object>> GetEnumerator() => throw new NotImplementedException();
  2788. IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
  2789. public void Add(KeyValuePair<string, object> item) => throw new NotImplementedException();
  2790. public void Clear() => throw new NotImplementedException();
  2791. public bool Contains(KeyValuePair<string, object> item) => throw new NotImplementedException();
  2792. public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex) => throw new NotImplementedException();
  2793. public bool Remove(KeyValuePair<string, object> item) => throw new NotImplementedException();
  2794. public int Count { get; set; }
  2795. public bool IsReadOnly { get; set; }
  2796. public bool ContainsKey(string key) => throw new NotImplementedException();
  2797. public void Add(string key, object value) => throw new NotImplementedException();
  2798. public bool Remove(string key) => throw new NotImplementedException();
  2799. public bool TryGetValue(string key, out object value)
  2800. {
  2801. value = "from-wrapper";
  2802. return true;
  2803. }
  2804. public object this[string key]
  2805. {
  2806. get => "from-wrapper";
  2807. set
  2808. {
  2809. }
  2810. }
  2811. public ICollection<string> Keys { get; set; }
  2812. public ICollection<object> Values { get; set; }
  2813. }
  2814. private class ShadowedGetter : IReadOnlyDictionary<string, object>
  2815. {
  2816. private Dictionary<string, object> _dictionary = new();
  2817. public void SetInitial(object value, string key)
  2818. {
  2819. _dictionary[key] = value;
  2820. }
  2821. public IEnumerator<KeyValuePair<string, object>> GetEnumerator() => throw new NotImplementedException();
  2822. IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
  2823. public int Count { get; }
  2824. public bool ContainsKey(string key) => _dictionary.ContainsKey(key);
  2825. public bool TryGetValue(string key, out object value) => _dictionary.TryGetValue(key, out value);
  2826. public object this[string key]
  2827. {
  2828. get
  2829. {
  2830. _dictionary.TryGetValue(key, out var value);
  2831. return value;
  2832. }
  2833. }
  2834. public IEnumerable<string> Keys { get; set; }
  2835. public IEnumerable<object> Values { get; set; }
  2836. }
  2837. private class ShadowingSetter : ShadowedGetter
  2838. {
  2839. public Dictionary<string, int> Metadata
  2840. {
  2841. set
  2842. {
  2843. SetInitial(new MetadataWrapper(), "metadata");
  2844. }
  2845. }
  2846. }
  2847. [Fact]
  2848. public void CanSelectShadowedPropertiesBasedOnReadableAndWritable()
  2849. {
  2850. var engine = new Engine();
  2851. engine.SetValue("test", new ShadowingSetter
  2852. {
  2853. Metadata = null
  2854. });
  2855. engine.Evaluate("test.metadata['abc'] = 123");
  2856. var result = engine.Evaluate("test.metadata['abc']");
  2857. Assert.Equal("from-wrapper", result);
  2858. }
  2859. [Fact]
  2860. public void ShouldRespectConcreteGenericReturnTypes()
  2861. {
  2862. var engine = new Engine(opt =>
  2863. {
  2864. opt.AddExtensionMethods(typeof(Enumerable)); // Allow LINQ extension methods.
  2865. });
  2866. var result = new List<string>();
  2867. void Debug(object o)
  2868. {
  2869. result.Add($"{o?.GetType().Name ?? "null"}: {o ?? "null"}");
  2870. }
  2871. engine.SetValue("debug", Debug);
  2872. engine.SetValue("dict", new Dictionary<string, string> { ["test"] = "val" });
  2873. engine.Execute("var t = dict.last(kvp => { debug(kvp); debug(kvp.key); return kvp.key != null; } );");
  2874. engine.Execute("debug(t); debug(t.key);");
  2875. Assert.Equal(4, result.Count);
  2876. Assert.Equal("KeyValuePair`2: [test, val]", result[0]);
  2877. Assert.Equal("String: test", result[1]);
  2878. Assert.Equal("KeyValuePair`2: [test, val]", result[2]);
  2879. Assert.Equal("String: test", result[3]);
  2880. }
  2881. private class ClrMembersVisibilityTestClass
  2882. {
  2883. public int A { get; set; } = 10;
  2884. public int F()
  2885. {
  2886. return 4;
  2887. }
  2888. }
  2889. [Fact]
  2890. public void ShouldNotSeeClrMethods()
  2891. {
  2892. var engine = new Engine(opt =>
  2893. {
  2894. opt.Interop.ObjectWrapperReportedMemberTypes = MemberTypes.Field | MemberTypes.Property;
  2895. });
  2896. engine.SetValue("clrInstance", new ClrMembersVisibilityTestClass());
  2897. var val = engine.GetValue("clrInstance");
  2898. var obj = val.AsObject();
  2899. var props = obj.GetOwnProperties().Select(x => x.Key.ToString()).ToList();
  2900. props.Should().BeEquivalentTo(["A"]);
  2901. }
  2902. [Fact]
  2903. public void ShouldSeeClrMethods()
  2904. {
  2905. var engine = new Engine();
  2906. engine.SetValue("clrInstance", new ClrMembersVisibilityTestClass());
  2907. var val = engine.GetValue("clrInstance");
  2908. var obj = val.AsObject();
  2909. var props = obj.GetOwnProperties().Select(x => x.Key.ToString()).ToList();
  2910. props.Should().BeEquivalentTo(["A", "F"]);
  2911. }
  2912. private class ClrMembersVisibilityTestClass2
  2913. {
  2914. public int Get_A { get; set; } = 5;
  2915. }
  2916. [Fact]
  2917. public void ShouldSeeClrMethods2()
  2918. {
  2919. var engine = new Engine();
  2920. engine.SetValue("clrInstance", new ClrMembersVisibilityTestClass2());
  2921. var val = engine.GetValue("clrInstance");
  2922. var obj = val.AsObject();
  2923. var props = obj.GetOwnProperties().Select(x => x.Key.ToString()).ToList();
  2924. props.Should().BeEquivalentTo(["Get_A"]);
  2925. }
  2926. }