InteropTests.cs 47 KB

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