InteropTests.cs 117 KB

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