InteropTests.cs 52 KB

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