InteropTests.cs 110 KB

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