InteropTests.cs 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023
  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.Array;
  9. using Jint.Native.Object;
  10. using Jint.Runtime.Interop;
  11. using Jint.Tests.Runtime.Converters;
  12. using Jint.Tests.Runtime.Domain;
  13. using Shapes;
  14. using Xunit;
  15. namespace Jint.Tests.Runtime
  16. {
  17. public class InteropTests : IDisposable
  18. {
  19. private readonly Engine _engine;
  20. public InteropTests()
  21. {
  22. _engine = new Engine(cfg => cfg.AllowClr(
  23. typeof(Shape).GetTypeInfo().Assembly,
  24. typeof(Console).GetTypeInfo().Assembly,
  25. typeof(System.IO.File).GetTypeInfo().Assembly))
  26. .SetValue("log", new Action<object>(Console.WriteLine))
  27. .SetValue("assert", new Action<bool>(Assert.True))
  28. .SetValue("equal", new Action<object, object>(Assert.Equal))
  29. ;
  30. }
  31. void IDisposable.Dispose()
  32. {
  33. }
  34. private void RunTest(string source)
  35. {
  36. _engine.Execute(source);
  37. }
  38. [Fact]
  39. public void PrimitiveTypesCanBeSet()
  40. {
  41. _engine.SetValue("x", 10);
  42. _engine.SetValue("y", true);
  43. _engine.SetValue("z", "foo");
  44. RunTest(@"
  45. assert(x === 10);
  46. assert(y === true);
  47. assert(z === 'foo');
  48. ");
  49. }
  50. [Fact]
  51. public void DelegatesCanBeSet()
  52. {
  53. _engine.SetValue("square", new Func<double, double>(x => x * x));
  54. RunTest(@"
  55. assert(square(10) === 100);
  56. ");
  57. }
  58. [Fact]
  59. public void DelegateWithNullableParameterCanBePassedANull()
  60. {
  61. _engine.SetValue("isnull", new Func<double?, bool>(x => x == null));
  62. RunTest(@"
  63. assert(isnull(null) === true);
  64. ");
  65. }
  66. [Fact]
  67. public void DelegateWithObjectParameterCanBePassedANull()
  68. {
  69. _engine.SetValue("isnull", new Func<object, bool>(x => x == null));
  70. RunTest(@"
  71. assert(isnull(null) === true);
  72. ");
  73. }
  74. [Fact]
  75. public void DelegateWithNullableParameterCanBePassedAnUndefined()
  76. {
  77. _engine.SetValue("isnull", new Func<double?, bool>(x => x == null));
  78. RunTest(@"
  79. assert(isnull(undefined) === true);
  80. ");
  81. }
  82. [Fact]
  83. public void DelegateWithObjectParameterCanBePassedAnUndefined()
  84. {
  85. _engine.SetValue("isnull", new Func<object, bool>(x => x == null));
  86. RunTest(@"
  87. assert(isnull(undefined) === true);
  88. ");
  89. }
  90. [Fact]
  91. public void DelegateWithNullableParameterCanBeExcluded()
  92. {
  93. _engine.SetValue("isnull", new Func<double?, bool>(x => x == null));
  94. RunTest(@"
  95. assert(isnull() === true);
  96. ");
  97. }
  98. [Fact]
  99. public void DelegateWithObjectParameterCanBeExcluded()
  100. {
  101. _engine.SetValue("isnull", new Func<object, bool>(x => x == null));
  102. RunTest(@"
  103. assert(isnull() === true);
  104. ");
  105. }
  106. [Fact]
  107. public void DynamicDelegateCanBeSet()
  108. {
  109. #if NETFRAMEWORK
  110. var parameters = new[]
  111. {
  112. System.Linq.Expressions.Expression.Parameter(typeof(int)),
  113. System.Linq.Expressions.Expression.Parameter(typeof(int))
  114. };
  115. var exp = System.Linq.Expressions.Expression.Add(parameters[0], parameters[1]);
  116. var del = System.Linq.Expressions.Expression.Lambda(exp, parameters).Compile();
  117. _engine.SetValue("add", del);
  118. RunTest(@"
  119. assert(add(1,1) === 2);
  120. ");
  121. #endif
  122. }
  123. [Fact]
  124. public void ExtraParametersAreIgnored()
  125. {
  126. _engine.SetValue("passNumber", new Func<int, int>(x => x));
  127. RunTest(@"
  128. assert(passNumber(123,'test',{},[],null) === 123);
  129. ");
  130. }
  131. private delegate string callParams(params object[] values);
  132. private delegate string callArgumentAndParams(string firstParam, params object[] values);
  133. [Fact]
  134. public void DelegatesWithParamsParameterCanBeInvoked()
  135. {
  136. var a = new A();
  137. _engine.SetValue("callParams", new callParams(a.Call13));
  138. _engine.SetValue("callArgumentAndParams", new callArgumentAndParams(a.Call14));
  139. RunTest(@"
  140. assert(callParams('1','2','3') === '1,2,3');
  141. assert(callParams('1') === '1');
  142. assert(callParams() === '');
  143. assert(callArgumentAndParams('a','1','2','3') === 'a:1,2,3');
  144. assert(callArgumentAndParams('a','1') === 'a:1');
  145. assert(callArgumentAndParams('a') === 'a:');
  146. assert(callArgumentAndParams() === ':');
  147. ");
  148. }
  149. [Fact]
  150. public void DelegateWithDefaultValueParametersCanBeInvoked()
  151. {
  152. var instance = new A();
  153. _engine.SetValue("Instance", instance);
  154. _engine.SetValue("Class", TypeReference.CreateTypeReference(_engine, typeof(A)));
  155. RunTest(@"
  156. assert(Instance.Call19() === 0);
  157. assert(Instance.Call19(1) === 1);
  158. assert(Instance.Call20(1) === 4);
  159. assert(Instance.Call20(1, 2) === 5);
  160. assert(Instance.Call20(1 , 2, 3) === 6);
  161. assert(Class.Call19Static() === 0);
  162. assert(Class.Call19Static(1) === 1);
  163. assert(Class.Call20Static(1) === 4);
  164. assert(Class.Call20Static(1, 2) === 5);
  165. assert(Class.Call20Static(1 , 2, 3) === 6);
  166. ");
  167. }
  168. [Fact]
  169. public void CanGetObjectProperties()
  170. {
  171. var p = new Person
  172. {
  173. Name = "Mickey Mouse"
  174. };
  175. _engine.SetValue("p", p);
  176. RunTest(@"
  177. assert(p.Name === 'Mickey Mouse');
  178. ");
  179. }
  180. [Fact]
  181. public void CanInvokeObjectMethods()
  182. {
  183. var p = new Person
  184. {
  185. Name = "Mickey Mouse"
  186. };
  187. _engine.SetValue("p", p);
  188. RunTest(@"
  189. assert(p.ToString() === 'Mickey Mouse');
  190. ");
  191. }
  192. [Fact]
  193. public void CanInvokeObjectMethodsWithPascalCase()
  194. {
  195. var p = new Person
  196. {
  197. Name = "Mickey Mouse"
  198. };
  199. _engine.SetValue("p", p);
  200. RunTest(@"
  201. assert(p.toString() === 'Mickey Mouse');
  202. ");
  203. }
  204. [Fact]
  205. public void CanSetObjectProperties()
  206. {
  207. var p = new Person
  208. {
  209. Name = "Mickey Mouse"
  210. };
  211. _engine.SetValue("p", p);
  212. RunTest(@"
  213. p.Name = 'Donald Duck';
  214. assert(p.Name === 'Donald Duck');
  215. ");
  216. Assert.Equal("Donald Duck", p.Name);
  217. }
  218. [Fact]
  219. public void CanGetIndexUsingStringKey()
  220. {
  221. var dictionary = new Dictionary<string, Person>();
  222. dictionary.Add("person1", new Person { Name = "Mickey Mouse" });
  223. dictionary.Add("person2", new Person { Name = "Goofy" });
  224. _engine.SetValue("dictionary", dictionary);
  225. RunTest(@"
  226. assert(dictionary['person1'].Name === 'Mickey Mouse');
  227. assert(dictionary['person2'].Name === 'Goofy');
  228. ");
  229. }
  230. [Fact]
  231. public void CanSetIndexUsingStringKey()
  232. {
  233. var dictionary = new Dictionary<string, Person>();
  234. dictionary.Add("person1", new Person { Name = "Mickey Mouse" });
  235. dictionary.Add("person2", new Person { Name = "Goofy" });
  236. _engine.SetValue("dictionary", dictionary);
  237. RunTest(@"
  238. dictionary['person2'].Name = 'Donald Duck';
  239. assert(dictionary['person2'].Name === 'Donald Duck');
  240. ");
  241. Assert.Equal("Donald Duck", dictionary["person2"].Name);
  242. }
  243. [Fact]
  244. public void CanGetIndexUsingIntegerKey()
  245. {
  246. var dictionary = new Dictionary<int, string>();
  247. dictionary.Add(1, "Mickey Mouse");
  248. dictionary.Add(2, "Goofy");
  249. _engine.SetValue("dictionary", dictionary);
  250. RunTest(@"
  251. assert(dictionary[1] === 'Mickey Mouse');
  252. assert(dictionary[2] === 'Goofy');
  253. ");
  254. }
  255. [Fact]
  256. public void CanSetIndexUsingIntegerKey()
  257. {
  258. var dictionary = new Dictionary<int, string>();
  259. dictionary.Add(1, "Mickey Mouse");
  260. dictionary.Add(2, "Goofy");
  261. _engine.SetValue("dictionary", dictionary);
  262. RunTest(@"
  263. dictionary[2] = 'Donald Duck';
  264. assert(dictionary[2] === 'Donald Duck');
  265. ");
  266. Assert.Equal("Mickey Mouse", dictionary[1]);
  267. Assert.Equal("Donald Duck", dictionary[2]);
  268. }
  269. private class DoubleIndexedClass
  270. {
  271. public int this[int index]
  272. {
  273. get { return index; }
  274. }
  275. public string this[string index]
  276. {
  277. get { return index; }
  278. }
  279. }
  280. [Fact]
  281. public void CanGetIndexUsingBothIntAndStringIndex()
  282. {
  283. var dictionary = new DoubleIndexedClass();
  284. _engine.SetValue("dictionary", dictionary);
  285. RunTest(@"
  286. assert(dictionary[1] === 1);
  287. assert(dictionary['test'] === 'test');
  288. ");
  289. }
  290. [Fact]
  291. public void CanUseGenericMethods()
  292. {
  293. var dictionary = new Dictionary<int, string>();
  294. dictionary.Add(1, "Mickey Mouse");
  295. _engine.SetValue("dictionary", dictionary);
  296. RunTest(@"
  297. dictionary.Add(2, 'Goofy');
  298. assert(dictionary[2] === 'Goofy');
  299. ");
  300. Assert.Equal("Mickey Mouse", dictionary[1]);
  301. Assert.Equal("Goofy", dictionary[2]);
  302. }
  303. [Fact]
  304. public void CanUseMultiGenericTypes()
  305. {
  306. RunTest(@"
  307. var type = System.Collections.Generic.Dictionary(System.Int32, System.String);
  308. var dictionary = new type();
  309. dictionary.Add(1, 'Mickey Mouse');
  310. dictionary.Add(2, 'Goofy');
  311. assert(dictionary[2] === 'Goofy');
  312. ");
  313. }
  314. [Fact]
  315. public void CanUseIndexOnCollection()
  316. {
  317. var collection = new System.Collections.ObjectModel.Collection<string>();
  318. collection.Add("Mickey Mouse");
  319. collection.Add("Goofy");
  320. _engine.SetValue("dictionary", collection);
  321. RunTest(@"
  322. dictionary[1] = 'Donald Duck';
  323. assert(dictionary[1] === 'Donald Duck');
  324. ");
  325. Assert.Equal("Mickey Mouse", collection[0]);
  326. Assert.Equal("Donald Duck", collection[1]);
  327. }
  328. [Fact]
  329. public void CanUseIndexOnList()
  330. {
  331. var list = new List<object>(2);
  332. list.Add("Mickey Mouse");
  333. list.Add("Goofy");
  334. _engine.SetValue("list", list);
  335. RunTest(@"
  336. list[1] = 'Donald Duck';
  337. assert(list[1] === 'Donald Duck');
  338. ");
  339. Assert.Equal("Mickey Mouse", list[0]);
  340. Assert.Equal("Donald Duck", list[1]);
  341. }
  342. [Fact]
  343. public void CanAccessAnonymousObject()
  344. {
  345. var p = new
  346. {
  347. Name = "Mickey Mouse",
  348. };
  349. _engine.SetValue("p", p);
  350. RunTest(@"
  351. assert(p.Name === 'Mickey Mouse');
  352. ");
  353. }
  354. [Fact]
  355. public void CanAccessAnonymousObjectProperties()
  356. {
  357. var p = new
  358. {
  359. Address = new
  360. {
  361. City = "Mouseton"
  362. }
  363. };
  364. _engine.SetValue("p", p);
  365. RunTest(@"
  366. assert(p.Address.City === 'Mouseton');
  367. ");
  368. }
  369. [Fact]
  370. public void PocosCanReturnJsValueDirectly()
  371. {
  372. var o = new
  373. {
  374. x = new JsNumber(1),
  375. y = new JsString("string"),
  376. };
  377. _engine.SetValue("o", o);
  378. RunTest(@"
  379. assert(o.x === 1);
  380. assert(o.y === 'string');
  381. ");
  382. }
  383. [Fact]
  384. public void PocosCanReturnObjectInstanceDirectly()
  385. {
  386. var x = new ObjectInstance(_engine);
  387. x.Set("foo", new JsString("bar"));
  388. var o = new
  389. {
  390. x
  391. };
  392. _engine.SetValue("o", o);
  393. RunTest(@"
  394. assert(o.x.foo === 'bar');
  395. ");
  396. }
  397. [Fact]
  398. public void DateTimeIsConvertedToDate()
  399. {
  400. var o = new
  401. {
  402. z = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
  403. };
  404. _engine.SetValue("o", o);
  405. RunTest(@"
  406. assert(o.z.valueOf() === 0);
  407. ");
  408. }
  409. [Fact]
  410. public void DateTimeOffsetIsConvertedToDate()
  411. {
  412. var o = new
  413. {
  414. z = new DateTimeOffset(1970, 1, 1, 0, 0, 0, new TimeSpan())
  415. };
  416. _engine.SetValue("o", o);
  417. RunTest(@"
  418. assert(o.z.valueOf() === 0);
  419. ");
  420. }
  421. [Fact]
  422. public void EcmaValuesAreAutomaticallyConvertedWhenSetInPoco()
  423. {
  424. var p = new Person
  425. {
  426. Name = "foo",
  427. };
  428. _engine.SetValue("p", p);
  429. RunTest(@"
  430. assert(p.Name === 'foo');
  431. assert(p.Age === 0);
  432. p.Name = 'bar';
  433. p.Age = 10;
  434. ");
  435. Assert.Equal("bar", p.Name);
  436. Assert.Equal(10, p.Age);
  437. }
  438. [Fact]
  439. public void EcmaValuesAreAutomaticallyConvertedToBestMatchWhenSetInPoco()
  440. {
  441. var p = new Person
  442. {
  443. Name = "foo",
  444. };
  445. _engine.SetValue("p", p);
  446. RunTest(@"
  447. p.Name = 10;
  448. p.Age = '20';
  449. ");
  450. Assert.Equal("10", p.Name);
  451. Assert.Equal(20, p.Age);
  452. }
  453. [Fact]
  454. public void ShouldCallInstanceMethodWithoutArgument()
  455. {
  456. _engine.SetValue("a", new A());
  457. RunTest(@"
  458. assert(a.Call1() === 0);
  459. ");
  460. }
  461. [Fact]
  462. public void ShouldCallInstanceMethodOverloadArgument()
  463. {
  464. _engine.SetValue("a", new A());
  465. RunTest(@"
  466. assert(a.Call1(1) === 1);
  467. ");
  468. }
  469. [Fact]
  470. public void ShouldCallInstanceMethodWithString()
  471. {
  472. var p = new Person();
  473. _engine.SetValue("a", new A());
  474. _engine.SetValue("p", p);
  475. RunTest(@"
  476. p.Name = a.Call2('foo');
  477. assert(p.Name === 'foo');
  478. ");
  479. Assert.Equal("foo", p.Name);
  480. }
  481. [Fact]
  482. public void CanUseTrim()
  483. {
  484. var p = new Person { Name = "Mickey Mouse "};
  485. _engine.SetValue("p", p);
  486. RunTest(@"
  487. assert(p.Name === 'Mickey Mouse ');
  488. p.Name = p.Name.trim();
  489. assert(p.Name === 'Mickey Mouse');
  490. ");
  491. Assert.Equal("Mickey Mouse", p.Name);
  492. }
  493. [Fact]
  494. public void CanUseMathFloor()
  495. {
  496. var p = new Person();
  497. _engine.SetValue("p", p);
  498. RunTest(@"
  499. p.Age = Math.floor(1.6);p
  500. assert(p.Age === 1);
  501. ");
  502. Assert.Equal(1, p.Age);
  503. }
  504. [Fact]
  505. public void CanUseDelegateAsFunction()
  506. {
  507. var even = new Func<int, bool>(x => x % 2 == 0);
  508. _engine.SetValue("even", even);
  509. RunTest(@"
  510. assert(even(2) === true);
  511. ");
  512. }
  513. private struct TestStruct
  514. {
  515. public int Value;
  516. public TestStruct(int value)
  517. {
  518. Value = value;
  519. }
  520. }
  521. private class TestClass
  522. {
  523. public int? NullableInt { get; set; }
  524. public DateTime? NullableDate { get; set; }
  525. public bool? NullableBool { get; set; }
  526. public TestEnumInt32? NullableEnum { get; set; }
  527. public TestStruct? NullableStruct { get; set; }
  528. }
  529. [Fact]
  530. public void CanSetNullablePropertiesOnPocos()
  531. {
  532. var instance = new TestClass();
  533. _engine.SetValue("instance", instance);
  534. _engine.SetValue("TestStruct", typeof(TestStruct));
  535. RunTest(@"
  536. instance.NullableInt = 2;
  537. instance.NullableDate = new Date();
  538. instance.NullableBool = true;
  539. instance.NullableEnum = 1;
  540. instance.NullableStruct = new TestStruct(5);
  541. assert(instance.NullableInt===2);
  542. assert(instance.NullableDate!=null);
  543. assert(instance.NullableBool===true);
  544. assert(instance.NullableEnum===1);
  545. assert(instance.NullableStruct.Value===5);
  546. ");
  547. }
  548. private class ReadOnlyList : IReadOnlyList<Person>
  549. {
  550. private readonly Person[] _data;
  551. public ReadOnlyList(params Person[] data)
  552. {
  553. _data = data;
  554. }
  555. public IEnumerator<Person> GetEnumerator()
  556. {
  557. return ((IEnumerable<Person>) _data).GetEnumerator();
  558. }
  559. IEnumerator IEnumerable.GetEnumerator()
  560. {
  561. return _data.GetEnumerator();
  562. }
  563. public int Count => _data.Length;
  564. public Person this[int index] => _data[index];
  565. }
  566. [Fact]
  567. public void CanAddArrayPrototypeForArrayLikeClrObjects()
  568. {
  569. var e = new Engine(cfg => cfg
  570. .AllowClr(typeof(Person).Assembly)
  571. .SetWrapObjectHandler((engine, target) =>
  572. {
  573. var instance = new ObjectWrapper(engine, target);
  574. if (instance.IsArrayLike)
  575. {
  576. instance.SetPrototypeOf(engine.Array.PrototypeObject);
  577. }
  578. return instance;
  579. })
  580. );
  581. var person = new Person
  582. {
  583. Age = 12,
  584. Name = "John"
  585. };
  586. dynamic obj = new
  587. {
  588. values = new ReadOnlyList(person)
  589. };
  590. e.SetValue("o", obj);
  591. var name = e.Execute("o.values.filter(x => x.age == 12)[0].name").GetCompletionValue().ToString();
  592. Assert.Equal("John", name);
  593. }
  594. [Fact]
  595. public void ShouldConvertArrayToArrayInstance()
  596. {
  597. var result = _engine
  598. .SetValue("values", new[] { 1, 2, 3, 4, 5, 6 })
  599. .Execute("values.filter(function(x){ return x % 2 == 0; })");
  600. var parts = result.GetCompletionValue().ToObject();
  601. Assert.True(parts.GetType().IsArray);
  602. Assert.Equal(3, ((object[])parts).Length);
  603. Assert.Equal(2d, ((object[])parts)[0]);
  604. Assert.Equal(4d, ((object[])parts)[1]);
  605. Assert.Equal(6d, ((object[])parts)[2]);
  606. }
  607. [Fact]
  608. public void ShouldConvertListsToArrayInstance()
  609. {
  610. var result = _engine
  611. .SetValue("values", new List<object> { 1, 2, 3, 4, 5, 6 })
  612. .Execute("new Array(values).filter(function(x){ return x % 2 == 0; })");
  613. var parts = result.GetCompletionValue().ToObject();
  614. Assert.True(parts.GetType().IsArray);
  615. Assert.Equal(3, ((object[])parts).Length);
  616. Assert.Equal(2d, ((object[])parts)[0]);
  617. Assert.Equal(4d, ((object[])parts)[1]);
  618. Assert.Equal(6d, ((object[])parts)[2]);
  619. }
  620. [Fact]
  621. public void ShouldConvertArrayInstanceToArray()
  622. {
  623. var result = _engine.Execute("'[email protected]'.split('@');");
  624. var parts = result.GetCompletionValue().ToObject();
  625. Assert.True(parts.GetType().IsArray);
  626. Assert.Equal(2, ((object[])parts).Length);
  627. Assert.Equal("foo", ((object[])parts)[0]);
  628. Assert.Equal("bar.com", ((object[])parts)[1]);
  629. }
  630. [Fact]
  631. public void ShouldLoopWithNativeEnumerator()
  632. {
  633. JsValue adder(JsValue argValue)
  634. {
  635. ArrayInstance args = argValue.AsArray();
  636. double sum = 0;
  637. foreach (var item in args)
  638. {
  639. if (item.IsNumber())
  640. {
  641. sum += item.AsNumber();
  642. }
  643. }
  644. return sum;
  645. }
  646. var result = _engine.SetValue("getSum", new Func<JsValue, JsValue>(adder))
  647. .Execute("getSum([1,2,3]);");
  648. Assert.True(result.GetCompletionValue() == 6);
  649. }
  650. [Fact]
  651. public void ShouldConvertBooleanInstanceToBool()
  652. {
  653. var result = _engine.Execute("new Boolean(true)");
  654. var value = result.GetCompletionValue().ToObject();
  655. Assert.Equal(typeof(bool), value.GetType());
  656. Assert.Equal(true, value);
  657. }
  658. [Fact]
  659. public void ShouldConvertDateInstanceToDateTime()
  660. {
  661. var result = _engine.Execute("new Date(0)");
  662. var value = result.GetCompletionValue().ToObject();
  663. Assert.Equal(typeof(DateTime), value.GetType());
  664. Assert.Equal(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), value);
  665. }
  666. [Fact]
  667. public void ShouldConvertNumberInstanceToDouble()
  668. {
  669. var result = _engine.Execute("new Number(10)");
  670. var value = result.GetCompletionValue().ToObject();
  671. Assert.Equal(typeof(double), value.GetType());
  672. Assert.Equal(10d, value);
  673. }
  674. [Fact]
  675. public void ShouldConvertStringInstanceToString()
  676. {
  677. var result = _engine.Execute("new String('foo')");
  678. var value = result.GetCompletionValue().ToObject();
  679. Assert.Equal(typeof(string), value.GetType());
  680. Assert.Equal("foo", value);
  681. }
  682. [Fact]
  683. public void ShouldConvertObjectInstanceToExpando()
  684. {
  685. _engine.Execute("var o = {a: 1, b: 'foo'}");
  686. var result = _engine.GetValue("o");
  687. dynamic value = result.ToObject();
  688. Assert.Equal(1, value.a);
  689. Assert.Equal("foo", value.b);
  690. var dic = (IDictionary<string, object>)result.ToObject();
  691. Assert.Equal(1d, dic["a"]);
  692. Assert.Equal("foo", dic["b"]);
  693. }
  694. [Fact]
  695. public void ShouldNotTryToConvertCompatibleTypes()
  696. {
  697. _engine.SetValue("a", new A());
  698. RunTest(@"
  699. assert(a.Call3('foo') === 'foo');
  700. assert(a.Call3(1) === '1');
  701. ");
  702. }
  703. [Fact]
  704. public void ShouldNotTryToConvertDerivedTypes()
  705. {
  706. _engine.SetValue("a", new A());
  707. _engine.SetValue("p", new Person { Name = "Mickey" });
  708. RunTest(@"
  709. assert(a.Call4(p) === 'Mickey');
  710. ");
  711. }
  712. [Fact]
  713. public void ShouldExecuteFunctionCallBackAsDelegate()
  714. {
  715. _engine.SetValue("a", new A());
  716. RunTest(@"
  717. assert(a.Call5(function(a,b){ return a+b }) === '1foo');
  718. ");
  719. }
  720. [Fact]
  721. public void ShouldExecuteFunctionCallBackAsFuncAndThisCanBeAssigned()
  722. {
  723. _engine.SetValue("a", new A());
  724. RunTest(@"
  725. assert(a.Call6(function(a,b){ return this+a+b }) === 'bar1foo');
  726. ");
  727. }
  728. [Fact]
  729. public void ShouldExecuteFunctionCallBackAsPredicate()
  730. {
  731. _engine.SetValue("a", new A());
  732. // Func<>
  733. RunTest(@"
  734. assert(a.Call8(function(){ return 'foo'; }) === 'foo');
  735. ");
  736. }
  737. [Fact]
  738. public void ShouldExecuteFunctionWithParameterCallBackAsPredicate()
  739. {
  740. _engine.SetValue("a", new A());
  741. // Func<,>
  742. RunTest(@"
  743. assert(a.Call7('foo', function(a){ return a === 'foo'; }) === true);
  744. ");
  745. }
  746. [Fact]
  747. public void ShouldExecuteActionCallBackAsPredicate()
  748. {
  749. _engine.SetValue("a", new A());
  750. // Action
  751. RunTest(@"
  752. var value;
  753. a.Call9(function(){ value = 'foo'; });
  754. assert(value === 'foo');
  755. ");
  756. }
  757. [Fact]
  758. public void ShouldExecuteActionWithParameterCallBackAsPredicate()
  759. {
  760. _engine.SetValue("a", new A());
  761. // Action<>
  762. RunTest(@"
  763. var value;
  764. a.Call10('foo', function(b){ value = b; });
  765. assert(value === 'foo');
  766. ");
  767. }
  768. [Fact]
  769. public void ShouldExecuteActionWithMultipleParametersCallBackAsPredicate()
  770. {
  771. _engine.SetValue("a", new A());
  772. // Action<,>
  773. RunTest(@"
  774. var value;
  775. a.Call11('foo', 'bar', function(a,b){ value = a + b; });
  776. assert(value === 'foobar');
  777. ");
  778. }
  779. [Fact]
  780. public void ShouldExecuteFunc()
  781. {
  782. _engine.SetValue("a", new A());
  783. // Func<int, int>
  784. RunTest(@"
  785. var result = a.Call12(42, function(a){ return a + a; });
  786. assert(result === 84);
  787. ");
  788. }
  789. [Fact]
  790. public void ShouldExecuteActionCallbackOnEventChanged()
  791. {
  792. var collection = new System.Collections.ObjectModel.ObservableCollection<string>();
  793. Assert.True(collection.Count == 0);
  794. _engine.SetValue("collection", collection);
  795. RunTest(@"
  796. var eventAction;
  797. collection.add_CollectionChanged(function(sender, eventArgs) { eventAction = eventArgs.Action; } );
  798. collection.Add('test');
  799. ");
  800. var eventAction = _engine.GetValue("eventAction").AsNumber();
  801. Assert.True(eventAction == 0);
  802. Assert.True(collection.Count == 1);
  803. }
  804. [Fact]
  805. public void ShouldUseSystemIO()
  806. {
  807. RunTest(@"
  808. var filename = System.IO.Path.GetTempFileName();
  809. var sw = System.IO.File.CreateText(filename);
  810. sw.Write('Hello World');
  811. sw.Dispose();
  812. var content = System.IO.File.ReadAllText(filename);
  813. System.Console.WriteLine(content);
  814. assert(content === 'Hello World');
  815. ");
  816. }
  817. [Fact]
  818. public void ShouldBeInstanceOfTypeReferenceType()
  819. {
  820. _engine.SetValue("A", typeof(A));
  821. RunTest(@"
  822. var a = new A();
  823. assert(a instanceof A);
  824. ");
  825. }
  826. [Fact]
  827. public void ShouldImportNamespace()
  828. {
  829. RunTest(@"
  830. var Shapes = importNamespace('Shapes');
  831. var circle = new Shapes.Circle();
  832. assert(circle.Radius === 0);
  833. assert(circle.Perimeter() === 0);
  834. ");
  835. }
  836. [Fact]
  837. public void ShouldConstructReferenceTypeWithParameters()
  838. {
  839. RunTest(@"
  840. var Shapes = importNamespace('Shapes');
  841. var circle = new Shapes.Circle(1);
  842. assert(circle.Radius === 1);
  843. assert(circle.Perimeter() === Math.PI);
  844. ");
  845. }
  846. [Fact]
  847. public void ShouldConstructValueTypeWithoutParameters()
  848. {
  849. RunTest(@"
  850. var guid = new System.Guid();
  851. assert('00000000-0000-0000-0000-000000000000' === guid.ToString());
  852. ");
  853. }
  854. [Fact]
  855. public void ShouldInvokeAFunctionByName()
  856. {
  857. RunTest(@"
  858. function add(x, y) { return x + y; }
  859. ");
  860. Assert.Equal(3, _engine.Invoke("add", 1, 2));
  861. }
  862. [Fact]
  863. public void ShouldNotInvokeNonFunctionValue()
  864. {
  865. RunTest(@"
  866. var x= 10;
  867. ");
  868. Assert.Throws<ArgumentException>(() => _engine.Invoke("x", 1, 2));
  869. }
  870. [Fact]
  871. public void CanGetField()
  872. {
  873. var o = new ClassWithField
  874. {
  875. Field = "Mickey Mouse"
  876. };
  877. _engine.SetValue("o", o);
  878. RunTest(@"
  879. assert(o.Field === 'Mickey Mouse');
  880. ");
  881. }
  882. [Fact]
  883. public void CanSetField()
  884. {
  885. var o = new ClassWithField();
  886. _engine.SetValue("o", o);
  887. RunTest(@"
  888. o.Field = 'Mickey Mouse';
  889. assert(o.Field === 'Mickey Mouse');
  890. ");
  891. Assert.Equal("Mickey Mouse", o.Field);
  892. }
  893. [Fact]
  894. public void CanGetStaticField()
  895. {
  896. RunTest(@"
  897. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  898. var statics = domain.ClassWithStaticFields;
  899. assert(statics.Get == 'Get');
  900. ");
  901. }
  902. [Fact]
  903. public void CanSetStaticField()
  904. {
  905. RunTest(@"
  906. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  907. var statics = domain.ClassWithStaticFields;
  908. statics.Set = 'hello';
  909. assert(statics.Set == 'hello');
  910. ");
  911. Assert.Equal(ClassWithStaticFields.Set, "hello");
  912. }
  913. [Fact]
  914. public void CanGetStaticAccessor()
  915. {
  916. RunTest(@"
  917. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  918. var statics = domain.ClassWithStaticFields;
  919. assert(statics.Getter == 'Getter');
  920. ");
  921. }
  922. [Fact]
  923. public void CanSetStaticAccessor()
  924. {
  925. RunTest(@"
  926. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  927. var statics = domain.ClassWithStaticFields;
  928. statics.Setter = 'hello';
  929. assert(statics.Setter == 'hello');
  930. ");
  931. Assert.Equal(ClassWithStaticFields.Setter, "hello");
  932. }
  933. [Fact]
  934. public void CantSetStaticReadonly()
  935. {
  936. RunTest(@"
  937. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  938. var statics = domain.ClassWithStaticFields;
  939. statics.Readonly = 'hello';
  940. assert(statics.Readonly == 'Readonly');
  941. ");
  942. Assert.Equal(ClassWithStaticFields.Readonly, "Readonly");
  943. }
  944. [Fact]
  945. public void CanSetCustomConverters()
  946. {
  947. var engine1 = new Engine();
  948. engine1.SetValue("p", new { Test = true });
  949. engine1.Execute("var result = p.Test;");
  950. Assert.True((bool)engine1.GetValue("result").ToObject());
  951. var engine2 = new Engine(o => o.AddObjectConverter(new NegateBoolConverter()));
  952. engine2.SetValue("p", new { Test = true });
  953. engine2.Execute("var result = p.Test;");
  954. Assert.False((bool)engine2.GetValue("result").ToObject());
  955. }
  956. [Fact]
  957. public void CanConvertEnumsToString()
  958. {
  959. var engine1 = new Engine(o => o.AddObjectConverter(new EnumsToStringConverter()))
  960. .SetValue("assert", new Action<bool>(Assert.True));
  961. engine1.SetValue("p", new { Comparison = StringComparison.CurrentCulture });
  962. engine1.Execute("assert(p.Comparison === 'CurrentCulture');");
  963. engine1.Execute("var result = p.Comparison;");
  964. Assert.Equal("CurrentCulture", (string)engine1.GetValue("result").ToObject());
  965. }
  966. [Fact]
  967. public void CanUserIncrementOperator()
  968. {
  969. var p = new Person
  970. {
  971. Age = 1,
  972. };
  973. _engine.SetValue("p", p);
  974. RunTest(@"
  975. assert(++p.Age === 2);
  976. ");
  977. Assert.Equal(2, p.Age);
  978. }
  979. [Fact]
  980. public void CanOverwriteValues()
  981. {
  982. _engine.SetValue("x", 3);
  983. _engine.SetValue("x", 4);
  984. RunTest(@"
  985. assert(x === 4);
  986. ");
  987. }
  988. [Fact]
  989. public void ShouldCreateGenericType()
  990. {
  991. RunTest(@"
  992. var ListOfString = System.Collections.Generic.List(System.String);
  993. var list = new ListOfString();
  994. list.Add('foo');
  995. list.Add(1);
  996. assert(2 === list.Count);
  997. ");
  998. }
  999. [Fact]
  1000. public void EnumComparesByName()
  1001. {
  1002. var o = new
  1003. {
  1004. r = Colors.Red,
  1005. b = Colors.Blue,
  1006. g = Colors.Green,
  1007. b2 = Colors.Red
  1008. };
  1009. _engine.SetValue("o", o);
  1010. _engine.SetValue("assertFalse", new Action<bool>(Assert.False));
  1011. RunTest(@"
  1012. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1013. var colors = domain.Colors;
  1014. assert(o.r === colors.Red);
  1015. assert(o.g === colors.Green);
  1016. assert(o.b === colors.Blue);
  1017. assertFalse(o.b2 === colors.Blue);
  1018. ");
  1019. }
  1020. [Fact]
  1021. public void ShouldSetEnumProperty()
  1022. {
  1023. var s = new Circle
  1024. {
  1025. Color = Colors.Red,
  1026. };
  1027. _engine.SetValue("s", s);
  1028. RunTest(@"
  1029. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1030. var colors = domain.Colors;
  1031. s.Color = colors.Blue;
  1032. assert(s.Color === colors.Blue);
  1033. ");
  1034. _engine.SetValue("s", s);
  1035. RunTest(@"
  1036. s.Color = colors.Blue | colors.Green;
  1037. assert(s.Color === colors.Blue | colors.Green);
  1038. ");
  1039. Assert.Equal(Colors.Blue | Colors.Green, s.Color);
  1040. }
  1041. enum TestEnumInt32 : int
  1042. {
  1043. None,
  1044. One = 1,
  1045. Min = int.MaxValue,
  1046. Max = int.MaxValue,
  1047. }
  1048. enum TestEnumUInt32 : uint
  1049. {
  1050. None,
  1051. One = 1,
  1052. Min = uint.MaxValue,
  1053. Max = uint.MaxValue,
  1054. }
  1055. enum TestEnumInt64 : long
  1056. {
  1057. None,
  1058. One = 1,
  1059. Min = long.MaxValue,
  1060. Max = long.MaxValue,
  1061. }
  1062. enum TestEnumUInt64 : ulong
  1063. {
  1064. None,
  1065. One = 1,
  1066. Min = ulong.MaxValue,
  1067. Max = ulong.MaxValue,
  1068. }
  1069. void TestEnum<T>(T enumValue)
  1070. {
  1071. object i = Convert.ChangeType(enumValue, Enum.GetUnderlyingType(typeof(T)));
  1072. string s = Convert.ToString(i, CultureInfo.InvariantCulture);
  1073. var o = new Tuple<T>(enumValue);
  1074. _engine.SetValue("o", o);
  1075. RunTest("assert(o.Item1 === " + s + ");");
  1076. }
  1077. [Fact]
  1078. public void ShouldWorkWithEnumInt32()
  1079. {
  1080. TestEnum(TestEnumInt32.None);
  1081. TestEnum(TestEnumInt32.One);
  1082. TestEnum(TestEnumInt32.Min);
  1083. TestEnum(TestEnumInt32.Max);
  1084. }
  1085. [Fact]
  1086. public void ShouldWorkWithEnumUInt32()
  1087. {
  1088. TestEnum(TestEnumUInt32.None);
  1089. TestEnum(TestEnumUInt32.One);
  1090. TestEnum(TestEnumUInt32.Min);
  1091. TestEnum(TestEnumUInt32.Max);
  1092. }
  1093. [Fact]
  1094. public void ShouldWorkWithEnumInt64()
  1095. {
  1096. TestEnum(TestEnumInt64.None);
  1097. TestEnum(TestEnumInt64.One);
  1098. TestEnum(TestEnumInt64.Min);
  1099. TestEnum(TestEnumInt64.Max);
  1100. }
  1101. [Fact]
  1102. public void ShouldWorkWithEnumUInt64()
  1103. {
  1104. TestEnum(TestEnumUInt64.None);
  1105. TestEnum(TestEnumUInt64.One);
  1106. TestEnum(TestEnumUInt64.Min);
  1107. TestEnum(TestEnumUInt64.Max);
  1108. }
  1109. [Fact]
  1110. public void EnumIsConvertedToNumber()
  1111. {
  1112. var o = new
  1113. {
  1114. r = Colors.Red,
  1115. b = Colors.Blue,
  1116. g = Colors.Green
  1117. };
  1118. _engine.SetValue("o", o);
  1119. RunTest(@"
  1120. assert(o.r === 0);
  1121. assert(o.g === 1);
  1122. assert(o.b === 10);
  1123. ");
  1124. }
  1125. [Fact]
  1126. public void ShouldConvertToEnum()
  1127. {
  1128. var s = new Circle
  1129. {
  1130. Color = Colors.Red,
  1131. };
  1132. _engine.SetValue("s", s);
  1133. RunTest(@"
  1134. assert(s.Color === 0);
  1135. s.Color = 10;
  1136. assert(s.Color === 10);
  1137. ");
  1138. _engine.SetValue("s", s);
  1139. RunTest(@"
  1140. s.Color = 11;
  1141. assert(s.Color === 11);
  1142. ");
  1143. Assert.Equal(Colors.Blue | Colors.Green, s.Color);
  1144. }
  1145. [Fact]
  1146. public void ShouldUseExplicitPropertyGetter()
  1147. {
  1148. _engine.SetValue("c", new Company("ACME"));
  1149. RunTest(@"
  1150. assert(c.Name === 'ACME');
  1151. ");
  1152. }
  1153. [Fact]
  1154. public void ShouldUseExplicitIndexerPropertyGetter()
  1155. {
  1156. var company = new Company("ACME");
  1157. ((ICompany)company)["Foo"] = "Bar";
  1158. _engine.SetValue("c", company);
  1159. RunTest(@"
  1160. assert(c.Foo === 'Bar');
  1161. ");
  1162. }
  1163. [Fact]
  1164. public void ShouldUseExplicitPropertySetter()
  1165. {
  1166. _engine.SetValue("c", new Company("ACME"));
  1167. RunTest(@"
  1168. c.Name = 'Foo';
  1169. assert(c.Name === 'Foo');
  1170. ");
  1171. }
  1172. [Fact]
  1173. public void ShouldUseExplicitIndexerPropertySetter()
  1174. {
  1175. var company = new Company("ACME");
  1176. ((ICompany)company)["Foo"] = "Bar";
  1177. _engine.SetValue("c", company);
  1178. RunTest(@"
  1179. c.Foo = 'Baz';
  1180. assert(c.Foo === 'Baz');
  1181. ");
  1182. }
  1183. [Fact]
  1184. public void ShouldUseExplicitMethod()
  1185. {
  1186. _engine.SetValue("c", new Company("ACME"));
  1187. RunTest(@"
  1188. assert(0 === c.CompareTo(c));
  1189. ");
  1190. }
  1191. [Fact]
  1192. public void ShouldCallInstanceMethodWithParams()
  1193. {
  1194. _engine.SetValue("a", new A());
  1195. RunTest(@"
  1196. assert(a.Call13('1','2','3') === '1,2,3');
  1197. assert(a.Call13('1') === '1');
  1198. assert(a.Call13(1) === '1');
  1199. assert(a.Call13() === '');
  1200. assert(a.Call14('a','1','2','3') === 'a:1,2,3');
  1201. assert(a.Call14('a','1') === 'a:1');
  1202. assert(a.Call14('a') === 'a:');
  1203. function call13wrapper(){ return a.Call13.apply(a, Array.prototype.slice.call(arguments)); }
  1204. assert(call13wrapper('1','2','3') === '1,2,3');
  1205. assert(a.Call13('1','2','3') === a.Call13(['1','2','3']));
  1206. ");
  1207. }
  1208. [Fact]
  1209. public void ShouldCallInstanceMethodWithJsValueParams()
  1210. {
  1211. _engine.SetValue("a", new A());
  1212. RunTest(@"
  1213. assert(a.Call16('1','2','3') === '1,2,3');
  1214. assert(a.Call16('1') === '1');
  1215. assert(a.Call16(1) === '1');
  1216. assert(a.Call16() === '');
  1217. assert(a.Call16('1','2','3') === a.Call16(['1','2','3']));
  1218. ");
  1219. }
  1220. [Fact]
  1221. public void NullValueAsArgumentShouldWork()
  1222. {
  1223. _engine.SetValue("a", new A());
  1224. RunTest(@"
  1225. var x = a.Call2(null);
  1226. assert(x === null);
  1227. ");
  1228. }
  1229. [Fact]
  1230. public void ShouldSetPropertyToNull()
  1231. {
  1232. var p = new Person { Name = "Mickey" };
  1233. _engine.SetValue("p", p);
  1234. RunTest(@"
  1235. assert(p.Name != null);
  1236. p.Name = null;
  1237. assert(p.Name == null);
  1238. ");
  1239. Assert.True(p.Name == null);
  1240. }
  1241. [Fact]
  1242. public void ShouldCallMethodWithNull()
  1243. {
  1244. _engine.SetValue("a", new A());
  1245. RunTest(@"
  1246. a.Call15(null);
  1247. var result = a.Call2(null);
  1248. assert(result == null);
  1249. ");
  1250. }
  1251. [Fact]
  1252. public void ShouldReturnUndefinedProperty()
  1253. {
  1254. _engine.SetValue("uo", new { foo = "bar" });
  1255. _engine.SetValue("ud", new Dictionary<string, object> { {"foo", "bar"} });
  1256. _engine.SetValue("ul", new List<string> { "foo", "bar" });
  1257. RunTest(@"
  1258. assert(!uo.undefinedProperty);
  1259. assert(!ul[5]);
  1260. assert(!ud.undefinedProperty);
  1261. ");
  1262. }
  1263. [Fact]
  1264. public void ShouldAutomaticallyConvertArraysToFindBestInteropResulution()
  1265. {
  1266. _engine.SetValue("a", new ArrayConverterTestClass());
  1267. _engine.SetValue("item1", new ArrayConverterItem(1));
  1268. _engine.SetValue("item2", new ArrayConverterItem(2));
  1269. RunTest(@"
  1270. assert(a.MethodAcceptsArrayOfInt([false, '1', 2]) === a.MethodAcceptsArrayOfInt([0, 1, 2]));
  1271. assert(a.MethodAcceptsArrayOfStrings(['1', 2]) === a.MethodAcceptsArrayOfStrings([1, 2]));
  1272. assert(a.MethodAcceptsArrayOfBool(['1', 0]) === a.MethodAcceptsArrayOfBool([true, false]));
  1273. assert(a.MethodAcceptsArrayOfStrings([item1, item2]) === a.MethodAcceptsArrayOfStrings(['1', '2']));
  1274. assert(a.MethodAcceptsArrayOfInt([item1, item2]) === a.MethodAcceptsArrayOfInt([1, 2]));
  1275. ");
  1276. }
  1277. [Fact]
  1278. public void ShouldImportNamespaceNestedType()
  1279. {
  1280. RunTest(@"
  1281. var shapes = importNamespace('Shapes.Circle');
  1282. var kinds = shapes.Kind;
  1283. assert(kinds.Unit === 0);
  1284. assert(kinds.Ellipse === 1);
  1285. assert(kinds.Round === 5);
  1286. ");
  1287. }
  1288. [Fact]
  1289. public void ShouldImportNamespaceNestedNestedType()
  1290. {
  1291. RunTest(@"
  1292. var meta = importNamespace('Shapes.Circle.Meta');
  1293. var usages = meta.Usage;
  1294. assert(usages.Public === 0);
  1295. assert(usages.Private === 1);
  1296. assert(usages.Internal === 11);
  1297. ");
  1298. }
  1299. [Fact]
  1300. public void ShouldGetNestedNestedProp()
  1301. {
  1302. RunTest(@"
  1303. var meta = importNamespace('Shapes.Circle');
  1304. var m = new meta.Meta();
  1305. assert(m.Description === 'descp');
  1306. ");
  1307. }
  1308. [Fact]
  1309. public void ShouldSetNestedNestedProp()
  1310. {
  1311. RunTest(@"
  1312. var meta = importNamespace('Shapes.Circle');
  1313. var m = new meta.Meta();
  1314. m.Description = 'hello';
  1315. assert(m.Description === 'hello');
  1316. ");
  1317. }
  1318. [Fact]
  1319. public void CanGetStaticNestedField()
  1320. {
  1321. RunTest(@"
  1322. var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
  1323. var statics = domain.ClassWithStaticFields;
  1324. assert(statics.Get == 'Get');
  1325. ");
  1326. }
  1327. [Fact]
  1328. public void CanSetStaticNestedField()
  1329. {
  1330. RunTest(@"
  1331. var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
  1332. var statics = domain.ClassWithStaticFields;
  1333. statics.Set = 'hello';
  1334. assert(statics.Set == 'hello');
  1335. ");
  1336. Assert.Equal(Nested.ClassWithStaticFields.Set, "hello");
  1337. }
  1338. [Fact]
  1339. public void CanGetStaticNestedAccessor()
  1340. {
  1341. RunTest(@"
  1342. var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
  1343. var statics = domain.ClassWithStaticFields;
  1344. assert(statics.Getter == 'Getter');
  1345. ");
  1346. }
  1347. [Fact]
  1348. public void CanSetStaticNestedAccessor()
  1349. {
  1350. RunTest(@"
  1351. var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
  1352. var statics = domain.ClassWithStaticFields;
  1353. statics.Setter = 'hello';
  1354. assert(statics.Setter == 'hello');
  1355. ");
  1356. Assert.Equal(Nested.ClassWithStaticFields.Setter, "hello");
  1357. }
  1358. [Fact]
  1359. public void CantSetStaticNestedReadonly()
  1360. {
  1361. RunTest(@"
  1362. var domain = importNamespace('Jint.Tests.Runtime.Domain.Nested');
  1363. var statics = domain.ClassWithStaticFields;
  1364. statics.Readonly = 'hello';
  1365. assert(statics.Readonly == 'Readonly');
  1366. ");
  1367. Assert.Equal(Nested.ClassWithStaticFields.Readonly, "Readonly");
  1368. }
  1369. [Fact]
  1370. public void ShouldExecuteFunctionWithValueTypeParameterCorrectly()
  1371. {
  1372. _engine.SetValue("a", new A());
  1373. // Func<int, int>
  1374. RunTest(@"
  1375. assert(a.Call17(function(value){ return value; }) === 17);
  1376. ");
  1377. }
  1378. [Fact]
  1379. public void ShouldExecuteActionWithValueTypeParameterCorrectly()
  1380. {
  1381. _engine.SetValue("a", new A());
  1382. // Action<int>
  1383. RunTest(@"
  1384. a.Call18(function(value){ assert(value === 18); });
  1385. ");
  1386. }
  1387. [Fact]
  1388. public void ShouldConvertToJsValue()
  1389. {
  1390. RunTest(@"
  1391. var now = System.DateTime.Now;
  1392. assert(new String(now) == now.toString());
  1393. var zero = System.Int32.MaxValue;
  1394. assert(new String(zero) == zero.toString());
  1395. ");
  1396. }
  1397. [Fact]
  1398. public void ShouldNotCatchClrExceptions()
  1399. {
  1400. var engine = new Engine()
  1401. .SetValue("throwMyException", new Action(() => { throw new NotSupportedException(); }))
  1402. .SetValue("Thrower", typeof(Thrower))
  1403. .Execute(@"
  1404. function throwException1(){
  1405. try {
  1406. throwMyException();
  1407. return;
  1408. }
  1409. catch(e) {
  1410. return;
  1411. }
  1412. }
  1413. function throwException2(){
  1414. try {
  1415. new Thrower().ThrowNotSupportedException();
  1416. return;
  1417. }
  1418. catch(e) {
  1419. return;
  1420. }
  1421. }
  1422. ");
  1423. Assert.ThrowsAny<NotSupportedException>(() => engine.Invoke("throwException1"));
  1424. Assert.ThrowsAny<NotSupportedException>(() => engine.Invoke("throwException2"));
  1425. }
  1426. [Fact]
  1427. public void ShouldCatchAllClrExceptions()
  1428. {
  1429. string exceptionMessage = "myExceptionMessage";
  1430. var engine = new Engine(o => o.CatchClrExceptions())
  1431. .SetValue("throwMyException", new Action(() => { throw new Exception(exceptionMessage); }))
  1432. .SetValue("Thrower", typeof(Thrower))
  1433. .Execute(@"
  1434. function throwException1(){
  1435. try {
  1436. throwMyException();
  1437. return '';
  1438. }
  1439. catch(e) {
  1440. return e.message;
  1441. }
  1442. }
  1443. function throwException2(){
  1444. try {
  1445. new Thrower().ThrowExceptionWithMessage('myExceptionMessage');
  1446. return;
  1447. }
  1448. catch(e) {
  1449. return e.message;
  1450. }
  1451. }
  1452. ");
  1453. Assert.Equal(engine.Invoke("throwException1").AsString(), exceptionMessage);
  1454. Assert.Equal(engine.Invoke("throwException2").AsString(), exceptionMessage);
  1455. }
  1456. class MemberExceptionTest
  1457. {
  1458. public MemberExceptionTest(bool throwOnCreate)
  1459. {
  1460. if (throwOnCreate)
  1461. throw new InvalidOperationException();
  1462. }
  1463. public JsValue ThrowingProperty1
  1464. {
  1465. get { throw new InvalidOperationException(); }
  1466. set { throw new InvalidOperationException(); }
  1467. }
  1468. public object ThrowingProperty2
  1469. {
  1470. get { throw new InvalidOperationException(); }
  1471. set { throw new InvalidOperationException(); }
  1472. }
  1473. public void ThrowingFunction()
  1474. {
  1475. throw new InvalidOperationException();
  1476. }
  1477. }
  1478. [Fact]
  1479. public void ShouldCatchClrMemberExceptions()
  1480. {
  1481. var engine = new Engine(cfg =>
  1482. {
  1483. cfg.AllowClr();
  1484. cfg.CatchClrExceptions();
  1485. });
  1486. engine.SetValue("assert", new Action<bool>(Assert.True));
  1487. engine.SetValue("log", new Action<object>(Console.WriteLine));
  1488. engine.SetValue("create", typeof(MemberExceptionTest));
  1489. engine.SetValue("instance", new MemberExceptionTest(throwOnCreate: false));
  1490. // Test calling a constructor that throws an exception
  1491. engine.Execute(@"
  1492. try
  1493. {
  1494. create(true);
  1495. assert(false);
  1496. }
  1497. catch (e)
  1498. {
  1499. assert(true);
  1500. }
  1501. ");
  1502. // Test calling a member function that throws an exception
  1503. engine.Execute(@"
  1504. try
  1505. {
  1506. instance.ThrowingFunction();
  1507. assert(false);
  1508. }
  1509. catch (e)
  1510. {
  1511. assert(true);
  1512. }
  1513. ");
  1514. // Test using a property getter that throws an exception
  1515. engine.Execute(@"
  1516. try
  1517. {
  1518. log(o.ThrowingProperty);
  1519. assert(false);
  1520. }
  1521. catch (e)
  1522. {
  1523. assert(true);
  1524. }
  1525. ");
  1526. // Test using a property setter that throws an exception
  1527. engine.Execute(@"
  1528. try
  1529. {
  1530. instance.ThrowingProperty1 = 123;
  1531. assert(false);
  1532. }
  1533. catch (e)
  1534. {
  1535. assert(true);
  1536. }
  1537. try
  1538. {
  1539. instance.ThrowingProperty2 = 456;
  1540. assert(false);
  1541. }
  1542. catch (e)
  1543. {
  1544. assert(true);
  1545. }
  1546. ");
  1547. }
  1548. [Fact]
  1549. public void ShouldCatchSomeExceptions()
  1550. {
  1551. string exceptionMessage = "myExceptionMessage";
  1552. var engine = new Engine(o => o.CatchClrExceptions(e => e is NotSupportedException))
  1553. .SetValue("throwMyException1", new Action(() => { throw new NotSupportedException(exceptionMessage); }))
  1554. .SetValue("throwMyException2", new Action(() => { throw new ArgumentNullException(); }))
  1555. .SetValue("Thrower", typeof(Thrower))
  1556. .Execute(@"
  1557. function throwException1(){
  1558. try {
  1559. throwMyException1();
  1560. return '';
  1561. }
  1562. catch(e) {
  1563. return e.message;
  1564. }
  1565. }
  1566. function throwException2(){
  1567. try {
  1568. throwMyException2();
  1569. return '';
  1570. }
  1571. catch(e) {
  1572. return e.message;
  1573. }
  1574. }
  1575. function throwException3(){
  1576. try {
  1577. new Thrower().ThrowNotSupportedExceptionWithMessage('myExceptionMessage');
  1578. return '';
  1579. }
  1580. catch(e) {
  1581. return e.message;
  1582. }
  1583. }
  1584. function throwException4(){
  1585. try {
  1586. new Thrower().ThrowArgumentNullException();
  1587. return '';
  1588. }
  1589. catch(e) {
  1590. return e.message;
  1591. }
  1592. }
  1593. ");
  1594. Assert.Equal(engine.Invoke("throwException1").AsString(), exceptionMessage);
  1595. Assert.Throws<ArgumentNullException>(() => engine.Invoke("throwException2"));
  1596. Assert.Equal(engine.Invoke("throwException3").AsString(), exceptionMessage);
  1597. Assert.Throws<ArgumentNullException>(() => engine.Invoke("throwException4"));
  1598. }
  1599. [Fact]
  1600. public void ArrayFromShouldConvertListToArrayLike()
  1601. {
  1602. var list = new List<Person>
  1603. {
  1604. new Person {Name = "Mike"},
  1605. new Person {Name = "Mika"}
  1606. };
  1607. _engine.SetValue("a", list);
  1608. RunTest(@"
  1609. var arr = new Array(a);
  1610. assert(arr.length === 2);
  1611. assert(arr[0].Name === 'Mike');
  1612. assert(arr[1].Name === 'Mika');
  1613. ");
  1614. RunTest(@"
  1615. var arr = Array.from(a);
  1616. assert(arr.length === 2);
  1617. assert(arr[0].Name === 'Mike');
  1618. assert(arr[1].Name === 'Mika');
  1619. ");
  1620. }
  1621. [Fact]
  1622. public void ArrayFromShouldConvertArrayToArrayLike()
  1623. {
  1624. var list = new []
  1625. {
  1626. new Person {Name = "Mike"},
  1627. new Person {Name = "Mika"}
  1628. };
  1629. _engine.SetValue("a", list);
  1630. RunTest(@"
  1631. var arr = new Array(a);
  1632. assert(arr.length === 2);
  1633. assert(arr[0].Name === 'Mike');
  1634. assert(arr[1].Name === 'Mika');
  1635. ");
  1636. RunTest(@"
  1637. var arr = Array.from(a);
  1638. assert(arr.length === 2);
  1639. assert(arr[0].Name === 'Mike');
  1640. assert(arr[1].Name === 'Mika');
  1641. ");
  1642. }
  1643. [Fact]
  1644. public void ArrayFromShouldConvertIEnumerable()
  1645. {
  1646. var enumerable = new []
  1647. {
  1648. new Person {Name = "Mike"},
  1649. new Person {Name = "Mika"}
  1650. }.Select(x => x);
  1651. _engine.SetValue("a", enumerable);
  1652. RunTest(@"
  1653. var arr = new Array(a);
  1654. assert(arr.length === 2);
  1655. assert(arr[0].Name === 'Mike');
  1656. assert(arr[1].Name === 'Mika');
  1657. ");
  1658. RunTest(@"
  1659. var arr = Array.from(a);
  1660. assert(arr.length === 2);
  1661. assert(arr[0].Name === 'Mike');
  1662. assert(arr[1].Name === 'Mika');
  1663. ");
  1664. }
  1665. [Fact]
  1666. public void ShouldBeAbleToPlusAssignStringProperty()
  1667. {
  1668. var p = new Person();
  1669. var engine = new Engine();
  1670. engine.SetValue("P", p);
  1671. engine.Execute("P.Name = 'b';");
  1672. engine.Execute("P.Name += 'c';");
  1673. Assert.Equal("bc", p.Name);
  1674. }
  1675. [Fact]
  1676. public void ShouldNotResolvetoPrimitiveSymbol()
  1677. {
  1678. var engine = new Engine(options =>
  1679. options.AllowClr(typeof(FloatIndexer).GetTypeInfo().Assembly));
  1680. var c = engine.Execute(@"
  1681. var domain = importNamespace('Jint.Tests.Runtime.Domain');
  1682. return new domain.FloatIndexer();
  1683. ").GetCompletionValue();
  1684. Assert.NotNull(c.ToString());
  1685. Assert.Equal((uint)0, c.As<ObjectInstance>().Length);
  1686. }
  1687. }
  1688. }