InteropTests.cs 80 KB

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