InteropTests.cs 78 KB

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