InteropTests.cs 112 KB

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