InteropTests.cs 42 KB

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