InteropTests.cs 70 KB

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