InteropTests.cs 99 KB

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